branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>15835229565/TongSheng_TSDZ2_motor_controller_firmware<file_sep>/motor.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _MOTOR_H_ #define _MOTOR_H_ #include <stdint.h> // motor states #define BLOCK_COMMUTATION 1 #define SINEWAVE_INTERPOLATION_60_DEGREES 2 #define MOTOR_CONTROLLER_STATE_OK 1 #define MOTOR_CONTROLLER_STATE_BRAKE 2 #define MOTOR_CONTROLLER_STATE_OVER_CURRENT 4 #define MOTOR_CONTROLLER_STATE_UNDER_VOLTAGE 8 #define MOTOR_CONTROLLER_STATE_THROTTLE_ERROR 16 #define MOTOR_CONTROLLER_STATE_MOTOR_BLOCKED 32 extern volatile uint8_t ui8_duty_cycle_target; extern volatile uint8_t ui8_duty_cycle; extern volatile uint16_t ui16_motor_speed_erps; extern volatile uint8_t ui8_adc_motor_phase_current_offset; extern volatile uint8_t ui8_adc_motor_phase_current; extern volatile uint8_t ui8_pas_1; extern volatile uint8_t ui8_pas_2; extern volatile uint16_t ui16_torque_sensor_throttle_processed_value; extern volatile uint8_t ui8_adc_battery_current; extern volatile uint8_t ui8_foc_angle; /***************************************************************************************/ // Motor interface void hall_sensor_init (void); // must be called before using the motor void motor_init (void); // must be called before using the motor void motor_enable_PWM (void); void motor_disable_PWM (void); void motor_set_pwm_duty_cycle_target (uint8_t value); void motor_set_current_max (uint8_t value); // steps of 0.25A each step void motor_set_pwm_duty_cycle_ramp_up_inverse_step (uint16_t value); // each step = 64us void motor_set_pwm_duty_cycle_ramp_down_inverse_step (uint16_t value); // each step = 64us uint16_t ui16_motor_get_motor_speed_erps (void); void motor_controller_set_state (uint8_t state); void motor_controller_reset_state (uint8_t state); uint8_t motor_controller_state_is_set (uint8_t state); void motor_set_pwm_duty_cycle_target (uint8_t ui8_value); void motor_controller (void); uint8_t motor_get_adc_battery_current_filtered_10b (void); uint16_t motor_get_adc_battery_voltage_filtered_10b (void); void motor_set_adc_battery_voltage_cut_off (uint8_t ui8_value); /***************************************************************************************/ #endif /* _MOTOR_H_ */ <file_sep>/torque_sensor.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include "stm8s.h" #include "stm8s_gpio.h" #include "pins.h" #include "torque_sensor.h" void torque_sensor_init (void) { GPIO_Init(TORQUE_SENSOR_EXCITATION__PORT, TORQUE_SENSOR_EXCITATION__PIN, GPIO_MODE_OUT_OD_HIZ_FAST); } <file_sep>/wheel_speed_sensor.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include "stm8s.h" #include "pins.h" void wheel_speed_sensor_init (void) { //whell speed sensor pin as input GPIO_Init(WHEEL_SPEED_SENSOR__PORT, WHEEL_SPEED_SENSOR__PIN, GPIO_MODE_IN_PU_NO_IT); // input pull-up, no external interrupt } <file_sep>/torque_sensor.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _TORQUE_SENSOR_H_ #define _TORQUE_SENSOR_H_ #include "main.h" #include "stm8s_gpio.h" void torque_sensor_init (void); #endif /* _TORQUE_SENSOR_H_ */ <file_sep>/utils.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _UTILS_H #define _UTILS_H #include "main.h" typedef struct pi_controller_state { uint8_t ui8_current_value; uint8_t ui8_target_value; uint8_t ui8_controller_output_value; uint8_t ui8_kp_dividend; uint8_t ui8_kp_divisor; uint8_t ui8_ki_dividend; uint8_t ui8_ki_divisor; int16_t i16_i_term; } struct_pi_controller_state; int32_t map (int32_t x, int32_t in_min, int32_t in_max, int32_t out_min, int32_t out_max); int32_t map_inverse (int32_t x, int32_t in_min, int32_t in_max, int32_t out_min, int32_t out_max); uint8_t ui8_max (uint8_t value_a, uint8_t value_b); uint8_t ui8_min (uint8_t value_a, uint8_t value_b); void pi_controller (struct_pi_controller_state *pi_controller_state); void pi_controller_reset (struct_pi_controller_state *pi_controller); void crc16(uint8_t ui8_data, uint16_t* ui16_crc); #endif /* _UTILS_H */ <file_sep>/eeprom.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include "stm8s.h" #include "stm8s_flash.h" #include "eeprom.h" #include "ebike_app.h" static uint8_t array_default_values [EEPROM_BYTES_STORED] = { KEY, DEFAULT_VALUE_ASSIST_LEVEL_FACTOR_X10, DEFAULT_VALUE_CONFIG_0, DEFAULT_VALUE_BATTERY_MAX_CURRENT, DEFAULT_VALUE_TARGET_BATTERY_MAX_POWER_X10, DEFAULT_VALUE_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_0, DEFAULT_VALUE_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_1, DEFAULT_VALUE_WHEEL_PERIMETER_0, DEFAULT_VALUE_WHEEL_PERIMETER_1, DEFAULT_VALUE_WHEEL_MAX_SPEED, DEFAULT_VALUE_PAS_MAX_CADENCE, DEFAULT_VALUE_CONFIG_1, DEFAULT_VALUE_OFFROAD_CONFIG, DEFAULT_VALUE_OFFROAD_SPEED_LIMIT, DEFAULT_VALUE_OFFROAD_POWER_LIMIT_DIV25 }; static void eeprom_read_values_to_variables (void); static void eeprom_write_array (uint8_t *array_values); static void variables_to_array (uint8_t *ui8_array); void eeprom_init (void) { uint8_t ui8_data; // start by reading address 0 and see if value is different from our key, // if so mean that eeprom memory is clean and we need to populate: should happen after erasing the microcontroller ui8_data = FLASH_ReadByte (ADDRESS_KEY); if (ui8_data != KEY) // verify if our key exist { eeprom_write_array (array_default_values); } } void eeprom_init_variables (void) { struct_configuration_variables *p_configuration_variables; p_configuration_variables = get_configuration_variables (); eeprom_read_values_to_variables (); // now verify if any EEPROM saved value is out of valid range and if so, // write correct ones and read again if ((p_configuration_variables->ui8_battery_max_current > 100) || (p_configuration_variables->ui8_motor_power_x10 > 195) || (p_configuration_variables->ui16_battery_low_voltage_cut_off_x10 > 630) || (p_configuration_variables->ui16_battery_low_voltage_cut_off_x10 < 160) || (p_configuration_variables->ui16_wheel_perimeter > 3000) || (p_configuration_variables->ui16_wheel_perimeter < 750) || (p_configuration_variables->ui8_wheel_max_speed > 99) || (p_configuration_variables->ui8_pas_max_cadence > 175)) { eeprom_write_array (array_default_values); eeprom_read_values_to_variables (); } } static void eeprom_read_values_to_variables (void) { static uint8_t ui8_temp; static uint16_t ui16_temp; struct_configuration_variables *p_configuration_variables; p_configuration_variables = get_configuration_variables (); p_configuration_variables->ui8_power_regular_state_div25 = FLASH_ReadByte (ADDRESS_ASSIST_LEVEL_FACTOR_X10); ui8_temp = FLASH_ReadByte (ADDRESS_CONFIG_0); p_configuration_variables->ui8_lights = ui8_temp & 1 ? 1 : 0; p_configuration_variables->ui8_walk_assist = ui8_temp & (1 << 1) ? 1 : 0; p_configuration_variables->ui8_offroad_mode = ui8_temp & (1 << 2) ? 1 : 0; p_configuration_variables->ui8_battery_max_current = FLASH_ReadByte (ADDRESS_BATTERY_MAX_CURRENT); p_configuration_variables->ui8_motor_power_x10 = FLASH_ReadByte (ADDRESS_MOTOR_POWER_X10); ui16_temp = FLASH_ReadByte (ADDRESS_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_0); ui8_temp = FLASH_ReadByte (ADDRESS_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_1); ui16_temp += (((uint16_t) ui8_temp << 8) & 0xff00); p_configuration_variables->ui16_battery_low_voltage_cut_off_x10 = ui16_temp; ui16_temp = FLASH_ReadByte (ADDRESS_WHEEL_PERIMETER_0); ui8_temp = FLASH_ReadByte (ADDRESS_WHEEL_PERIMETER_1); ui16_temp += (((uint16_t) ui8_temp << 8) & 0xff00); p_configuration_variables->ui16_wheel_perimeter = ui16_temp; p_configuration_variables->ui8_wheel_max_speed = FLASH_ReadByte (ADDRESS_WHEEL_MAX_SPEED); p_configuration_variables->ui8_pas_max_cadence = FLASH_ReadByte (ADDRESS_PAS_MAX_CADENCE); ui8_temp = FLASH_ReadByte (ADDRESS_CONFIG_1); p_configuration_variables->ui8_motor_voltage_type = ui8_temp & 1; p_configuration_variables->ui8_motor_assistance_startup_without_pedal_rotation = (ui8_temp & 2) >> 1; ui8_temp = FLASH_ReadByte (ADDRESS_OFFROAD_CONFIG); p_configuration_variables->ui8_offroad_func_enabled = ui8_temp & 1; p_configuration_variables->ui8_offroad_enabled_on_startup = ui8_temp & (1 << 1); p_configuration_variables->ui8_offroad_power_limit_enabled = ui8_temp & (1 << 2); p_configuration_variables->ui8_offroad_speed_limit = FLASH_ReadByte (ADDRESS_OFFROAD_SPEED_LIMIT); p_configuration_variables->ui8_offroad_power_limit_div25 = FLASH_ReadByte (ADDRESS_OFFROAD_POWER_LIMIT_DIV25); } void eeprom_write_variables (void) { uint8_t array_variables [EEPROM_BYTES_STORED]; variables_to_array (array_variables); eeprom_write_array (array_variables); } static void variables_to_array (uint8_t *ui8_array) { struct_configuration_variables *p_configuration_variables; p_configuration_variables = get_configuration_variables (); ui8_array [0] = KEY; ui8_array [1] = p_configuration_variables->ui8_power_regular_state_div25; ui8_array [2] = (p_configuration_variables->ui8_lights & 1) | ((p_configuration_variables->ui8_walk_assist & 1) << 1) | ((p_configuration_variables->ui8_offroad_mode & 1) << 2); ui8_array [3] = p_configuration_variables->ui8_battery_max_current; ui8_array [4] = p_configuration_variables->ui8_motor_power_x10; ui8_array [5] = p_configuration_variables->ui16_battery_low_voltage_cut_off_x10 & 255; ui8_array [6] = (p_configuration_variables->ui16_battery_low_voltage_cut_off_x10 >> 8) & 255; ui8_array [7] = p_configuration_variables->ui16_wheel_perimeter & 255; ui8_array [8] = (p_configuration_variables->ui16_wheel_perimeter >> 8) & 255; ui8_array [9] = p_configuration_variables->ui8_wheel_max_speed; ui8_array [10] = p_configuration_variables->ui8_pas_max_cadence; ui8_array [11] = (p_configuration_variables->ui8_motor_voltage_type & 1) | ((p_configuration_variables->ui8_motor_assistance_startup_without_pedal_rotation & 1) << 1); ui8_array [12] = (p_configuration_variables->ui8_offroad_func_enabled & 1) | ((p_configuration_variables->ui8_offroad_enabled_on_startup & 1) << 1) | ((p_configuration_variables->ui8_offroad_power_limit_enabled & 1) << 2); ui8_array [13] = p_configuration_variables->ui8_offroad_speed_limit; ui8_array [14] = p_configuration_variables->ui8_offroad_power_limit_div25; } static void eeprom_write_array (uint8_t *array) { uint8_t ui8_i; if (FLASH_GetFlagStatus(FLASH_FLAG_DUL) == 0) { FLASH_Unlock (FLASH_MEMTYPE_DATA); } for (ui8_i = 0; ui8_i < EEPROM_BYTES_STORED; ui8_i++) { FLASH_ProgramByte (EEPROM_BASE_ADDRESS + ui8_i, *array++); } FLASH_Lock (FLASH_MEMTYPE_DATA); } void eeprom_write_if_values_changed (void) { // 2018.08.29: // NOTE: the next code gives a problem with motor, when we exchange assist level on LCD3 and // all the variables all written to EEPROM. As per datasheet, seems each byte takes ~6ms to be written // I am not sure the issue is the amount of time... // uint8_t ui8_index; // // uint8_t array_variables [EEPROM_BYTES_STORED]; // variables_to_array (array_variables); // // ui8_index = 1; // do not verify the first byte: ADDRESS_KEY // while (ui8_index < EEPROM_BYTES_STORED) // { // if (array_variables [ui8_index] != FLASH_ReadByte (EEPROM_BASE_ADDRESS + ui8_index)) // { // eeprom_write_array (array_variables); // break; // exit the while loop // } // // ui8_index++; // } } <file_sep>/ebike_app.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include "ebike_app.h" #include <stdint.h> #include <stdio.h> #include "stm8s.h" #include "stm8s_gpio.h" #include "main.h" #include "interrupts.h" #include "adc.h" #include "utils.h" #include "motor.h" #include "pwm.h" #include "uart.h" #include "brake.h" #include "eeprom.h" #include "config.h" #include "utils.h" #include "lights.h" #define STATE_NO_PEDALLING 0 #define STATE_STARTUP_PEDALLING 1 #define STATE_PEDALLING 2 #define BOOST_STATE_BOOST_DISABLED 0 #define BOOST_STATE_START_BOOST 1 #define BOOST_STATE_BOOST 2 #define BOOST_STATE_END_BOOST 3 #define BOOST_STATE_FADE 4 #define BOOST_STATE_BOOST_WAIT_TO_RESTART 5 uint8_t ui8_adc_battery_max_current = ADC_BATTERY_CURRENT_MAX; uint8_t ui8_target_battery_max_power_x10 = ADC_BATTERY_CURRENT_MAX; volatile uint8_t ui8_throttle = 0; volatile uint8_t ui8_torque_sensor_value1 = 0; volatile uint8_t ui8_torque_sensor = 0; volatile uint8_t ui8_torque_sensor_raw = 0; volatile uint8_t ui8_adc_torque_sensor_min_value; volatile uint8_t ui8_adc_torque_sensor_max_value; volatile uint8_t ui8_adc_battery_current_offset; volatile uint8_t ui8_ebike_app_state = EBIKE_APP_STATE_MOTOR_STOP; volatile uint8_t ui8_adc_target_battery_max_current; uint8_t ui8_adc_battery_current_max; volatile uint16_t ui16_pas_pwm_cycles_ticks = (uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS; volatile uint8_t ui8_pas_direction = 0; uint8_t ui8_pas_cadence_rpm = 0; uint8_t ui8_pedal_human_power = 0; uint8_t ui8_startup_boost_enable = 0; uint8_t ui8_startup_boost_fade_enable = 0; uint8_t ui8_startup_boost_state_machine = 0; uint8_t ui8_startup_boost_no_torque = 0; uint8_t ui8_startup_boost_timer = 0; uint8_t ui8_startup_boost_fade_steps = 0; uint16_t ui16_startup_boost_fade_variable_x256; uint16_t ui16_startup_boost_fade_variable_step_amount_x256; // wheel speed volatile uint16_t ui16_wheel_speed_sensor_pwm_cycles_ticks = (uint16_t) WHEEL_SPEED_SENSOR_MAX_PWM_CYCLE_TICKS; uint8_t ui8_wheel_speed_max = 0; float f_wheel_speed_x10; uint16_t ui16_wheel_speed_x10; volatile uint32_t ui32_wheel_speed_sensor_tick_counter = 0; volatile struct_configuration_variables configuration_variables; // UART volatile uint8_t ui8_received_package_flag = 0; volatile uint8_t ui8_rx_buffer[11]; volatile uint8_t ui8_rx_counter = 0; volatile uint8_t ui8_tx_buffer[22]; volatile uint8_t ui8_tx_counter = 0; volatile uint8_t ui8_i; volatile uint8_t ui8_checksum; volatile uint8_t ui8_byte_received; volatile uint8_t ui8_state_machine = 0; volatile uint8_t ui8_uart_received_first_package = 0; static uint16_t ui16_crc_rx; static uint16_t ui16_crc_tx; static uint8_t ui8_master_comm_package_id = 0; static uint8_t ui8_slave_comm_package_id = 0; uint8_t ui8_tstr_state_machine = STATE_NO_PEDALLING; uint8_t ui8_rtst_counter = 0; uint16_t ui16_adc_motor_temperatured_accumulated = 0; uint8_t ui8_adc_battery_target_current; // function prototypes static void ebike_control_motor (void); void ebike_app_set_battery_max_current (uint8_t ui8_value); void ebike_app_set_target_adc_battery_max_current (uint8_t ui8_value); void communications_controller (void); void uart_send_package (void); void calc_wheel_speed (void); void throttle_read (void); void torque_sensor_read (void); void startup_boost (void); void calc_motor_temperature (void); void read_pas_cadence (void) { // cadence in RPM = 60 / (ui16_pas_timer2_ticks * PAS_NUMBER_MAGNETS * 0.000064) if (ui16_pas_pwm_cycles_ticks >= ((uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS)) { ui8_pas_cadence_rpm = 0; } else { ui8_pas_cadence_rpm = (uint8_t) (60 / (((float) ui16_pas_pwm_cycles_ticks) * ((float) PAS_NUMBER_MAGNETS) * 0.000064)); if (ui8_pas_cadence_rpm > configuration_variables.ui8_pas_max_cadence) { ui8_pas_cadence_rpm = configuration_variables.ui8_pas_max_cadence; } } } void torque_sensor_read (void) { // map value from 0 up to 255 // map value from 0 up to 255 ui8_torque_sensor_raw = (uint8_t) (map ( UI8_ADC_TORQUE_SENSOR, (uint8_t) ui8_adc_torque_sensor_min_value, (uint8_t) ui8_adc_torque_sensor_max_value, (uint8_t) 0, (uint8_t) 255)); switch (ui8_tstr_state_machine) { // ebike is stopped, wait for throttle signal case STATE_NO_PEDALLING: if ((ui8_torque_sensor_raw > 0) && (!brake_is_set())) { ui8_tstr_state_machine = STATE_STARTUP_PEDALLING; } break; // now count 2 seconds case STATE_STARTUP_PEDALLING: if (ui8_rtst_counter++ > 20) // 2 seconds { ui8_rtst_counter = 0; ui8_tstr_state_machine = STATE_PEDALLING; } // ebike is not moving, let's return to begin if (ui16_wheel_speed_x10 == 0) { ui8_rtst_counter = 0; ui8_tstr_state_machine = 0; } break; // wait on this state and reset when ebike stops case STATE_PEDALLING: if ((ui16_wheel_speed_x10 == 0) && (ui8_torque_sensor_raw == 0)) { ui8_tstr_state_machine = STATE_NO_PEDALLING; } break; default: break; } // bike is moving but user doesn't pedal, disable torque sensor signal because user can be resting the feet on the pedals if ((ui8_tstr_state_machine == STATE_PEDALLING) && (ui8_pas_cadence_rpm == 0)) { ui8_torque_sensor = 0; } else { ui8_torque_sensor = ui8_torque_sensor_raw; } } void throttle_read (void) { // map value from 0 up to 255 ui8_throttle = (uint8_t) (map ( UI8_ADC_THROTTLE, (uint8_t) ADC_THROTTLE_MIN_VALUE, (uint8_t) ADC_THROTTLE_MAX_VALUE, (uint8_t) 0, (uint8_t) 255)); } void startup_boost (void) { if (configuration_variables.ui8_startup_motor_power_boost_time > 0) { switch (ui8_startup_boost_state_machine) { // ebike is stopped, wait for throttle signal to startup boost case BOOST_STATE_BOOST_DISABLED: if ((ui8_torque_sensor > 0) && (!brake_is_set())) { ui8_startup_boost_state_machine = BOOST_STATE_START_BOOST; } break; case BOOST_STATE_START_BOOST: ui8_startup_boost_enable = 1; ui8_startup_boost_timer = configuration_variables.ui8_startup_motor_power_boost_time; ui8_startup_boost_state_machine = BOOST_STATE_BOOST; break; case BOOST_STATE_BOOST: // decrement timer if (ui8_startup_boost_timer > 0) { ui8_startup_boost_timer--; } // disable boost if if ((ui8_torque_sensor == 0) || (ui8_startup_boost_timer == 0)) { ui8_startup_boost_state_machine = BOOST_STATE_END_BOOST; } break; case BOOST_STATE_END_BOOST: ui8_startup_boost_enable = 0; // setup variables for fade ui8_startup_boost_fade_steps = configuration_variables.ui8_startup_motor_power_boost_fade_time; ui16_startup_boost_fade_variable_x256 = ((uint16_t) ui8_adc_battery_target_current << 8); ui16_startup_boost_fade_variable_step_amount_x256 = (ui16_startup_boost_fade_variable_x256 / ((uint16_t) ui8_startup_boost_fade_steps)); ui8_startup_boost_fade_enable = 1; ui8_startup_boost_state_machine = BOOST_STATE_FADE; break; case BOOST_STATE_FADE: if (ui8_startup_boost_fade_steps > 0) { ui8_startup_boost_fade_steps--; } // disable fade if if ((ui8_torque_sensor_raw == 0) || (ui8_pas_cadence_rpm == 0) || (ui8_startup_boost_fade_steps == 0)) { ui8_startup_boost_fade_enable = 0; ui8_startup_boost_fade_steps = 0; ui8_startup_boost_state_machine = BOOST_STATE_BOOST_WAIT_TO_RESTART; } break; // restart when user is not pressing the pedals AND/OR wheel speed = 0 case BOOST_STATE_BOOST_WAIT_TO_RESTART: // wheel speed must be 0 as also torque sensor if ((configuration_variables.ui8_startup_motor_power_boost_state & 1) == 0) { if ((ui16_wheel_speed_x10 == 0) && (ui8_torque_sensor_raw == 0)) { ui8_startup_boost_state_machine = BOOST_STATE_BOOST_DISABLED; } } // torque sensor must be 0 if ((configuration_variables.ui8_startup_motor_power_boost_state & 1) > 0) { if ((ui8_torque_sensor_raw == 0) || (ui8_pas_cadence_rpm == 0)) { ui8_startup_boost_state_machine = BOOST_STATE_BOOST_DISABLED; } } break; default: break; } } } void ebike_app_init (void) { // init variables with the stored value on EEPROM eeprom_init_variables (); ebike_app_set_battery_max_current (ADC_BATTERY_CURRENT_MAX); } void ebike_app_controller (void) { throttle_read (); torque_sensor_read (); read_pas_cadence (); calc_wheel_speed (); calc_motor_temperature (); ebike_control_motor (); communications_controller (); } void communications_controller (void) { uint32_t ui32_temp; #ifndef DEBUG_UART if (ui8_received_package_flag) { // verify crc of the package ui16_crc_rx = 0xffff; for (ui8_i = 0; ui8_i < 9; ui8_i++) { crc16 (ui8_rx_buffer[ui8_i], &ui16_crc_rx); } // see if CRC is ok... if (((((uint16_t) ui8_rx_buffer [10]) << 8) + ((uint16_t) ui8_rx_buffer [9])) == ui16_crc_rx) { ui8_master_comm_package_id = ui8_rx_buffer [1]; // send a variable for each package sent but first verify if the last one was received otherwise, keep repeating // keep cycling so all variables are sent #define VARIABLE_ID_MAX_NUMBER 5 if ((ui8_rx_buffer [2]) == ui8_slave_comm_package_id) // last package data ID was receipt, so send the next one { ui8_slave_comm_package_id = (ui8_slave_comm_package_id + 1) % VARIABLE_ID_MAX_NUMBER; } // assist level configuration_variables.ui8_power_regular_state_div25 = ui8_rx_buffer [3]; // head light configuration_variables.ui8_lights = (ui8_rx_buffer [4] & (1 << 0)) ? 1: 0; lights_set_state (configuration_variables.ui8_lights); // walk assist configuration_variables.ui8_walk_assist = (ui8_rx_buffer [4] & (1 << 1)) ? 1: 0; // battery max current configuration_variables.ui8_battery_max_current = ui8_rx_buffer [5]; ebike_app_set_battery_max_current (configuration_variables.ui8_battery_max_current); // target battery max power configuration_variables.ui8_target_battery_max_power_div25 = ui8_rx_buffer [6]; switch (ui8_master_comm_package_id) { case 0: // battery low voltage cut-off configuration_variables.ui16_battery_low_voltage_cut_off_x10 = (((uint16_t) ui8_rx_buffer [8]) << 8) + ((uint16_t) ui8_rx_buffer [7]); // calc the value in ADC steps and set it up ui32_temp = ((uint32_t) configuration_variables.ui16_battery_low_voltage_cut_off_x10 << 8) / ((uint32_t) ADC8BITS_BATTERY_VOLTAGE_PER_ADC_STEP_INVERSE_X256); ui32_temp /= 10; motor_set_adc_battery_voltage_cut_off ((uint8_t) ui32_temp); break; case 1: // wheel perimeter configuration_variables.ui16_wheel_perimeter = (((uint16_t) ui8_rx_buffer [8]) << 8) + ((uint16_t) ui8_rx_buffer [7]); break; case 2: // wheel max speed configuration_variables.ui8_wheel_max_speed = ui8_rx_buffer [7]; // PAS max cadence RPM configuration_variables.ui8_pas_max_cadence = ui8_rx_buffer [8]; break; case 3: configuration_variables.ui8_cruise_control = ui8_rx_buffer [7] & 1; configuration_variables.ui8_motor_voltage_type = (ui8_rx_buffer [7] & 2) >> 1; configuration_variables.ui8_motor_assistance_startup_without_pedal_rotation = (ui8_rx_buffer [7] & 4) >> 2; configuration_variables.ui8_throttle_adc_measures_motor_temperature = (ui8_rx_buffer [7] & 8) >> 3; configuration_variables.ui8_startup_motor_power_boost_state = ui8_rx_buffer [8] & 1; configuration_variables.ui8_startup_motor_power_boost_limit_to_max_power = (ui8_rx_buffer [8] & 2) >> 1; break; case 4: // startup motor power boost configuration_variables.ui8_startup_motor_power_boost_div25 = ui8_rx_buffer [7]; // startup motor power boost time configuration_variables.ui8_startup_motor_power_boost_time = ui8_rx_buffer [8]; break; case 5: // startup motor power boost fade time configuration_variables.ui8_startup_motor_power_boost_fade_time = ui8_rx_buffer [7]; break; case 6: // motor temperature min and max values to limit configuration_variables.ui8_motor_temperature_min_value_to_limit = ui8_rx_buffer [7]; configuration_variables.ui8_motor_temperature_max_value_to_limit = ui8_rx_buffer [8]; break; case 7: // offroad mode configuration configuration_variables.ui8_offroad_func_enabled = ui8_rx_buffer [7] & 1; configuration_variables.ui8_offroad_enabled_on_startup = (ui8_rx_buffer [7]) & (1 << 1); configuration_variables.ui8_offroad_speed_limit = ui8_rx_buffer [8]; break; case 8: // offroad mode power limit configuration configuration_variables.ui8_offroad_power_limit_enabled = ui8_rx_buffer [7] & 1; configuration_variables.ui8_offroad_power_limit_div25 = ui8_rx_buffer [8]; break; default: // nothing break; } // verify if any configuration_variables did change and if so, save all of them in the EEPROM eeprom_write_if_values_changed (); // signal that we processed the full package ui8_received_package_flag = 0; ui8_uart_received_first_package = 1; } // enable UART2 receive interrupt as we are now ready to receive a new package UART2->CR2 |= (1 << 5); } uart_send_package (); #endif } void uart_send_package (void) { uint16_t ui16_temp; // send the data to the LCD // start up byte ui8_tx_buffer[0] = 0x43; ui8_tx_buffer[1] = ui8_master_comm_package_id; ui8_tx_buffer[2] = ui8_slave_comm_package_id; ui16_temp = motor_get_adc_battery_voltage_filtered_10b (); // adc 10 bits battery voltage ui8_tx_buffer[3] = (ui16_temp & 0xff); ui8_tx_buffer[4] = ((uint8_t) (ui16_temp >> 4)) & 0x30; // battery current x5 ui8_tx_buffer[5] = (uint8_t) ((float) motor_get_adc_battery_current_filtered_10b () * 0.826); // wheel speed ui8_tx_buffer[6] = (uint8_t) (ui16_wheel_speed_x10 & 0xff); ui8_tx_buffer[7] = (uint8_t) (ui16_wheel_speed_x10 >> 8); // brake state if (motor_controller_state_is_set (MOTOR_CONTROLLER_STATE_BRAKE)) { ui8_tx_buffer[8] |= 1; } else { ui8_tx_buffer[8] &= ~1; } if (configuration_variables.ui8_throttle_adc_measures_motor_temperature) { ui8_tx_buffer[9] = UI8_ADC_THROTTLE; ui8_tx_buffer[10] = configuration_variables.ui8_motor_temperature; } else { // ADC throttle ui8_tx_buffer[9] = UI8_ADC_THROTTLE; // throttle value with offset removed and mapped to 255 ui8_tx_buffer[10] = ui8_throttle; } // ADC torque_sensor ui8_tx_buffer[11] = UI8_ADC_TORQUE_SENSOR; // torque sensor value with offset removed and mapped to 255 ui8_tx_buffer[12] = ui8_torque_sensor; // PAS cadence ui8_tx_buffer[13] = ui8_pas_cadence_rpm; // pedal human power mapped to 255 ui8_tx_buffer[14] = ui8_pedal_human_power; // PWM duty_cycle ui8_tx_buffer[15] = ui8_duty_cycle; // motor speed in ERPS ui16_temp = ui16_motor_get_motor_speed_erps (); ui8_tx_buffer[16] = (uint8_t) (ui16_temp & 0xff); ui8_tx_buffer[17] = (uint8_t) (ui16_temp >> 8); // FOC angle ui8_tx_buffer[18] = ui8_foc_angle; switch (ui8_slave_comm_package_id) { case 0: // error states ui8_tx_buffer[19] = 0; break; case 1: // temperature actual limiting value ui8_tx_buffer[19] = configuration_variables.ui8_temperature_current_limiting_value; break; case 2: // wheel_speed_sensor_tick_counter ui8_tx_buffer[19] = (uint8_t) (ui32_wheel_speed_sensor_tick_counter & 0xff); break; case 3: // wheel_speed_sensor_tick_counter ui8_tx_buffer[19] = (uint8_t) ((ui32_wheel_speed_sensor_tick_counter >> 8) & 0xff); break; case 4: // wheel_speed_sensor_tick_counter ui8_tx_buffer[19] = (uint8_t) ((ui32_wheel_speed_sensor_tick_counter >> 16) & 0xff); break; default: // keep at 0 ui8_tx_buffer[19] = 0; break; } // prepare crc of the package ui16_crc_tx = 0xffff; for (ui8_i = 0; ui8_i <= 19; ui8_i++) { crc16 (ui8_tx_buffer[ui8_i], &ui16_crc_tx); } ui8_tx_buffer[20] = (uint8_t) (ui16_crc_tx & 0xff); ui8_tx_buffer[21] = (uint8_t) (ui16_crc_tx >> 8) & 0xff; // send the full package to UART for (ui8_i = 0; ui8_i <= 21; ui8_i++) { putchar (ui8_tx_buffer[ui8_i]); } } static void ebike_control_motor (void) { static uint16_t ui16_temp; uint8_t ui8_temp; uint8_t _ui8_pas_cadence_rpm; uint16_t ui16_battery_voltage_filtered; uint32_t ui32_adc_max_battery_current_boost_state_x4; uint32_t ui32_adc_max_battery_current_regular_state_x4; uint32_t ui32_adc_max_battery_current_x4; uint8_t ui8_adc_max_battery_current = 0; uint8_t ui8_startup_enable; uint16_t ui16_adc_battery_target_current_x256; uint8_t ui8_boost_enable; uint32_t ui32_temp; uint8_t ui8_tmp_max_speed; uint8_t ui8_offroad_mode_max_current; // calc battery voltage ui16_battery_voltage_filtered = (uint16_t) motor_get_adc_battery_voltage_filtered_10b () * ADC10BITS_BATTERY_VOLTAGE_PER_ADC_STEP_X512; ui16_battery_voltage_filtered = ui16_battery_voltage_filtered >> 9; // calc max battery current for boost state // calc max battery current for regular state // calc max battery current (defined by user on LCD3) ui32_adc_max_battery_current_boost_state_x4 = 0; ui32_adc_max_battery_current_regular_state_x4 = 0; if (ui16_battery_voltage_filtered > 15) { // 1.6 = 1 / 0.625 (each adc step for current) // 25 * 1.6 = 40 // 40 * 4 = 160 if (configuration_variables.ui8_startup_motor_power_boost_div25 > 0) { ui32_adc_max_battery_current_boost_state_x4 = (((uint32_t) configuration_variables.ui8_startup_motor_power_boost_div25) * 160) / ((uint32_t) ui16_battery_voltage_filtered); } if (configuration_variables.ui8_power_regular_state_div25 > 0) { ui32_adc_max_battery_current_regular_state_x4 = (((uint32_t) configuration_variables.ui8_power_regular_state_div25) * 160) / ((uint32_t) ui16_battery_voltage_filtered); } if (configuration_variables.ui8_target_battery_max_power_div25 > 0) { ui32_adc_max_battery_current_x4 = (((uint32_t) configuration_variables.ui8_target_battery_max_power_div25) * 160) / ((uint32_t) ui16_battery_voltage_filtered); ui8_adc_max_battery_current = ui32_adc_max_battery_current_x4 >> 2; } } // start with disabled ui8_startup_enable = 0; // start when we press the pedals if ((configuration_variables.ui8_power_regular_state_div25 && ui8_torque_sensor)) { ui8_startup_enable = 1; } _ui8_pas_cadence_rpm = ui8_pas_cadence_rpm; if (configuration_variables.ui8_motor_assistance_startup_without_pedal_rotation) { if (ui8_pas_cadence_rpm < 10) { _ui8_pas_cadence_rpm = 10; } } else { if (ui8_pas_cadence_rpm < 10) { _ui8_pas_cadence_rpm = 0; } } // startup boost state machine startup_boost (); if (ui8_startup_boost_enable && configuration_variables.ui8_power_regular_state_div25 && (_ui8_pas_cadence_rpm > 0)) { ui8_boost_enable = 1; } else { ui8_boost_enable = 0; } if (ui8_boost_enable) { ui32_temp = map ((uint32_t) ui8_torque_sensor, (uint32_t) 0, (uint32_t) 255, (uint32_t) 0, (uint32_t) ui32_adc_max_battery_current_boost_state_x4); ui32_temp >>= 2; if (ui32_temp > 255) { ui8_adc_battery_target_current = 255; } else { ui8_adc_battery_target_current = (uint8_t) ui32_temp; } } else { // cadence percentage (in x256) ui16_temp = (uint16_t) (map (((uint32_t) _ui8_pas_cadence_rpm), (uint32_t) 0, (uint32_t) configuration_variables.ui8_pas_max_cadence, (uint32_t) 0, (uint32_t) 255)); // human power: pedal torque * pedal cadence ui8_pedal_human_power = ((((uint16_t) ui8_torque_sensor) * ui16_temp) >> 8); ui32_temp = map ((uint32_t) ui8_pedal_human_power, (uint32_t) 0, (uint32_t) 254, // 254 because max of (255 * 255) >> 8 is 254 (uint32_t) 0, (uint32_t) ui32_adc_max_battery_current_regular_state_x4); ui32_temp >>= 2; if (ui32_temp > 255) { ui8_adc_battery_target_current = 255; } else { ui8_adc_battery_target_current = (uint8_t) ui32_temp; } } // *********************************************************************************** // make transition from boost to regular level // if (ui8_startup_boost_fade_enable) { // here we try to converge to the regular value, ramping down or up step by step ui16_adc_battery_target_current_x256 = ((uint16_t) ui8_adc_battery_target_current) << 8; if (ui16_startup_boost_fade_variable_x256 > ui16_adc_battery_target_current_x256) { ui16_startup_boost_fade_variable_x256 -= ui16_startup_boost_fade_variable_step_amount_x256; } else if (ui16_startup_boost_fade_variable_x256 < ui16_adc_battery_target_current_x256) { ui16_startup_boost_fade_variable_x256 += ui16_startup_boost_fade_variable_step_amount_x256; } ui8_adc_battery_target_current = (uint8_t) (ui16_startup_boost_fade_variable_x256 >> 8); } // *********************************************************************************** // *********************************************************************************** // throttle: if throttle has higher value, then use it! // ui8_temp = (uint8_t) (map ((uint32_t) ui8_throttle, (uint32_t) 0, (uint32_t) 255, (uint32_t) 0, (uint32_t) ui8_adc_battery_current_max)); ui8_adc_battery_target_current = ui8_max (ui8_adc_battery_target_current, ui8_temp); // flag that motor assistance should happen because we may be running with throttle if (ui8_adc_battery_target_current) { ui8_startup_enable = 1; } // *********************************************************************************** ui8_tmp_max_speed = configuration_variables.ui8_wheel_max_speed; // *********************************************************************************** // offroad mode (limit speed if offroad mode is not active) // if (configuration_variables.ui8_offroad_func_enabled && !configuration_variables.ui8_offroad_mode) { ui8_tmp_max_speed = configuration_variables.ui8_offroad_speed_limit; if (configuration_variables.ui8_offroad_power_limit_enabled && configuration_variables.ui8_offroad_power_limit_div25 > 0) { ui8_offroad_mode_max_current = (uint8_t) (((((uint32_t) configuration_variables.ui8_offroad_power_limit_div25) * 160) / ((uint32_t) ui16_battery_voltage_filtered)) >> 2); ui8_adc_battery_target_current = ui8_min (ui8_offroad_mode_max_current, ui8_adc_battery_target_current); } } // *********************************************************************************** // *********************************************************************************** // speed limit // ui8_adc_battery_target_current = (uint8_t) (map ((uint32_t) ui16_wheel_speed_x10, (uint32_t) ((ui8_tmp_max_speed * 10) - 20), (uint32_t) ((ui8_tmp_max_speed * 10) + 20), (uint32_t) ui8_adc_battery_target_current, (uint32_t) 0)); // *********************************************************************************** // *********************************************************************************** // limit the current to max value defined by user on LCD max power, if: // - user defined to make that limitation // - we are not on boost or fade state if ((configuration_variables.ui8_startup_motor_power_boost_limit_to_max_power == 1) || (!((ui8_boost_enable == 1) || (ui8_startup_boost_fade_enable == 1)))) { // now let's limit the target battery current to battery max current (use min value of both) ui8_adc_battery_target_current = ui8_min (ui8_adc_battery_target_current, ui8_adc_max_battery_current); } // *********************************************************************************** // *********************************************************************************** // reduce battery current if motor over temperature // if (configuration_variables.ui8_throttle_adc_measures_motor_temperature) { // min temperature value can't be equal or higher than max temperature value... if (configuration_variables.ui8_motor_temperature_min_value_to_limit >= configuration_variables.ui8_motor_temperature_max_value_to_limit) { ui8_adc_battery_target_current = 0; configuration_variables.ui8_temperature_current_limiting_value = 0; } else { // reduce motor current if over temperature ui8_adc_battery_target_current = (uint8_t) (map ((uint32_t) configuration_variables.ui16_motor_temperature_x2, (uint32_t) (((uint16_t) configuration_variables.ui8_motor_temperature_min_value_to_limit) << 1), (uint32_t) (((uint16_t) configuration_variables.ui8_motor_temperature_max_value_to_limit) << 1), (uint32_t) ui8_adc_battery_target_current, (uint32_t) 0)); // get a value linear to the current limitation, just to show to user configuration_variables.ui8_temperature_current_limiting_value = (uint8_t) (map ((uint32_t) configuration_variables.ui16_motor_temperature_x2, (uint32_t) (((uint16_t) configuration_variables.ui8_motor_temperature_min_value_to_limit) << 1), (uint32_t) (((uint16_t) configuration_variables.ui8_motor_temperature_max_value_to_limit) << 1), (uint32_t) 255, (uint32_t) 0)); } } else { // keep ui8_temperature_current_limiting_value = 255 because 255 means no current limiting happening configuration_variables.ui8_temperature_current_limiting_value = 255; } // *********************************************************************************** // finally set the target battery current to the current controller ebike_app_set_target_adc_battery_max_current (ui8_adc_battery_target_current); // set the target duty_cycle to max, as the battery current controller will manage it // if battery_target_current == 0, put duty_cycle at 0 // if ui8_startup_enable == 0, put duty_cycle at 0 if (ui8_adc_battery_target_current && ui8_startup_enable && (!brake_is_set())) { motor_set_pwm_duty_cycle_target (255); } else { motor_set_pwm_duty_cycle_target (0); } } // each 1 unit = 0.625 amps void ebike_app_set_target_adc_battery_max_current (uint8_t ui8_value) { // limit max number of amps if (ui8_value > ui8_adc_battery_current_max) ui8_value = ui8_adc_battery_current_max; ui8_adc_target_battery_max_current = ui8_adc_battery_current_offset + ui8_value; } // in amps void ebike_app_set_battery_max_current (uint8_t ui8_value) { // each 1 unit = 0.625 amps (0.625 * 256 = 160) ui8_adc_battery_current_max = ((((uint16_t) ui8_value) << 8) / 160); if (ui8_adc_battery_current_max > ADC_BATTERY_CURRENT_MAX) ui8_adc_battery_current_max = ADC_BATTERY_CURRENT_MAX; } // This is the interrupt that happens when UART2 receives data. We need it to be the fastest possible and so // we do: receive every byte and assembly as a package, finally, signal that we have a package to process (on main slow loop) // and disable the interrupt. The interrupt should be enable again on main loop, after the package being processed void UART2_IRQHandler(void) __interrupt(UART2_IRQHANDLER) { if (UART2_GetFlagStatus(UART2_FLAG_RXNE) == SET) { UART2->SR &= (uint8_t)~(UART2_FLAG_RXNE); // this may be redundant ui8_byte_received = UART2_ReceiveData8 (); switch (ui8_state_machine) { case 0: if (ui8_byte_received == 0x59) // see if we get start package byte { ui8_rx_buffer [ui8_rx_counter] = ui8_byte_received; ui8_rx_counter++; ui8_state_machine = 1; } else { ui8_rx_counter = 0; ui8_state_machine = 0; } break; case 1: ui8_rx_buffer [ui8_rx_counter] = ui8_byte_received; ui8_rx_counter++; // see if is the last byte of the package if (ui8_rx_counter > 12) { ui8_rx_counter = 0; ui8_state_machine = 0; ui8_received_package_flag = 1; // signal that we have a full package to be processed UART2->CR2 &= ~(1 << 5); // disable UART2 receive interrupt } break; default: break; } } } void calc_wheel_speed (void) { // calc wheel speed in km/h if (ui16_wheel_speed_sensor_pwm_cycles_ticks < WHEEL_SPEED_SENSOR_MIN_PWM_CYCLE_TICKS) { f_wheel_speed_x10 = ((float) PWM_CYCLES_SECOND) / ((float) ui16_wheel_speed_sensor_pwm_cycles_ticks); // rps f_wheel_speed_x10 *= configuration_variables.ui16_wheel_perimeter; // millimeters per second f_wheel_speed_x10 *= 0.036; // ((3600 / (1000 * 1000)) * 10) kms per hour * 10 ui16_wheel_speed_x10 = (uint16_t) f_wheel_speed_x10; } else { ui16_wheel_speed_x10 = 0; } } struct_configuration_variables* get_configuration_variables (void) { return &configuration_variables; } void calc_motor_temperature (void) { uint16_t ui16_adc_motor_temperatured_filtered_10b; // low pass filter to avoid possible fast spikes/noise ui16_adc_motor_temperatured_accumulated -= ui16_adc_motor_temperatured_accumulated >> READ_MOTOR_TEMPERATURE_FILTER_COEFFICIENT; ui16_adc_motor_temperatured_accumulated += ui16_adc_read_throttle_10b (); ui16_adc_motor_temperatured_filtered_10b = ui16_adc_motor_temperatured_accumulated >> READ_MOTOR_TEMPERATURE_FILTER_COEFFICIENT; configuration_variables.ui16_motor_temperature_x2 = (uint16_t) ((float) ui16_adc_motor_temperatured_filtered_10b / 1.024); configuration_variables.ui8_motor_temperature = (uint8_t) (configuration_variables.ui16_motor_temperature_x2 >> 1); } <file_sep>/pins.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _PINS_H_ #define _PINS_H_ #include "stm8s_gpio.h" /* Connections: * * Motor PHASE_A: blue wire * Motor PHASE_B: green wire * Motor PHASE_C: yellow wire * * The battery_current is measured using the LM385 opamp in an non inverting configuration. The pin 1 is the output and has a low pass filter. * The pin 3 (+) has the signal input and pin 2 (-) has the feedback loop, composed of R1 = 11k and R2 = 1k. * The gain is: (R1 / R2) + 1 = (11k / 1k) + 1 = 12. * We know that 1 Amp of battery current is equal to 5 ADC_12bits steps, so 1 Amp = (5V / 1024) * 5 = 0.0244V. * Each 1 Amp at the shunt is then 0.0244V / 12 = 0.002V. This also means shunt should has 0.002 ohms resistance. * Since there is a transistor that has a base resistor connected throught a 1K resisitor to the shunt voltage, and also the base has * another connected resistor of 27K, I think the transistor will switch on at arround 0.5V on the shunt voltage and that means arround 22 amps. * The microcontroller should read the turned on transistor signal on PD0, to detect the battery_over_current of 22 amps. (?????) * * PIN | IN/OUT|Function * ---------------------------------------------------------- * PD0 | in | battery_over_current (PD0 on original firmware configured as: Port D0 alternate function = TIM1_BKIN) * PB4 (ADC_AIN4) | in | torque sensor signal, this signal is amplified by the opamp * PB5 (ADC_AIN5) | in | battery_current (14 ADC bits step per 1 amp; this signal amplified by the opamp 358) * PB6 (ADC_AIN6) | in | battery_voltage (0.344V per ADC 8bits step: 17.9V --> ADC_10bits = 52; 40V --> ADC_10bits = 116; this signal atenuated by the opamp 358) * * PE5 | in | Hall_sensor_A * PD2 | in | Hall_sensor_B * PC5 | in | Hall_sensor_C * * PB2 (TIM1_CH3N) | out | PWM_phase_A_low * PB1 (TIM1_CH2N) | out | PWM_phase_B_low * PB0 (TIM1_CH1N) | out | PWM_phase_C_low * PC3 (TIM1_CH3) | out | PWM_phase_A_high * PC2 (TIM1_CH2) | out | PWM_phase_B_high * PC1 (TIM1_CH1) | out | PWM_phase_C_high * * PD5 (UART2_TX) | out | usart_tx * PD6 (UART2_RX) | in | usart_rx * * PC6 | in | brake * PB7 (ADC_AIN7) | in | throttle * PD7 | in | PAS1 (yellow wire) * PE0 | in | PAS2 (blue wire) * PA1 | in | wheel speed * * PD3 | out | torque sensor excitation * PB3 (ADC_AIN3) | in | ???? realted to torque sensor ??? * PD4 | out | lights. Enable/disable 5V output of the circuit that powers the lights wire of 6V. * * PE6 (ADC_AIN9) | in | this signal goes to a pad of a resistor that is not assembled. If was assembled, it would measure the opamp output value related to AIN4. * * PE1 tested as input on original firmware | External interrupt enabled * PE2 tested as input on original firmware * PD1 tested as input on original firmware | External interrupt enabled * * PA2 tested as input on original firmware * PA4 configured as output on original firmware, original firmware seems to only put it at 1 / enable * PA5 tested as input on original firmware * PA6 configured as output on original firmware, original firmware seems to only put it at 1 / enable * */ #define HALL_SENSOR_A__PORT GPIOE #define HALL_SENSOR_A__PIN GPIO_PIN_5 #define HALL_SENSOR_B__PORT GPIOD #define HALL_SENSOR_B__PIN GPIO_PIN_2 #define HALL_SENSOR_C__PORT GPIOC #define HALL_SENSOR_C__PIN GPIO_PIN_5 #define PMW_PHASE_A_LOW__PORT GPIOB #define PMW_PHASE_A_LOW__PIN GPIO_PIN_2 #define PMW_PHASE_B_LOW__PORT GPIOB #define PMW_PHASE_B_LOW__PIN GPIO_PIN_1 #define PMW_PHASE_C_LOW__PORT GPIOB #define PMW_PHASE_C_LOW__PIN GPIO_PIN_0 #define PMW_PHASE_A_HIGH__PORT GPIOC #define PMW_PHASE_A_HIGH__PIN GPIO_PIN_3 #define PMW_PHASE_B_HIGH__PORT GPIOC #define PMW_PHASE_B_HIGH__PIN GPIO_PIN_2 #define PMW_PHASE_C_HIGH__PORT GPIOC #define PMW_PHASE_C_HIGH__PIN GPIO_PIN_1 #define UART2_TX__PORT GPIOD #define UART2_TX__PIN GPIO_PIN_5 #define UART2_RX__PORT GPIOD #define UART2_RX__PIN GPIO_PIN_6 #define BRAKE__PORT GPIOC #define BRAKE__PIN GPIO_PIN_6 #define PAS1__PORT GPIOE #define PAS1__PIN GPIO_PIN_0 #define PAS2__PORT GPIOD #define PAS2__PIN GPIO_PIN_7 #define WHEEL_SPEED_SENSOR__PORT GPIOA #define WHEEL_SPEED_SENSOR__PIN GPIO_PIN_1 #define TORQUE_SENSOR_EXCITATION__PORT GPIOD #define TORQUE_SENSOR_EXCITATION__PIN GPIO_PIN_3 #define TORQUE_SENSOR__PORT GPIOB #define TORQUE_SENSOR__PIN GPIO_PIN_3 #define LIGHTS__PORT GPIOD #define LIGHTS__PIN GPIO_PIN_4 #define THROTTLE__PORT GPIOB #define THROTTLE__PIN GPIO_PIN_7 #define BATTERY_CURRENT__PORT GPIOB #define BATTERY_CURRENT__PIN GPIO_PIN_5 #endif /* _PINS_H_ */ <file_sep>/main.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include <stdio.h> #include "interrupts.h" #include "stm8s.h" #include "pins.h" #include "uart.h" #include "pwm.h" #include "motor.h" #include "wheel_speed_sensor.h" #include "brake.h" #include "pas.h" #include "adc.h" #include "timers.h" #include "ebike_app.h" #include "torque_sensor.h" #include "eeprom.h" #include "lights.h" ///////////////////////////////////////////////////////////////////////////////////////////// //// Functions prototypes // main -- start of firmware and main loop int main (void); // With SDCC, interrupt service routine function prototypes must be placed in the file that contains main () // in order for an vector for the interrupt to be placed in the the interrupt vector space. It's acceptable // to place the function prototype in a header file as long as the header file is included in the file that // contains main (). SDCC will not generate any warnings or errors if this is not done, but the vector will // not be in place so the ISR will not be executed when the interrupt occurs. // Calling a function from interrupt not always works, SDCC manual says to avoid it. Maybe the best is to put // all the code inside the interrupt // Local VS global variables // Sometimes I got the following error when compiling the firmware: motor.asm:750: Error: <r> relocation error // when I have this code inside a function: "static uint8_t ui8_cruise_counter = 0;" // and the solution was define the variable as global instead // Another error example: // *** buffer overflow detected ***: sdcc terminated // Caught signal 6: SIGABRT // PWM cycle interrupt void TIM1_CAP_COM_IRQHandler(void) __interrupt(TIM1_CAP_COM_IRQHANDLER); void EXTI_PORTC_IRQHandler(void) __interrupt(EXTI_PORTC_IRQHANDLER); void UART2_IRQHandler(void) __interrupt(UART2_IRQHANDLER); ///////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// int main (void) { uint16_t ui16_TIM3_counter = 0; uint16_t ui16_ebike_app_controller_counter = 0; uint16_t ui16_motor_controller_counter = 0; uint16_t ui16_debug_uart_counter = 0; uint16_t ui16_temp = 0, ui16_throttle_value_filtered = 0; //set clock at the max 16MHz CLK_HSIPrescalerConfig (CLK_PRESCALER_HSIDIV1); brake_init (); while (brake_is_set()) ; // hold here while brake is pressed -- this is a protection for development eeprom_init (); lights_init (); uart2_init (); timer2_init (); timer3_init (); adc_init (); torque_sensor_init (); pas_init (); wheel_speed_sensor_init (); hall_sensor_init (); pwm_init_bipolar_4q (); motor_init (); ebike_app_init (); enableInterrupts (); while (1) { // because of continue; at the end of each if code block that will stop the while (1) loop there, // the first if block code will have the higher priority over any others ui16_TIM3_counter = TIM3_GetCounter (); if ((ui16_TIM3_counter - ui16_motor_controller_counter) > 4) // every 4ms { ui16_motor_controller_counter = ui16_TIM3_counter; motor_controller (); continue; } ui16_TIM3_counter = TIM3_GetCounter (); if ((ui16_TIM3_counter - ui16_ebike_app_controller_counter) > 100) // every 100ms { ui16_ebike_app_controller_counter = ui16_TIM3_counter; ebike_app_controller (); continue; } #ifdef DEBUG_UART ui16_TIM3_counter = TIM3_GetCounter (); if ((ui16_TIM3_counter - ui16_debug_uart_counter) > 50) { ui16_debug_uart_counter = ui16_TIM3_counter; // sugestion: no more than 6 variables printed (takes about 3ms to printf 6 variables) printf ("%d,%d,%d,%d\n", ui16_motor_get_motor_speed_erps(), ui8_duty_cycle, ui8_adc_battery_current, ui8_foc_angle ); } #endif } return 0; } <file_sep>/pas.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include "stm8s.h" #include "pins.h" void pas_init (void) { //PAS1 pin as external input pin GPIO_Init(PAS1__PORT, PAS1__PIN, GPIO_MODE_IN_PU_NO_IT); // input pull-up, no external interrupt //PAS2 pin as external input pin interrupt GPIO_Init(PAS2__PORT, PAS2__PIN, GPIO_MODE_IN_PU_NO_IT); // input pull-up, no external interrupt } <file_sep>/utils.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include <stdio.h> #include "stm8s.h" #include "utils.h" int32_t map (int32_t x, int32_t in_min, int32_t in_max, int32_t out_min, int32_t out_max) { // if input is smaller/bigger than expected return the min/max out ranges value if (x < in_min) return out_min; else if (x > in_max) return out_max; // map the input to the output range. // round up if mapping bigger ranges to smaller ranges else if ((in_max - in_min) > (out_max - out_min)) return (x - in_min) * (out_max - out_min + 1) / (in_max - in_min + 1) + out_min; // round down if mapping smaller ranges to bigger ranges else return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } int32_t map_inverse (int32_t x, int32_t in_min, int32_t in_max, int32_t out_min, int32_t out_max) { // if input is smaller/bigger than expected return the min/max out ranges value if (x < in_min) return out_min; else if (x > in_max) return out_max; return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } uint8_t ui8_min (uint8_t value_a, uint8_t value_b) { if (value_a < value_b) return value_a; else return value_b; } uint8_t ui8_max (uint8_t value_a, uint8_t value_b) { if (value_a > value_b) return value_a; else return value_b; } void pi_controller (struct_pi_controller_state *pi_controller) { int16_t i16_error; int16_t i16_p_term; int16_t i16_temp; i16_error = pi_controller->ui8_target_value - pi_controller->ui8_current_value; // 255-0 or 0-255 --> [-255 ; 255] i16_p_term = (i16_error * pi_controller->ui8_kp_dividend) >> pi_controller->ui8_kp_divisor; pi_controller->i16_i_term += (i16_error * pi_controller->ui8_ki_dividend) >> pi_controller->ui8_ki_divisor; if (pi_controller->i16_i_term > 255) { pi_controller->i16_i_term = 255; } if (pi_controller->i16_i_term < 0) { pi_controller->i16_i_term = 0; } i16_temp = i16_p_term + pi_controller->i16_i_term; // limit to [0 ; 255] as duty_cycle that will be controlled can't have other values than that ones if (i16_temp > 255) { i16_temp = 255; } if (i16_temp < 0) { i16_temp = 0; } pi_controller->ui8_controller_output_value = (uint8_t) i16_temp; } void pi_controller_reset (struct_pi_controller_state *pi_controller) { pi_controller->i16_i_term = 0; } // from here: https://github.com/FxDev/PetitModbus/blob/master/PetitModbus.c /* * Function Name : CRC16 * @param[in] : ui8_data - Data to Calculate CRC * @param[in/out] : ui16_crc - Anlik CRC degeri * @How to use : First initial data has to be 0xFFFF. */ void crc16(uint8_t ui8_data, uint16_t* ui16_crc) { unsigned int i; *ui16_crc = *ui16_crc ^(uint16_t) ui8_data; for (i = 8; i > 0; i--) { if (*ui16_crc & 0x0001) *ui16_crc = (*ui16_crc >> 1) ^ 0xA001; else *ui16_crc >>= 1; } } <file_sep>/eeprom.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _EEPROM_H_ #define _EEPROM_H_ #include "main.h" #define KEY 0xcc #define EEPROM_BASE_ADDRESS 0x4000 #define ADDRESS_KEY EEPROM_BASE_ADDRESS #define ADDRESS_ASSIST_LEVEL_FACTOR_X10 1 + EEPROM_BASE_ADDRESS #define ADDRESS_CONFIG_0 2 + EEPROM_BASE_ADDRESS #define ADDRESS_BATTERY_MAX_CURRENT 3 + EEPROM_BASE_ADDRESS #define ADDRESS_MOTOR_POWER_X10 4 + EEPROM_BASE_ADDRESS #define ADDRESS_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_0 5 + EEPROM_BASE_ADDRESS #define ADDRESS_BATTERY_LOW_VOLTAGE_CUT_OFF_X10_1 6 + EEPROM_BASE_ADDRESS #define ADDRESS_WHEEL_PERIMETER_0 7 + EEPROM_BASE_ADDRESS #define ADDRESS_WHEEL_PERIMETER_1 8 + EEPROM_BASE_ADDRESS #define ADDRESS_WHEEL_MAX_SPEED 9 + EEPROM_BASE_ADDRESS #define ADDRESS_PAS_MAX_CADENCE 10 + EEPROM_BASE_ADDRESS #define ADDRESS_CONFIG_1 11 + EEPROM_BASE_ADDRESS #define ADDRESS_OFFROAD_CONFIG 12 + EEPROM_BASE_ADDRESS #define ADDRESS_OFFROAD_SPEED_LIMIT 13 + EEPROM_BASE_ADDRESS #define ADDRESS_OFFROAD_POWER_LIMIT_DIV25 14 + EEPROM_BASE_ADDRESS #define EEPROM_BYTES_STORED 15 void eeprom_init (void); void eeprom_init_variables (void); void eeprom_write_if_values_changed (void); #endif /* _EEPROM_H_ */ <file_sep>/pas.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _PAS_H_ #define _PAS_H_ #include "main.h" void pas_init (void); void pas2_init (void); #endif /* _PAS_H_ */ <file_sep>/adc.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _ADC_H #define _ADC_H #include "main.h" // for AIN6: 0x53E0 + 2*6 = 0x53E8 #define UI8_ADC_BATTERY_VOLTAGE (*(uint8_t*)(0x53EC)) // AIN6 #define UI8_ADC_BATTERY_CURRENT (*(uint8_t*)(0x53EA)) // AIN5 #define UI8_ADC_THROTTLE (*(uint8_t*)(0x53EE)) // AIN7 #define UI8_ADC_TORQUE_SENSOR (*(uint8_t*)(0x53E8)) // AIN4 void adc_init (void); uint16_t ui16_adc_read_battery_current_10b (void); uint16_t ui16_adc_read_battery_voltage_10b (void); uint16_t ui16_adc_read_torque_sensor_10b (void); uint16_t ui16_adc_read_throttle_10b (void); #endif /* _ADC_H */ <file_sep>/watchdog.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include "stm8s.h" #include "stm8s_clk.h" #include "stm8s_iwdg.h" // PLEASE NOTE: while debuging using STLinkV2, watchdog seems to be disable and to test, you will need to run without the debugger void watchdog_init (void) { IWDG_Enable (); IWDG_WriteAccessCmd (IWDG_WriteAccess_Enable); IWDG_SetPrescaler (IWDG_Prescaler_4); // Timeout period // The timeout period can be configured through the IWDG_PR and IWDG_RLR registers. It // is determined by the following equation: // T = 2 * T LSI * P * R // where: // T = Timeout period // T LSI = 1/f LSI // P = 2 (PR[2:0] + 2) // R = RLR[7:0]+1 // // 0.0159 = 2 * (1 / 128000) * 4 * 255 // R = 255 IWDG_SetReload (255); // ~16ms IWDG_ReloadCounter (); } <file_sep>/ebike_app.h /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #ifndef _EBIKE_APP_H_ #define _EBIKE_APP_H_ #include <stdint.h> #include "main.h" #define EBIKE_APP_STATE_MOTOR_COAST 0 #define EBIKE_APP_STATE_MOTOR_STOP 1 #define EBIKE_APP_STATE_MOTOR_STARTUP 2 #define EBIKE_APP_STATE_MOTOR_COOL 3 #define EBIKE_APP_STATE_MOTOR_RUNNING 4 typedef struct _configuration_variables { uint8_t ui8_power_regular_state_div25; uint8_t ui8_battery_max_current; uint8_t ui8_motor_power_x10; uint16_t ui16_battery_low_voltage_cut_off_x10; uint16_t ui16_wheel_perimeter; uint8_t ui8_lights; uint8_t ui8_walk_assist; uint8_t ui8_offroad_mode; uint8_t ui8_wheel_max_speed; uint8_t ui8_pas_max_cadence; uint8_t ui8_motor_voltage_type; uint8_t ui8_motor_assistance_startup_without_pedal_rotation; uint8_t ui8_target_battery_max_power_div25; uint8_t ui8_cruise_control; uint8_t configuration_variables; uint8_t ui8_startup_motor_power_boost_div25; uint8_t ui8_startup_motor_power_boost_state; uint8_t ui8_startup_motor_power_boost_limit_to_max_power; uint8_t ui8_startup_motor_power_boost_time; uint8_t ui8_startup_motor_power_boost_fade_time; uint8_t ui8_throttle_adc_measures_motor_temperature; uint8_t ui8_motor_temperature_min_value_to_limit; uint8_t ui8_motor_temperature_max_value_to_limit; uint8_t ui8_temperature_current_limiting_value; uint16_t ui16_motor_temperature_x2; uint8_t ui8_motor_temperature; uint8_t ui8_offroad_func_enabled; uint8_t ui8_offroad_enabled_on_startup; uint8_t ui8_offroad_speed_limit; uint8_t ui8_offroad_power_limit_enabled; uint8_t ui8_offroad_power_limit_div25; } struct_configuration_variables; extern volatile uint8_t ui8_adc_torque_sensor_min_value; extern volatile uint8_t ui8_adc_torque_sensor_max_value; extern volatile uint8_t ui8_adc_battery_current_offset; extern volatile uint8_t ui8_ebike_app_state; extern volatile uint8_t ui8_adc_target_battery_max_current; extern volatile uint16_t ui16_pas_pwm_cycles_ticks; extern volatile uint8_t ui8_pas_direction; extern uint8_t ui8_pas_cadence_rpm; extern volatile uint16_t ui16_wheel_speed_sensor_pwm_cycles_ticks; extern volatile uint8_t ui8_wheel_speed_sensor_is_disconnected; extern volatile uint32_t ui32_wheel_speed_sensor_tick_counter; void ebike_app_init (void); void ebike_app_controller (void); void read_pas_cadence (void); struct_configuration_variables* get_configuration_variables (void); #endif /* _EBIKE_APP_H_ */ <file_sep>/adc.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include <stdio.h> #include "stm8s.h" #include "pins.h" #include "stm8s_adc1.h" #include "adc.h" #include "ebike_app.h" #include "motor.h" static void adc_trigger (void); void adc_init (void) { uint16_t ui16_counter; uint16_t ui16_adc_battery_current_offset; uint16_t ui16_adc_torque_sensor_offset; uint8_t ui8_i; //init GPIO for the used ADC pins GPIO_Init(GPIOB, (GPIO_PIN_7 | GPIO_PIN_6 | GPIO_PIN_5 | GPIO_PIN_3), GPIO_MODE_IN_FL_NO_IT); //init ADC1 peripheral ADC1_Init(ADC1_CONVERSIONMODE_SINGLE, ADC1_CHANNEL_7, ADC1_PRESSEL_FCPU_D2, ADC1_EXTTRIG_TIM, DISABLE, ADC1_ALIGN_LEFT, (ADC1_SCHMITTTRIG_CHANNEL3 | ADC1_SCHMITTTRIG_CHANNEL5 | ADC1_SCHMITTTRIG_CHANNEL6 | ADC1_SCHMITTTRIG_CHANNEL7), DISABLE); ADC1_ScanModeCmd (ENABLE); ADC1_Cmd (ENABLE); //******************************************************************************** // next code is for "calibrating" the offset value of some ADC channels // read and discard few samples of ADC, to make sure the next samples are ok for (ui8_i = 0; ui8_i <= 64; ui8_i++) { ui16_counter = TIM3_GetCounter () + 10; // delay ~10ms while (TIM3_GetCounter () < ui16_counter) ; // delay ~10ms adc_trigger (); while (!ADC1_GetFlagStatus (ADC1_FLAG_EOC)) ; // wait for end of conversion } // read and average a few values of ADC battery current ui16_adc_battery_current_offset = 0; for (ui8_i = 0; ui8_i <= 16; ui8_i++) { ui16_counter = TIM3_GetCounter () + 10; // delay ~10ms while (TIM3_GetCounter () < ui16_counter) ; // delay ~10ms adc_trigger (); while (!ADC1_GetFlagStatus (ADC1_FLAG_EOC)) ; // wait for end of conversion ui16_adc_battery_current_offset += UI8_ADC_BATTERY_CURRENT; } ui16_adc_battery_current_offset >>= 4; ui8_adc_battery_current_offset = ui16_adc_battery_current_offset >> 2; ui8_adc_motor_phase_current_offset = ui8_adc_battery_current_offset; // read and average a few values of ADC torque sensor ui16_adc_torque_sensor_offset = 0; for (ui8_i = 0; ui8_i <= 16; ui8_i++) { ui16_counter = TIM3_GetCounter () + 10; // delay ~10ms while (TIM3_GetCounter () < ui16_counter) ; // delay ~10ms adc_trigger (); while (!ADC1_GetFlagStatus (ADC1_FLAG_EOC)) ; // wait for end of conversion ui16_adc_torque_sensor_offset += UI8_ADC_TORQUE_SENSOR; } ui16_adc_torque_sensor_offset >>= 4; ui8_adc_torque_sensor_min_value = ((uint8_t) ui16_adc_torque_sensor_offset) + ADC_TORQUE_SENSOR_THRESHOLD; ui8_adc_torque_sensor_max_value = ui8_adc_torque_sensor_min_value + 32; } static void adc_trigger (void) { // trigger ADC conversion of all channels (scan conversion, buffered) ADC1->CSR &= 0x07; // clear EOC flag first (selected also channel 7) ADC1->CR1 |= ADC1_CR1_ADON; // Start ADC1 conversion } uint16_t ui16_adc_read_battery_current_10b (void) { uint16_t temph; uint8_t templ; templ = *(uint8_t*)(0x53EB); temph = *(uint8_t*)(0x53EA); return ((uint16_t) temph) << 2 | ((uint16_t) templ); } uint16_t ui16_adc_read_torque_sensor_10b (void) { uint16_t temph; uint8_t templ; templ = *(uint8_t*)(0x53E9); temph = *(uint8_t*)(0x53E8); return ((uint16_t) temph) << 2 | ((uint16_t) templ); } uint16_t ui16_adc_read_throttle_10b (void) { uint16_t temph; uint8_t templ; templ = *(uint8_t*)(0x53EF); temph = *(uint8_t*)(0x53EE); return ((uint16_t) temph) << 2 | ((uint16_t) templ); } uint16_t ui16_adc_read_battery_voltage_10b (void) { uint16_t temph; uint8_t templ; templ = *(uint8_t*)(0x53ED); temph = *(uint8_t*)(0x53EC); return ((uint16_t) temph) << 2 | ((uint16_t) templ); } <file_sep>/motor.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include <stdio.h> #include "motor.h" #include "interrupts.h" #include "stm8s_gpio.h" #include "stm8s_tim1.h" #include "motor.h" #include "ebike_app.h" #include "pins.h" #include "pwm.h" #include "config.h" #include "adc.h" #include "utils.h" #include "uart.h" #include "adc.h" #include "watchdog.h" #include "math.h" #define SVM_TABLE_LEN 256 #define SIN_TABLE_LEN 60 uint8_t ui8_svm_table [SVM_TABLE_LEN] = { 239 , 241 , 242 , 243 , 245 , 246 , 247 , 248 , 249 , 250 , 251 , 251 , 252 , 253 , 253 , 254 , 254 , 254 , 255 , 255 , 255 , 255 , 255 , 255 , 254 , 254 , 254 , 253 , 253 , 252 , 251 , 250 , 250 , 249 , 248 , 247 , 245 , 244 , 243 , 242 , 240 , 239 , 236 , 231 , 227 , 222 , 217 , 212 , 207 , 202 , 197 , 191 , 186 , 181 , 176 , 170 , 165 , 160 , 154 , 149 , 144 , 138 , 133 , 127 , 122 , 116 , 111 , 106 , 100 , 95 , 89 , 84 , 79 , 74 , 68 , 63 , 58 , 53 , 48 , 43 , 38 , 33 , 28 , 23 , 18 , 16 , 14 , 13 , 12 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 3 , 2 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 6 , 8 , 9 , 10 , 11 , 12 , 14 , 15 , 17 , 15 , 14 , 12 , 11 , 10 , 9 , 8 , 6 , 6 , 5 , 4 , 3 , 2 , 2 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 2 , 3 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 12 , 13 , 14 , 16 , 18 , 23 , 28 , 33 , 38 , 43 , 48 , 53 , 58 , 63 , 68 , 74 , 79 , 84 , 89 , 95 , 100 , 106 , 111 , 116 , 122 , 127 , 133 , 138 , 144 , 149 , 154 , 160 , 165 , 170 , 176 , 181 , 186 , 191 , 197 , 202 , 207 , 212 , 217 , 222 , 227 , 231 , 236 , 239 , 240 , 242 , 243 , 244 , 245 , 247 , 248 , 249 , 250 , 250 , 251 , 252 , 253 , 253 , 254 , 254 , 254 , 255 , 255 , 255 , 255 , 255 , 255 , 254 , 254 , 254 , 253 , 253 , 252 , 251 , 251 , 250 , 249 , 248 , 247 , 246 , 245 , 243 , 242 , 241 , 239 , 238 , }; uint8_t ui8_sin_table [SVM_TABLE_LEN] = { 0 , 3 , 6 , 9 , 12 , 16 , 19 , 22 , 25 , 28 , 31 , 34 , 37 , 40 , 43 , 46 , 49 , 52 , 54 , 57 , 60 , 63 , 66 , 68 , 71 , 73 , 76 , 78 , 81 , 83 , 86 , 88 , 90 , 92 , 95 , 97 , 99 , 101 , 102 , 104 , 106 , 108 , 109 , 111 , 113 , 114 , 115 , 117 , 118 , 119 , 120 , 121 , 122 , 123 , 124 , 125 , 125 , 126 , 126 , 127 }; uint16_t ui16_PWM_cycles_counter = 1; uint16_t ui16_PWM_cycles_counter_6 = 1; uint16_t ui16_PWM_cycles_counter_total = 0xffff; volatile uint16_t ui16_motor_speed_erps = 0; uint8_t ui8_motor_over_speed_erps_flag = 0; uint8_t ui8_svm_table_index = 0; uint8_t ui8_motor_rotor_absolute_angle; uint8_t ui8_motor_rotor_angle; volatile uint8_t ui8_foc_angle = 0; uint8_t ui8_interpolation_angle = 0; uint8_t ui8_motor_commutation_type = BLOCK_COMMUTATION; volatile uint8_t ui8_motor_controller_state = MOTOR_CONTROLLER_STATE_OK; uint8_t ui8_hall_sensors_state = 0; uint8_t ui8_hall_sensors_state_last = 0; uint8_t ui8_half_erps_flag = 0; volatile uint8_t ui8_duty_cycle = 0; volatile uint8_t ui8_duty_cycle_target; uint16_t ui16_duty_cycle_ramp_up_inverse_step; uint16_t ui16_duty_cycle_ramp_down_inverse_step; uint16_t ui16_counter_duty_cycle_ramp_up = 0; uint16_t ui16_counter_duty_cycle_ramp_down = 0; uint8_t ui8_phase_a_voltage; uint8_t ui8_phase_b_voltage; uint8_t ui8_phase_c_voltage; uint16_t ui16_value; uint8_t ui8_first_time_run_flag = 1; volatile uint8_t ui8_adc_battery_voltage_cut_off = 0xff; // safe value so controller will not discharge the battery if not receiving a lower value from the LCD uint16_t ui16_adc_battery_voltage_accumulated = 0; uint16_t ui16_adc_battery_voltage_filtered_10b; uint16_t ui16_adc_battery_current_accumulated = 0; uint8_t ui8_adc_battery_current_filtered_10b; uint16_t ui16_foc_angle_accumulated = 0; uint16_t ui16_adc_battery_current_10b; volatile uint8_t ui8_adc_battery_current; volatile uint8_t ui8_adc_motor_phase_current; uint8_t ui8_current_controller_counter = 0; uint8_t ui8_current_controller_flag = 0; volatile uint8_t ui8_adc_target_motor_phase_max_current; volatile uint8_t ui8_adc_motor_phase_current_offset; uint8_t ui8_pas_state; uint8_t ui8_pas_state_old; uint16_t ui16_pas_counter = (uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS; volatile uint16_t ui16_torque_sensor_throttle_processed_value = 0; uint8_t ui8_torque_sensor_pas_signal_change_counter = 0; uint16_t ui16_torque_sensor_throttle_max_value = 0; uint16_t ui16_torque_sensor_throttle_value; // wheel speed uint8_t ui8_wheel_speed_sensor_state = 1; uint8_t ui8_wheel_speed_sensor_state_old = 1; uint16_t ui16_wheel_speed_sensor_counter = 0; void read_battery_voltage (void); void read_battery_current (void); void calc_foc_angle (void); uint8_t asin_table (uint8_t ui8_inverted_angle_x128); void motor_set_phase_current_max (uint8_t ui8_value); void motor_controller (void) { // reads battery voltage and current read_battery_voltage (); read_battery_current (); calc_foc_angle (); } // Measures did with a 24V Q85 328 RPM motor, rotating motor backwards by hand: // Hall sensor A positivie to negative transition | BEMF phase B at max value / top of sinewave // Hall sensor B positivie to negative transition | BEMF phase A at max value / top of sinewave // Hall sensor C positive to negative transition | BEMF phase C at max value / top of sinewave // runs every 64us (PWM frequency) void TIM1_CAP_COM_IRQHandler(void) __interrupt(TIM1_CAP_COM_IRQHANDLER) { static uint8_t ui8_temp; /****************************************************************************/ // read battery current ADC value | should happen at middle of the PWM duty_cycle // disable scan mode ADC1->CR2 &= (uint8_t)(~ADC1_CR2_SCAN); // clear EOC flag first (selected also channel 5) ADC1->CSR = 0x05; // start ADC1 conversion ADC1->CR1 |= ADC1_CR1_ADON; while (!(ADC1->CSR & ADC1_FLAG_EOC)) ; ui16_adc_battery_current_10b = ui16_adc_read_battery_current_10b (); ui8_adc_battery_current = ui16_adc_battery_current_10b >> 2; // calculate motor phase current ADC value if (ui8_duty_cycle > 0) { ui8_adc_motor_phase_current = ((ui16_adc_battery_current_10b << 6) / ((uint16_t) ui8_duty_cycle)); } else { ui8_adc_motor_phase_current = 0; } /****************************************************************************/ /****************************************************************************/ // trigger ADC conversion of all channels (scan conversion, buffered) ADC1->CR2 |= ADC1_CR2_SCAN; // enable scan mode ADC1->CSR = 0x07; // clear EOC flag first (selected also channel 7) ADC1->CR1 |= ADC1_CR1_ADON; // start ADC1 conversion /****************************************************************************/ /****************************************************************************/ // read hall sensor signals and: // - find the motor rotor absolute angle // - calc motor speed in erps (ui16_motor_speed_erps) // read hall sensors signal pins and mask other pins // hall sensors sequence with motor forward rotation: 4, 6, 2, 3, 1, 5 ui8_hall_sensors_state = ((HALL_SENSOR_A__PORT->IDR & HALL_SENSOR_A__PIN) >> 5) | ((HALL_SENSOR_B__PORT->IDR & HALL_SENSOR_B__PIN) >> 1) | ((HALL_SENSOR_C__PORT->IDR & HALL_SENSOR_C__PIN) >> 3); // make sure we run next code only when there is a change on the hall sensors signal if (ui8_hall_sensors_state != ui8_hall_sensors_state_last) { ui8_hall_sensors_state_last = ui8_hall_sensors_state; switch (ui8_hall_sensors_state) { case 3: ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_150; break; case 1: if (ui8_half_erps_flag == 1) { ui8_half_erps_flag = 0; ui16_PWM_cycles_counter_total = ui16_PWM_cycles_counter; ui16_PWM_cycles_counter = 1; // this division takes 4.4us and without the cast (uint16_t) PWM_CYCLES_SECOND, would take 111us!! Verified on 2017.11.20 // avoid division by 0 if (ui16_PWM_cycles_counter_total > 0) { ui16_motor_speed_erps = ((uint16_t) PWM_CYCLES_SECOND) / ui16_PWM_cycles_counter_total; } else { ui16_motor_speed_erps = ((uint16_t) PWM_CYCLES_SECOND); } // disable flag at every ERPS when ui16_motor_speed_erps is calculated ui8_motor_over_speed_erps_flag = 0; // update motor commutation state based on motor speed if (ui16_motor_speed_erps > MOTOR_ROTOR_ERPS_START_INTERPOLATION_60_DEGREES) { if (ui8_motor_commutation_type == BLOCK_COMMUTATION) { ui8_motor_commutation_type = SINEWAVE_INTERPOLATION_60_DEGREES; ui8_ebike_app_state = EBIKE_APP_STATE_MOTOR_RUNNING; } } else { if (ui8_motor_commutation_type == SINEWAVE_INTERPOLATION_60_DEGREES) { ui8_motor_commutation_type = BLOCK_COMMUTATION; ui8_foc_angle = 0; } } } ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_210; break; case 5: ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_270; break; case 4: ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_330; break; case 6: ui8_half_erps_flag = 1; ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_30; break; // BEMF is always 90 degrees advanced over motor rotor position degree zero // and here (hall sensor C blue wire, signal transition from positive to negative), // phase B BEMF is at max value (measured on osciloscope by rotating the motor) case 2: ui8_motor_rotor_absolute_angle = (uint8_t) MOTOR_ROTOR_ANGLE_90; break; default: return; break; } ui16_PWM_cycles_counter_6 = 1; } /****************************************************************************/ /****************************************************************************/ // count number of fast loops / PWM cycles and reset some states when motor is near zero speed if (ui16_PWM_cycles_counter < ((uint16_t) PWM_CYCLES_COUNTER_MAX)) { ui16_PWM_cycles_counter++; ui16_PWM_cycles_counter_6++; } else // happens when motor is stopped or near zero speed { ui16_PWM_cycles_counter = 1; // don't put to 0 to avoid 0 divisions ui16_PWM_cycles_counter_6 = 1; ui8_half_erps_flag = 0; ui16_motor_speed_erps = 0; ui16_PWM_cycles_counter_total = 0xffff; ui8_foc_angle = 0; ui8_motor_commutation_type = BLOCK_COMMUTATION; ui8_hall_sensors_state_last = 0; // this way we force execution of hall sensors code next time // ebike_app_cruise_control_stop (); // if (ui8_ebike_app_state == EBIKE_APP_STATE_MOTOR_RUNNING) { ui8_ebike_app_state = EBIKE_APP_STATE_MOTOR_STOP; } } /****************************************************************************/ /****************************************************************************/ // - calc interpolation angle and sinewave table index #define DO_INTERPOLATION 1 // may be usefull to disable interpolation when debugging #if DO_INTERPOLATION == 1 // calculate the interpolation angle (and it doesn't work when motor starts and at very low speeds) if (ui8_motor_commutation_type == SINEWAVE_INTERPOLATION_60_DEGREES) { // division by 0: ui16_PWM_cycles_counter_total should never be 0 // TODO: verifiy if (ui16_PWM_cycles_counter_6 << 8) do not overflow ui8_interpolation_angle = (ui16_PWM_cycles_counter_6 << 8) / ui16_PWM_cycles_counter_total; // this operations take 4.4us ui8_motor_rotor_angle = ui8_motor_rotor_absolute_angle + ui8_interpolation_angle; ui8_svm_table_index = ui8_motor_rotor_angle + ui8_foc_angle; } else #endif { ui8_svm_table_index = ui8_motor_rotor_absolute_angle + ui8_foc_angle; } // we need to put phase voltage 90 degrees ahead of rotor position, to get current 90 degrees ahead and have max torque per amp ui8_svm_table_index -= 63; /****************************************************************************/ /****************************************************************************/ // PWM duty_cycle controller: // - limit battery undervoltage // - limit battery max current // - limit motor max phase current // - limit motor max ERPS // - ramp up/down PWM duty_cycle value // control current only at every some PWM cycles, otherwise will be to fast, maybe because of low pass filter on hardware about reading the current ui8_current_controller_counter++; if (ui8_current_controller_counter > 12) { ui8_current_controller_counter = 0; if ((ui8_adc_battery_current > ui8_adc_target_battery_max_current) || // battery max current, reduce duty_cycle (ui8_adc_motor_phase_current > ui8_adc_target_motor_phase_max_current)) // motor max phase current, reduce duty_cycle { ui8_current_controller_flag = 1; if (ui8_duty_cycle > 0) { ui8_duty_cycle--; } } } if (ui8_current_controller_flag) // when we control the current, don't execute next ifs otherwise ui8_duty_cycle would be decremented more than one time on each PWM cycle { ui8_current_controller_flag = 0; } else if (UI8_ADC_BATTERY_VOLTAGE < ui8_adc_battery_voltage_cut_off) // battery voltage under min voltage, reduce duty_cycle { if (ui8_duty_cycle > 0) { ui8_duty_cycle--; } } else if ((ui16_motor_speed_erps > MOTOR_OVER_SPEED_ERPS) && // motor speed over max ERPS, reduce duty_cycle (ui8_motor_over_speed_erps_flag == 0)) { ui8_motor_over_speed_erps_flag = 1; if (ui8_duty_cycle > 0) { ui8_duty_cycle--; } } else // nothing to limit, so, adjust duty_cycle to duty_cycle_target, including ramping { if (ui8_duty_cycle_target > ui8_duty_cycle) { if (ui16_counter_duty_cycle_ramp_up++ >= ui16_duty_cycle_ramp_up_inverse_step) { ui16_counter_duty_cycle_ramp_up = 0; // don't increase duty_cycle if motor_over_speed_erps if (ui8_motor_over_speed_erps_flag == 0) { ui8_duty_cycle++; } } } else if (ui8_duty_cycle_target < ui8_duty_cycle) { if (ui16_counter_duty_cycle_ramp_down++ >= ui16_duty_cycle_ramp_down_inverse_step) { ui16_counter_duty_cycle_ramp_down = 0; ui8_duty_cycle--; } } } /****************************************************************************/ /****************************************************************************/ // calc final PWM duty_cycle values to be applied to TIMER1 // scale and apply PWM duty_cycle for the 3 phases // phase A is advanced 240 degrees over phase B ui8_temp = ui8_svm_table [(uint8_t) (ui8_svm_table_index + 171 /* 240º */)]; if (ui8_temp > MIDDLE_PWM_DUTY_CYCLE_MAX) { ui16_value = ((uint16_t) (ui8_temp - MIDDLE_PWM_DUTY_CYCLE_MAX)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_a_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX + ui8_temp; } else { ui16_value = ((uint16_t) (MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_a_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp; } // phase B as reference phase ui8_temp = ui8_svm_table [ui8_svm_table_index]; if (ui8_temp > MIDDLE_PWM_DUTY_CYCLE_MAX) { ui16_value = ((uint16_t) (ui8_temp - MIDDLE_PWM_DUTY_CYCLE_MAX)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_b_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX + ui8_temp; } else { ui16_value = ((uint16_t) (MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_b_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp; } // phase C is advanced 120 degrees over phase B ui8_temp = ui8_svm_table [(uint8_t) (ui8_svm_table_index + 85 /* 120º */)]; if (ui8_temp > MIDDLE_PWM_DUTY_CYCLE_MAX) { ui16_value = ((uint16_t) (ui8_temp - MIDDLE_PWM_DUTY_CYCLE_MAX)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_c_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX + ui8_temp; } else { ui16_value = ((uint16_t) (MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp)) * ui8_duty_cycle; ui8_temp = (uint8_t) (ui16_value >> 8); ui8_phase_c_voltage = MIDDLE_PWM_DUTY_CYCLE_MAX - ui8_temp; } // set final duty_cycle value // phase B TIM1->CCR3H = (uint8_t) (ui8_phase_b_voltage >> 7); TIM1->CCR3L = (uint8_t) (ui8_phase_b_voltage << 1); // phase C TIM1->CCR2H = (uint8_t) (ui8_phase_c_voltage >> 7); TIM1->CCR2L = (uint8_t) (ui8_phase_c_voltage << 1); // phase A TIM1->CCR1H = (uint8_t) (ui8_phase_a_voltage >> 7); TIM1->CCR1L = (uint8_t) (ui8_phase_a_voltage << 1); /****************************************************************************/ /****************************************************************************/ // calc PAS timming between each positive pulses, in PWM cycles ticks // calc PAS on and off timming of each pulse, in PWM cycles ticks ui16_pas_counter++; // detect PAS signal changes if ((PAS1__PORT->IDR & PAS1__PIN) == 0) { ui8_pas_state = 0; } else { ui8_pas_state = 1; } // PAS signal did change if (ui8_pas_state != ui8_pas_state_old) { ui8_pas_state_old = ui8_pas_state; // consider only when PAS signal transition from 0 to 1 if (ui8_pas_state == 1) { // limit PAS cadence to be less than PAS_ABSOLUTE_MAX_CADENCE_PWM_CYCLE_TICKS // also PAS cadence should be zero if rotating backwards if ((ui16_pas_counter < ((uint16_t) PAS_ABSOLUTE_MAX_CADENCE_PWM_CYCLE_TICKS)) || (ui8_pas_direction)) { ui16_pas_pwm_cycles_ticks = (uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS; } else { ui16_pas_pwm_cycles_ticks = ui16_pas_counter; } ui16_pas_counter = 0; } else { // PAS cadence should be zero if rotating backwards if ((PAS2__PORT->IDR & PAS2__PIN) != 0) { ui8_pas_direction = 1; ui16_pas_pwm_cycles_ticks = (uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS; } else { ui8_pas_direction = 0; } } // filter the torque signal, by saving the max value of each one pedal rotation ui16_torque_sensor_throttle_value = ui16_adc_read_torque_sensor_10b () - 184; if (ui16_torque_sensor_throttle_value > 800) ui16_torque_sensor_throttle_value = 0; ui8_torque_sensor_pas_signal_change_counter++; if (ui8_torque_sensor_pas_signal_change_counter > (PAS_NUMBER_MAGNETS << 1)) // PAS_NUMBER_MAGNETS*2 means a full pedal rotation { ui8_torque_sensor_pas_signal_change_counter = 1; // this is the first cycle ui16_torque_sensor_throttle_processed_value = ui16_torque_sensor_throttle_max_value; // store the max value on the output variable of this algorithm ui16_torque_sensor_throttle_max_value = 0; // reset the max value } else { // store the max value if (ui16_torque_sensor_throttle_value > ui16_torque_sensor_throttle_max_value) { ui16_torque_sensor_throttle_max_value = ui16_torque_sensor_throttle_value; } } } // limit min PAS cadence if (ui16_pas_counter > ((uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS)) { ui16_pas_pwm_cycles_ticks = (uint16_t) PAS_ABSOLUTE_MIN_CADENCE_PWM_CYCLE_TICKS; ui16_pas_counter = 0; ui8_pas_direction = 0; ui16_torque_sensor_throttle_processed_value = 0; } /****************************************************************************/ /****************************************************************************/ // calc wheel speed sensor timming between each positive pulses, in PWM cycles ticks ui16_wheel_speed_sensor_counter++; // detect wheel speed sensor signal changes if (WHEEL_SPEED_SENSOR__PORT->IDR & WHEEL_SPEED_SENSOR__PIN) { ui8_wheel_speed_sensor_state = 1; } else { ui8_wheel_speed_sensor_state = 0; } if (ui8_wheel_speed_sensor_state != ui8_wheel_speed_sensor_state_old) // wheel speed sensor signal did change { ui8_wheel_speed_sensor_state_old = ui8_wheel_speed_sensor_state; if (ui8_wheel_speed_sensor_state == 1) // consider only when wheel speed sensor signal transition from 0 to 1 { ui16_wheel_speed_sensor_pwm_cycles_ticks = ui16_wheel_speed_sensor_counter; ui16_wheel_speed_sensor_counter = 0; ui32_wheel_speed_sensor_tick_counter++; } } // limit min wheel speed if (ui16_wheel_speed_sensor_counter > ((uint16_t) WHEEL_SPEED_SENSOR_MIN_PWM_CYCLE_TICKS)) { ui16_wheel_speed_sensor_pwm_cycles_ticks = (uint16_t) WHEEL_SPEED_SENSOR_MIN_PWM_CYCLE_TICKS; ui16_wheel_speed_sensor_counter = 0; } /****************************************************************************/ // /****************************************************************************/ // // reload watchdog timer, every PWM cycle to avoid automatic reset of the microcontroller // if (ui8_first_time_run_flag) // { // from the init of watchdog up to first reset on PWM cycle interrupt, // // it can take up to 250ms and so we need to init here inside the PWM cycle // ui8_first_time_run_flag = 0; // watchdog_init (); // } // else // { // IWDG->KR = IWDG_KEY_REFRESH; // reload watch dog timer counter // } // /****************************************************************************/ /****************************************************************************/ // clears the TIM1 interrupt TIM1_IT_UPDATE pending bit TIM1->SR1 = (uint8_t)(~(uint8_t)TIM1_IT_CC4); /****************************************************************************/ } void motor_disable_PWM (void) { TIM1_CtrlPWMOutputs(DISABLE); } void motor_enable_PWM (void) { TIM1_CtrlPWMOutputs(ENABLE); } void motor_controller_set_state (uint8_t ui8_state) { ui8_motor_controller_state |= ui8_state; } void motor_controller_reset_state (uint8_t ui8_state) { ui8_motor_controller_state &= ~ui8_state; } uint8_t motor_controller_state_is_set (uint8_t ui8_state) { return ui8_motor_controller_state & ui8_state; } void hall_sensor_init (void) { GPIO_Init (HALL_SENSOR_A__PORT, (GPIO_Pin_TypeDef) HALL_SENSOR_A__PIN, GPIO_MODE_IN_FL_NO_IT); GPIO_Init (HALL_SENSOR_B__PORT, (GPIO_Pin_TypeDef) HALL_SENSOR_B__PIN, GPIO_MODE_IN_FL_NO_IT); GPIO_Init (HALL_SENSOR_C__PORT, (GPIO_Pin_TypeDef) HALL_SENSOR_C__PIN, GPIO_MODE_IN_FL_NO_IT); } void motor_init (void) { motor_set_pwm_duty_cycle_ramp_up_inverse_step (PWM_DUTY_CYCLE_RAMP_UP_INVERSE_STEP); // each step = 64us motor_set_pwm_duty_cycle_ramp_down_inverse_step (PWM_DUTY_CYCLE_RAMP_DOWN_INVERSE_STEP); // each step = 64us motor_set_phase_current_max (ADC_MOTOR_PHASE_CURRENT_MAX); } void motor_set_pwm_duty_cycle_target (uint8_t ui8_value) { if (ui8_value > PWM_DUTY_CYCLE_MAX) { ui8_value = PWM_DUTY_CYCLE_MAX; } // if brake is active, keep duty_cycle target at 0 if (ui8_motor_controller_state & MOTOR_CONTROLLER_STATE_BRAKE) { ui8_value = 0; } ui8_duty_cycle_target = ui8_value; } void motor_set_pwm_duty_cycle_ramp_up_inverse_step (uint16_t ui16_value) { ui16_duty_cycle_ramp_up_inverse_step = ui16_value; } void motor_set_pwm_duty_cycle_ramp_down_inverse_step (uint16_t ui16_value) { ui16_duty_cycle_ramp_down_inverse_step = ui16_value; } void motor_set_phase_current_max (uint8_t ui8_value) { ui8_adc_target_motor_phase_max_current = ui8_adc_motor_phase_current_offset + ui8_value; } uint16_t ui16_motor_get_motor_speed_erps (void) { return ui16_motor_speed_erps; } void read_battery_voltage (void) { // low pass filter the voltage readed value, to avoid possible fast spikes/noise ui16_adc_battery_voltage_accumulated -= ui16_adc_battery_voltage_accumulated >> READ_BATTERY_VOLTAGE_FILTER_COEFFICIENT; ui16_adc_battery_voltage_accumulated += ui16_adc_read_battery_voltage_10b (); ui16_adc_battery_voltage_filtered_10b = ui16_adc_battery_voltage_accumulated >> READ_BATTERY_VOLTAGE_FILTER_COEFFICIENT; } void read_battery_current (void) { // low pass filter the positive battery readed value (no regen current), to avoid possible fast spikes/noise ui16_adc_battery_current_accumulated -= ui16_adc_battery_current_accumulated >> READ_BATTERY_CURRENT_FILTER_COEFFICIENT; ui16_adc_battery_current_accumulated += ui16_adc_battery_current_10b; ui8_adc_battery_current_filtered_10b = ui16_adc_battery_current_accumulated >> READ_BATTERY_CURRENT_FILTER_COEFFICIENT; } void calc_foc_angle (void) { uint16_t ui16_temp; uint32_t ui32_temp; uint16_t ui16_e_phase_voltage; uint32_t ui32_i_phase_current_x2; uint32_t ui32_l_x1048576; uint32_t ui32_w_angular_velocity_x16; uint16_t ui16_iwl_128; struct_configuration_variables *p_configuration_variables; p_configuration_variables = get_configuration_variables (); // FOC implementation by calculating the angle between phase current and rotor magnetic flux (BEMF) // 1. phase voltage is calculate // 2. I*w*L is calculated, where I is the phase current. L was a measured value for 48V motor. // 3. inverse sin is calculated of (I*w*L) / phase voltage, were we obtain the angle // 4. previous calculated angle is applied to phase voltage vector angle and so the // angle between phase current and rotor magnetic flux (BEMF) is kept at 0 (max torque per amp) // calc E phase voltage ui16_temp = ui16_adc_battery_voltage_filtered_10b * ADC10BITS_BATTERY_VOLTAGE_PER_ADC_STEP_X512; ui16_temp = (ui16_temp >> 8) * ui8_duty_cycle; ui16_e_phase_voltage = ui16_temp >> 9; // calc I phase current if (ui8_duty_cycle > 10) { ui16_temp = ((uint16_t) ui8_adc_battery_current_filtered_10b) * ADC_BATTERY_CURRENT_PER_ADC_STEP_X512; ui32_i_phase_current_x2 = ui16_temp / ui8_duty_cycle; } else { ui32_i_phase_current_x2 = 0; } // calc W angular velocity: erps * 6.3 ui32_w_angular_velocity_x16 = ui16_motor_speed_erps * 101; // --------------------------------------------------------------------------------------------------------------------- // NOTE: EXPERIMENTAL and may not be good for the brushless motor inside TSDZ2 // Original message from jbalat on 28.08.2018, about increasing the limits on 36V motor -- please see that this seems to go over the recomended values // The ui32_l_x1048576 = 105 is working well so give that a try if you have a 36v motor. // This is the minimum value that gives me 550w of power when I have asked for 550w at level 5 assist, >36km/hr // // remember also to boost the max overdrive erps in main.h to get higher cadence // #define MOTOR_OVER_SPEED_ERPS 700 // motor max speed, protection max value | 30 points for the sinewave at max speed // --------------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------------- // 36V motor: L = 76uH // 48V motor: L = 135uH // ui32_l_x1048576 = 142; // 1048576 = 2^20 | 48V // ui32_l_x1048576 = 80; // 1048576 = 2^20 | 36V // --------------------------------------------------------------------------------------------------------------------- // ui32_l_x1048576 = 142 <--- THIS VALUE WAS verified experimentaly on 2018.07 to be near the best value for a 48V motor, // test done with a fixed mechanical load, duty_cycle = 200 and 100 and measured battery current was 16 and 6 (10 and 4 amps) if (p_configuration_variables->ui8_motor_voltage_type) { ui32_l_x1048576 = 80; // 36V motor } else { ui32_l_x1048576 = 142; // 48V motor } // calc IwL ui32_temp = ui32_i_phase_current_x2 * ui32_l_x1048576; ui32_temp *= ui32_w_angular_velocity_x16; ui16_iwl_128 = ui32_temp >> 18; // calc FOC angle ui8_foc_angle = asin_table (ui16_iwl_128 / ui16_e_phase_voltage); // low pass filter FOC angle ui16_foc_angle_accumulated -= ui16_foc_angle_accumulated >> 4; ui16_foc_angle_accumulated += ui8_foc_angle; ui8_foc_angle = ui16_foc_angle_accumulated >> 4; } // calc asin also converts the final result to degrees uint8_t asin_table (uint8_t ui8_inverted_angle_x128) { uint8_t ui8_index = 0; while (ui8_index < SIN_TABLE_LEN) { if (ui8_inverted_angle_x128 < ui8_sin_table [ui8_index]) { break; } ui8_index++; } // first value of table is 0 so ui8_index will always increment to at least 1 and return 0 return ui8_index--; } uint8_t motor_get_adc_battery_current_filtered_10b (void) { return ui8_adc_battery_current_filtered_10b; } uint16_t motor_get_adc_battery_voltage_filtered_10b (void) { return ui16_adc_battery_voltage_filtered_10b; } void motor_set_adc_battery_voltage_cut_off (uint8_t ui8_value) { ui8_adc_battery_voltage_cut_off = ui8_value; } <file_sep>/lights.c /* * TongSheng TSDZ2 motor controller firmware/ * * Copyright (C) Casainho, 2018. * * Released under the GPL License, Version 3 */ #include <stdint.h> #include "stm8s.h" #include "pins.h" #include "stm8s_gpio.h" void lights_init (void) { GPIO_Init(LIGHTS__PORT, LIGHTS__PIN, GPIO_MODE_OUT_PP_LOW_SLOW); } void lights_set_state (uint8_t ui8_state) { if (ui8_state) { GPIO_WriteHigh (LIGHTS__PORT, LIGHTS__PIN); } else { GPIO_WriteLow (LIGHTS__PORT, LIGHTS__PIN); } }
1d0e051d0d0857d2ef731a6dd08d76e1f06dce48
[ "C" ]
19
C
15835229565/TongSheng_TSDZ2_motor_controller_firmware
c0f16b3e4e7ca37041527140c4370335eae9c225
4a136b9a990deec40e7379ea664dc731e14604e0
refs/heads/master
<repo_name>a-vzhik/ExtractFacebookThread<file_sep>/README.md Sometimes you want to read a conversation on Facebook with a specified person, but doing this at Facebook site may be painfull. It requires scrolling up till the beginning of a conversation, then scrolling it down while reading. Happily Facebook developers provide a feature that allows to export your Facebook data into a solid archive. This archive contains a webpage named "messages.html" with all your conversations in the single file. Even more desperate fact is that messages are sorted from new to old, so you have to read a chat in the reversed direction. This script allows you to extract a conversation with a person in a separate file with messages sorted in historical order. USAGE 1. Download a facebook archive. 2. Unzip it to a folder (say TARGET_FOLDER). 3. Copy the script to the folder "TARGET_FOLDER/html". 4. Run the script and follow instuctions. You can run the ruby script as well as the exe-file available in "Releases" section. <file_sep>/extract-chat.rb require 'nokogiri' require 'date' require 'io/console' class MessageThreads attr_reader :html def initialize(path) file = File.open(path, "r"); @html = Nokogiri::HTML(file); end def find_thread_with(username) if block_given? then html.xpath("//div[@class='thread']").each do |node| thread = MessageThread.new(node) if thread.header.include? username then yield thread end end end end end class MessageThread def initialize(thread) @thread = thread end def header @thread.children[0].to_s end def messages Messages.new(@thread) end end class Messages def initialize(thread) @thread = thread end def each return if !block_given? @thread.xpath("div[@class='message']").reverse.each do |message| yield Message.new(message) end end end class Message attr_reader :metadata, :original_content def initialize(message) @metadata = message @original_content = message.next_sibling end def htmlized_content node = Nokogiri::XML::Node.new(@original_content.name, @original_content.document) node.inner_html = @original_content.inner_html.gsub(/\n/, '<br/>') node end def write_to(io) metadata.write_to io htmlized_content.write_to io end end class OutputMessageThreadFile def initialize(thread_header) @thread_header = thread_header end def build_html_skeleton builder = Nokogiri::HTML::Builder.new do |doc| doc.html { doc.head { doc.title "Messages between #{@thread_header}" doc.link({'href'=>'../html/style.css', 'rel'=>'stylesheet', 'type'=>'text/css'}) { } doc.meta({'content'=>'text/html; charset=UTF-8', 'http-equiv'=>'Content-Type'}){ } } doc.body { doc.div('class'=>'thread'){ } } } end builder.doc.encoding = 'UTF-8' builder.doc end def write output_html_doc = build_html_skeleton html = output_html_doc.to_html index = html.index "</div>"; File.open(name, 'w') do |output_file| output_file.write html.slice(0, index) yield output_file output_file.write html.slice(index..html.length) end end def name "messages-#{@thread_header}.html" end end class Application def self.run if ARGV[0] != nil then chatmate = ARGV[0] else puts "Enter a name of a friend: " chatmate = gets chatmate.chomp! end begin threads = MessageThreads.new("messages.htm") threads.find_thread_with(chatmate) do |thread| puts "\nA thread between #{thread.header} found\n" output = OutputMessageThreadFile.new(thread.header) output.write do |file| file.write thread.header processed_count = 0 thread.messages.each do |msg| msg.write_to file processed_count = processed_count + 1 puts "#{processed_count} messages exported" if processed_count % 500 == 0 end puts "#{processed_count} messages exported" end puts "\nThe thread between #{thread.header} exported successfully to the file \"#{output.name}\"" end rescue Exception => e puts "Error happened: #{e}" end puts "\nPress any key" STDIN.getch end end Application.run
6cd019d77d66876835cf487971d794947544862a
[ "Markdown", "Ruby" ]
2
Markdown
a-vzhik/ExtractFacebookThread
c246396248884aaee68c6e5af7f8c68a4dd708fb
bb37fabfce5b8920c5b7df9280520f133ad6c33a
refs/heads/main
<file_sep>- [ ] Adicionar sistema de audio - [x] Quando der play o butão player - [ ] Next - [ ] Previstes - [ ] Loping - [ ] Shuffle - [ ] Controller do Time - [ ] Auto Next - [ ] <file_sep>import { format, parseISO } from "date-fns"; import ptBR from "date-fns/locale/pt-BR"; export function formatDataPublishedAt(date: string) { return format(parseISO(date), "d MMM yy", { locale: ptBR, }); } <file_sep><h1 align="center"> <img src="./.github/logo-podcastr.svg" width="175"/> </h1> <h5 align="center"> PodCastr | O melhor para vocé ouvir sempre </h5> <h5 align="center"> Projeto web construído durante o Next Level Week #05 | Trilha ReactJS <img src="./.github/logo-react.svg" height="15" alt="logo react"> </h5> <p align="center"> <img src="https://img.shields.io/static/v1?label=Plataforma&message=PC&color=04d361&labelColor=8257e5"> <img src="https://img.shields.io/static/v1?label=License&labelColor=8257e5&message=MIT&color=04d361"> <img alt="Podcastr" src="https://img.shields.io/badge/Podcastr-NLW 5.0-04d361?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAALVBMVEVHcExxWsF0XMJzXMJxWcFsUsD///9jRrzY0u6Xh9Gsn9n39fyMecy0qd2bjNJWBT0WAAAABHRSTlMA2Do606wF2QAAAGlJREFUGJVdj1cWwCAIBLEsRU3uf9xobDH8+GZwUYi8i6ucJwrxKE+7D0G9Q4vlYqtmCSjndr4CgCgzlyFgfKfKCVO0LrPKjmiqMxGXkJwNnXskqWG+1oSM+BSwD8f29YLNjvx/OQrn+g99oQSoNmt3PgAAAABJRU5ErkJggg==&labelColor=8257e5"> <img src="https://img.shields.io/static/v1?label=Author&labelColor=8257e5&message=GustavoSantosCS&color=04d361"> <img src="https://img.shields.io/static/v1?label=Language&labelColor=8257e5&message=JavaScript&color=04d361"> </p> <p align="center"> <a href="#descricao">Descrição</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#layout">Layout</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#tecnologias">Tecnologias</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#funcionalidades">Funcionalidades</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#instalacao">Instalação</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#licenca">Licença</a> </p> <h2 id="descricao">:page_facing_up: Descrição</h2> O Podcastr é uma aplicação web para ouvir podcasts sobre programação produzidos pela RocketSeat. <h2 id="layout">:art: Layout </h2> <span align="center"> <img src="./.github/desktop/home-with-podcast.png" width="750px"/> </span> <p align="center"> Você pode acessar o Layout pelo <a href="https://www.figma.com">Figma</a> através <a href="https://www.figma.com/file/ZGsvRs0PjjI8KARiebR0Xc/Podcastr?node-id=160%3A2761">clicando aqui</a>. </p> <h2 id="tecnologias">:hammer: Tecnologias</h2> Este projeto foi desenvolvido com as seguintes tecnologias - [Next.js](https://nextjs.org/) - [React.js](https://pt-br.reactjs.org/) - [TypeScript](https://www.typescriptlang.org/) - [Sass](https://sass-lang.com/) <h2 id="funcionalidades">:clipboard: Funcionalidades </h2> - [x] Play podcast. - [x] Selecionar apenas um podcast para ouvir. - [x] Opção de ir para o próximo podcast. - [x] Opção de ir para o anterior podcast. - [x] Opção de Loop. - [x] Opção para embaralhar. <h2 id="instalacao">:closed_book: Instalação </h2> <h3>Pré-requisitos </h3> <h4>Dependências: </h4> - [Git](https://git-scm.com) - [Node.js](https://nodejs.org/pt-br/) ```bash # Clone este repositório. $ git clone <EMAIL>:GustavoSantosCS/Podcastr-frontend.git podcastr # Vá para a pasta podcastr $ cd podcastr # Instale as dependências $ npm install / yarn install # Execute aplicação $ npm run dev / yarn dev # O app vai está rodando na porta 3000 - acesse <http://localhost:3000> ``` <h2 id="licenca">:memo: Licença </h2> <p> Copyright © 2020 <a href="https://https://github.com/GustavoSantosCS"><NAME></a>. </p> <p> This project is under the <a href="./.github/LICENSE">MIT</a> license. See the archive LICENSE for more details. </p> --- <p align="center">Desenvovido por <NAME> com 💚</p> <file_sep>import { useContext } from "react"; import { PlayerContext, PlayerContextProps } from "../contents/PlayerContext"; export function usePlayer() { const context = useContext<PlayerContextProps>(PlayerContext); if (!context) { throw new Error("usePlayer must be used within a PlayerContext"); } return { ...context }; } <file_sep>export * from "./convertDurationToTimeString"; export * from "./formatDataPublishedAt";
df5678d701fe320cc312a7a52545bc8ded8f927f
[ "Markdown", "TypeScript", "Text" ]
5
Text
GustavoSantosCS/Podcastr-frontend
e4857b2f1167cab15dd3984c4061655b49d13f21
fadc6d82f064c997e756cb363c8e9e2b3f6f299c
refs/heads/master
<repo_name>BirdBeep/birbeep<file_sep>/Birbeep/src/Entidades/PeticionUPDATEMsg.java package Entidades; public class PeticionUPDATEMsg extends Peticion{ private Usuarios emisor; public PeticionUPDATEMsg(){}; public PeticionUPDATEMsg(Usuarios emisor){ super(4); this.emisor=emisor; } public Usuarios getEmisor() { return emisor; } public void setEmisor(Usuarios emisor) { this.emisor = emisor; } }<file_sep>/Birbeep/src/DAO/ConexionDAO.java package DAO; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import Entidades.Conexiones; import Entidades.Mensajes; import Entidades.Usuarios; import Util.DbQuery; public class ConexionDAO { private Connection con; public ConexionDAO(Connection con) { this.con = con; } public void altaConexion(Conexiones conexion) { DateFormat ultiCon = new SimpleDateFormat(); Calendar cal = Calendar.getInstance(); ultiCon.setCalendar(cal); //cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE); java.sql.Date now = new java.sql.Date(cal.getTimeInMillis()); PreparedStatement orden=null; try { orden =con.prepareStatement(DbQuery.insertConexion()); orden.setString(1, conexion.getIp()); orden.setString(2, conexion.getUser()); orden.setDate(3, now); orden.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally{ try { orden.close(); //datos.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } } public Conexiones obtenerUltimaCon(String id) {//Comprobar los campos PreparedStatement orden=null; ResultSet datos=null; Conexiones conexion = new Conexiones(); try { orden =con.prepareStatement(DbQuery.getLastCon()); orden.setString(1, id); datos=orden.executeQuery(); if (datos.next()){ conexion.setIdConexion(datos.getString(1)); conexion.setIp(datos.getString(2)); conexion.setUser(datos.getString(4)); conexion.setUltimaActualizacion(datos.getDate(3)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally{ try { orden.close(); datos.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return conexion; } } <file_sep>/README.md # birbeep Es un proyecto de una aplicación de mesajería instantánea con cifrado. <file_sep>/Birbeep/src/Entidades/PeticionLOGOUT.java package Entidades; public class PeticionLOGOUT extends Peticion { private Usuarios usuario; public Usuarios getUsuario() { return usuario; } public void setUsuario(Usuarios usuario) { this.usuario = usuario; } public PeticionLOGOUT(){}; public PeticionLOGOUT(Usuarios user){ super(7); this.usuario=usuario; }; } <file_sep>/Birbeep/src/Client/SSLConexion.java package Client; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import Client.Modelo.PeticionMensaje; import Client.Modelo.Usuarios; import Client.Modelo.Mensajes; import Client.Modelo.PeticionCertificado; public class SSLConexion extends Thread{ private static final int PORT = 12345; private static InetAddress server; private static SSLContext sc; private static SSLSocketFactory ssf; private static SSLSocket socket; private static Sender sender = new Sender(); private static Listener listener = new Listener(); private static Certificate cert; public void run() { TrustManager[] trustManagers = null; KeyManager[] keyManagers = null; try { server = InetAddress.getLocalHost(); try { trustManagers = getTrusts(); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { keyManagers = getKeys(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } sc = SSLContext.getInstance("TLS"); sc.init(keyManagers, trustManagers, null); ssf = sc.getSocketFactory(); socket = (SSLSocket) ssf.createSocket(server, PORT); socket.startHandshake(); sender.start(); listener.start(); } catch (NoSuchAlgorithmException e) {// Para cuando obtiene el contexto System.out.println(e.getMessage()); // } catch (KeyStoreException e) {// Para el almacen de certificados de // // confianza // System.out.println(e.getMessage()); // } catch (CertificateException e) { // System.out.println(e.getMessage()); // } catch (UnrecoverableKeyException e) {// Para obtener su propio // // certificado (Metodo // getKEys()) System.out.println(e.getMessage()); } catch (FileNotFoundException e) {// Para cuando recupera el fichero de // la ruta System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (KeyManagementException e) {// Para cuando inicializa el alamcen // y su certificado en el contexto // SSL System.out.println(e.getMessage()); } } private static TrustManager[] getTrusts() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { KeyStore trustedStore = KeyStore.getInstance("JKS"); trustedStore.load(new FileInputStream( "src/Main/certs/client1/sebasTrustedCerts.jks"), "111111" .toCharArray()); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustedStore); TrustManager[] trustManagers = tmf.getTrustManagers(); return trustManagers; } private static KeyManager[] getKeys() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load( new FileInputStream("src/Main/certs/client1/sebasKey.jks"), "123456".toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); kmf.init(keyStore, "123456".toCharArray()); KeyManager[] keyManagers = kmf.getKeyManagers(); return keyManagers; } public static InetAddress getServer() { return server; } public static void setServer(InetAddress server) { SSLConexion.server = server; } public static SSLContext getSc() { return sc; } public static void setSc(SSLContext sc) { SSLConexion.sc = sc; } public static SSLSocketFactory getSsf() { return ssf; } public static void setSsf(SSLSocketFactory ssf) { SSLConexion.ssf = ssf; } public static SSLSocket getSocket() { return socket; } public static void setSocket(SSLSocket socket) { SSLConexion.socket = socket; } public static Sender getSender() { return sender; } public static void setSender(Sender sender) { SSLConexion.sender = sender; } public static Listener getListener() { return listener; } public static void setListener(Listener listener) { SSLConexion.listener = listener; } public static int getPort() { return PORT; } public static void setCert(Certificate cert){ SSLConexion.cert=cert; } public static Certificate getCert(){ return cert; } }<file_sep>/Birbeep/src/Main/Server.java package Main; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.ServerSocket; import java.net.Socket; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.sql.SQLException; import java.util.Scanner; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import flexjson.JSONDeserializer; /** * * @author BirdBeep * * Clase principal del servidor, se mantiene a la escucha por si se envia un mensaje y debe procesarlo y enviarlo * */ public class Server { private static final int PORT = 12345; private static ServerSocket serverSocket; public static void main(String[] args){ TrustManager[] trustManagers=null; KeyManager[] keyManagers=null; try { trustManagers = getTrusts(); keyManagers = getKeys(); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(keyManagers, trustManagers, null); SSLServerSocketFactory ssf = sc.getServerSocketFactory(); serverSocket = ssf.createServerSocket(PORT); do{ Socket dialogo = (SSLSocket) serverSocket.accept();//Esperando... ClientHandler clienthandler = new ClientHandler(dialogo); clienthandler.start(); }while(true); } catch (IOException | SQLException socketEx) {//Aqui está tambien la SQL que se propaga desde los Handler System.out.println(socketEx.getMessage()); } catch (NoSuchAlgorithmException e) {//Para cuando obtiene el contexto System.out.println(e.getMessage()); } catch (KeyStoreException e) {//Para el almacen de certificados de confianza System.out.println(e.getMessage()); } catch (CertificateException e) { System.out.println(e.getMessage()); } catch (KeyManagementException e) {//Para cuando obtiene certificado propio desde el almacen de confianza System.out.println(e.getMessage()); } catch (UnrecoverableKeyException e) {//Para obtener su propio certificado (Metodo getKeys()) System.out.println(e.getMessage()); } } /** * * @return Array con los certificados de confianza, las excepciones siguientes son tratadas en el "main()" * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException */ private static TrustManager[] getTrusts() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { KeyStore trustedStore = KeyStore.getInstance("JKS"); trustedStore.load(new FileInputStream("src/Main/certs/server/serverTrustedCerts.jks"), "000000".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustedStore); TrustManager[] trustManagers = tmf.getTrustManagers(); return trustManagers; } /** * * @return Array con la clave pública, las excepciones siguientes son tratadas en el "main()" * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException */ private static KeyManager[] getKeys() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("src/Main/certs/server/serverKey.jks"),"servpass".toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, "servpass".toCharArray()); KeyManager[] keyManagers = kmf.getKeyManagers(); return keyManagers; } } <file_sep>/Birbeep/src/Entidades/Mensajes.java package Entidades; public class Mensajes { private int id; private String emisor; private String receptor; private String texto; private int conver; public Mensajes(){}; public int getConver() { return conver; } public void setConver(int conver) { this.conver = conver; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmisor() { return emisor; } public void setEmisor(String emisor) { this.emisor = emisor; } public String getReceptor() { return receptor; } public void setReceptor(String receptor) { this.receptor = receptor; } public String getTexto() { return texto; } public void setTexto(String texto) { this.texto = texto; } } <file_sep>/Birbeep/src/DAO/MensajeDAO.java package DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import Entidades.Conversaciones; import Entidades.Mensajes; import Entidades.Usuarios; import Util.DbQuery; public class MensajeDAO { private Connection con; public MensajeDAO(Connection con) { this.con = con; } public void insertarMensaje(Mensajes mensaje) { PreparedStatement orden=null; try { orden =con.prepareStatement(DbQuery.setMSG()); orden.setString(1, mensaje.getEmisor()); orden.setString(2, mensaje.getReceptor()); orden.setString(3, mensaje.getTexto()); orden.setInt(4, mensaje.getConver()); orden.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally{ try { orden.close(); //datos.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } } public List<Mensajes> recuperarMensajes(Usuarios u) { List<Mensajes> mnsgs=new ArrayList<Mensajes>(); PreparedStatement orden=null; ResultSet datos=null; try{ orden=con.prepareStatement(DbQuery.getMensajes()); orden.setString(1, u.getId()); datos=orden.executeQuery(); while (datos.next()){ Mensajes m = new Mensajes(); m.setEmisor(datos.getString(1)); m.setReceptor(datos.getString(2)); m.setTexto(datos.getString(3)); m.setConver(datos.getInt(4)); mnsgs.add(m); } }catch(SQLException e){ System.out.println(e.getMessage()); }finally{ try { orden.close(); datos.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return mnsgs; } } <file_sep>/Birbeep/src/Client/EnvCert.java package Client; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; public class EnvCert implements Serializable{ public transient Certificate certificate; private void writeObject(ObjectOutputStream out)throws IOException { out.defaultWriteObject(); try { out.writeObject(certificate.getEncoded()); } catch (CertificateEncodingException cee) { throw new IOException("Can't serialize object " + cee); } } private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException { in.defaultReadObject(); try { byte b[] = (byte []) in.readObject(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = cf.generateCertificate(new ByteArrayInputStream(b)); } catch (CertificateException ce) { throw new IOException("Can't de-serialize object " + ce); } } } <file_sep>/Birbeep/src/Entidades/PeticionLogin.java package Entidades; public class PeticionLogin extends Peticion{ private Usuarios usuario; public PeticionLogin(){ super(); }; public PeticionLogin(Usuarios usuario) { super(1); this.usuario=usuario; } public Usuarios getUsuario() { return usuario; } public void setUsuario(Usuarios usuario) { this.usuario = usuario; } }
416fb48d1db9074633305f7d41563fec36529040
[ "Markdown", "Java" ]
10
Java
BirdBeep/birbeep
eb5e846bbcd18dd7a99622575af4028713f2aac3
c0e7d7bf83d701a37b11cd8cc987bc187417d385
refs/heads/master
<repo_name>jhnferraris/f-sa<file_sep>/app.js const { performance } = require('perf_hooks'); const arguments = process.argv; if (arguments[2] !== '--problem') { console.log('Missing argument: problem'); process.exit(1); } const problem = arguments[3]; if (problem !== 'spring') { console.log('It only supports spring function for now'); process.exit(1); } const config = require('./config'); const functions = require('./functions'); const simulatedAnnealing = require('./simulated-annealing'); const fireflies = []; const { population } = config.fsaConfig; const designFunction = config.functions[problem]; const { initialAlpha, finalAlpha } = config.globalSearchConfig; let alpha = initialAlpha; const initializePopulation = () => { while (fireflies.length != population) { fireflies.push(functions[problem].generator()); } }; const updateLightIntensity = (index, leastFirefly) => { for (let k = 0; k < designFunction.dimension - 1; k++) { fireflies[index][k] = leastFirefly[k]; } fireflies[index][designFunction.config.dimension] = functions[designFunction.fn]['function'](...fireflies[index]); }; const cartesianDistance = (leastFirefly, betterFirefly) => { let distance = 0.0; for (let k = 0; k < designFunction.dimension; k++) { distance += Math.pow(leastFirefly[k] - betterFirefly[k], 2); } return Math.sqrt(distance); }; const moveFirefly = (leastFirefly, betterFirefly) => { let newLeastFirefly = new Array(designFunction.dimension); const distance = cartesianDistance(leastFirefly, betterFirefly); const { initialAttractiveness, absorptionCoefficient } = config.globalSearchConfig; for (let k = 0; k < designFunction.dimension; k++) { const secondTerm = initialAttractiveness * Math.exp(-1 * absorptionCoefficient * Math.pow(distance, 2.0)) * (betterFirefly[k] - leastFirefly[k]); const thirdTerm = alpha * (Math.random() - 0.5); newLeastFirefly = leastFirefly[k] + secondTerm + thirdTerm; } newLeastFirefly = functions[problem].checkLimits(newLeastFirefly); return newLeastFirefly; }; const main = () => { console.log('Running F-SA'); initializePopulation(); let bestFirefly = fireflies[0]; let candidateFirefly = null; const { globalGeneration } = config.fsaConfig; const startTime = performance.now(); for (let generationIndex = 1; generationIndex <= globalGeneration; generationIndex++) { for (let i = 0; i < population; i++) { for (let j = 0; j < i; j++) { const lightIntensityJ = fireflies[j][designFunction.config.dimension]; const lightIntensityI = fireflies[i][designFunction.config.dimension]; if (lightIntensityJ < lightIntensityI) { candidateFirefly = fireflies[j]; updateLightIntensity(i, moveFirefly(fireflies[i], fireflies[j])); const localFirefly = simulatedAnnealing.executeLocalSearch(problem, fireflies[i]); if (fireflies[i][designFunction.config.dimension] > localFirefly[designFunction.config.dimension]) { updateLightIntensity(i, localFirefly); } } else if (lightIntensityI < lightIntensityJ) { candidateFirefly = fireflies[i]; updateLightIntensity(j, moveFirefly(fireflies[j], fireflies[i])); const localFirefly = simulatedAnnealing.executeLocalSearch(problem, fireflies[j]); if (fireflies[j][designFunction.config.dimension] > localFirefly[designFunction.config.dimension]) { updateLightIntensity(j, localFirefly); } } else { updateLightIntensity(j, moveFirefly(fireflies[j], fireflies[i])); const localFirefly = simulatedAnnealing.executeLocalSearch(problem, fireflies[j]); if (candidateFirefly[designFunction.config.dimension] > localFirefly[designFunction.config.dimension]) { updateLightIntensity(i, localFirefly); } } if (candidateFirefly[designFunction.dimension] < bestFirefly[designFunction.dimension]) { bestFirefly = candidateFirefly; } } } alpha = finalAlpha + (initialAlpha - finalAlpha) * Math.exp(-1 * generationIndex); } console.log({ bestFirefly, runtime: performance.now() - startTime }); }; main(); <file_sep>/README.md # f-sa Firefly-Simulated Annealing Algorithm This is just a Node.JS version of my undergraduate thesis. I just coded this out of boredom and to allow me to revisit Javascript coding from time to time. Currently it solves the Spring Problem, one of the many engineering problems out there Feel free to check this out and let me know if there's a problem on my version. # Related Literatures: * [Firefly Algorithm](https://en.wikipedia.org/wiki/Firefly_algorithm) * [Simulated Annealing](https://en.wikipedia.org/wiki/Simulated_annealing) <file_sep>/functions/index.js const { functions } = require('../config'); module.exports = { spring: { generator() { const { bounds } = functions.spring.config; let g1, g2, g3, g4, x1, x2, x3, x4; x1 = bounds[0].lower + Math.random() * (bounds[0].upper - bounds[0].lower); x2 = bounds[1].lower + Math.random() * (bounds[1].upper - bounds[1].lower); x3 = bounds[2].lower + Math.random() * (bounds[2].upper - bounds[2].lower); g1 = 1 - Math.pow(x2, 3) * x3 / (7178 * Math.pow(x1, 4)); g2 = 4 * Math.pow(x2, 2) - x1 * x2 / (12566 * (x2 * Math.pow(x1, 3) - Math.pow(x1, 4))) + 1 / (5108 * Math.pow(x1, 2)) - 1; g3 = 1 - 140.45 * x1 / (Math.pow(x2, 2) * x3); g4 = (x2 + x1) / 1.5 - 1; while (!(g1 <= 0 && g2 <= 0 && g3 <= 0 && g4 <= 0)) { x1 = bounds[0].lower + Math.random() * (bounds[0].upper - bounds[0].lower); x2 = bounds[1].lower + Math.random() * (bounds[1].upper - bounds[1].lower); x3 = bounds[2].lower + Math.random() * (bounds[2].upper - bounds[2].lower); g1 = 1 - Math.pow(x2, 3) * x3 / (7178 * Math.pow(x1, 4)); g2 = 4 * Math.pow(x2, 2) - x1 * x2 / (12566 * (x2 * Math.pow(x1, 3) - Math.pow(x1, 4))) + 1 / (5108 * Math.pow(x1, 2)) - 1; g3 = 1 - 140.45 * x1 / (Math.pow(x2, 2) * x3); g4 = (x2 + x1) / 1.5 - 1; } let firefly = [x1, x2, x3, this.function(x1, x2, x3)]; return firefly; }, checkLimits(firefly) { const { bounds, dimension } = functions.spring.config; for (let i = 0; i < dimension - 1; i++) { if (firefly[i] < bounds[i].lower) { firefly[i] = bounds[i].lower; } if (firefly[i] > bounds[i].upper) { firefly[i] = bounds[i].upper; } } return firefly; }, function(x1, x2, x3) { return (x3 + 2) * x2 * Math.pow(x1, 2); } } }; <file_sep>/simulated-annealing.js const { fsaConfig, localSearch, functions } = require('./config'); const functionsList = require('./functions'); module.exports = { executeLocalSearch: (problem, firefly) => { let temp = localSearch.initialTemperature; let bestLocalFirefly; for (let j = 0; j < fsaConfig.localIteration; j++) { const newFirefly = functionsList[problem].generator(); let rand = Math.random() * 1; let energyDelta = newFirefly[functions[problem]['config']['dimension']] - firefly[functions[problem]['config']['dimension']]; if (energyDelta < 0) { bestLocalFirefly = newFirefly; } else if (rand < Math.pow(Math.E, -1 * (energyDelta / temp))) { bestLocalFirefly = newFirefly; } temp *= localSearch.geometricRatio; } return bestLocalFirefly; } };
9296afcd3714ac2bd7673c7bc8130ee8ab587978
[ "JavaScript", "Markdown" ]
4
JavaScript
jhnferraris/f-sa
33ff4852cd5929abc5bae093f9f464827e1b0393
ae09f0f17e07a2d6f56fbd448637a7f0db3fb062
refs/heads/master
<repo_name>nherder41/pythonRegex<file_sep>/regexScript.py import argparse import re parser = argparse.ArgumentParser(description="Match patters of files using regex") parser.add_argument("-s", "--regex", metavar="", type=str, required=True, help="regex to find") parser.add_argument("-f", "--file", type=str, metavar="", required=True, help="file to search") parser.add_argument("-r", "--replace", type=str, metavar="", required=False, help="replacement string") args = parser.parse_args() #@ regex - python regular expression #@ file - path to file to search #return a list of strings #return a list of regex patterns found in a specific file def search(regex, file): results = [] with open(file, "r") as searchFile: for line in searchFile: results.append(re.search(regex, line)) print(results) #@ regex - python regular expression #@ file - path to file to search #@ replace - replacement for found item #this method is a find and replace on a specified file using regex #def search_and_replace(regex, file, file2): if __name__ == '__main__': if args.replace is None: search(args.regex, args.file) # else: # search_and_replace(args.regex, args.file, args.replace)
23ac5de5abc03ecd07e7c9c0adfbab31683a066b
[ "Python" ]
1
Python
nherder41/pythonRegex
d02c8ffa486d02dad53e5f7a9beea8b504fd8b2d
62d00439352f3cfcd3e91fea1e9ad12c95383e28
refs/heads/master
<file_sep>package main // DO NOT CHANGE THIS CACHE SIZE VALUE const CACHE_SIZE int = 3 var lruMap map[int]node = make(map[int]node) var head *node var end *node type node struct { key int value int previous *node next *node } func Set(key int, value int) { if setNode, ok := lruMap[key]; ok { setNode.value = value lruMap[setNode.key] = setNode Get(setNode.key) } else { createdNode := node{key: key, value: value} if CACHE_SIZE == len(lruMap) { removeLast() } //fmt.Println("Cache size:", len(cache.lruMap)) if len(lruMap) == 0 { createdNode.next = nil createdNode.previous = nil lruMap[key] = createdNode head = &createdNode end = &createdNode } else { var tempHead *node = head var previousNode = lruMap[head.key] previousNode.previous = &createdNode lruMap[previousNode.key] = previousNode createdNode.next = tempHead createdNode.previous = nil lruMap[key] = createdNode head = &createdNode } } } func Get(key int) int { if getNode, ok := lruMap[key]; ok { //fmt.Println("Get Node",getNode.key) // if key is not at head if head.key != key { // if key is at the end if end.key == key { lastNode := lruMap[end.key] end = lastNode.previous var secondLast = lruMap[lastNode.previous.key] secondLast.next = nil lruMap[secondLast.key] = secondLast end.next = nil } if getNode.next != nil { nextNode := lruMap[getNode.next.key] nextNode.previous = getNode.previous lruMap[nextNode.key] = nextNode } if getNode.previous != nil { prevNode := lruMap[getNode.previous.key] prevNode.next = getNode.next lruMap[prevNode.key] = prevNode } firstNode := lruMap[head.key] firstNode.previous = &getNode lruMap[firstNode.key] = firstNode getNode.next = &firstNode getNode.previous = nil lruMap[getNode.key] = getNode head = nil head = &getNode } return getNode.value } else { return -1 } } func removeLast() { if len(lruMap) < 2 || lruMap == nil { lruMap = make(map[int]node) //fmt.Printf("corner") } else { lastNode := lruMap[end.key] end = lastNode.previous var secondLast = lruMap[lastNode.previous.key] secondLast.next = nil lruMap[secondLast.key] = secondLast end.next = nil delete(lruMap, lastNode.key) } }
0379275317c66ccab8e0fa03e77ea66439d8a714
[ "Go" ]
1
Go
Niveditha-Jain/LRU-Cache
c41417a97974476324922fdc872177e8d7318f73
73c9e56118960cec6013cda8215d45e7c8214002
refs/heads/master
<repo_name>solarium-was-swapped-for-lunarium/SolariumCoin-MN-Install-Script<file_sep>/README.md # Solarium Coin Shell script to install an [Solarium Masternode](http://solariumcoin.com/) on a Linux server running Ubuntu 16.04. *** ## Installation: wget -q https://raw.githubusercontent.com/solarium-community/SolariumCoin-MN-Install-Script/master/solarium_install.sh bash solarium_install.sh *** ## Desktop wallet setup After the MN is up and running, you need to configure the desktop wallet accordingly. Here are the steps: 1. Open the Solarium Coin Desktop Wallet. 2. Go to RECEIVE and create a New Address: **MN1** 3. Send **5000** SLRC to **MN1**. 4. Wait for 15 confirmations. 5. Go to **Help -> "Debug window - Console"** 6. Type the following command: **masternode outputs** 7. Go to **Masternodes** tab 8. Click **Create** and fill the details: * Alias: **MN1** * Address: **VPS_IP:PORT** * Privkey: **Masternode Private Key** * TxHash: **First value from Step 6** * Output index: **Second value from Step 6** * Reward address: leave blank * Reward %: leave blank 9. Click **OK** to add the masternode 10. Click **Start All** *** ## Usage: For security reasons **Solarium** is installed under **solarium** user, hence you need to **su - solarium** before checking: ``` SOLARIUM_USER=solarium #replace solarium with the MN username you want to check su - $SOLARIUM_USER Solariumd masternode status Solariumd getinfo ``` Also, if you want to check/start/stop **Solarium**, run one of the following commands as **root**: ``` SOLARIUM_USER=solarium #replace solarium with the MN username you want to check systemctl status $SOLARIUM_USER #To check the service is running. systemctl start $SOLARIUM_USER #To start Solarium service. systemctl stop $SOLARIUM_USER #To stop Solarium service. systemctl is-enabled $SOLARIUM_USER #To check whetether Solarium service is enabled on boot or not. ``` *** ## Credits: Based on a script by Zoldur (https://github.com/zoldur). Thanks! <file_sep>/solarium_install.sh #!/bin/bash TMP_FOLDER=$(mktemp -d) CONFIG_FILE="Solarium.conf" SOLARIUM_DAEMON="/usr/local/bin/Solariumd" SOLARIUM_REPO="https://github.com/solarium-community/solarium.git" DEFAULT_SOLARIUM_PORT=4848 DEFAULT_SOLARIUM_RPC_PORT=4141 DEFAULT_SOLARIUM_USER="solarium" NODE_IP=$(curl -s4 icanhazip.com) RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' function compile_error() { if [ "$?" -gt "0" ]; then echo -e "${RED}Failed to compile $@. Please investigate.${NC}" exit 1 fi } function checks() { if [[ $(lsb_release -d) != *16.04* ]]; then echo -e "${RED}You are not running Ubuntu 16.04. Installation is cancelled.${NC}" exit 1 fi if [[ $EUID -ne 0 ]]; then echo -e "${RED}$0 must be run as root.${NC}" exit 1 fi if [ -n "$(pidof $SOLARIUM_DAEMON)" ] || [ -e "$SOLARIUM_DAEMON" ] ; then echo -e "${GREEN}\c" echo -e "Solarium is already installed. Exiting..." echo -e "{NC}" clear exit 1 fi } function prepare_system() { echo -e "Prepare the system to install Solarium master node." apt-get update >/dev/null 2>&1 DEBIAN_FRONTEND=noninteractive apt-get update > /dev/null 2>&1 DEBIAN_FRONTEND=noninteractive apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y -qq upgrade >/dev/null 2>&1 apt install -y software-properties-common >/dev/null 2>&1 echo -e "${GREEN}Adding bitcoin PPA repository" apt-add-repository -y ppa:bitcoin/bitcoin >/dev/null 2>&1 echo -e "Installing required packages, it may take some time to finish.${NC}" apt-get update >/dev/null 2>&1 apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" make software-properties-common \ build-essential libtool autoconf libssl-dev libboost-dev libboost-chrono-dev libboost-filesystem-dev libboost-program-options-dev \ libboost-system-dev libboost-test-dev libboost-thread-dev sudo automake git wget pwgen curl libdb4.8-dev bsdmainutils libdb4.8++-dev \ libminiupnpc-dev libgmp3-dev ufw fail2ban >/dev/null 2>&1 clear if [ "$?" -gt "0" ]; then echo -e "${RED}Not all required packages were installed properly. Try to install them manually by running the following commands:${NC}\n" echo "apt-get update" echo "apt -y install software-properties-common" echo "apt-add-repository -y ppa:bitcoin/bitcoin" echo "apt-get update" echo "apt install -y make build-essential libtool software-properties-common autoconf libssl-dev libboost-dev libboost-chrono-dev libboost-filesystem-dev \ libboost-program-options-dev libboost-system-dev libboost-test-dev libboost-thread-dev sudo automake git pwgen curl libdb4.8-dev \ bsdmainutils libdb4.8++-dev libminiupnpc-dev libgmp3-dev" exit 1 fi clear echo -e "Checking if swap space is needed." PHYMEM=$(free -g|awk '/^Mem:/{print $2}') SWAP=$(free -g|awk '/^Swap:/{print $2}') if [ "$PHYMEM" -lt "4" ] && [ -n "$SWAP" ] then echo -e "${GREEN}Server is running with less than 4G of RAM without SWAP, creating 8G swap file.${NC}" SWAPFILE=/swapfile dd if=/dev/zero of=$SWAPFILE bs=1024 count=8290304 chown root:root $SWAPFILE chmod 600 $SWAPFILE mkswap $SWAPFILE swapon $SWAPFILE echo "${SWAPFILE} none swap sw 0 0" >> /etc/fstab else echo -e "${GREEN}Server running with at least 2G of RAM, no swap needed.${NC}" fi clear } function compile_solarium() { echo -e "Clone git repo and compile it. This may take some time." cd $TMP_FOLDER git clone $SOLARIUM_REPO solarium cd solarium/src make -f makefile.unix strip Solariumd chmod +x Solariumd cp -a Solariumd /usr/local/bin cd ~ rm -rf $TMP_FOLDER clear } function enable_firewall() { echo -e "Installing fail2ban and setting up firewall to allow ingress on port ${GREEN}$SOLARIUM_PORT${NC}" ufw allow $SOLARIUM_PORT/tcp comment "Solarium MN port" >/dev/null ufw allow ssh comment "SSH" >/dev/null 2>&1 ufw limit ssh/tcp >/dev/null 2>&1 ufw default allow outgoing >/dev/null 2>&1 echo "y" | ufw enable >/dev/null 2>&1 systemctl enable fail2ban >/dev/null 2>&1 systemctl start fail2ban >/dev/null 2>&1 } function systemd_solarium() { cat << EOF > /etc/systemd/system/$SOLARIUM_USER.service [Unit] Description=Solarium service After=network.target [Service] ExecStart=$SOLARIUM_DAEMON -conf=$SOLARIUM_FOLDER/$CONFIG_FILE -datadir=$SOLARIUM_FOLDER ExecStop=$SOLARIUM_DAEMON -conf=$SOLARIUM_FOLDER/$CONFIG_FILE -datadir=$SOLARIUM_FOLDER stop Restart=on-abort User=$SOLARIUM_USER Group=$SOLARIUM_USER [Install] WantedBy=multi-user.target EOF systemctl daemon-reload sleep 3 systemctl start $SOLARIUM_USER.service systemctl enable $SOLARIUM_USER.service if [[ -z "$(ps axo user:15,cmd:100 | egrep ^$SOLARIUM_USER | grep $SOLARIUM_DAEMON)" ]]; then echo -e "${RED}Solariumd is not running${NC}, please investigate. You should start by running the following commands as root:" echo -e "${GREEN}systemctl start $SOLARIUM_USER.service" echo -e "systemctl status $SOLARIUM_USER.service" echo -e "less /var/log/syslog${NC}" exit 1 fi } function ask_port() { read -p "SOLARIUM Port: " -i $DEFAULT_SOLARIUM_PORT -e SOLARIUM_PORT : ${SOLARIUM_PORT:=$DEFAULT_SOLARIUM_PORT} } function ask_user() { echo -e "${GREEN}The script will now setup Solarium user and configuration directory. Press ENTER to accept defaults values.${NC}" read -p "Solarium user: " -i $DEFAULT_SOLARIUM_USER -e SOLARIUM_USER : ${SOLARIUM_USER:=$DEFAULT_SOLARIUM_USER} if [ -z "$(getent passwd $SOLARIUM_USER)" ]; then USERPASS=$(pwgen -s 12 1) useradd -m $SOLARIUM_USER echo "$SOLARIUM_USER:$USERPASS" | chpasswd SOLARIUM_HOME=$(sudo -H -u $SOLARIUM_USER bash -c 'echo $HOME') DEFAULT_SOLARIUM_FOLDER="$SOLARIUM_HOME/.Solarium" read -p "Configuration folder: " -i $DEFAULT_SOLARIUM_FOLDER -e SOLARIUM_FOLDER : ${SOLARIUM_FOLDER:=$DEFAULT_SOLARIUM_FOLDER} mkdir -p $SOLARIUM_FOLDER chown -R $SOLARIUM_USER: $SOLARIUM_FOLDER >/dev/null else clear echo -e "${RED}User exits. Please enter another username: ${NC}" ask_user fi } function check_port() { declare -a PORTS PORTS=($(netstat -tnlp | awk '/LISTEN/ {print $4}' | awk -F":" '{print $NF}' | sort | uniq | tr '\r\n' ' ')) ask_port while [[ ${PORTS[@]} =~ $SOLARIUM_PORT ]] || [[ ${PORTS[@]} =~ $[SOLARIUM_PORT+1] ]]; do clear echo -e "${RED}Port in use, please choose another port:${NF}" ask_port done } function create_config() { RPCUSER=$(pwgen -s 8 1) RPCPASSWORD=$(pwgen -s 15 1) cat << EOF > $SOLARIUM_FOLDER/$CONFIG_FILE rpcuser=$RPCUSER rpcpassword=$<PASSWORD> rpcallowip=127.0.0.1 rpcport=$DEFAULT_SOLARIUM_RPC_PORT listen=1 server=1 daemon=1 port=$SOLARIUM_PORT EOF } function create_key() { echo -e "Enter your ${RED}Masternode Private Key${NC}. Leave it blank to generate a new ${RED}Masternode Private Key${NC} for you:" read -e SOLARIUM_KEY if [[ -z "$SOLARIUM_KEY" ]]; then su $SOLARIUM_USER -c "$SOLARIUM_DAEMON -conf=$SOLARIUM_FOLDER/$CONFIG_FILE -datadir=$SOLARIUM_FOLDER" sleep 15 if [ -z "$(ps axo user:15,cmd:100 | egrep ^$SOLARIUM_USER | grep $SOLARIUM_DAEMON)" ]; then echo -e "${RED}Solariumd server couldn't start. Check /var/log/syslog for errors.{$NC}" exit 1 fi SOLARIUM_KEY=$(su $SOLARIUM_USER -c "$SOLARIUM_DAEMON -conf=$SOLARIUM_FOLDER/$CONFIG_FILE -datadir=$SOLARIUM_FOLDER masternode genkey") su $SOLARIUM_USER -c "$SOLARIUM_DAEMON -conf=$SOLARIUM_FOLDER/$CONFIG_FILE -datadir=$SOLARIUM_FOLDER stop" fi } function update_config() { sed -i 's/daemon=1/daemon=0/' $SOLARIUM_FOLDER/$CONFIG_FILE cat << EOF >> $SOLARIUM_FOLDER/$CONFIG_FILE maxconnections=256 masternode=1 masternodeaddr=$NODE_IP:$SOLARIUM_PORT masternodeprivkey=$SOLARIUM_KEY addnode=192.168.3.11 addnode=192.168.3.11 addnode=192.168.3.11 addnode=172.16.58.3 addnode=172.16.58.3 addnode=172.16.31.10 addnode=172.16.17.32 addnode=192.168.3.11 addnode=172.16.31.10 addnode=172.16.31.10 EOF chown -R $SOLARIUM_USER: $SOLARIUM_FOLDER >/dev/null } function important_information() { echo echo -e "================================================================================================================================" echo -e "Solarium Masternode is up and running as user ${GREEN}$SOLARIUM_USER${NC} and it is listening on port ${GREEN}$SOLARIUM_PORT${NC}." echo -e "${GREEN}$SOLARIUM_USER${NC} password is ${RED}$USERPASS${NC}" echo -e "Configuration file is: ${RED}$SOLARIUM_FOLDER/$CONFIG_FILE${NC}" echo -e "Start: ${RED}systemctl start $SOLARIUM_USER.service${NC}" echo -e "Stop: ${RED}systemctl stop $SOLARIUM_USER.service${NC}" echo -e "VPS_IP:PORT ${RED}$NODE_IP:$SOLARIUM_PORT${NC}" echo -e "MASTERNODE PRIVATEKEY is: ${RED}$SOLARIUM_KEY${NC}" echo -e "Please check Solarium is running with the following command: ${GREEN}systemctl status $SOLARIUM_USER.service${NC}" echo -e "================================================================================================================================" } function setup_node() { ask_user check_port create_config create_key update_config enable_firewall systemd_solarium important_information } ##### Main ##### clear checks prepare_system compile_solarium setup_node
2041a3b0a1e0f496c117abb531be52641baf5672
[ "Markdown", "Shell" ]
2
Markdown
solarium-was-swapped-for-lunarium/SolariumCoin-MN-Install-Script
ad9ba6a614e4d0793db4d94bad15b3503f9a039b
aa77a7c49d4f5e0a0af53968229527b1d366879e
refs/heads/master
<file_sep># LCKit [![CI Status](https://img.shields.io/travis/lattecat/LCKit.svg?style=flat)](https://travis-ci.org/lattecat/LCKit) [![Version](https://img.shields.io/cocoapods/v/LCKit.svg?style=flat)](https://cocoapods.org/pods/LCKit) [![License](https://img.shields.io/cocoapods/l/LCKit.svg?style=flat)](https://cocoapods.org/pods/LCKit) [![Platform](https://img.shields.io/cocoapods/p/LCKit.svg?style=flat)](https://cocoapods.org/pods/LCKit) ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements ## Installation LCKit is available through [CocoaPods](https://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod 'LCKit' ``` ## Author lattecat, <EMAIL> ## License LCKit is available under the MIT license. See the LICENSE file for more info. <file_sep>use_frameworks! platform :ios, '9.0' target 'LCKit_Example' do pod 'LCKit', :path => '../' target 'LCKit_Tests' do inherit! :search_paths end end <file_sep>// // LCKitMacro.h // Pods // // Created by lattecat on 2020/3/10. // #ifndef LCKitMacro_h #define LCKitMacro_h /** * 防止循环引用的 __weak __strong 的宏定义 */ #define weakify(self) \ try{}@catch(NSException *e){} \ __weak typeof(self) self_weak = self; #define strongify(self) \ try{}@catch(NSException *e){} \ __strong typeof(self_weak) self = self_weak; /** * 用于执行 Block * @warning 注意在 C++ 中使用此宏定义没有返回值,如果需要获取 block 返回值,请手动实现; */ #ifdef __cplusplus #define PERFORM_SAFE_BLOCK(block, ...) if (block) { block(__VA_ARGS__); } #else #define PERFORM_SAFE_BLOCK(block, ...) (block) ? block(__VA_ARGS__) : nil; #endif #endif /* LCKitMacro_h */
db5b11dc75dcee4859e16b91cdb5079e2ba0d0ec
[ "Markdown", "Ruby", "C++" ]
3
Markdown
LatteCat/LCKit
b411ff02ca155abc2f401df4a3219f1cbd982bd3
bd4e7f4f7e17981c5068f4ea3ce67d2f6bd3e996
refs/heads/master
<repo_name>crisstianlino/Sistemas-de-Gerenciamento-de-Banco-de-Dados<file_sep>/ExternalMergeSort/src/ordenacao/EMS.java package ordenacao; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class EMS { int tamanhobuffer = 125; Pagina buffer[] = new Pagina[tamanhobuffer]; public Registro[] ordenarbuffer(int atributo) { if (atributo == 1){ // ordenar por idade Registro[] temp = new Registro[tamanhobuffer*16]; for(int j = 0 ; j < tamanhobuffer ; j++) { for(int k = 0 ; k < 16 ;k++) { temp[16*j+k] = this.buffer[j].getRegistro(k); } } ordena_idade(temp); return temp; } if (atributo == 2){ // ordenar por id Registro[] temp = new Registro[tamanhobuffer*16]; for(int j = 0 ; j < tamanhobuffer ; j++) { for(int k = 0 ; k < 16 ;k++) { temp[16*j+k] = this.buffer[j].getRegistro(k); } } ordena_id(temp); return temp; } return null; } public void preencherbuffer(int i, Tabela tabela){ int qtd_arq = 625/tamanhobuffer; int count = 0; int comeco = i*tamanhobuffer; while (count < tamanhobuffer){ this.buffer[count] = tabela.getPagina(comeco); comeco++; count++; } } public void ordenar(int atributo, Tabela tabela) throws IOException { if (atributo == 1) // o atributo escolhido para ordenar foi idade { for(int i=0;i<625/tamanhobuffer;i++){ Registro[] temp = new Registro[tamanhobuffer*16]; preencherbuffer(i,tabela); temp = ordenarbuffer(atributo); FileWriter arquivo = new FileWriter(new File("C:\\Users\\crist\\Downloads\\diretorio\\temp"+i+".txt")); for(int j=0;j<tamanhobuffer*16;j++){ String linha = ""+temp[j].getId_func()+","+temp[j].getNome()+","+temp[j].getSobrenome()+","+temp[j].getIdade()+"\n"; arquivo.write(linha); } arquivo.close(); } } } public void ordena_idade(Registro elementos[]){ int cont1, cont2; Registro aux = new Registro(); for(cont1 =0; cont1<tamanhobuffer*16; cont1++){ for(cont2 =0; cont2 <tamanhobuffer*16-1; cont2++){ if(elementos[cont2].getIdade()> elementos[cont2+1].getIdade()){ aux = elementos[cont2]; elementos[cont2] = elementos[cont2+1]; elementos[cont2+1] = aux; } } } } public void ordena_id(Registro elementos[]){ int cont1, cont2; Registro aux = new Registro(); for(cont1 =0; cont1<this.tamanhobuffer*16; cont1++){ for(cont2 =0; cont2 <this.tamanhobuffer*16-1; cont2++){ if(elementos[cont2].getId_func()> elementos[cont2+1].getId_func()){ aux = elementos[cont2]; elementos[cont2] = elementos[cont2+1]; elementos[cont2+1] = aux; } } } } } <file_sep>/Transacoes/sgbd_t3.py #Cada linha do arquivo será adicionada na variável historias arq = open('trab.txt', 'r') historias = [] for linha in arq: historias.append(linha.split(',')) arq.close() def limpar(historia): # Retorna a historia sem as operações CP() e FL() lista = historia[:] while 'CP()' in lista: lista.remove('CP()') while 'FL()' in lista: lista.remove('FL()') return lista def descobrir_variaveis(historia): # Retorna uma lista de listas das variaveis da historia # Ex: [[x,0,0],[y,0,0],[z,0,0]] variavel = [] lista = [] for i in range(len(historia)): if not historia[i][3].isdigit() and historia[i][3] != ")": variavel.append(historia[i][3]) aux = set(variavel) aux = list(aux) aux.sort() for i in range(len(aux)): formato = [aux[i],0,0] lista.append(formato) return lista def timestamp(Tx, dado, operacao): if operacao == 'r': if Tx < dado[2]: # A transação está tentando ler um dado enquanto outra está escrevendo o dado print("") print(operacao+""+str(Tx)+"("+dado[0]+")"+" "+"PROBLEMA ENCONTRADO NA OPERACAO "+operacao+""+str(Tx)+"("+dado[0]+") "+"POIS A TRANSACAO "+str(dado[2])+" VAI ESCREVER O DADO "+dado[0]+".",end='') return False else: dado[1] = Tx return True else: if Tx < dado[1]: # A transação está tentando escrever um dado enquanto outra está lendo o dado print("") print(operacao+""+str(Tx)+"("+dado[0]+")"+" "+"PROBLEMA ENCONTRADO NA OPERACAO "+operacao+""+str(Tx)+"("+dado[0]+") "+"POIS A TRANSACAO "+str(dado[1])+" JA LEU O DADO "+dado[0]+".",end='') return False elif Tx < dado[2]: # A transação está tentando escrever um dado enquanto outra também está querendo escrever o dado print("") print(operacao+""+str(Tx)+"("+dado[0]+")"+" "+"PROBLEMA ENCONTRADO NA OPERACAO "+operacao+""+str(Tx)+"("+dado[0]+") "+"POIS A TRANSACAO "+str(dado[2])+" ESTÁ ESCREVENDO O DADO "+dado[0]+".",end='') return False else: dado[2] = Tx return True def print_entrada(historia): print("ENTRADA:") for i in historia: print(""+i,end=" ") print("") def print_resultado(historia): print("\n") print("RESULTADO:",end=' ') for i in historia: print(""+i,end=" ") print("") def print_saida(variavel): print("") print("SAÍDA:") print(" ",end="") for i in variavel: print("<"+i[0]+","+str(i[1])+","+str(i[2])+">",end=" ") def shift_right(historia,posicao): #O elemento da posição desejada é inserido no inicio e empurra os outros pra direita em uma posição aux = [] time = int(historia[posicao][1]) condicao = True tamanho = len(historia) i = 0 while condicao: if i > tamanho-2: condicao = False if historia[i] == 'BT('+str(time)+')': aux.append(historia[i]) aux.append(historia[posicao]) i = i+1 elif i != posicao: aux.append(historia[i]) i = i+1 else: i = i+1 return aux def concorrencia(historia): print_entrada(historia) variaveis = descobrir_variaveis(historia) # variaveis é uma lista que armazena todas as variaveis print_saida(variaveis) condicao = True i = 0 while condicao: if i > len(historia)-2: condicao = False if historia[i][0] == 'r' or historia[i][0] == 'w': Tx = int(historia[i][1]) letra = historia[i][3] for j in range(len(variaveis)): if variaveis[j][0] == letra: dado = variaveis[j] operacao = historia[i][0] ts = timestamp(Tx,dado,operacao) if ts: print("") print(historia[i]+" ",end="") for k in variaveis: print("<"+k[0]+","+str(k[1])+","+str(k[2])+">",end=" ") i = i+1 else: return i else: i = i+1 print_resultado(historia) recuperar(undo_redo(historia),historia) return -1 def undo_redo(historia): #Retorna as listas com os numeros das transações que precisam de UNDO e REDO trans_redo = [] trans_undo = [] retorno = [] pos_falha = historia.index('FL()') i = len(historia) - 1 cond = True while cond: if historia[i] == 'FL()': cond = False elif historia[i][1] == 'M': trans_undo.append(int(historia[i][3])) i = i-1 condicao = True pos_falha = historia.index('FL()') i = pos_falha - 1 while condicao: if historia[i] == 'CP()': condicao = False elif historia[i][1] == 'M': trans_redo.append(int(historia[i][3])) else: trans_undo.append(int(historia[i][1])) i = i-1 trans_undo = set(trans_undo) trans_redo = set(trans_redo) trans_undo = trans_undo - trans_redo trans_undo = list(trans_undo) trans_redo = list(trans_redo) trans_undo.sort() trans_redo.sort() retorno.append(trans_undo) retorno.append(trans_redo) return retorno def recuperar(lista_ur,historia): print("") print("UNDO:") pos_falha = historia.index('FL()')+1 for i in range(len(lista_ur[0])): print("T"+str(lista_ur[0][i]),end=": ") for j in range(pos_falha): if historia[j][0] == 'w' and historia[j][1] == str(lista_ur[0][i]): print(""+historia[j],end=' ') print("\n") print("REDO:") for i in range(len(lista_ur[1])): print("T"+str(lista_ur[1][i]),end=": ") for j in range(pos_falha): if historia[j][0] == 'w' and historia[j][1] == str(lista_ur[1][i]): print(""+historia[j],end=' ') print("") print("\n------------------------------------------------------------------------------------------------------------------------") # #MAIN # for i in range(len(historias)): teste = concorrencia(historias[i]) tentativas = 0 print("") while teste != -1: historias[i] = shift_right(historias[i],teste) print("") tentativas = tentativas + 1 print("TENTATIVA "+str(tentativas)) teste = concorrencia(historias[i]) <file_sep>/ExternalMergeSort/src/ordenacao/Registro.java package ordenacao; public class Registro { Integer id_func; String nome; String sobrenome; Integer idade; public Registro() { } public Registro(Integer id_func, String nome, String sobrenome, Integer idade) { this.id_func = id_func; this.nome = nome; this.sobrenome = sobrenome; this.idade = idade; } public Integer getId_func() { return id_func; } public String getNome() { return nome; } public String getSobrenome() { return sobrenome; } public Integer getIdade() { return idade; } public void display(){ System.out.println(this.getId_func()+" "+this.getNome()+" "+this.getSobrenome()+" "+this.getIdade()); } } <file_sep>/ExternalMergeSort/src/ordenacao/Tabela.java package ordenacao; import java.util.List; public class Tabela { Pagina paginas[]; int qtd_paginas; public Tabela() { this.paginas = new Pagina[1000]; this.qtd_paginas = 0; } public void setPaginas(Pagina paginas, int n) { this.paginas[n] = paginas; this.qtd_paginas++; } public Pagina getPagina(int i){ return paginas[i]; } } <file_sep>/ExternalMergeSort/src/ordenacao/Importar.java package ordenacao; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class Importar { public static void displayRegistro(Registro registro) { System.out.println(registro.id_func + " " + registro.nome + " " + registro.sobrenome + " " + registro.idade); } public static Tabela importador(String pathname) throws IOException { Registro reg = null; int registrosPorPagina = 16; Pagina pagina = new Pagina(); Tabela tabela = new Tabela(); Pagina print = new Pagina(); Registro print2 = new Registro(); File arquivo = new File(pathname); if (arquivo.exists()) { Scanner entradaDoArquivo = new Scanner(new BufferedReader(new FileReader(arquivo))); String linhaDoArquivo; int count = 0; int i = 0; while (entradaDoArquivo.hasNextLine()) { linhaDoArquivo = entradaDoArquivo.nextLine(); String[] InArray = linhaDoArquivo.split(","); reg = new Registro(Integer.parseInt(InArray[0]), InArray[1], InArray[2], Integer.parseInt(InArray[3])); pagina.setRegistros(count,reg); count++; if (count == 16) { tabela.setPaginas(pagina,i); Pagina temp = new Pagina(); pagina = temp; count = 0; i++; } } } return tabela; } } <file_sep>/README.md # Sistemas-de-Gerenciamento-de-Banco-de-Dados
4a343f2b020f5225a0b436712a5e0cfb28afeb25
[ "Markdown", "Java", "Python" ]
6
Java
crisstianlino/Sistemas-de-Gerenciamento-de-Banco-de-Dados
3a64d7a7234d05e917290af60d58bff1324af307
dc4186cc35729a6b8da21763b41d1bde4d6d3ae8
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Telephone.Models; using System.Data.Entity; using System.Data; using System.Net; namespace Telephone.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return RedirectToAction("Index1", "Product"); } } }
e279a4a720d097ae0446179842320c9e14df44fc
[ "C#" ]
1
C#
haidy-ismail/project
86f623ad123c10b238f63c7a2250396390506cf7
cb521dff381f4e27a31845e93d33c28a1bd590c5
refs/heads/master
<repo_name>yaoelvon/Flask-Fixtures<file_sep>/tests/test_default_fixtures_dir.py """ test_default_fixtures_dir ~~~~~~~~~~~~~ A set of tests that check the default fixtures directory of Flask-Fixtures. :copyright: (c) 2016 <NAME> <<EMAIL>>. :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import import unittest from myapp import app from myapp.models import db, Author from flask.ext.fixtures import FixturesMixin class TestDefaultFixturesDir(unittest.TestCase, FixturesMixin): '''Test fixtures directory set problem. When coder set app.config['FIXTURES_DIRS'] and FIXTURES_DIRS path and "current_app.root_path + '/fixtures'" together have a same file like 'author.json', flask-fixtures will get "current_app.root_path + '/fixtures/author.json'" file. I think that default can use "current_app.root_path + '/fixtures'", but we shoud use app.config['FIXTURES_DIRS'] when coder had set "app.config['FIXTURES_DIRS']". ''' app = app db = db app.config['FIXTURES_DIRS'] = [app.root_path + '/../fixtures'] fixtures = ['authors.json'] def setUp(self): self.SUT_app = app if hasattr(app, 'app_context'): self.app_context = self.SUT_app.app_context() else: self.app_context = self.SUT_app.test_request_context() self.app_context.push() app.logger.debug('app.root_path={0}'.format(app.config['FIXTURES_DIRS'])) def tearDown(self): app.config.pop('FIXTURES_DIRS') self.app_context.pop() def test_get_authors_json_from_dir_set(self): author = Author.query.first() self.assertEqual(author.first_name, 'Feng') self.assertEqual(author.last_name, 'Yao')
88758001e1e87c7e74c221319cca2659930b11c7
[ "Python" ]
1
Python
yaoelvon/Flask-Fixtures
be2b170c17492d6befcf31126f653b87e907d138
5f2e466f346feead0ea790051377153ff67c7d04
refs/heads/master
<file_sep>ImageSpiral =========== A work-in-progress image hosting site built using node.js, express, bootstrap and redis. Current features include: - Automatic thumbnail generation with customizable thumbnail sizes - Automatic gallery creation and linking - Sharing via forum and html embeds - Dead simple single or multiple file upload - Designed so that no database reads are required for non-account pages - Threaded architecture for maximum speed - User session and account management built on a redis data store Demo available at [imagespiral.collectivecognition.com](http://imagespiral.collectivecognition.com/) <file_sep>#!/bin/sh FILES=../queue/* for f in $FILES do echo "file=@$f" # curl -X POST --form "file=@$f" http://localhost:3000/ curl -X POST --form "file=@$f" http://192.168.127.12:3000/ # rm -rf "$f" # sleep 0.1 done<file_sep>#!/bin/sh rm ../src/public/images/* rm ../src/public/thumbs/* rm ../src/public/tiny/* rm ../src/public/small/*
107a747c3f7eec8cba5146b6ec56b9c84ed41788
[ "Markdown", "Shell" ]
3
Markdown
collectivecognition/imagespiral
b290e6c13122eb4ba28e2891c9f31bf7245aaf80
5ebf600f488b48d94abff8b59e1c373ff9f911fc
refs/heads/master
<repo_name>chihirotange/neko_generator<file_sep>/Img.py import pandas as pd from DataGenerator import DataGenerator import constants from os import path class CharacterImage: def __init__(self, name, asset_list, df = (DataGenerator().data)): "asset_list la list cac asset cau tao thanh img, gia tri mac dinh la random se tao ra asset random tu database" self.name = name self.df = df self.emotions_dict = None self.image_path = None filt = self.df[constants.INTERNAL_NAME].isin(asset_list) self.assets = self.df[filt] dna = self.assets[constants.INTERNAL_NAME].tolist() self._true_dna(dna) def _true_dna(self,dna): true_dna = set([d for d in dna if any(e not in d for e in constants.NOT_TRUE_DNA)]) self.dna = true_dna def _filter_red_flags(self): pass def _get_paths(self): temp_df = self.assets.sort_values(by= constants.ASSET_POS) new_dict = { constants.INTERNAL_NAME: None, constants.ASSET_POS: None } sub_layer_assets = self.assets[constants.SUBLAYER].tolist() new_sublayer = [x for x in sub_layer_assets if pd.isnull(x) == False] sub_layer_pos = self.assets[constants.SUBLAYER_POS].tolist() new_sublayer_pos = [x for x in sub_layer_pos if pd.isnull(x) == False] new_dict[constants.INTERNAL_NAME] = new_sublayer new_dict[constants.ASSET_POS] = new_sublayer_pos df_to_append = pd.DataFrame(new_dict) temp_df = temp_df.append(df_to_append, ignore_index = True) temp_df.sort_values(by = constants.ASSET_POS, ascending=False, inplace=True) series_to_list = temp_df[constants.INTERNAL_NAME].tolist() for i in series_to_list: file_paths = [path.join(constants.IMAGE_DIR, i) + ".png" for i in series_to_list] img_paths = {} for emo in constants.EMOTIONS: emo_path = [] for f in file_paths: asset = f.replace(constants.DEFAULT_EMO, emo) emo_path.append(asset) img_paths[emo] = emo_path return img_paths<file_sep>/constants.py SHEET_ID = "1pBvMA-SCzoMC677LOMdS3M2OP7SlyKWBXIUEBgNb9uM" ANCHOR_TRAIT = "trait" # trait quyet dinh cac part cua nhan vat (la row dau tien trong sheet) IMAGE_DIR = "imgs" # duong dan toi folder chua anh asset da cat layer INTERNAL_NAME = "internal_name" # ten row dau tien cua sheet quy dinh ten file trong folder layer asset PERCENTAGE = "percentage" # ten row dau tien cua sheet quy dinh percentage SORT_VAR = "position" # ten row dau tien cua sheet quy dinh percentage IMAGE_RATIO = 5682/5067 #height / width IMAGE_DESTINATION = "saved" #tro toi folder chua cac file da render DEFAULT_WIDTH = 2000 NOT_TRUE_DNA = ["bg_"] #list cac asset ko tinh vao dna de tinh unique ASSET_POS = "position" SUBLAYER_POS = "sublayer_pos" SUBLAYER = "sublayer" NUM_OF_ASSETS = "number" EMOTIONS = ["default" ,"angry", "nervous", "sad"] DEFAULT_EMO = "default" FULLSET_BODY = "fullset_body" FULLSET = "fullset"<file_sep>/NFTCollection.py import Img from concurrent import futures from random import shuffle from DataGenerator import DataGenerator import constants from random import randint from PIL import Image from os import path counter = DataGenerator().data.set_index(constants.INTERNAL_NAME)[constants.NUM_OF_ASSETS].dropna().to_dict() full_num = [] class NFTCollection: def __init__(self, num_of_nft): self.unique_dnas = [] self.unique_imgs = [] self.df = DataGenerator().data fullset_list = self._get_fullset() missing_nft_num = num_of_nft - len(fullset_list) missing_nft = [self._get_random() for __ in range(missing_nft_num)] combined_list = fullset_list + missing_nft for nft in combined_list: img = Img.CharacterImage(name = None, asset_list = nft) if self._not_duplicated(img): self.unique_imgs.append(img) self.unique_dnas.append(img.dna) print(len(self.unique_imgs)) shuffle(self.unique_imgs) for i,img in enumerate(self.unique_imgs): img.name = str(i+1).zfill(6) def _get_random(self): chosen_assets = [] # cac asset dc chon se nam trong list nay trait_groups = self.df[constants.ANCHOR_TRAIT].unique() for trait_group in trait_groups: #loop lan luot cac trait de chon asset filt = (self.df[constants.ANCHOR_TRAIT] == trait_group) & (~self.df[constants.INTERNAL_NAME].isin(full_num)) traits = self.df[filt] #filter panda try: picked_asset = traits.sample() #list cac asset tu trait da filter if self._choose_asset(picked_asset): asset_name = picked_asset[constants.INTERNAL_NAME].item() chosen_assets.append(asset_name) #item() de return dang list, de sau nay ref vao dataframe tong ko la no se return dang dataframe except: continue self._add_to_counter(chosen_assets) return chosen_assets def _add_to_counter(self, assets): for a in assets: if counter.get(a) != None: counter[a] -= 1 if counter[a] == 0: full_num.append(a) def _get_fullset(self): fullset_collection = [] fullset_filt = self.df[constants.FULLSET].notna() all_fullsets = self.df[fullset_filt][constants.FULLSET].unique() for trait_group in all_fullsets: filt = self.df[constants.FULLSET] == trait_group fullset = self.df[filt] fullset_assets = fullset[constants.INTERNAL_NAME].tolist() fullset_collection.append(fullset_assets) self._add_to_counter(fullset_assets) return fullset_collection def _not_duplicated(self, img): return True if img.dna not in self.unique_dnas else False def _choose_asset(self,series): percentage = float((series[constants.PERCENTAGE])) if percentage == 100: return True else: roll_random = randint(0,100) if roll_random <= percentage: return True else: return False def print_img(self, img, img_width = constants.DEFAULT_WIDTH, full_emo = False): "pass in img object to print" image_size = (img_width, round(img_width*constants.IMAGE_RATIO)) emotions_path = img._get_paths() for emotion, file_paths in emotions_path.items(): image = Image.new("RGBA", image_size) for f in file_paths: next_image = Image.open(f).convert("RGBA").resize(image_size) image = Image.alpha_composite(image,next_image) image_path = f"{path.join(constants.IMAGE_DESTINATION, img.name)}_{emotion}.png" image.save(image_path) if full_emo == True: continue else: break def print_collection(self): with futures.ThreadPoolExecutor() as executor: executor.map(self.print_img, self.unique_imgs) def _hash_image(self, file): try: with open(file, "rb") as f: bytes = f.read() #read file as bytes hash = md5(bytes).hexdigest() return hash except: print("No image to hash!") def export_metadata(self): for image in self.unique_imgs: print(image.image_hash) pass if __name__ == "__main__": collection = NFTCollection(20) print(collection.unique_imgs[0]._get_paths()) collection.print_collection() # print(collection.unique_imgs[2].emotions_dict) # collection.export_metadata() # with concurrent.futures.ThreadPoolExecutor() as executor: # for _ in collection.unique_imgs: # executor.submit(_.print_image(full_emo=False)) <file_sep>/DataGenerator.py import pandas as pd import constants class DataGenerator: def __init__(self, sheet_id = constants.SHEET_ID): self.sheet_id = sheet_id self.data = self.gsheet_to_pandas() def gsheet_to_pandas(self): df = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{self.sheet_id}/export?format=csv") #trick convert sheet thanh CSV bang cach thay doi URL return df
60b3cbe140187e2380e738e49d7119c5ffe6f30b
[ "Python" ]
4
Python
chihirotange/neko_generator
660d0db5eeb38af4f0946f924d95cb83939e83f4
9103b6db36f5a1dbe70aab08a98c73ee5110517b
refs/heads/master
<repo_name>AnaisG14/hello-world<file_sep>/README.md # Salut tout le monde/hello world nouveau repository pour débuter Je me lance depuis peu dans le code, après html5 et css3, me voilà partie pour php. première leçon, utiliser github et créer des commits. 2ème changement pour voir modif directement sur mon ordinateur et on voit ce qui se passe (modif dans la console avec vim décembre 2020 : quelques années sans utiliser git, révisions et nouveau test. Aujourd'hui, après création de 2 sites en php, apprentissage de du langage python. C'est parti pour de nouvelles aventures. <file_sep>/hello.py """ branche master""" print("hello everybody") print("We are the 14th of December of 2020") name = input("Entrez votre prénom: ") print("Bonjour {}, voici une première modif".format(name)) cp = input("Entrez votre code postal: ") print(cp) print("Today is Wednesday, 18/08/21") print("Test")
8c593e5f944920caf7ebded47f547a55dd9d1165
[ "Markdown", "Python" ]
2
Markdown
AnaisG14/hello-world
8deae3d401cc00aea36aa56fab9ba644c361729f
5b21649513fed5f374f176183a8ab740e6f55525
refs/heads/master
<file_sep>jQuery SimpleSlider =================== Copyright (C) 2011 <NAME> Overview -------- jQuery SimpleSlider is a light weight panel sliding in page navigation plugin for when you just need a simple sliding menu system and not the weight and options of something like jqTouch. Features -------- Pass a container object that acts as the wrapper for all the panels. Back buttons will be automatically be generated for each subsequent page. The links you use to switch panels must match the ID of the target panel to work, see example below. Currently the plugin supports four options that can be passed to it: * speed : 200 - The speed at which the pannels move * backClassName : back - The class name that is used for the back button * root : null - The starting and root page element, by default it will be the first child of the container * callback : function() {} - A function that is executed when the plugin finishes executing Example -------- <div id="main"> <section id="lists"> <h1>Pages</h1> <ul> <li><a href="#create">Create</a></li> <li><a href="#update">Update</a></li> </ul> </section> <section id="create"> <h1>Create</h1> </section> <section id="update"> <h1>Update</h1> </section> </div> $(document).ready(function() { $('#main').simpleSlider({ 'speed' : 300 }); }); <file_sep>(function( $ ){ var settings = { 'speed' : 200, 'backButtons' : true, 'backClassName' : 'back', 'root' : null }; var statusData = 'data-ss_status'; var previousData = 'data-ss_previous'; function swapStatus(target, active){ $(target).attr(statusData, 'active'); active.removeAttr(statusData); } function transition(active, target, speed, direction, callback){ active = $(active); target = $(target); parent = target.parent(); /* should be the container */ callback = callback || function() {}; var containerHeight = Math.max(active.height(), target.height()); var value = ""; if(direction == '+'){ value = '-'; } parent.height(containerHeight); $(active).css('position', 'absolute'); target.css('left', value + target.width()); target.show(); $(active).add(target).animate({left: direction + '=' + active.width()}, speed, function() { target.css('position', 'static'); parent.css('height', 'auto'); active.hide(); location.hash = "#" + target.attr('id'); callback.call(this); }); swapStatus(target, active); } $.fn.transitionLeft = function(target, speed, callback) { return this.each(function() { transition($(this), target, speed, '-', callback); }); } $.fn.transitionRight = function(target, speed, callback) { return this.each(function() { transition($(this), target, speed, '+', callback); }); } $.fn.simpleSlider = function(options, callback) { if ( options ) { $.extend( settings, options ); } return this.each(function() { var backClass = '.' + settings.backClassName; var anchorExclude = backClass; var container = $(this); var children = container.children(); var root = settings.root || children.first(); var width = container.width(); var height = root.height(); var hash = window.location.hash; container.css({'position' : 'relative', 'overflow' : 'hidden'}); children.css({'width' : width + 'px', 'left' : width + 'px', 'top' : 0, 'position' : 'absolute' }); children.not(root).hide(); root.css({'left' : '0'}).attr(statusData, 'active'); root.css('position', 'static'); if(settings.backButtons == true){ children.not(root).prepend('<a class="' + settings.backClassName + '" href="#">Back</a>'); } $('a[href^="#"]').not(anchorExclude).click(function(e) { e.preventDefault(); var active = $('[' + statusData +'="active"]'); var target = $($(this).attr('href')); active.transitionLeft(target, settings.speed); target.attr(previousData, '#' + active.attr('id')); }); $(backClass).click(function(e) { e.preventDefault(); var active = $(this).parent(); var prev = active.attr(previousData); var target = $(prev || ('#' + root.attr('id'))); active.transitionRight(target, settings.speed); }); if(location.hash == ''){ location.hash = "#" + $(root).attr('id'); }else{ $('a[href="' + location.hash + '"]').click(); } callback.call(this); }); }; })( jQuery );
9da604955a60b8d8fcd20271e0bd682adea2ebfa
[ "Markdown", "JavaScript" ]
2
Markdown
conzett/jquery.simpleSlider
ebeab940202ac3f06fafb8e41313e635a93da006
0789019a34b236125d060a2835ffea9914b1297f
refs/heads/master
<file_sep>unit testing: //movies.spec.js describe("Testing the movies API", () => { it("tests our testing framework if it works", () => { expect(2).toBe(2); }); }); Integration testing: //movies.spec.js const supertest = require('supertest'); const app = require('.../server'); describe("Testing the movies API", () => { it("tests the base route and returns true for status", async ()=> { const response = await supertest(app).get('/'); expect(response.status).toBe(200); expect(response.body.status).toBe(true); }); }); end to end testing: //movies.spec.js .... it("tests the post new movies endpoint and returns as successmessege",asyn() => { const response = await supertest(app).post('/movies').send({ title: 'New Movie', sysnopsis: 'Synopsis of the new movie', rating: 'PG' }); expect(response.status).toBe(200); expect(response.body.status).toBe('Success'); expect(response.body.messege).toBe('Movies saved Successfully.'); }); afterEach(async () => { await Movies.deleteOne({ title: 'New Movie' })
2f2a0a16b954a21326808f897288dd89ff38c46b
[ "JavaScript" ]
1
JavaScript
sk807209/repo
20675745badcc125a88f17697ad977e5c942cbf3
f5db42f193f0fc2accf75cbbe1afb099d3031943
refs/heads/master
<repo_name>cran/CVR<file_sep>/R/myfunctions.R ## PMA package is needed to install CVR ## PMA depends on impute, which is removed from CRAN to bioconuctor ## Use the following to install impute ## (try http:// if https:// URLs are not supported) ## source("https://bioconductor.org/biocLite.R") ## biocLite("impute") ## useDynLib(CVR, .registration = TRUE) #' @useDynLib CVR #' @import Rcpp #' @import graphics #' @import stats #' @title Sparse canonical correlation analysis. #' #' @description Get sparse CCA solutions of X1 and X2. Use \code{CCA} and \code{CCA.permute} from PMA package. #' See PMA package for details. #' #' @usage SparseCCA(X1, X2, rank = 2, penaltyx1 = NULL, penaltyx2 = NULL, #' nperms = 25, ifplot = 0) #' @param X1,X2 Numeric matrices representing the two sets of covariates. They should have the same number of rows and #' cannot contain missing values. #' @param rank The number of canonical variate pairs wanted. The default is 2. #' @param penaltyx1,penaltyx2 Numeric vectors as the penalties to be applied to X1 and X2. The defaults are seq(0.1, 0.7, len = 20). #' See PMA package for details. #' @param nperms Number of times the data should be permuted. The default is 25. Don't use too small value. See PMA package for details. #' @param ifplot 0 or 1. The default is 0 which means don't plot the result. See PMA package for details. #' @details This function is generally used for tuning the penalties in sparse CCA if \code{penaltyx1} and \code{penaltyx2} are supplied as vectors. #' The CCA solution is based on PMD algorithm and the tuning is based on permutation. #' The fitted W1 and W2 are scaled so that the diagonals of W1'X1'X1W1 and W2'X2'X2W2 are all 1's. #' #' Specifically, if a single value of mild penalty is provided for both \code{penaltyx1} and \code{penaltyx2}, the result can be used as #' initial values of W's in CVR. For instance, with \code{penaltyx1 = 0.7} and \code{penaltyx2 = 0.7}, #' the fitted W1 and W2 are only shrinked, but mostly not zero yet. #' @return \item{W1}{Loading matrix corresponding to X1. X1*W1 gives the canonical variates from X1.} #' @return \item{W2}{Loading matrix corresponding to X2. X2*W2 gives the canonical variates from X2.} #' @author <NAME>, <NAME>. #' @references <NAME>, <NAME> and <NAME> (2009) A penalized matrix decomposition, with applications to #' sparse principal components and canonical correlation analysis. Biostatistics 10(3), 515-534. #' #' <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{CVR}}, \code{\link{CCA}}, \code{\link{CCA.permute}}. #' @import PMA #' @export SparseCCA <- function(X1, X2, rank = 2, penaltyx1 = NULL, penaltyx2 = NULL, nperms = 25, ifplot = 0){ if (nrow(X1) != nrow(X2)) stop("X1 and X2 should have the same row number!") if (ncol(X1) == 1 | ncol(X2) == 1) stop("X1 and X2 should have at least 2 columns!") if (is.null(penaltyx1) | is.null(penaltyx2)){ penaltyx1 <- seq(0.1, 0.7, len = 20) penaltyx2 <- seq(0.1, 0.7, len = 20) } if (length(penaltyx1) > 1){ perm.out <- CCA.permute(X1, X2, "standard", "standard", penaltyx1, penaltyx2, nperms = nperms) if (ifplot == 1 ) { print(c(perm.out$bestpenaltyx, perm.out$bestpenaltyz)) plot(perm.out) } SparseCCA_X12 <- CCA(X1, X2, typex = "standard", typez = "standard", K = rank, penaltyx = perm.out$bestpenaltyx, penaltyz = perm.out$bestpenaltyz, v = perm.out$v.init, trace = FALSE) } else { SparseCCA_X12 <- CCA(X1, X2, typex = "standard", typez = "standard", K = rank, penaltyx = penaltyx1, penaltyz = penaltyx2, trace = FALSE) } D1 <- diag(diag(t(X1 %*% SparseCCA_X12$u) %*% X1 %*% SparseCCA_X12$u)^(-0.5), rank, rank) D2 <- diag(diag(t(X2 %*% SparseCCA_X12$v) %*% X2 %*% SparseCCA_X12$v)^(-0.5), rank, rank) W1 <- SparseCCA_X12$u %*% D1 W2 <- SparseCCA_X12$v %*% D2 ## to make X1 %*% W1 orthogonal return(list(W1 = W1, W2 = W2)) } #' @title Generate simulation data. #' #' @description Generate two sets of covariates and an univariate response driven by several latent factors. #' #' @usage SimulateCVR(family = c("gaussian", "binomial", "poisson"), n = 100, #' rank = 4, p1 = 50, p2 = 70, pnz = 10, sigmax = 0.2, #' sigmay = 0.5, beta = c(2, 1, 0, 0), standardization = TRUE) #' #' @param family Type of response. \code{"gaussian"} for continuous response, \code{"binomial"} #' for binary response, and \code{"poisson"} for Poisson response. The default is \code{"gaussian"}. #' @param n Number of rows. The default is 100. #' @param rank Number of latent factors generating the covariates. The default is 4. #' @param p1 Number of variables in X1. The default is 50. #' @param p2 Number of variables in X2. The default is 70. #' @param pnz Number of variables in X1 and X2 related to the signal. The default is 10. #' @param sigmax Standard deviation of normal noise in X1 and X2. The default is 0.2. #' @param sigmay Standard deviation of normal noise in Y. Only used when the response is Gaussian. The default is 0.5. #' @param beta Numeric vector, the coefficients used to generate respose from the latent factors. The default is c(2, 1, 0, 0). #' @param standardization Logical. If TRUE, standardize X1 and X2 before output. The default is TRUE. #' #' @details The latent factors in U are randomly generated normal vectors, #' #' \eqn{X_1 = U*V_1 + \sigma_x*E_1, X_2 = U*V_2 + \sigma_x*E_2, E_1, E_2}{% #' X1 = U*V1 + sigmax*E1, X2 = U*V2 + sigmax*E2, E1, E2} are N(0,1) noise matrices. #' #' The nonzero entries of \eqn{V_1}{% #' V1} and \eqn{V_2}{% #' V2} are generated from Uniform([-1,-0.5]U[0.5,1]). #' #' For Gaussian response, #' #' \eqn{y = U*\beta + \sigma_y*e_y, e_y}{% #' y = U*\beta + sigmay*ey, ey} is N(0,1) noise vector, #' #' for binary response, #' #' \eqn{y \sim rbinom(n, 1, 1/(1 + \exp(-U*\beta)))}, #' #' and for Poisson response, #' #' \eqn{y \sim rpois(n, \exp(U*\beta))}. #' #' See the reference for more details. #' #' @return \item{X1, X2}{The two sets of covariates with dimensions n*p1 and n*p2 respectively.} #' @return \item{y}{The response vector with length n.} #' @return \item{U}{The true latent factor matrix with dimension n*rank.} #' @return \item{beta}{The coefficients used to generate response from \code{U}. The length is rank.} #' @return \item{V1, V2}{The true loading matrices for X1 and X2 with dimensions p1*rank and p2*rank. The first \code{pnz} rows are nonzero.} #' @author <NAME>, <NAME>. #' @references <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{CVR}}, \code{\link{cvrsolver}}. #' @examples #' set.seed(42) #' mydata <- SimulateCVR(family = "g", n = 100, rank = 4, p1 = 50, p2 = 70, #' pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1 #' X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' opts <- list(standardization = FALSE, maxIters = 300, tol = 0.005) #' ## use sparse CCA solution as initial values, see SparseCCA() #' Wini <- SparseCCA(X1, X2, 4, 0.7, 0.7) #' ## perform CVR with fixed eta and lambda, see cvrsolver() #' fit <- cvrsolver(Y, Xlist, rank = 4, eta = 0.5, Lam = c(1, 1), #' family = "gaussian", Wini, penalty = "GL1", opts) #' ## check sparsity recovery #' fit$W[[1]]; #' fit$W[[2]]; #' ## check orthogonality #' X1W1 <- X1 %*% fit$W[[1]]; #' t(X1W1) %*% X1W1 #' @export SimulateCVR <- function(family = c("gaussian", "binomial", "poisson"), n = 100, rank = 4, p1 = 50, p2 = 70, pnz = 10, sigmax = 0.2, sigmay = 0.5, beta = c(2, 1, 0, 0), standardization = TRUE){ family <- match.arg(family) U <- matrix(rnorm(2 * n * rank), 2 * n, rank); ## U = svd(U)$u*sqrt(n); # n by r V1 <- matrix(0, p1, rank); V11 <- matrix(runif(rank * pnz) * (rbinom(rank * pnz, 1, 0.5) * 2-1), ncol = rank); V2 <- matrix(0, p2, rank); V21 <- matrix(runif(rank * pnz) * (rbinom(rank * pnz, 1, 0.5) * 2 - 1), ncol = rank); V1[1:pnz, ] <- svd(V11)$u; V2[1:pnz, ] <- svd(V21)$u; x1 <- U %*% t(V1); x2 <- U %*% t(V2); lp <- U %*% beta; e1 <- matrix(rnorm(2 * n * p1), 2 * n, p1) * sigmax; e2 <- matrix(rnorm(2 * n * p2), 2 * n, p2) * sigmax; X1 <- x1[1:n, ] + e1[1:n, ]; X2 <- x2[1:n, ] + e2[1:n, ]; X1test <- x1[(n + 1):(2 * n), ] + e1[(n + 1):(2 * n), ]; X2test <- x2[(n + 1):(2 * n), ] + e2[(n + 1):(2 * n), ]; U <- U[1:n, ] if (family == "gaussian") { e <- rnorm(2 * n) * sigmay; y <- lp[1:n] + e[1:n]; ytest <- lp[(n + 1):(2 * n)] + e[(n + 1):(2 * n)]; if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1) V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); y <- scale(y); X1 <- scale(X1); X2 <- scale(X2);#/sqrt(n-1) ytest <- scale(ytest); X1test <- scale(X1test); X2test <- scale(X2test);#/sqrt(n-1) } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr.y <- sd(lp) / sd(e); snr <- c(snr.x1, snr.x2, snr.y) } else if (family == "binomial") { px <- 1 / (1 + exp(-lp)); y <- rbinom(n, 1, px[1:n]) ytest <- rbinom(n, 1, px[(n + 1):(2 * n)]) if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1); V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); X1 <- scale(X1); X2 <- scale(X2); X1test <- scale(X1test); X2test <- scale(X2test); } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr <- c(snr.x1, snr.x2, 0) } else if (family == "poisson") { px <- exp(lp); y <- rpois(n, px[1:n]) ytest <- rpois(n, px[(n + 1):(2 * n)]) if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1); V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); X1 <- scale(X1); X2 <- scale(X2); X1test <- scale(X1test); X2test <- scale(X2test); } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr <- c(snr.x1, snr.x2, 0) } ## X1test = X1test, X2test = X2test, ytest = as.matrix(ytest), x1 = x1, x2 = x2, lp = lp, snr = snr return(list(X1 = X1, X2 = X2, y = as.matrix(y), U = U, beta = beta, V1 = V1, V2 = V2)) } ## calculate area under ROC curve (AUC) and deviance in binomial case CalcROC <- function(y, px, ifplot = 0){ ## predict binomial response with given fitted prob px, ## compute AUC of ROC / (neg) deviance (use it instead of AUC, for small sample size) ## input: ## y: real response ## px: fitted prob seq ## output: ## list(spec = spec, sens = sens, auc = auc, dev = dev) n <- length(px); np <- sum(y == 1); nn <- n - np; sens <- c(); spec <- c(); if (np == 0) { auc <- sum(px < 0.5) / nn; } else if (nn == 0) { auc <- sum(px > 0.5) / np; } else { for (i in 1:n) { sens[i] <- (sum(px > px[i] & y == 1) + 0.5 * sum(px == px[i] & y == 1)) / np; spec[i] <- (sum(px < px[i] & y == 0) + 0.5 * sum(px == px[i] & y == 0)) / nn; } } if (ifplot == 1) plot(1 - spec, sens); ##auc = trapz(sort(1-spec),sort(sens)); xx <- sort(1 - spec, index.return = TRUE) yy <- c(0, sens[xx$ix], 1) xx <- c(0, xx$x, 1) auc <- sum((xx[-1] - xx[-(n + 2)]) * (yy[-1] + yy[-(n + 2)])) / 2 dev <- -2 * sum(y * log(px + 0.00001) + (1 - y) * log(1 - px + 0.0001)) return(list(spec = spec, sens = sens, auc = auc, dev = dev)) } ## calculate the error of testing data (mse, auc or deviance) using fitted W1, W2, alpha, beta PredCVR <- function(Ytest, X1test, X2test, W1, W2, alpha = 0, beta = 0, Y, X1, X2, family = "gaussian", refit = TRUE, combine = TRUE, type.measure = NULL){ ## compute the pred mse/AUC(deviance) of testing data X1testW1 <- X1test %*% W1; X2testW2 <- X2test %*% W2; if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if(length(Ytest) > 10 & is.null(type.measure)) type.measure <- "auc"; if(length(Ytest) < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure <- "deviance"; } if (refit) { X1W1 <- X1 %*% W1; X2W2 <- X2 %*% W2; XW <- cbind(X1W1, X2W2) XtestW <- cbind(X1testW1, X2testW2) if (family == "gaussian") { ## mse is the average of two predictions from X1testW1 and X2testW2 if (combine) { ab <- coef(lm(Y ~ XW)); ab[is.na(ab)] <- 0 mse <- sum((Ytest - ab[1] - XtestW %*% ab[-1])^2) / length(Ytest) } else { ab1 <- coef(lm(Y ~ X1W1)) ab2 <- coef(lm(Y ~ X2W2)) ab1[is.na(ab1)] <- 0; ab2[is.na(ab2)] <- 0; mse <- (sum((Ytest - ab1[1] - X1testW1 %*% ab1[-1])^2) + sum((Ytest - ab2[1] - X2testW2 %*% ab2[-1])^2)) / length(Ytest) / 2 } if (is.na(mse)) mse <- sum(Ytest^2) / length(Ytest) # for empty W1 and W2 return(mse) } else if (family == "binomial") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { ## avoid fitting glm with zero predictors if (type.measure == "auc") { return(0) } else if (type.measure == "deviance") { dev <- -2 * length(Ytest) * log(0.00001) return(dev) } } else { if (combine) { refit12 <- glm(Y ~ XW, family = "binomial") ab <- coef(refit12) ab[is.na(ab)] <- 0 px <- 1 / (1 + exp(-XtestW %*% ab[-1] - ab[1])) if (type.measure == "auc") { auc <- CalcROC(Ytest, px)$auc; return(auc) } else if (type.measure == "deviance") { dev <- CalcROC(Ytest, px)$dev; return(dev) } } else { refit1 <- glm(Y ~ X1W1, family = "binomial") refit2 <- glm(Y ~ X2W2, family = "binomial") ab1 <- coef(refit1) ab2 <- coef(refit2) ab1[is.na(ab1)] <- 0 ab2[is.na(ab2)] <- 0 px1 <- 1 / (1 + exp(-X1testW1 %*% ab1[-1] - ab1[1])) px2 <- 1 / (1 + exp(-X2testW2 %*% ab2[-1] - ab2[1])) if (type.measure == "auc") { auc <- (CalcROC(Ytest, px1)$auc + CalcROC(Ytest, px2)$auc) / 2 return(auc) } else if (type.measure == "deviance") { dev <- (CalcROC(Ytest, px1)$dev + CalcROC(Ytest, px2)$dev) / 2 return(dev) } } } } else if (family == "poisson") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { dev <- -2 * length(Ytest) * log(0.000001) return(dev) } else { if (combine) { refit12 <- glm(Y ~ XW, family = "poisson") ab <- coef(refit12) ab[is.na(ab)] <- 0 px <- exp(XtestW %*% ab[-1] + ab[1]) dev <- -2 * sum(Ytest * log(px) - px) return(dev) } else { refit1 <- glm(Y ~ X1W1, family = "poisson") refit2 <- glm(Y ~ X2W2, family = "poisson") ab1 <- coef(refit1); ab2 <- coef(refit2) ab1[is.na(ab1)] <- 0; ab2[is.na(ab2)] <- 0 px1 <- exp(X1testW1 %*% ab1[-1] + ab1[1]) px2 <- exp(X2testW2 %*% ab2[-1] + ab2[1]) dev <- -sum(Ytest * log(px1) - px1) - sum(Ytest * log(px2) - px2) return(dev) } } } } else { if (family == "gaussian") { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta mse <- sum((Ytest - lp1)^2 + (Ytest - lp2)^2) / length(Ytest) / 2 return(mse) } else if (family == "binomial") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { if (type.measure == "auc") { return(0) } else if (type.measure == "deviance") { dev <- -2 * length(Ytest) * log(0.00001) return(dev) } } else { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta px1 <- 1 / (1 + exp(-lp1)) px2 <- 1 / (1 + exp(-lp2)) if (type.measure == "auc") { auc <- (CalcROC(Ytest, px1)$auc + CalcROC(Ytest, px2)$auc) / 2 return(auc) } else if (type.measure == "deviance") { dev <- (CalcROC(Ytest, px1)$dev + CalcROC(Ytest, px2)$dev) / 2 return(dev) } } } else if (family == "poisson") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { dev <- -2 * length(Ytest) * log(0.000001) return(dev) } else { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta px1 <- exp(lp1) px2 <- exp(lp2) dev <- -sum(Ytest * log(px1) - px1) - sum(Ytest * log(px2) - px2) return(dev) } } } } ## calculate solution path of CVR (along the sequence of lambda) CVRPath <- function(Y, Xlist, rank = 2, eta = 0.5, Lamseq, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), opts){ family <- match.arg(family) penalty <- match.arg(penalty) Y <- as.matrix(Y) K <- length(Xlist) if (dim(Lamseq)[2] != K) stop("The length of Lambda is not the same to K!"); nlam <- dim(Lamseq)[1] family <- match.arg(family) penalty <- match.arg(penalty) if (is.null(Wini)) Wini <- SparseCCA(Xlist[[1]], Xlist[[2]], rank, 0.7, 0.7) p <- c() WPath <- list() for (k in 1:K) { p[k] <- dim(Xlist[[k]])[2] WPath[[k]] <- array(0, c(nlam, p[k], rank)); } betaPath <- matrix(0, nlam, rank) alphaPath <- rep(0, nlam) iterPath <- rep(0, nlam) fitwork <- list() warm <- TRUE Wwork <- Wini for (i in 1:nlam){ if (i == 1) { optswork <- opts; optswork$maxIters <- 2 * opts$maxIters; } else { optswork <- opts; if (warm) Wwork <- fitwork$W; ## warm start } fitwork <- cvrsolver(Y, Xlist, rank, eta, as.vector(Lamseq[i, ]), family, Wwork, penalty, optswork); Wzero <- 0 for (k in 1:K) Wzero <- Wzero + sum(fitwork$W[[k]]!=0); if (Wzero == 0) break; for (k in 1:K) WPath[[k]][i, , ] <- fitwork$W[[k]]; betaPath[i, ] <- fitwork$beta; alphaPath[i] <- fitwork$alpha; iterPath[i] <- fitwork$iter } return(list(WPath = WPath, betaPath = betaPath, alphaPath = alphaPath, iterPath = iterPath)) } ## cross validate to select lambda, with fixed rank and eta TuneCVR <- function(Y, Xlist, rank, eta, Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, type.measure = NULL, opts){ ## cross-validate to select lam's ## input: Lamseq: nlam by K, K=2 ## output: list(Lamseq = Lamseq, cverror = pred, cvm = mpred, msparse = msparse, ## Lamhat = Lamhat, W1trace = W1trace, W2trace = W2trace, cvr.fit = fit, ## alpha = alpha.refit, beta = beta.refit, type.measure = type.measure) ## cvr.fit: Refit all the data using the selected parameters, ## see the output of cvrsolver(). Also output the coefficients of regressing ## the response to the combined fitted canonical variates (Y ~ cbind(X1W1, X2W2)). ## family <- match.arg(family) penalty <- match.arg(penalty) Y <- as.matrix(Y) n <- dim(Y)[1] K <- length(Xlist) X1 <- as.matrix(Xlist[[1]]) X2 <- as.matrix(Xlist[[2]]) p1 <- ncol(X1) p2 <- ncol(X2) if (is.null(Wini)) Wini <- SparseCCA(X1, X2, rank, 0.7, 0.7) if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if (n / nfold > 10 & is.null(type.measure)) type.measure <- "auc"; if (n / nfold < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure <- "deviance"; } warm <- TRUE; opts$nrank <- rank opts$family <- family opts$penalty <- penalty Lamseq <- as.matrix(Lamseq) if (dim(Lamseq)[2] != K) { lamseq <- 10^(seq(-2, 1.3, len = 50)) Lamseq <- cbind(lamseq, lamseq * p2 / p1) } nlam <- dim(Lamseq)[1]; pred <- matrix(0, nlam, nfold); itertrace <- matrix(0, nlam, nfold) W1trace <- array(0, c(nlam, nfold, p1, rank)) W2trace <- array(0, c(nlam, nfold, p2, rank)) sparse <- matrix(0, nlam, nfold) # monitor sparsity if (is.null(foldid)) { tmp <- ceiling(c(1:n) / (n / nfold)); foldid <- sample(tmp, n) } for (i in 1:nfold) { X1train <- Xlist[[1]][foldid != i, ]; X2train <- Xlist[[2]][foldid != i, ]; Xtrain <- list(X1 = X1train, X2 = X2train); Ytrain <- as.matrix(Y[foldid != i, ]); X1test <- Xlist[[1]][foldid == i, ]; X2test <- Xlist[[2]][foldid == i, ]; Ytest <- as.matrix(Y[foldid == i, ]); if (is.null(opts$W)) opts$W = SparseCCA(X1train, X2train, rank, 0.7, 0.7) obj <- CVRPath(Ytrain, Xtrain, rank, eta, Lamseq, family, opts$W, penalty, opts); W1trace[, i, , ] <- obj$WPath[[1]] W2trace[, i, , ] <- obj$WPath[[2]] itertrace[, i] <- obj$iterPath for (j in 1:nlam){ W1 <- obj$WPath[[1]][j, , ] W2 <- obj$WPath[[2]][j, , ] ## sparse = proportion of nonzero elements among W1 and W2 sparse[j, i] <- (sum(W1 != 0) + sum(W2 != 0)) / (length(W1) + length(W2)) alpha <- as.numeric(obj$alphaPath[j]) beta <- obj$betaPath[j, ] pred[j, i] <- PredCVR(Ytest, X1test, X2test, W1, W2, alpha, beta, Ytrain, X1train, X2train, family = family, refit = TRUE, type.measure = type.measure) } } mpred <- apply(pred, 1, mean) msparse <- apply(sparse, 1, mean) spthresh <- opts$spthresh if (type.measure == "mse" | type.measure == "deviance") { ## search the best lam only among sparse models ilam <- which.min(mpred[msparse <= spthresh]) + min(which(msparse <= spthresh)) - 1 ifold <- which.min(pred[ilam, ]) mmpred <- min(mpred[msparse <= spthresh]) } else if (type.measure == "auc") { ilam <- which.max(mpred[msparse <= spthresh]) + min(which(msparse <= spthresh)) - 1 ifold <- which.max(pred[ilam, ]) mmpred <- max(mpred[msparse <= spthresh]) } Lamhat <- Lamseq[ilam, ] ## refit all the data with Lamhat if (warm) { Wini <- list(W1 = as.matrix(W1trace[max(ilam - 1, 1), ifold, , ]), W2 = as.matrix(W2trace[max(ilam - 1, 1), ifold, , ])) } fit <- cvrsolver(Y, Xlist, rank, eta, Lamhat, family, Wini, penalty, opts) XW <- cbind(X1 %*% fit$W[[1]], X2 %*% fit$W[[2]]) if (family == "gaussian") { ab <- coef(lm(Y ~ XW)); ab[is.na(ab)] <- 0 alpha.refit <- ab[1] beta.refit <- ab[-1] } else { ab <- coef(glm(Y ~ XW, family = family)) ab[is.na(ab)] <- 0 alpha.refit <- ab[1] beta.refit <- ab[-1] } refit <- list(alpha = alpha.refit, beta = beta.refit, W = fit$W) cv.out <- list(Lamseq = Lamseq, eta = eta, rank = rank, cverror = pred, cvm = mpred, mmpred = mmpred, msparse = msparse, Lamhat = Lamhat, W1trace = W1trace, W2trace = W2trace, cvr.fit = fit, refit = refit, type.measure = type.measure, spthresh = spthresh) class(cv.out) <- "TuneCVR" return(cv.out) } ## plot mean cv error and sparsity of the solution path from TuneCVR objects plot.TuneCVR <- function(x) { par(mfrow = c(2, 1)) plot(log(x$Lamseq[, 1]), x$cvm, xlab="", ylab = x$type.measure, type = "l", col = "red", main = paste("CVR(eta = ", round(x$eta, 5), ", rank = ", x$rank, ")", sep="")) abline(v = log(x$Lamhat[1])) plot(log(x$Lamseq[, 1]), x$msparse, xlab = expression(log ~ lambda), ylab = "sparsity", type = "l") abline(h = x$spthresh) } #' @title Fit canonical variate regression with tuning parameters selected by cross validation. #' #' @description This function fits the solution path of canonical variate regression, #' with tuning parameters selected by cross validation. The tuning parameters #' include the rank, the \eqn{\eta} and the \eqn{\lambda}. #' @usage #' CVR(Y, Xlist, rankseq = 2, neta = 10, etaseq = NULL, nlam = 50, #' Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), #' Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, #' opts = list(), type.measure = NULL) #' #' @param Y A univariate response variable. #' @param Xlist A list of two covariate matrices as in \code{cvrsolver}. #' @param rankseq A sequence of candidate ranks. The default is a single value 2. #' @param neta Number of \eqn{\eta} values. The default is 10. #' @param etaseq A sequence of length \code{neta} containing candidate \eqn{\eta} values between 0 and 1. #' The default is 10^seq(-2, log10(0.9), length = neta). #' @param nlam Number of \eqn{\lambda} values. The default is 50. #' @param Lamseq A matrix of \eqn{\lambda} values. The column number is the number of sets in \code{Xlist}, #' and the row number is \code{nlam}. The default is 10^(seq(-2, 2, length = nlam)) for each column. #' @param family Type of response as in \code{cvrsolver}. The default is \code{"gaussian"}. #' @param Wini A list of initial loading W's. The default is from the SparseCCA solution. See \code{SparseCCA}. #' @param penalty Type of penalty on loading matrices W's as in \code{cvrsolver}. The default is \code{"GL1"}. #' @param nfold Number of folds in cross validation. The default is 10. #' @param foldid Specifying training and testing sets in cross validation; random generated if not supplied. #' It remains the same across different rank and \eqn{\eta}. #' @param opts A list of options for controlling the algorithm. The default of \code{opts$spthresh} is 0.4, which means #' we only search sparse models with at most 40\% nonzero entries in W1 and W2. See the other options #' (\code{standardization}, \code{maxIters} and \code{tol}) in \code{cvrsolver}. #' @param type.measure Type of measurement used in cross validation. \code{"mse"} for Gaussian, \code{"auc"} for binomial, #' and \code{"deviance"} for binomial and Poisson. #' #' @details In this function, the rank, \eqn{\eta} and \eqn{\lambda} are tuned by cross validation. CVR then is refitted with #' all data using the selected tuning parameters. The \code{plot} function shows the tuning of \eqn{\lambda}, #' with selected rank and \eqn{\eta}. #' #' @return An object with S3 class "CVR" containing the following components #' @return \item{cverror}{A matrix containing the CV errors. The number of rows is the length #' of \code{etaseq} and the number of columns is the length of \code{rankseq}.} #' @return \item{etahat}{Selected \eqn{\eta}.} #' @return \item{rankhat}{Selected rank.} #' @return \item{Lamhat}{Selected \eqn{\lambda}'s.} #' @return \item{Alphapath}{An array containing the fitted paths of the intercept term \eqn{\alpha}.} #' @return \item{Betapath}{An array containing the fitted paths of the regression coefficient \eqn{\beta}.} #' @return \item{W1path, W2path}{Arrays containing the fitted paths of W1 and W2.} #' @return \item{foldid}{\code{foldid} used in cross validation.} #' @return \item{cvout}{Cross validation results using selected \eqn{\eta} and rank.} #' @return \item{solution}{A list including the solutions of \eqn{\alpha}, \eqn{\beta}, W1 and W2, by refitting all the data #' using selected tuning parameters.} #' #' @author <NAME>, <NAME>. #' #' @references <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{cvrsolver}}, \code{\link{SparseCCA}}, \code{\link{SimulateCVR}}. #' @examples #' ############## Gaussian response ###################### #' set.seed(42) #' mydata <- SimulateCVR(family = "g", n = 100, rank = 4, p1 = 50, p2 = 70, #' pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1; #' X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## fix rank = 4, tune eta and lambda #' ##out_cvr <- CVR(Y, Xlist, rankseq = 4, neta = 5, nlam = 25, #' ## family = "g", nfold = 5) #' ## out_cvr$solution$W[[1]]; #' ## out_cvr$solution$W[[2]]; #' ### uncomment to see plots #' ## plot.CVR(out_cvr) #' ## #' ## Distance of subspaces #' ##U <- mydata$U #' ##Pj <- function(U) U %*% solve(t(U) %*% U, t(U)) #' ##sum((Pj(U) - (Pj(X1 %*% out_cvr$sol$W[[1]]) + Pj(X2 %*% out_cvr$sol$W[[2]]))/2)^2) #' ## Precision/Recall rate #' ## the first 10 rows of the true W1 and W2 are set to be nonzero #' ##W12 <- rbind(out_cvr$sol$W[[1]], out_cvr$sol$W[[1]]) #' ##W12norm <- apply(W12, 1, function(a)sqrt(sum(a^2))) #' ##prec <- sum(W12norm[c(1:10, 51:60)] != 0)/sum(W12norm != 0); prec #' ##rec <- sum(W12norm[c(1:10, 51:60)] != 0)/20; rec #' ## sequential SparseCCA, compare the Distance of subspaces and Prec/Rec #' ##W12s <- SparseCCA(X1, X2, 4) #' ## Distance larger than CVR's #' ##sum((Pj(U) - (Pj(X1 %*% W12s$W1) + Pj(X2 %*% W12s$W2))/2)^2) #' ##W12snorm <- apply(rbind(W12s$W1, W12s$W2), 1, function(a)sqrt(sum(a^2))) #' ## compare Prec/Rec #' ##sum(W12snorm[c(1:10, 51:60)] != 0)/sum(W12snorm != 0); #' ##sum(W12snorm[c(1:10, 51:60)] != 0)/20; #' #' ############## binary response ######################## #' set.seed(12) #' mydata <- SimulateCVR(family = "binomial", n = 300, rank = 4, p1 = 50, #' p2 = 70, pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1; X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## out_cvr <- CVR(Y, Xlist, 4, neta = 5, nlam=25, family = "b", nfold = 5) #' ## out_cvr$sol$W[[1]]; #' ## out_cvr$sol$W[[2]]; #' ## plot.CVR(out_cvr) #' #' ############## Poisson response ###################### #' set.seed(34) #' mydata <- SimulateCVR(family = "p", n = 100, rank = 4, p1 = 50, #' p2 = 70, pnz = 10, beta = c(0.2, 0.1, 0, 0)) #' X1 <- mydata$X1; X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## etaseq <- 10^seq(-3, log10(0.95), len = 10) #' ## out_cvr <- CVR(Y, Xlist, 4, neta = 5, nlam = 25, family = "p", nfold = 5) #' ## out_cvr$sol$W[[1]]; #' ## out_cvr$sol$W[[2]]; #' ## plot.CVR(out_cvr) #' @export CVR <- function(Y, Xlist, rankseq = 2, neta = 10, etaseq = NULL, nlam = 50, Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, opts = list(), type.measure = NULL){ family <- match.arg(family) penalty <- match.arg(penalty) if(is.null(family)) stop('Must specify family of the response!') if(is.null(penalty)) { penalty = "GL1"; cat('Use default: penalty = "GL1".\n') } Y <- as.matrix(Y) X1 <- as.matrix(Xlist[[1]]) X2 <- as.matrix(Xlist[[2]]) Xlist <- list(X1 = X1, X2 = X2) n <- dim(Y)[1] p1 <- ncol(X1) p2 <- ncol(X2) if(p1 == 1 | p2 == 1) stop("X1 and X2 should have at least 2 columns!") if(nrow(X1) != nrow(X2)) stop("X1 and X2 should have the same row number!") if(n != nrow(X1)) stop("Y and X1, X2 should have the same row number!") opts$n <- n opts$p1 <- p1 opts$p2 <- p2 mrank <- max(rankseq) if (is.null(Wini)) { Wini <- SparseCCA(X1, X2, mrank, 0.7, 0.7); cat('Use default: initial W = SparseCCA(X1, X2, rank, 0.7, 0.7).\n') } if (is.null(opts$standardization)) { opts$standardization <- TRUE; #cat('Use default: standardization = TRUE.\n') } if (is.null(opts$maxIters)) { opts$maxIters <- 300; #cat('Use default: maxIters = 300.\n') } if (is.null(opts$tol)) { opts$tol <- 0.01; #cat('Use default: tol = 0.01.\n') } if (is.null(opts$spthresh)) { spthresh <- 0.4 opts$spthresh = spthresh; #cat('Use default: spthresh = 0.4.\n') } if (is.null(etaseq)) { if(is.null(neta)) neta <- 10 etaseq <- 10^seq(-2, log10(0.9), len = neta) } if (is.null(Lamseq)) { if (is.null(nlam)) nlam <- 50 lamseq <- 10^(seq(-2, 2, len = nlam)) Lamseq <- cbind(lamseq, lamseq) } if (is.null(foldid)) { if(is.null(nfold)) nfold <- 10 tmp <- ceiling(c(1:n)/(n/nfold)); foldid <- sample(tmp, n) } else { if(nfold != length(unique(foldid))){ #warning("nfold not equal to no. unique values in foldid") nfold <- length(unique(foldid)) } } if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if (n / nfold > 10 & is.null(type.measure)) type.measure <- "auc"; if (n / nfold < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure = "deviance"; } Lr <- length(rankseq) Leta <- length(etaseq) pred <- matrix(0, Leta, Lr) Lamhat <- matrix(0, Leta, Lr) Alphapath <- matrix(0, Leta, Lr) Betapath <- array(0, c(Leta, Lr, mrank)) W1path <- array(0, c(Leta, Lr, p1, mrank)) W2path <- array(0, c(Leta, Lr, p2, mrank)) for (ir in 1:Lr) { for (ieta in 1:Leta) { obj_cv <- TuneCVR(Y, Xlist, rankseq[ir], etaseq[ieta], Lamseq, family, Wini, penalty, nfold = nfold, foldid = foldid, type.measure = type.measure, opts) pred[ieta, ir] <- obj_cv$mmpred Lamhat[ieta, ir] <- obj_cv$Lamhat[1] Alphapath[ieta, ir] <- obj_cv$cvr.fit$alpha Betapath[ieta, ir, 1:rankseq[ir]] <- obj_cv$cvr.fit$beta W1path[ieta, ir, , 1:rankseq[ir]] <- obj_cv$cvr.fit$W[[1]] W2path[ieta, ir, , 1:rankseq[ir]] <- obj_cv$cvr.fit$W[[2]] } } if (type.measure == "mse" | type.measure == "deviance") { ind <- apply(pred, 2, which.min) ind2 <- which.min(apply(pred, 2, min)) mmpred <- min(pred) } else if (type.measure == "auc") { ind <- apply(pred, 2, which.max) ind2 <- which.max(apply(pred, 2, max)) mmpred <- max(pred) } etahat <- etaseq[ind[ind2]] rankhat <- rankseq[ind2] cvout <- TuneCVR(Y, Xlist, rankhat, etahat, Lamseq, family, Wini, penalty, nfold, foldid = foldid, type.measure, opts) cvrout <- list(cverror = pred, etahat = etahat, rankhat = rankhat, Lamhat = Lamhat, Alphapath = Alphapath, Betapath = Betapath, W1path = W1path, W2path = W2path, foldid = foldid, cvout = cvout, solution = append(cvout$refit, list(rankseq = rankseq, etaseq = etaseq, Lamseq = Lamseq))) class(cvrout) <- "CVR" return(cvrout) } #' @title Plot a CVR object. #' #' @description Plot the tuning of CVR #' #' @usage #' \method{plot}{CVR}(x, ...) #' #' @param x A CVR object. #' @param ... Other graphical parameters used in plot. #' #' @details The first plot is mean cv error vs log(\eqn{\lambda}). The type of mean cv error is #' decided by \code{type.measure} (see parameters of \code{CVR}). The selected \eqn{\lambda} is marked #' by a vertical line in the plot. The second plot is sparsity vs log(\eqn{\lambda}). #' Sparsity is the proportion of non-zero elements in fitted W1 and W2. #' The threshold is marked by a horizontal line. #' Press ENTER to see the second plot, which shows the tuning of \eqn{\eta}. #' @export plot.CVR <- function(x, ...) { plot.TuneCVR(x$cvout) cat ("Press [enter] to continue") line <- readline() par(mfrow = c(1, 1)) plot(x$cverror[, which(x$solution$rankseq == x$rankhat)] ~ log10(x$solution$etaseq), xlab = "log10(etaseq)", ylab = x$cvout$type.measure, main = "CVR(tune eta)") } <file_sep>/R/RcppExports.R # Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: <PASSWORD> #' @title Canonical Variate Regression. #' #' @description Perform canonical variate regression with a set of fixed tuning parameters. #' #' @usage cvrsolver(Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) #' #' @param Y A response matrix. The response can be continuous, binary or Poisson. #' @param Xlist A list of covariate matrices. Cannot contain missing values. #' @param rank Number of pairs of canonical variates. #' @param eta Weight parameter between 0 and 1. #' @param Lam A vector of penalty parameters \eqn{\lambda} for regularizing the loading matrices #' corresponding to the covariate matrices in \code{Xlist}. #' @param family Type of response. \code{"gaussian"} if Y is continuous, \code{"binomial"} if Y is binary, and \code{"poisson"} if Y is Poisson. #' @param Wini A list of initial loading matrices W's. It must be provided. See \code{cvr} and \code{scca} for using sCCA solution as the default. #' @param penalty Type of penalty on W's. "GL1" for rowwise sparsity and #' "L1" for entrywise sparsity. #' @param opts A list of options for controlling the algorithm. Some of the options are: #' #' \code{standardization}: need to standardize the data? Default is TRUE. #' #' \code{maxIters}: maximum number of iterations allowed in the algorithm. The default is 300. #' #' \code{tol}: convergence criterion. Stop iteration if the relative change in the objective is less than \code{tol}. #' #' @details CVR is used for extracting canonical variates and also predicting the response #' for multiple sets of covariates (Xlist = list(X1, X2)) and response (Y). #' The covariates can be, for instance, gene expression, SNPs or DNA methylation data. #' The response can be, for instance, quantitative measurement or binary phenotype. #' The criterion minimizes the objective function #' #' \deqn{(\eta/2)\sum_{k < j} ||X_kW_k - X_jW_j||_F^2 + (1-\eta)\sum_{k} l_k(\alpha, \beta, Y,X_kW_k) #' + \sum_k \rho_k(\lambda_k, W_k),}{% #' (\eta/2) \Sigma_\{k<j\}||X_kW_k - X_jW_j||_F^2 + (1 - \eta) \Sigma_k l_k(\alpha, \beta, Y, X_kW_k) + \Sigma_k \rho_k(\lambda_k, W_k),} #' s.t. \eqn{W_k'X_k'X_kW_k = I_r,} for \eqn{k = 1, 2, \ldots, K}. #' \eqn{l_k()} are general loss functions with intercept \eqn{\alpha} and coefficients \eqn{\beta}. \eqn{\eta} is the weight parameter and #' \eqn{\lambda_k} are the regularization parameters. \eqn{r} is the rank, i.e. the number of canonical pairs. #' By adjusting \eqn{\eta}, one can change the weight of the first correlation term and the second prediction term. #' \eqn{\eta=0} is reduced rank regression and \eqn{\eta=1} is sparse CCA (with orthogonal constrained W's). By choosing appropriate \eqn{\lambda_k} #' one can induce sparsity of \eqn{W_k}'s to select useful variables for predicting Y. #' \eqn{W_k}'s with \eqn{B_k}'s and (\eqn{\alpha, \beta}) are iterated using an ADMM algorithm. See the reference for details. #' #' @return An object containing the following components #' \item{iter}{The number of iterations the algorithm takes.} #' @return \item{W}{A list of fitted loading matrices.} #' @return \item{B}{A list of fitted \eqn{B_k}'s.} #' @return \item{Z}{A list of fitted \eqn{B_kW_k}'s.} #' @return \item{alpha}{Fitted intercept term in the general loss term.} #' @return \item{beta}{Fitted regression coefficients in the general loss term.} #' @return \item{objvals}{A sequence of the objective values.} #' @author <NAME>, <NAME>. #' @references <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @examples ## see SimulateCVR for simulation examples, see CVR for parameter tuning. #' @seealso \code{\link{SimulateCVR}}, \code{\link{CVR}}. #' @export cvrsolver <- function(Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) { .Call('CVR_cvrsolver', PACKAGE = 'CVR', Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) } <file_sep>/R/alcohol.R #' Data sets for the alcohol dependence example #' #' A list of 3 data frames that contains the gene expression, #' DNA methylation and AUD (alcohol use disorder) of 46 human subjects. #' The data is already screened for quality control. #' For the raw data see the link below. For more details see the reference. #' #' @format A list of 3 data frames: #' \describe{ #' \item{gene}{Human gene expression. A data frame of 46 rows and 300 columns.} #' \item{meth}{Human DNA methylation. A data frame of 46 rows and 500 columns.} #' \item{disorder}{Human AUD indicator. A data frame of 46 rows and 1 column. #' The first 23 subjects are AUDs and the others are matched controls.} #' } #' #' @examples #' ############## Alcohol dependence example ###################### #' data(alcohol) #' gene <- scale(as.matrix(alcohol$gene)) #' meth <- scale(as.matrix(alcohol$meth)) #' disorder <- as.matrix(alcohol$disorder) #' alcohol.X <- list(X1 = gene, X2 = meth) #' \dontrun{ #' foldid <- c(rep(1:5, 4), c(3,4,5), rep(1:5, 4), c(1,2,5)) #' ## table(foldid, disorder) #' ## there maybe warnings due to the glm refitting with small sample size #' alcohol.cvr <- CVR(disorder, alcohol.X, rankseq = 2, etaseq = 0.02, #' family = "b", penalty = "L1", foldid = foldid ) #' plot(alcohol.cvr) #' plot(gene %*% alcohol.cvr$solution$W[[1]][, 1], meth %*% alcohol.cvr$solution$W[[2]][, 1]) #' cor(gene %*% alcohol.cvr$solution$W[[1]], meth %*% alcohol.cvr$solution$W[[2]]) #' } #' #' @references <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @source Alcohol dependence: \url{http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE49393}. "alcohol" <file_sep>/src/cvrsolver.cpp #include <RcppArmadillo.h> using namespace Rcpp; using namespace std; using namespace arma; //// [[Rcpp::export]] arma::mat Newtonlogistic(arma::mat GZ, arma::mat B, arma::mat alpha, arma::mat beta, double mu, arma::mat Y, double h, arma::mat Zini){ int maxiter = 20; int n = GZ.n_rows; int q = GZ.n_cols; arma::mat Z = Zini; arma::mat M = - GZ/h + B*beta + ones(n, 1)*alpha; arma::mat expZ, dz, Hz; // arma::vec funcVal, diff=ones(1); // double diffend = 1; int iter = 0; for (iter = 0; iter < maxiter; iter++){ expZ = exp(Z); dz = - mu*(Y - expZ/(1+expZ))/n + h*(Z - M); Hz = mu*expZ/square(1+expZ)/n + h; Hz = Hz*ones(1, q); Z = Z - dz/Hz; // funcVal = join_cols(funcVal, (-mu*(accu(Z.t()*Y) - accu(log(1+exp(Z))))/n + h/2*accu(square(Z-M)))*ones(1, 1)); // if (iter > 0){ // diffend = (funcVal(iter)-funcVal(iter-1))/abs(funcVal(iter-1)); // diff = join_cols(diff, diffend*ones(1, 1)); // } // if (abs(diffend) < 1e-6) break; } //Rcpp::List out; //out["Z"] = Z; // out["iter"] = iter; // out["funcVal"] = funcVal; // out["diff"] = diff; //return(out); return(Z); } //// [[Rcpp::export]] arma::mat Newtonpoisson(arma::mat GZ, arma::mat B, arma::mat alpha, arma::mat beta, double mu, arma::mat Y, double h, arma::mat Zini){ int maxiter = 20; int n = GZ.n_rows; int q = GZ.n_cols; arma::mat Z = Zini; arma::mat M = - GZ/h + B*beta + ones(n, 1)*alpha; arma::mat expZ, dz, Hz; // arma::vec funcVal, diff=ones(1); // double diffend = 1; int iter = 0; for (iter = 0; iter < maxiter; iter++){ expZ = exp(Z); dz = - mu*(Y - expZ)/n + h*(Z - M); Hz = mu*expZ/n + h; Hz = Hz*ones(1, q); Z = Z - dz/Hz; // funcVal = join_cols(funcVal, (-mu*(accu(Z.t()*Y) - accu(exp(Z)))/n + h/2*accu(square(Z-M)))*ones(1, 1)); // if (iter > 0){ // diffend = (funcVal(iter)-funcVal(iter-1))/abs(funcVal(iter-1)); // diff = join_cols(diff, diffend*ones(1, 1)); // } // if (abs(diffend) < 1e-6) break; } // Rcpp::List out; // out["Z"] = Z; // out["iter"] = iter; // out["funcVal"] = funcVal; // out["diff"] = diff; //return(out); return(Z); } //// [[Rcpp::export]] arma::mat MGlasso_C(arma::mat Y, arma::mat X, arma::vec lam, arma::mat B0, double conv, int maxiter) { // min_B {|Y-XB|^2 + lam*|B|} //cout << "checknode1" << endl; int p=X.n_cols, iter=0, j; // n=Y.n_rows, q=Y.n_cols, double diff=10*conv, l2B1; rowvec sh; arma::mat mat1=eye(p,p), B1, res1, res1j, XRj; // Rcpp::List out; //cout << "checknode2" << endl; if (lam.size() == 1) {lam = as_scalar(lam)*ones(p);} sh = sum(square(X), 0); if (B0.is_finite()) { B1 = B0; } else { //B1 = inv(X.t()*X)*X.t()*Y; //OLS Rcpp::Rcout <<"B need to be initialized"<< std::endl; // cout << "B need to be initialized" << endl; //Rcpp::List ini = RRR_C(Y, X, 1, FALSE, mat1, TRUE, TRUE); //arma::mat iniC = ini["C_ls"]; //B1 = iniC; B1 = solve(X.t()*X, X.t()*Y, solve_opts::fast + solve_opts::no_approx); } //cout << "X*B1:" <<size(X*B1) << endl; res1 = Y - X * B1; while ((diff > conv) & (iter < maxiter)) { B0 = B1; for (j = 0; j < p; j++) { res1j = res1 + X.col(j)* B1.row(j); //n q XRj = trans(X.col(j)) * res1j; //1 q rowvec t1=XRj/as_scalar(sh(j))*max(0.0,1-lam(j)/sqrt(accu(square(XRj)))); B1.row(j) = t1; res1 = res1j - X.col(j)* B1.row(j); } l2B1 = accu(square(B1)); if (l2B1 == 0) { iter = maxiter; } else { diff = sqrt(accu(square(B0 - B1))/l2B1); iter = iter + 1; } } //cout << "checknode3" << endl; //sse = accu(square(Y - X * B0)); //out["B"] = B1; //out["sse"] = sse; //out["iter"] = iter; return(B1); } //////////////////////////////////////////////////// //////////////////////////////////////////////////// //' @title Canonical Variate Regression. //' //' @description Perform canonical variate regression with a set of fixed tuning parameters. //' //' @usage cvrsolver(Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) //' //' @param Y A response matrix. The response can be continuous, binary or Poisson. //' @param Xlist A list of covariate matrices. Cannot contain missing values. //' @param rank Number of pairs of canonical variates. //' @param eta Weight parameter between 0 and 1. //' @param Lam A vector of penalty parameters \eqn{\lambda} for regularizing the loading matrices //' corresponding to the covariate matrices in \code{Xlist}. //' @param family Type of response. \code{"gaussian"} if Y is continuous, \code{"binomial"} if Y is binary, and \code{"poisson"} if Y is Poisson. //' @param Wini A list of initial loading matrices W's. It must be provided. See \code{cvr} and \code{scca} for using sCCA solution as the default. //' @param penalty Type of penalty on W's. "GL1" for rowwise sparsity and //' "L1" for entrywise sparsity. //' @param opts A list of options for controlling the algorithm. Some of the options are: //' //' \code{standardization}: need to standardize the data? Default is TRUE. //' //' \code{maxIters}: maximum number of iterations allowed in the algorithm. The default is 300. //' //' \code{tol}: convergence criterion. Stop iteration if the relative change in the objective is less than \code{tol}. //' //' @details CVR is used for extracting canonical variates and also predicting the response //' for multiple sets of covariates (Xlist = list(X1, X2)) and response (Y). //' The covariates can be, for instance, gene expression, SNPs or DNA methylation data. //' The response can be, for instance, quantitative measurement or binary phenotype. //' The criterion minimizes the objective function //' //' \deqn{(\eta/2)\sum_{k < j} ||X_kW_k - X_jW_j||_F^2 + (1-\eta)\sum_{k} l_k(\alpha, \beta, Y,X_kW_k) //' + \sum_k \rho_k(\lambda_k, W_k),}{% //' (\eta/2) \Sigma_\{k<j\}||X_kW_k - X_jW_j||_F^2 + (1 - \eta) \Sigma_k l_k(\alpha, \beta, Y, X_kW_k) + \Sigma_k \rho_k(\lambda_k, W_k),} //' s.t. \eqn{W_k'X_k'X_kW_k = I_r,} for \eqn{k = 1, 2, \ldots, K}. //' \eqn{l_k()} are general loss functions with intercept \eqn{\alpha} and coefficients \eqn{\beta}. \eqn{\eta} is the weight parameter and //' \eqn{\lambda_k} are the regularization parameters. \eqn{r} is the rank, i.e. the number of canonical pairs. //' By adjusting \eqn{\eta}, one can change the weight of the first correlation term and the second prediction term. //' \eqn{\eta=0} is reduced rank regression and \eqn{\eta=1} is sparse CCA (with orthogonal constrained W's). By choosing appropriate \eqn{\lambda_k} //' one can induce sparsity of \eqn{W_k}'s to select useful variables for predicting Y. //' \eqn{W_k}'s with \eqn{B_k}'s and (\eqn{\alpha, \beta}) are iterated using an ADMM algorithm. See the reference for details. //' //' @return An object containing the following components //' \item{iter}{The number of iterations the algorithm takes.} //' @return \item{W}{A list of fitted loading matrices.} //' @return \item{B}{A list of fitted \eqn{B_k}'s.} //' @return \item{Z}{A list of fitted \eqn{B_kW_k}'s.} //' @return \item{alpha}{Fitted intercept term in the general loss term.} //' @return \item{beta}{Fitted regression coefficients in the general loss term.} //' @return \item{objvals}{A sequence of the objective values.} //' @author <NAME>, <NAME>. //' @references <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. //' Biostatistics, doi: 10.1093/biostatistics/kxw001. //' @examples ## see SimulateCVR for simulation examples, see CVR for parameter tuning. //' @seealso \code{\link{SimulateCVR}}, \code{\link{CVR}}. //' @export // [[Rcpp::export]] Rcpp::List cvrsolver(arma::mat Y, Rcpp::List Xlist, int rank, double eta, arma::vec Lam, std::string family, Rcpp::List Wini, std::string penalty, Rcpp::List opts){ int K = Xlist.size(); int n = Y.n_rows; int q = Y.n_cols; int nrank = rank, maxIters = opts["maxIters"]; bool standardization = as<bool>(opts["standardization"]); double tol = opts["tol"], h = 2, heps = 1; //string family = opts["family"], penalty = opts["penalty"]; field <mat> X(K), XX(K), XW(K), W(K), B(K), Z(K), GW(K), GZ(K), W0(K), C(K); arma::vec p(K), Wknorm, funcVal, diff=ones(1);//presNorm, dresNorm, funcVal_1, funcVal_2, funcVal_3, arma::vec Wnz(K); //Wnz[k]=1: W[k] is all 0 uvec nzid; Rcpp::List obj; //outputs arma::mat alpha = zeros(1, q), beta = zeros(nrank, q); arma::mat sumCC = zeros(nrank+1, nrank+1); // (r+1)-by-(r+1) arma::mat sumCZ = zeros(nrank+1, q); // (r+1)-by-q arma::mat bhat = zeros(nrank+1, q); arma::mat sumB = zeros(n, nrank); //n by r arma::mat Ztmp, resNorm; // funcVals, arma::mat Mk, IrXk, vecW0k, BGWk, vecBGWk, onesXWk, IrXkalp, vecBGWk0; arma::mat Gchol, U, V; arma:vec d, s; double tmp1 = 0, tmp2 = 0, tmp3 = 0, t1, t2, difftmp; //cout << "Checknode 1: setups" << endl; if (standardization){ //cout << "Need standardization" << endl; for (int k = 0; k < K; k++){ X[k] = as<mat>(Xlist[k]) - ones(n)*mean(as<mat>(Xlist[k])); X[k] = X[k]/(ones(n)*stddev(as<mat>(Xlist[k]))); } } else { for (int k = 0; k < K; k++){ X[k] = as<mat>(Xlist[k]); } } for (int k = 0; k<K; k++){ p[k] = X[k].n_cols; XX[k] = X[k].t()*X[k]; W[k] = as<mat>(Wini[k]); XW[k] = X[k]*W[k]; B[k] = XW[k]; GW[k] = zeros(n, nrank); GZ[k] = zeros(n, q); } if (family=="gaussian"){ for (int k = 0; k < K; k++){ Z[k] = (2*(1-eta)*Y/n + h*(B[k]*beta + ones(n, 1)*alpha- GZ[k]/h))/(2*(1-eta)/n + h); } } else if (family=="binomial"){ for (int k = 0; k < K; k++){ Z[k] = zeros(n, q); //Nltmp = Newtonlogistic(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); //Z[k] = as<mat>(Nltmp["Z"]); Z[k] = Newtonlogistic(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); } } else if (family=="poisson"){ for (int k = 0; k < K; k++){ Z[k] = zeros(n, q); //Nltmp = Newtonpoisson(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); //Z[k] = as<mat>(Nltmp["Z"]); Z[k] = Newtonpoisson(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); } } //cout << "Checknode 3: initialization " << endl; //iteration begins int iter = 0; for (iter = 0; iter < maxIters; iter++){ //cout << " iter = " << iter << endl; Wnz = zeros(K); sumCC = zeros(nrank+1, nrank+1); sumCZ = zeros(nrank+1, q); sumB = zeros(n, nrank); for (int k = 0; k < K; k++){ W0[k] = W[k]; if(accu(abs(W[k]))==0){Wnz[k] = 1;} } if (accu(Wnz)!=0) break; // some Wk is all 0 // beta-step for (int k = 0; k < K; k++){ C[k] = join_rows(ones(n, 1), B[k]); // n by r+1 sumCC = sumCC + C[k].t()*C[k]; sumCZ = sumCZ + C[k].t()*(Z[k]+GZ[k]/h); } //Gchol = chol(sumCC); //svd_econ(U, d, V, Gchol); //bhat = fastLS(sumCC, sumCZ); // (r+1)-by-q bhat = solve(sumCC + diagmat(0.00000001 * ones(nrank + 1)), sumCZ ); alpha = bhat.row(0); // 1 by q beta = bhat.rows(1, nrank); // r by q //cout << "beta updated " << endl; // B-step for (int k = 0; k < K; k++){ // B[k] = OrthProc(B[k],sumB,X[k],W[k],Z[k],GW[k],GZ[k],beta,alpha,h,eta); sumB = zeros(n, nrank); for (int j = 0; j < K; j++){ sumB = sumB + B[j]; } Mk = eta/2*(sumB-B[k]) + h/2*(XW[k]+GW[k]/h) + h/2*(Z[k] - ones(n, 1)*alpha + GZ[k]/h)*beta.t(); bool success = svd_econ(U, s, V, Mk); if(!success) { Rcpp::Rcout <<"OrthProc failed!"<< std::endl; //cout << "OrthProc failed!!" << endl; } B[k] = U*V.t(); } //cout << "B updated " << endl; // W-step for (int k = 0; k < K; k++){ BGWk = B[k]-GW[k]/h; if (penalty=="GL1"){ //row-wise lasso penalty Wknorm = sum(square(W0[k]), 1); //remove zero columns of X nzid = find(Wknorm!=0); W[k].rows(nzid) = MGlasso_C(BGWk, X[k].cols(nzid), ones(nzid.size())*Lam[k]/h, W0[k].rows(nzid), 1e-2, 30); //MGltmp = MGlasso_C(BGWk, X[k].cols(nzid), ones(nzid.size())*Lam[k]/h, W0[k].rows(nzid), 1e-2, 50); //W[k].rows(nzid)= as<mat>(MGltmp["B"]); } else if (penalty=="L1"){ //entrywise lasso penalty: vectorize, then lasso vecW0k = reshape(W0[k], p[k]*nrank, 1); IrXk = kron(eye(nrank, nrank), X[k]); vecBGWk = reshape(BGWk, n*nrank, 1); //MGltmp = MGlasso_C(vecBGWk, IrXk, ones(p[k]*nrank)*Lam[k]/h, vecW0k, 1e-2, 50); //vecW0k = as<mat>(MGltmp["B"]); vecW0k = MGlasso_C(vecBGWk, IrXk, ones(p[k]*nrank)*Lam[k]/h, vecW0k, 1e-2, 30); W[k] = reshape(vecW0k, p[k], nrank); } else if (penalty=="enet"){ //entrywise enet penalty: vectorize, then enet, alp=0.1(L2 penalty) vecW0k = reshape(W0[k], p[k]*nrank, 1); IrXk = kron(eye(nrank, nrank), X[k]); double alp = 0.1; IrXkalp = join_cols(IrXk, sqrt(alp)*eye(p[k]*nrank, p[k]*nrank)); vecBGWk = reshape(BGWk, n*nrank, 1); vecBGWk0 = join_cols(vecBGWk, zeros(p[k]*nrank, 1)); //MGltmp = MGlasso_C(vecBGWk0, IrXkalp, ones(p[k]*nrank)*Lam[k]*(1-alp)/h, vecW0k, 1e-2, 50); //vecW0k = as<mat>(MGltmp["B"]); vecW0k = MGlasso_C(vecBGWk0, IrXkalp, ones(p[k]*nrank)*Lam[k]*(1-alp)/h, vecW0k, 1e-2, 30); vecW0k = (1+alp*Lam[k])*vecW0k; W[k] = reshape(vecW0k, p[k], nrank); } XW[k] = X[k]*W[k]; // store XW[k] fo later use } //cout << "W updated " << endl; // Z-step if (family=="binomial"){ for (int k = 0; k < K; k++){ // Nltmp = Newtonlogistic(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); // Z[k] = as<mat>(Nltmp["Z"]); Z[k] = Newtonlogistic(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); } } else if (family=="gaussian"){ for (int k = 0; k < K; k++){ Z[k] = (2*(1-eta)*Y/n + h*( - GZ[k]/h + B[k]*beta + ones(n, 1)*alpha))/(2*(1-eta)/n + h); } } else if (family=="poisson"){ for (int k = 0; k < K; k++){ //Nltmp = Newtonpoisson(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); //Z[k] = as<mat>(Nltmp["Z"]); Z[k] = Newtonpoisson(GZ[k],B[k],alpha,beta,1-eta,Y,h,Z[k]); } } //cout << "Z updated " << endl; // Dual-step for (int k = 0; k < K; k++){ GW[k] = GW[k] + h*(XW[k]-B[k]); GZ[k] = GZ[k] + h*(Z[k] - B[k]*beta - ones(n, 1)*alpha); } // objective function tmp1 = 0; for (int k = 1; k < K; k++){ for (int j = 0; j < k; j++){ tmp1 = tmp1 + accu(square(XW[k] - XW[j] ))/2; } } //funcVal_1 = join_cols(funcVal_1, tmp1*ones(1, 1)); //cout << "funcVal_1 " << endl; tmp2 = 0; if (family=="binomial"){ for (int k = 0; k < K; k++){ Ztmp = XW[k]*beta + ones(n, 1)*alpha; tmp2 = tmp2 - accu(Y%Ztmp - log(1+exp(Ztmp)))/n; } } else if (family=="gaussian"){ for (int k = 0; k < K; k++){ Ztmp = XW[k]*beta + ones(n, 1)*alpha; tmp2 = tmp2 + accu(square(Y-Ztmp))/n; } } else if (family=="poisson"){ for (int k = 0; k < K; k++){ Ztmp = XW[k]*beta + ones(n, 1)*alpha; tmp2 = tmp2 - accu(Y%Ztmp - exp(Ztmp))/n; } } //funcVal_2 = join_cols(funcVal_2, tmp2*ones(1, 1)); //cout << "funcVal_2 " << endl; tmp3 = 0; for (int k = 0; k < K; k++){ if(penalty=="GL1"){ tmp3 = tmp3 + Lam[k]*accu(sqrt(sum(square(W[k]), 1))); } else if(penalty=="L1"){ tmp3 = tmp3 + Lam[k]*accu(abs(W[k])); } } //funcVal_3 = join_cols(funcVal_3, tmp3*ones(1, 1)); funcVal = join_cols(funcVal, (eta*tmp1+(1-eta)*tmp2+tmp3)*ones(1, 1)); //cout << "funcVal " << endl; if (iter > 0){ t1 = as_scalar(funcVal(iter)-funcVal(iter-1)); t2 = abs(as_scalar(funcVal(iter-1))); difftmp = t1/t2; diff = join_cols(diff, difftmp*ones(1, 1)); //cout << diff << endl; if (abs(difftmp) < tol) break; } h = h*heps; //cout << "obj updated " << endl; if (iter == maxIters-1){ Rcpp::Rcout <<"Not converge yet!" << difftmp << std::endl; // cout << "Not converge yet!" <<difftmp << endl; } } //end of for // if(funcVal_1.is_empty()){ // funcVals = ones(5); // } else{ // funcVals = join_rows(funcVal_1, funcVal_2); // funcVals = join_rows(funcVals, funcVal_3); // funcVals = join_rows(funcVals, funcVal); // funcVals = join_rows(funcVals, diff); // } //obj["family"] = family; obj["iter"] = iter; //obj["X"] = X; obj["W"] = W; obj["B"] = B; obj["Z"] = Z; obj["alpha"] = alpha; obj["beta"] = beta; obj["objvals"] = funcVal; //obj["diff"] = diff; obj["ver"] = "test"; //cout << "CVR done!" << endl; return(obj); } // // RCPP_MODULE(CVRmod) // { // Rcpp::function("cvrsolver", &cvrsolver); // } <file_sep>/man/CVR-package.Rd \name{CVR-package} \alias{CVR-package} \docType{package} \title{ \packageTitle{CVR} } \description{ \packageDescription{CVR} } \details{ \packageIndices{CVR} functions: \code{cvrsolver}, \code{SparseCCA}, \code{SimulateCVR}, \code{CVR}, \code{plot.CVR}.} \author{ \packageAuthor{CVR} Maintainer: \packageMaintainer{CVR} } \references{ <NAME>, <NAME>, <NAME> and <NAME> (2016) Canonical variate regression. Accepted by Biostatistics, doi: 10.1093/biostatistics/kxw001. <NAME>, <NAME> and <NAME> (2009) A penalized matrix decomposition, with applications to sparse principal components and canonical correlation analysis. Biostatistics 10(3), 515-534. } \keyword{ package } \seealso{ PMA. }
80aa9d85142231856b53c4408e150b155c07770a
[ "R", "C++" ]
5
R
cran/CVR
2acdcd2056bff2ec47c40a4e44d912bdff85ba71
a6ea97e0ec66f1c5313422da29ee041c9afca98b
refs/heads/master
<file_sep>from tensorflow.keras.models import Model from tensorflow.keras.layers import Conv2DTranspose, Conv2D, BatchNormalization, Concatenate, Activation from layers.AttentionGate import attention_gate, double_conv_layer OUTPUT_MASK_CHANNEL = 3 # network structure FILTER_NUM = 16 # number of basic filters for the first layer FILTER_SIZE = 3 def find_block_ends(model): layer_names = [layer.name for layer in model.layers] prev_num = 0 ptr_current = 1 results = [] wanted_num = {2, 3, 4, 6, 7} while ptr_current < len(layer_names): if layer_names[ptr_current][:5] == "block": block_num = int(layer_names[ptr_current][5]) if block_num != prev_num: if prev_num in wanted_num: results.append(layer_names[ptr_current - 1]) prev_num = block_num ptr_current += 1 results.append("block7b_add") return results def eff_attention_unet(base_model, inputs, output_channel, dropout, batch_norm): connection_layers = find_block_ends(base_model) # upsampling block_7 = base_model.get_layer(connection_layers[-1]).output up_block_7 = Conv2DTranspose(FILTER_NUM * 16, FILTER_SIZE, strides=2, padding='same', kernel_initializer='he_normal')(block_7) block_6 = base_model.get_layer(connection_layers[-2]).output attention_76 = attention_gate(up_block_7, block_6, FILTER_NUM) cat_block_6 = Concatenate(axis=-1)([attention_76, up_block_7]) conv_block_6 = double_conv_layer(cat_block_6, FILTER_SIZE, FILTER_NUM * 8, dropout, batch_norm) up_block_6 = Conv2DTranspose(FILTER_NUM * 8, FILTER_SIZE, strides=2, padding='same', kernel_initializer='he_normal')(conv_block_6) block_4 = base_model.get_layer(connection_layers[-3]).output attention_64 = attention_gate(up_block_6, block_4, 2 * FILTER_NUM) cat_block_4 = Concatenate(axis=-1)([attention_64, up_block_6]) conv_block_4 = double_conv_layer(cat_block_4, FILTER_SIZE, FILTER_NUM * 4, dropout, batch_norm) up_block_4 = Conv2DTranspose(FILTER_NUM * 4, FILTER_SIZE, strides=2, padding='same', kernel_initializer='he_normal')(conv_block_4) block_3 = base_model.get_layer(connection_layers[-4]).output attention_43 = attention_gate(up_block_4, block_3, 4 * FILTER_NUM) cat_block_3 = Concatenate(axis=-1)([attention_43, up_block_4]) conv_block_3 = double_conv_layer(cat_block_3, FILTER_SIZE, FILTER_NUM * 2, dropout, batch_norm) up_block_3 = Conv2DTranspose(FILTER_NUM * 2, FILTER_SIZE, strides=2, padding='same', kernel_initializer='he_normal')(conv_block_3) block_2 = base_model.get_layer(connection_layers[-5]).output attention_32 = attention_gate(up_block_3, block_2, 8 * FILTER_NUM) cat_block_2 = Concatenate(axis=-1)([attention_32, up_block_3]) conv_block_2 = double_conv_layer(cat_block_2, FILTER_SIZE, FILTER_NUM, dropout, batch_norm) up_block_2 = Conv2DTranspose(FILTER_NUM, FILTER_SIZE, strides=2, padding='same', kernel_initializer='he_normal')(conv_block_2) conv_final = Conv2D(output_channel, kernel_size=(1, 1))(up_block_2) conv_final = BatchNormalization()(conv_final) conv_final = Activation('relu')(conv_final) model = Model(inputs, conv_final, name="EffAttentionUNet") return model<file_sep>from tensorflow.keras.layers import Conv2D, Multiply, Add, Conv2DTranspose, Activation, UpSampling2D, Dropout, \ BatchNormalization import tensorflow.keras.backend as K """ Code provided by MoleImg """ def attention_gate(x, g, inter_shape): shape_g = K.int_shape(g) shape_x = K.int_shape(x) conv_x = Conv2D(inter_shape, (2, 2), strides=(2, 2), padding='same', kernel_initializer='he_normal')(x) shape_theta_x = K.int_shape(conv_x) conv_g = Conv2D(inter_shape, (1, 1), padding='same', kernel_initializer='he_normal')(g) upsample_g = Conv2DTranspose(inter_shape, (3, 3), strides=(shape_theta_x[1] // shape_g[1], shape_theta_x[2] // shape_g[2]), padding='same', kernel_initializer='he_normal')(conv_g) concat_xg = Add()([upsample_g, conv_x]) act_xg = Activation('relu')(concat_xg) psi = Conv2D(1, (1, 1), padding='same', kernel_initializer='he_normal')(act_xg) sigmoid_xg = Activation('sigmoid')(psi) shape_sigmoid = K.int_shape(sigmoid_xg) upsample_psi = UpSampling2D(size=(shape_x[1] // shape_sigmoid[1], shape_x[2] // shape_sigmoid[2]))( sigmoid_xg) # upsample_psi = Lambda(lambda x, repnum: tf.repeat(x, repnum, axis=3), # arguments={'repnum': shape_x[-1]})(upsample_psi, shape_x[3]) y = Multiply()([upsample_psi, x]) return y def double_conv_layer(x, filter_size, size, dropout, batch_norm=False): ''' construction of a double convolutional layer using SAME padding RELU nonlinear activation function :param x: input :param filter_size: size of convolutional filter :param size: number of filters :param dropout: FLAG & RATE of dropout. if < 0 dropout cancelled, if > 0 set as the rate :param batch_norm: flag of if batch_norm used, if True batch normalization :return: output of a double convolutional layer ''' axis = 3 conv = Conv2D(size, (filter_size, filter_size), padding='same')(x) if batch_norm is True: conv = BatchNormalization(axis=axis)(conv) conv = Activation('relu')(conv) conv = Conv2D(size, (filter_size, filter_size), padding='same')(conv) if batch_norm is True: conv = BatchNormalization(axis=axis)(conv) conv = Activation('relu')(conv) if dropout > 0: conv = Dropout(dropout)(conv) shortcut = Conv2D(size, kernel_size=(1, 1), padding='same')(x) if batch_norm is True: shortcut = BatchNormalization(axis=axis)(shortcut) res_path = Add()([shortcut, conv]) return res_path <file_sep>from tensorflow.keras.layers import Conv2D, Conv2DTranspose, MaxPooling2D, BatchNormalization, Multiply, Add, \ Activation, AveragePooling2D import tensorflow.keras.backend as K def down_sample(inputs, input_shape): max_pool_1 = MaxPooling2D(strides=2)(inputs) conv7_1 = Conv2D(input_shape[-1], 7, padding='same', kernel_initializer='he_normal')(max_pool_1) conv7_1 = BatchNormalization()(conv7_1) conv7_1 = Activation('relu')(conv7_1) conv7_2 = Conv2D(input_shape[-1], 7, padding='same', kernel_initializer='he_normal')(conv7_1) conv7_2 = BatchNormalization()(conv7_2) conv7_2 = Activation('relu')(conv7_2) max_pool_2 = MaxPooling2D(strides=2)(conv7_1) conv5_1 = Conv2D(input_shape[-1], 5, padding='same', kernel_initializer='he_normal')(max_pool_2) conv5_1 = BatchNormalization()(conv5_1) conv5_1 = Activation('relu')(conv5_1) conv5_2 = Conv2D(input_shape[-1], 5, padding='same', kernel_initializer='he_normal')(conv5_1) conv5_2 = BatchNormalization()(conv5_2) conv5_2 = Activation('relu')(conv5_2) max_pool_3 = MaxPooling2D(strides=2)(conv5_1) conv3_1 = Conv2D(input_shape[-1], 3, padding='same', kernel_initializer='he_normal')(max_pool_3) conv3_1 = BatchNormalization()(conv3_1) conv3_1 = Activation('relu')(conv3_1) conv3_2 = Conv2D(input_shape[-1], 3, padding='same', kernel_initializer='he_normal')(conv3_1) conv3_2 = BatchNormalization()(conv3_2) conv3_2 = Activation('relu')(conv3_2) upsampled_8 = Conv2DTranspose(input_shape[-1], 2, strides=(2, 2), kernel_initializer='he_normal')(conv3_2) added_1 = Add()([upsampled_8, conv5_2]) upsampled_16 = Conv2DTranspose(input_shape[-1], 2, strides=(2, 2), kernel_initializer='he_normal')(added_1) added_2 = Add()([upsampled_16, conv7_2]) upsampled_32 = Conv2DTranspose(input_shape[-1], 2, strides=(2, 2), kernel_initializer='he_normal')(added_2) return upsampled_32 # def global_pooling_branch(inputs, input_shape): global_pool = AveragePooling2D(input_shape[1])(inputs) conv1_2 = Conv2D(input_shape[-1], 1, padding='valid', kernel_initializer='he_normal')(global_pool) upsampled = Conv2DTranspose(input_shape[-1], input_shape[1], kernel_initializer='he_normal')(conv1_2) # return upsampled def feature_pyramid_attention(inputs): input_shape = K.int_shape(inputs) down_up_conved = down_sample(inputs, input_shape) direct_conved = Conv2D(input_shape[-1], 1, padding='valid', kernel_initializer='he_normal')(inputs) gpb = global_pooling_branch(inputs, input_shape) multiplied = Multiply()([down_up_conved, direct_conved]) added_fpa = Add()([multiplied, gpb]) return added_fpa <file_sep>from tensorflow.keras.layers import Conv2D, Multiply, Add, Conv2DTranspose, AveragePooling2D import tensorflow.keras.backend as K def global_attention_upsample(high_feat, low_feat): high_feat_shape = K.int_shape(high_feat) low_feat_shape = K.int_shape(low_feat) global_pool = AveragePooling2D(high_feat_shape[1])(high_feat) conv1_1 = Conv2D(low_feat_shape[-1], 1, padding='same', kernel_initializer='he_normal')(global_pool) conv3_1 = Conv2D(low_feat_shape[-1], 3, padding='same', kernel_initializer='he_normal')(low_feat) multiplied_1 = Multiply()([conv3_1, conv1_1]) upsampled_1 = Conv2DTranspose(low_feat_shape[-1], 2, strides=(2, 2), kernel_initializer='he_normal')( high_feat) added_1 = Add()([upsampled_1, multiplied_1]) return added_1 <file_sep>from skimage.segmentation import find_boundaries import numpy as np from tqdm import tqdm W0 = 10 SIGMA = 5 def make_weight_map(masks): """ Generate the weight maps as specified in the UNet paper for a set of binary masks. Parameters ---------- masks: array-like A 3D array of shape (n_masks, image_height, image_width), where each slice of the matrix along the 0th axis represents one binary mask. Returns ------- array-like A 2D array of shape (image_height, image_width) """ nrows, ncols = masks.shape[1:] masks = (masks > 0).astype(int) distMap = np.zeros((nrows * ncols, masks.shape[0])) X1, Y1 = np.meshgrid(np.arange(nrows), np.arange(ncols)) X1, Y1 = np.c_[X1.ravel(), Y1.ravel()].T for i, mask in tqdm(enumerate(masks)): # find the boundary of each mask, # compute the distance of each pixel from this boundary bounds = find_boundaries(mask, mode='inner') X2, Y2 = np.nonzero(bounds) xSum = (X2.reshape(-1, 1) - X1.reshape(1, -1)) ** 2 ySum = (Y2.reshape(-1, 1) - Y1.reshape(1, -1)) ** 2 distMap[:, i] = np.sqrt(xSum + ySum).min(axis=0) ix = np.arange(distMap.shape[0]) if distMap.shape[1] == 1: d1 = distMap.ravel() border_loss_map = W0 * np.exp((-1 * (d1) ** 2) / (2 * (SIGMA ** 2))) else: if distMap.shape[1] == 2: d1_ix, d2_ix = np.argpartition(distMap, 1, axis=1)[:, :2].T else: d1_ix, d2_ix = np.argpartition(distMap, 2, axis=1)[:, :2].T d1 = distMap[ix, d1_ix] d2 = distMap[ix, d2_ix] border_loss_map = W0 * np.exp((-1 * (d1 + d2) ** 2) / (2 * (SIGMA ** 2))) xBLoss = np.zeros((nrows, ncols)) xBLoss[X1, Y1] = border_loss_map # class weight map loss = np.zeros((nrows, ncols)) w_1 = 1 - masks.sum() / loss.size w_0 = 1 - w_1 loss[masks.sum(0) == 1] = w_1 loss[masks.sum(0) == 0] = w_0 ZZ = xBLoss + loss return ZZ
0486f56213bb15e08c15b1f9d902f71ca614ddab
[ "Python" ]
5
Python
guide2157/EffAttentionUnet
4e9eefb5f6f3e14d4ec018e3dddc817767af5797
4495dd7ec6d7cb2dacdbb722f3bff9699584d996
refs/heads/main
<repo_name>pwez/Unity2D<file_sep>/Assets/Scripts/State/Attack/Special/NeutralSpecialAttackState.cs namespace State.Attack.Special { public abstract class NeutralSpecialAttackState : SpecialAttackState {} }<file_sep>/Assets/Scripts/State/Attack/Regular/RegularAttackState.cs namespace State.Attack { public class RegularAttackState : BaseState {} }<file_sep>/Assets/Scripts/State/Grounded/Mobile/WalkingState.cs using State.Grounded.Stationary; using UnityEngine; namespace State.Grounded.Mobile { public class WalkingState : MobileState { public override void Enter(Player player) { base.Enter(player); var physics = player.physics; if (player.input.dx == -physics.facingDirection && player.input.dx != -physics.movingDirection) FlipScale(player); } public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; var stateMachine = player.stateMachine; if (physics.wallDirection != 0 && input.dx == physics.wallDirection) stateMachine.Toggle<IdleState>(); else if (!input.left && !input.right) { if (physics.velocity.x > 0f) physics.AccelerateX(-physics.friction, 0f); else if (physics.velocity.x < 0f) physics.AccelerateX(physics.friction, 0f); else stateMachine.Toggle<IdleState>(); } else if (Mathf.Abs(input.x) >= 1f) stateMachine.Toggle<RunningState>(); else physics.velocity.x = input.x * physics.maxVelocity.x; } } }<file_sep>/Assets/Scripts/State/Airborne/Jumping/SideJumpingState.cs using State.Grounded.Stationary; using State.Interactive; using State.WallStates; using UnityEngine; namespace State.Airborne.Jumping { public class SideJumpingState : JumpingState { [Header("Horizontal Motion")] public float horizontalSpeed; public float maxHorizontalSpeed; public float minHorizontalSpeed; public override void Enter(Player player) { base.Enter(player); var direction = player.physics.facingDirection; player.physics.velocity = new Vector2(horizontalSpeed * -direction, maxJumpSpeed); } public override void Resume(Player player) { var input = player.input; var physics = player.physics; var stateMachine = player.stateMachine; physics.ApplyGravity(gravity); if (physics.isGrounded) stateMachine.Toggle<HardLandingState>(); else if (physics.wallDirection != 0 && input.dx == physics.wallDirection) { FlipScale(player); stateMachine.Toggle<WallStickingState>(); } else { if (input.left) { if (physics.velocity.x > 0) physics.AccelerateX(-horizontalDeceleration, minHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(-horizontalAcceleration, -maxHorizontalSpeed); } else if (input.right) { if (physics.velocity.x > 0) physics.AccelerateX(horizontalAcceleration, maxHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(horizontalDeceleration, -minHorizontalSpeed); } else if (input.up && physics.canClimb) stateMachine.Toggle<ClimbingState>(); } } } }<file_sep>/Assets/Scripts/State/Interactive/Lifting/ThrowingState.cs using State.Airborne; using State.Grounded.Mobile; using State.Grounded.Stationary; using UnityEngine; namespace State.Interactive.Lifting { public class ThrowingState : BaseState { [Header("Throw Animations")] public AnimationClip throwUpward; [Header("Throw Parameters")] public Transform liftPosition; public bool applyGravityOnThrow; public Vector2 maxThrowVelocity; public float throwDuration; public AnimationClip throwAnimationClip; public Vector2 throwVelocity; private float counter; public override void Enter(Player player) { throwAnimationClip = animationClip; var input = player.input; var physics = player.physics; if (physics.isGrounded) physics.velocity.x = 0f; if (input.right) throwVelocity = new Vector2(maxThrowVelocity.x, 3f); else if (input.left) throwVelocity = new Vector2(-maxThrowVelocity.x, 3f); else if (input.up) { throwAnimationClip = throwUpward; throwVelocity = new Vector2(0, maxThrowVelocity.y); } else if (!physics.isGrounded) { if (input.down) throwVelocity = new Vector2(0, -maxThrowVelocity.y); } else throwVelocity = new Vector2(physics.facingDirection * maxThrowVelocity.x, 3f); if (throwAnimationClip && animator) { animator.enabled = true; animator.Play(throwAnimationClip.name); } throwDuration = throwAnimationClip.length; counter = 0f; } public void Throw() { var objectToThrow = liftPosition.transform.GetChild(0); var objectToThrowBody = objectToThrow.GetComponent<Rigidbody2D>(); objectToThrowBody.constraints = RigidbodyConstraints2D.FreezeRotation; objectToThrow.parent = null; objectToThrowBody.velocity = throwVelocity; } public override void Resume(Player player) { var physics = player.physics; if (physics.isGrounded || applyGravityOnThrow) physics.ApplyGravity(); if (counter < throwDuration) { counter += Time.deltaTime; if (counter >= throwDuration) { // Throw(); var stateMachine = player.stateMachine; if (physics.isGrounded) { if (Mathf.Abs(physics.velocity.x) > 0) stateMachine.Toggle<WalkingState>(); else stateMachine.Toggle<IdleState>(); } else stateMachine.Toggle<FallingState>(); } } } } }<file_sep>/Assets/Scripts/Interactive/PendulumMotion.cs using UnityEngine; namespace Interactive { public class PendulumMotion : MonoBehaviour { public float angle = 40.0f; public float speed = 1.5f; private Quaternion _start, _end; private void Start () { _start = Quaternion.AngleAxis ( angle, Vector3.forward); _end = Quaternion.AngleAxis (-angle, Vector3.forward); } private void Update () { transform.rotation = Quaternion.Lerp ( _start, _end, (Mathf.Sin(Time.time * speed) + 1.0f) / 2.0f ); } } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/Crouching/CrouchingEnterState.cs using State.Airborne; using State.Attack.Special; using UnityEngine; namespace State.Grounded.Stationary.Crouching { public class CrouchingEnterState : CrouchingState { public override void Resume(Player player) { var stateMachine = player.stateMachine; var physics = player.physics; var input = player.input; physics.ApplyGravity(); if (!input.down) stateMachine.Toggle<CrouchingExitState>(); else if (input.commandPressed) stateMachine.Toggle<BackflipState>(); else if (Input.GetKeyDown(KeyCode.U)) stateMachine.Toggle<DownwardSpecialAttackState>(); } } }<file_sep>/Assets/Scripts/State/Machine/StateMachine.cs namespace State.Machine { public interface StateMachine { void Add(State state); void Toggle<TS>() where TS : State; void Resume(); } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/StationaryState.cs namespace State.Grounded.Stationary { public class StationaryState : GroundedState { public override void Enter(Player player) { base.Enter(player); player.physics.velocity.x = 0f; } } }<file_sep>/Assets/Scripts/Physics/Physics.cs using Physics.Collisions; using UnityEngine; namespace Physics { [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(BoxCollider2D))] [RequireComponent(typeof(CollisionDetection))] public abstract class Physics : MonoBehaviour, IPhysics { [Header("Config")] public bool simulating = true; public bool gravityEnabled = true; [Header("State")] public bool isGrounded; public bool canClimb; public bool canLift; [Header("Direction")] public int facingDirection; public int movingDirection; public int wallDirection; public int ledgeDirection; [Header("Constants")] public float gravity; public float friction; public float drag; [Header("Velocity")] public Vector2 maxVelocity; [HideInInspector] public Vector2 velocity; [HideInInspector] public Vector2 velocityBeforeCollision; [Header("Buffers")] public float jumpBuffer; [HideInInspector] public float jumpCounter; public float coyoteTime; [HideInInspector] public float coyoteTimeCounter; [HideInInspector] public Rigidbody2D rigidbody2d; [HideInInspector] public BoxCollider2D boxCollider; public virtual void Awake() { rigidbody2d = GetComponent<Rigidbody2D>(); boxCollider = GetComponent<BoxCollider2D>(); } public abstract void Simulate(); public abstract void ApplyGravity(); public abstract void ApplyGravity(float grv); public abstract void AccelerateX(float acceleration, float boundingValue); } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/SpotDodgeState.cs using UnityEngine; namespace State.Grounded.Stationary { public class SpotDodgeState : GroundedState { private float counter; public override void Enter(Player player) { base.Enter(player); counter = 0f; } public override void Resume(Player player) { var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) { if (Input.GetKey(KeyCode.Y)) stateMachine.Toggle<GuardingState>(); else stateMachine.Toggle<IdleState>(); } } } } }<file_sep>/Assets/Scripts/State/Ledge/LedgeJumpRecoverState.cs using State.Airborne; using UnityEngine; namespace State.Ledge { public class LedgeJumpRecoverState : LedgeState { public float horizontalSpeed; public float height; public float timeToHeight; private float gravity; private float maxJumpSpeed; private int ledgeDirection; private void Start() { gravity = 2 * height / Mathf.Pow (timeToHeight, 2); maxJumpSpeed = gravity * timeToHeight; } public override void Enter(Player player) { base.Enter(player); var physics = player.physics; ledgeDirection = physics.ledgeDirection; physics.ledgeDirection = 0; physics.velocity.y = maxJumpSpeed; physics.gravity = gravity; } public override void Resume(Player player) { base.Resume(player); var physics = player.physics; physics.ApplyGravity(); physics.velocity.x = horizontalSpeed * ledgeDirection; if (physics.velocity.y < 0) player.stateMachine.Toggle<FallingState>(); } public override void Exit(Player player) { base.Exit(player); player.physics.ledgeDirection = 0; } } }<file_sep>/Assets/Scripts/State/Interactive/ClimbingState.cs using State.Airborne; using State.Airborne.Jumping; using State.Grounded.Mobile; using State.Grounded.Stationary; using UnityEngine; namespace State.Interactive { public class ClimbingState : BaseState { public float horizontalSpeed; public float verticalSpeed; public override void Enter(Player player) { base.Enter(player); player.physics.velocity = Vector2.zero; player.physics.isGrounded = false; } public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; var stateMachine = player.stateMachine; if (!physics.canClimb) stateMachine.Toggle<FallingState>(); else if (physics.isGrounded) { if (Mathf.Abs(physics.velocity.x) > 0) stateMachine.Toggle<WalkingState>(); else stateMachine.Toggle<IdleState>(); } if (input.up || input.down) { ContinueAnimation(); physics.velocity.y = (input.up ? 1 : -1) * verticalSpeed; } else physics.velocity.y = 0f; if (input.left || input.right) { ContinueAnimation(); physics.velocity.x = (input.right ? 1 : -1) * horizontalSpeed; } else physics.velocity.x = 0f; if (!input.up && !input.down && !input.left && !input.right) ContinueAnimation(false); // ReSharper disable once InvertIf if (input.commandPressed) { if (physics.velocity.y < 0) stateMachine.Toggle<FallingState>(); else stateMachine.Toggle<JumpingState>(); } } } }<file_sep>/Assets/Scripts/State/WallStates/WallPushoffState.cs using State.Airborne; namespace State.WallStates { public class WallPushoffState : WallState { public override void Enter(Player player) { FlipScale(player); var physics = player.physics; physics.velocity.x = -physics.wallDirection * wallHorizontalLaunchSpeed; if (wallParticles) wallParticles.Play(); player.stateMachine.Toggle<FallingState>(); } } }<file_sep>/Assets/Scripts/State/WallStates/WallState.cs using State.Airborne; using State.Airborne.Jumping; using State.Grounded.Stationary; using UnityEngine; namespace State.WallStates { public abstract class WallState : BaseState { [Header("Jump & Release")] public float wallHorizontalLaunchSpeed; public float wallHorizontalReleaseSpeed; [Header("Wall Particles")] public ParticleSystem wallParticles; private int wallDirection; public override void Enter(Player player) { base.Enter(player); CheckToFlipLocalScale(player); player.transform.rotation = Quaternion.identity; var physics = player.physics; physics.velocity = Vector2.zero; wallDirection = physics.wallDirection; if (wallParticles) wallParticles.Play(); } public override void Resume(Player player) { var physics = player.physics; var stateMachine = player.stateMachine; var input = player.input; if (physics.isGrounded) stateMachine.Toggle<IdleState>(); else if (wallDirection != 0) { if (input.dx != wallDirection) { physics.wallDirection = 0; physics.velocity.x = -wallDirection * wallHorizontalReleaseSpeed; stateMachine.Toggle<FallingState>(); } else if (input.commandPressed) { if (physics.velocity.y < 0) stateMachine.Toggle<WallPushoffState>(); else { physics.wallDirection = 0; physics.velocity.x = -wallDirection * wallHorizontalLaunchSpeed; FlipScale(player); stateMachine.Toggle<BaseJumpingState>(); } } } } public override void Exit(Player player) { if (wallParticles) wallParticles.Stop(); } } }<file_sep>/Assets/Scripts/TestPlayer.cs using Physics; using State.Grounded.Stationary; using State.Machine; public class TestPlayer : Player { private void Awake() { physics = GetComponent<PlayerPhysics>(); input = GetComponent<ControllerInput>(); InitializeStateMachine(); } private void Update() { if (!physics.simulating) return; stateMachine.Resume(); physics.Simulate(); } private void InitializeStateMachine() { stateMachine = new PlayerStateMachine(this); foreach (var state in gameObject.GetComponentsInChildren<State.State>()) stateMachine.Add(state); stateMachine.Toggle<IdleState>(); } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/LookingUpState.cs namespace State.Grounded.Stationary { public class LookingUpState : StationaryState { public override void Resume(Player player) { base.Resume(player); if(!player.input.up) player.stateMachine.Toggle<IdleState>(); } } }<file_sep>/Assets/Scripts/State/Underwater/SwimmingState.cs namespace State.Underwater { public class SwimmingState : BaseState {} }<file_sep>/Assets/Scripts/State/WallStates/WallStickingState.cs namespace State.WallStates { public class WallStickingState : WallState { public override void Resume(Player player) { base.Resume(player); if (player.input.down) player.stateMachine.Toggle<WallSlidingState>(); } } }<file_sep>/Assets/Scripts/ControllerInput.cs using UnityEngine; public class ControllerInput : MonoBehaviour { [Header("Input Axes")] public string horizontalAxis = "Horizontal"; public string verticalAxis = "Vertical"; [Header("Horizontal Input")] [HideInInspector] public int dx; public float x; public bool right; public bool left; [Header("Vertical Input")] [HideInInspector] public int dy; public float y; public bool up; public bool down; [Header("Jump Command Input")] public bool commandHeld; public bool commandPressed; public bool commandReleased; [Header("Override")] public bool overrideDirectionalInput; public Vector2 overrideInput; void Update() { x = overrideDirectionalInput ? overrideInput.x : Input.GetAxisRaw(horizontalAxis); y = overrideDirectionalInput ? overrideInput.y : Input.GetAxisRaw(verticalAxis); int v = x > 0 ? 1 : x < 0 ? -1 : 0; dx = v; dy = y > 0 ? 1 : y < 0 ? -1 : 0; right = x > 0; left = x < 0; up = y > 0; down = y < 0; if (Input.GetButtonDown("Jump")) { commandPressed = true; commandHeld = false; commandReleased = false; } else if (Input.GetButton("Jump")) { commandPressed = false; commandHeld = true; commandReleased = false; } else if (Input.GetButtonUp("Jump")) { commandPressed = false; commandHeld = false; commandReleased = true; } else commandHeld = commandPressed = commandReleased = false; } }<file_sep>/Assets/Scripts/State/Grounded/Mobile/RunningState.cs using State.Airborne.Jumping; using State.Grounded.Stationary; using State.Grounded.Stationary.Crouching; using UnityEngine; namespace State.Grounded.Mobile { public class RunningState : MobileState { public override void Enter(Player player) { base.Enter(player); var physics = player.physics; var input = player.input; if (input.dx == -physics.facingDirection && input.dx != -physics.movingDirection) FlipScale(player); } public override void Resume(Player player) { base.Resume(player); var input = player.input; var physics = player.physics; var stateMachine = player.stateMachine; if (physics.wallDirection != 0 && input.dx == physics.wallDirection) stateMachine.Toggle<IdleState>(); else if (input.left) { if (physics.velocity.x > 0f) stateMachine.Toggle<BrakingState>(); else physics.velocity.x = -physics.maxVelocity.x; } else if (input.right) { if (physics.velocity.x < 0f) stateMachine.Toggle<BrakingState>(); else physics.velocity.x = physics.maxVelocity.x; } else { // TODO come back to the nested if conditions if (physics.velocity.x > 0f) { physics.AccelerateX(-physics.friction, 0f); if (Mathf.Abs(physics.velocity.x) < 0f) stateMachine.Toggle<IdleState>(); } else if (physics.velocity.x < 0f) { physics.AccelerateX(physics.friction, 0f); if (Mathf.Abs(physics.velocity.x) < 0f) stateMachine.Toggle<IdleState>(); } else stateMachine.Toggle<IdleState>(); } } } }<file_sep>/Assets/Scripts/Character.cs using JetBrains.Annotations; using UnityEngine; public abstract class Character : MonoBehaviour { [HideInInspector] [CanBeNull] public AudioSource audioSource; [HideInInspector] [CanBeNull] public Animator animator; }<file_sep>/Assets/Scripts/State/Underwater/UnderwaterSwimmingState.cs namespace State.Underwater { public abstract class UnderwaterSwimmingState : SwimmingState { } }<file_sep>/Assets/Scripts/State/Airborne/Jumping/JumpingState.cs using UnityEngine; namespace State.Airborne.Jumping { public abstract class JumpingState : AirborneState { [Header("Jump Particles")] public ParticleSystem jumpParticles; [Header("Jump Parameters")] public float timeToHeight; public float maxHeight; [HideInInspector] public float maxJumpSpeed; [HideInInspector] public float gravity; private void Start() { CalculateJumpParameters(); } private void CalculateJumpParameters() { gravity = 2 * maxHeight / Mathf.Pow (timeToHeight, 2); maxJumpSpeed = gravity * timeToHeight; } public override void Enter(Player player) { base.Enter(player); CalculateJumpParameters(); var physics = player.physics; physics.gravity = gravity; physics.velocity.y = maxJumpSpeed; if (jumpParticles) jumpParticles.Play(); } public override void Resume(Player player) { base.Resume(player); if (player.physics.velocity.y < 0) player.stateMachine.Toggle<FallingState>(); } } }<file_sep>/Assets/Scripts/State/Airborne/Jumping/BaseJumpingState.cs using System.Collections; using UnityEngine; namespace State.Airborne.Jumping { public class BaseJumpingState : JumpingState { public float minHeight; private float minJumpSpeed; [Header("Jump Squeeze")] public Vector2 squeezeAmount = new Vector2(0.5f, 1.2f); public float squeezeDuration = 0.1f; public override void Enter(Player player) { base.Enter(player); minJumpSpeed = Mathf.Sqrt (2 * gravity * minHeight); StartCoroutine(Squeeze(squeezeAmount, squeezeDuration)); } public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; if (!input.commandHeld || input.commandReleased) { if (physics.velocity.y > minJumpSpeed) physics.velocity.y = minJumpSpeed; } } } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/IdleState.cs using State.Attack.Special; using State.Grounded.Mobile; using State.Grounded.Stationary.Crouching; using State.Interactive; using UnityEngine; namespace State.Grounded.Stationary { public class IdleState : StationaryState { public override void Resume(Player player) { base.Resume(player); var input = player.input; var physics = player.physics; var stateMachine = player.stateMachine; if (input.left || input.right) { if (physics.wallDirection != 0 && input.dx == physics.wallDirection) return; if (Mathf.Abs(input.x) >= 1f) stateMachine.Toggle<RunningState>(); else stateMachine.Toggle<WalkingState>(); } else if (input.down) stateMachine.Toggle<CrouchingEnterState>(); else if (input.up) { if (physics.canClimb) stateMachine.Toggle<ClimbingState>(); else stateMachine.Toggle<LookingUpState>(); } else if (Input.GetKey(KeyCode.Y)) stateMachine.Toggle<GuardingState>(); } } }<file_sep>/Assets/Scripts/State/Grounded/Mobile/BrakingState.cs using State.Airborne.Jumping; using State.Grounded.Stationary; using UnityEngine; namespace State.Grounded.Mobile { public class BrakingState : MobileState { [Header("Deceleration")] public float brakeDeceleration; public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; var stateMachine = player.stateMachine; if (input.commandPressed) stateMachine.Toggle<SideJumpingState>(); else if (input.dx == -physics.movingDirection) physics.AccelerateX(input.x * brakeDeceleration, 0f); else if (Mathf.Abs(physics.velocity.x) > 0f) stateMachine.Toggle<WalkingState>(); else stateMachine.Toggle<IdleState>(); } } }<file_sep>/Assets/Scripts/State/Airborne/Jumping/LongJumpingState.cs using State.Grounded.Stationary; using State.WallStates; using UnityEngine; namespace State.Airborne.Jumping { public class LongJumpingState : JumpingState { [Header("Horizontal Motion")] public float maxHorizontalSpeed; public float minHorizontalSpeed; public override void Resume(Player player) { var input = player.input; var physics = player.physics; var stateMachine = player.stateMachine; physics.ApplyGravity(gravity); if (physics.isGrounded) stateMachine.Toggle<HardLandingState>(); else if (physics.wallDirection != 0 && input.dx == physics.wallDirection) stateMachine.Toggle<WallStickingState>(); else { if (input.left) { if (physics.velocity.x > 0) physics.AccelerateX(-horizontalDeceleration, minHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(-horizontalAcceleration, -maxHorizontalSpeed); } else if (input.right) { if (physics.velocity.x > 0) physics.AccelerateX(horizontalAcceleration, maxHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(horizontalDeceleration, -minHorizontalSpeed); } } } } }<file_sep>/Assets/Scripts/Players/Mario/States/MarioDownwardSpecialAttackState.cs using State.Airborne; using State.Attack.Special; using State.Grounded.Stationary; using UnityEngine; namespace Players.Mario.States { public class MarioDownwardSpecialAttackState : DownwardSpecialAttackState { private float counter; public override void Enter(Player player) { base.Enter(player); counter = 0f; } public override void Exit(Player player) { base.Exit(player); } public override void Resume(Player player) { var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) { if (physics.isGrounded) stateMachine.Toggle<IdleState>(); else stateMachine.Toggle<FallingState>(); } } } } }<file_sep>/Assets/Scripts/State/Attack/Special/ForwardSpecialAttackState.cs namespace State.Attack.Special{ public abstract class ForwardSpecialAttackState : SpecialAttackState {} }<file_sep>/Assets/Scripts/State/WallStates/WallSlidingState.cs using UnityEngine; namespace State.WallStates { public class WallSlidingState : WallState { [Header("Wall Slide Parameters")] public float maxWallSlideSpeed; public float wallSlideAcceleration; public float wallSlideDeceleration; public float wallFriction; public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; if (input.down) { physics.velocity.y -= wallSlideAcceleration * Time.deltaTime; physics.velocity.y = Mathf.Max(physics.velocity.y, -maxWallSlideSpeed); } else if (input.up && physics.velocity.y < 0f) physics.velocity.y += wallSlideDeceleration * Time.deltaTime; else if (physics.velocity.y < 0f) physics.velocity.y += wallFriction * Time.deltaTime; else if (physics.velocity.y >= 0f) player.stateMachine.Toggle<WallStickingState>(); } } }<file_sep>/Assets/Scripts/Physics/IPhysics.cs namespace Physics { public interface IPhysics { void ApplyGravity(); void ApplyGravity(float gravity); void AccelerateX(float acceleration, float boundingValue); } }<file_sep>/Assets/Scripts/State/Attack/Special/DownwardSpecialAttackState.cs namespace State.Attack.Special{ public abstract class DownwardSpecialAttackState : SpecialAttackState {} }<file_sep>/Assets/Scripts/State/Airborne/FallingState.cs namespace State.Airborne { public class FallingState : AirborneState { public override void Resume(Player player) { base.Resume(player); var physics = player.physics; if (physics.velocity.y < -physics.maxVelocity.y) physics.velocity.y = -physics.maxVelocity.y; } } }<file_sep>/Assets/Scripts/State/Attack/Special/SpecialAttackState.cs namespace State.Attack { public abstract class SpecialAttackState : BaseState {} }<file_sep>/Assets/Scripts/State/Grounded/Mobile/MobileState.cs using UnityEngine; namespace State.Grounded.Mobile { public abstract class MobileState : GroundedState { [Header("Ground Particles On Moving")] public ParticleSystem movingParticles; public override void Enter(Player player) { base.Enter(player); if (movingParticles) movingParticles.Play(); } public override void Exit(Player player) { base.Enter(player); if (movingParticles) movingParticles.Stop(); } } }<file_sep>/Assets/Scripts/Interactive/Liftable.cs using UnityEngine; namespace Interactive { public class Liftable : MonoBehaviour { private void OnCollisionEnter2D(Collision2D other) { var playerPhysics = other.gameObject.GetComponent<Physics.Physics>(); if (playerPhysics) playerPhysics.canLift = true; } private void OnCollisionExit2D(Collision2D other) { var playerPhysics = other.gameObject.GetComponent<Physics.Physics>(); if (playerPhysics) playerPhysics.canLift = false; } } }<file_sep>/Assets/Scripts/Player.cs using State.Machine; using UnityEngine; [RequireComponent(typeof(ControllerInput))] [RequireComponent(typeof(Physics.Physics))] public abstract class Player : MonoBehaviour { [HideInInspector] public ControllerInput input; [HideInInspector] public Physics.Physics physics; [HideInInspector] public StateMachine stateMachine; }<file_sep>/Assets/Scripts/State/Interactive/Lifting/LiftingState.cs using UnityEngine; namespace State.Interactive.Lifting { public class LiftingState : BaseState { [Header("Lift Parameters")] public Transform liftPosition; public LayerMask liftLayers; public float liftDuration; private float counter; public override void Enter(Player player) { base.Enter(player); player.physics.velocity.x = 0f; liftDuration = audioClip.length; counter = 0f; } public override void Resume(Player player) { if (counter < liftDuration) { counter += Time.deltaTime; if (counter >= liftDuration) player.stateMachine.Toggle<CarryingState>(); } } public override void Exit(Player player) { base.Exit(player); PositionLiftedObjectAbove(); player.physics.canLift = false; player.physics.isGrounded = false; } private void PositionLiftedObjectAbove() { var element = transform; var position = element.position; var ray = Physics2D.Raycast(position, -element.up, Mathf.Infinity, liftLayers); if (ray && ray.collider.tag.Equals("Lift")) { var objectToLift = ray.collider.gameObject; objectToLift.transform.position = liftPosition.position; objectToLift.transform.parent = liftPosition.transform; Physics2D.IgnoreCollision(objectToLift.GetComponent<BoxCollider2D>(), GetComponentInParent<BoxCollider2D>(), true); } } } }<file_sep>/Assets/Scripts/State/Grounded/GroundedState.cs using State.Airborne; using State.Airborne.Jumping; using UnityEngine; namespace State.Grounded { public abstract class GroundedState : MotionState { public override void Enter(Player player) { base.Enter(player); player.physics.isGrounded = true; } public override void Resume(Player player) { base.Resume(player); var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (physics.isGrounded) { if (physics.jumpCounter > 0f || player.input.commandPressed) { player.physics.jumpCounter = 0f; player.physics.coyoteTimeCounter = 0f; player.stateMachine.Toggle<BaseJumpingState>(); } } else { if (physics.coyoteTimeCounter > 0) { physics.velocity.y = 0f; physics.coyoteTimeCounter -= Time.deltaTime; if (physics.jumpCounter > 0f || player.input.commandPressed) { player.physics.jumpCounter = 0f; player.physics.coyoteTimeCounter = 0f; player.stateMachine.Toggle<BaseJumpingState>(); } } else if (physics.velocity.y <= 0) { physics.coyoteTimeCounter = 0f; stateMachine.Toggle<FallingState>(); } } } } }<file_sep>/Assets/Scripts/State/Ledge/LedgeState.cs namespace State.Ledge { public abstract class LedgeState : BaseState { public override void Enter(Player player) { base.Enter(player); player.physics.wallDirection = 0; } } }<file_sep>/Assets/Scripts/Physics/Collisions/RayProjector.cs using UnityEngine; namespace Physics.Collisions { public abstract class RayProjector : MonoBehaviour { [Header("Ray Cast Config")] public float skinWidth = 0.015f; public float distanceBetweenRays = 0.25f; [Header("Bounds Config")] public Bounds currentBounds; private Vector2 currentOffset; public CollisionBounds[] collisionBounds; [Header("Debug")] public bool debug; public float debugLength; public Color raysXColor; public Color raysYColor; public Color boxColor; protected int horizontalRayCount; protected int verticalRayCount; protected float horizontalRaySpacing; protected float verticalRaySpacing; public RayOrigins rayOrigins; protected BoxCollider2D boxCollider; public virtual void Awake() { boxCollider = GetComponent<BoxCollider2D>(); ToggleBounds(0); } public virtual void Start() { CalculateRaySpacing(); } public virtual void Update() { UpdateRayOrigins(); if (!debug) return; DrawCornerRays(); DrawHorizontalRays(); DrawVerticalRays(); } public void ToggleBounds(int index) { currentBounds = collisionBounds[index].bounds; currentBounds.center = collisionBounds[index].offset; currentOffset = collisionBounds[index].offset; boxCollider.size = currentBounds.size; boxCollider.offset = currentOffset; CalculateRaySpacing(); } public void ToggleBounds(CollisionBounds bounds) { currentBounds = bounds.bounds; currentBounds.center = bounds.offset; currentOffset = bounds.offset; boxCollider.size = currentBounds.size; boxCollider.offset = currentOffset; CalculateRaySpacing(); } private void CalculateRaySpacing() { var colliderBounds = currentBounds; colliderBounds.Expand(-2 * skinWidth); var size = colliderBounds.size; var width = size.x; var height = size.y; horizontalRayCount = Mathf.RoundToInt(height / distanceBetweenRays); verticalRayCount = Mathf.RoundToInt(width / distanceBetweenRays); horizontalRaySpacing = height / (horizontalRayCount - 1); verticalRaySpacing = width / (verticalRayCount - 1); } protected void UpdateRayOrigins() { var element = transform; var angle = element.rotation.eulerAngles.z * Mathf.Deg2Rad; var bounds = new Bounds(currentBounds.center, currentBounds.size); bounds.Expand(-2 * skinWidth); var extents = bounds.extents; rayOrigins.topLeft = RotateVector(-extents.x, extents.y, angle); rayOrigins.topRight = RotateVector(extents.x, extents.y, angle); rayOrigins.bottomLeft = RotateVector(-extents.x, -extents.y, angle); rayOrigins.bottomRight = RotateVector(extents.x, -extents.y, angle); } public struct RayOrigins { public Vector2 topLeft; public Vector2 topRight; public Vector2 bottomLeft; public Vector2 bottomRight; } protected Vector2 RotateVector(float x, float y, float angle) { var vertex = new Vector2(x, y); var vertexRotationX = vertex.x * Cos(angle) - vertex.y * Sin(angle); var vertexRotationY = vertex.x * Sin(angle) + vertex.y * Cos(angle); return new Vector2(vertexRotationX, vertexRotationY) + (Vector2) transform.position; } private static float Cos(float angle) { return Mathf.Cos(angle); } private static float Sin(float angle) { return Mathf.Sin(angle); } private void DrawCornerRays() { var element = transform; var up = element.up; var right = element.right; Debug.DrawRay(rayOrigins.topLeft + currentOffset, up * debugLength, Color.yellow); Debug.DrawRay(rayOrigins.topLeft + currentOffset, -right * debugLength, Color.yellow); Debug.DrawRay(rayOrigins.bottomLeft + currentOffset, -up * debugLength, Color.green); Debug.DrawRay(rayOrigins.bottomLeft + currentOffset, -right * debugLength, Color.green); Debug.DrawRay(rayOrigins.topRight + currentOffset, up * debugLength, Color.red); Debug.DrawRay(rayOrigins.topRight + currentOffset, right * debugLength, Color.red); Debug.DrawRay(rayOrigins.bottomRight + currentOffset, -up * debugLength, Color.cyan); Debug.DrawRay(rayOrigins.bottomRight + currentOffset, right * debugLength, Color.cyan); } private void DrawHorizontalRays() { var length = debugLength + skinWidth; var destination = transform.right; for(var x = 0; x < horizontalRayCount; x++) { var origin = rayOrigins.bottomRight; origin +=(Vector2) transform.up * (horizontalRaySpacing * x); origin += currentOffset; Debug.DrawRay(origin, destination * length, raysXColor); } destination = -transform.right; for(var x = 0; x < horizontalRayCount; x++) { var origin = rayOrigins.bottomLeft; origin +=(Vector2) transform.up * (horizontalRaySpacing * x); origin += currentOffset; Debug.DrawRay(origin, destination * length, raysXColor); } } private void DrawVerticalRays() { var lengthY = debugLength + skinWidth; var destinationY = transform.up; for(var y = 0; y < verticalRayCount; y++) { var origin = rayOrigins.topLeft; origin += (Vector2) transform.right * (verticalRaySpacing * y); origin += currentOffset; Debug.DrawRay(origin, destinationY * lengthY, raysYColor); } destinationY = -transform.up; for(var y = 0; y < verticalRayCount; y++) { var origin = rayOrigins.bottomLeft; origin += (Vector2) transform.right * (verticalRaySpacing * y); origin += currentOffset; Debug.DrawRay(origin, destinationY * lengthY, raysYColor); } } private void OnDrawGizmos() { if (!debug) return; var element = transform; var rotationMatrix = Matrix4x4.TRS(element.position, element.rotation, element.lossyScale); Gizmos.matrix = rotationMatrix; Gizmos.color = boxColor; Gizmos.DrawWireCube(currentBounds.center, currentBounds.size); } } }<file_sep>/Assets/Scripts/State/Machine/SimpleStateMachine.cs using System; using System.Collections.Generic; namespace State.Machine { public class SimpleStateMachine : StateMachine { private Type currentStateType; private readonly Dictionary<Type, State> states; private readonly Player player; public SimpleStateMachine(Player player) { this.player = player; states = new Dictionary<Type, State>(); } public void Add(State state) { var type = state.GetType(); if (!states.ContainsKey(type)) states.Add(type, state); } public void Toggle<TS>() where TS : State { var type = typeof(TS); if (!states.ContainsKey(type)) return; if (currentStateType != null) states[currentStateType].Exit(player); currentStateType = type; states[currentStateType].Enter(player); } public void Resume() { states[currentStateType].Resume(player); } } }<file_sep>/Assets/Scripts/State/Ledge/LedgeHangingState.cs using State.Airborne; using UnityEngine; namespace State.Ledge { public class LedgeHangingState : LedgeState { public override void Enter(Player player) { base.Enter(player); var physics = player.physics; physics.velocity = Vector2.zero; } public override void Resume(Player player) { base.Resume(player); var input = player.input; var state = player.stateMachine; if (input.commandPressed) state.Toggle<LedgeJumpRecoverState>(); else if (input.up) state.Toggle<LedgeClimbRecoverState>(); else if (input.down) { player.physics.ledgeDirection = 0; state.Toggle<FallingState>(); } } } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/GuardingState.cs using UnityEngine; namespace State.Grounded.Stationary { public class GuardingState : GroundedState { public override void Resume(Player player) { base.Resume(player); var stateMachine = player.stateMachine; if (!Input.GetKey(KeyCode.Y) || Input.GetKeyUp(KeyCode.Y)) stateMachine.Toggle<IdleState>(); else if (player.input.down) stateMachine.Toggle<SpotDodgeState>(); } } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/HardLandingState.cs using State.Airborne.Jumping; using State.Grounded.Mobile; using State.Grounded.Stationary.Crouching; using UnityEngine; namespace State.Grounded.Stationary { public class HardLandingState : StationaryState { private float counter; public override void Enter(Player player) { base.Enter(player); counter = 0; } public override void Resume(Player player) { base.Resume(player); if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) player.stateMachine.Toggle<IdleState>(); } else if (counter <= animationClip.length * 0.75f) { var input = player.input; if (input.left || input.right) player.stateMachine.Toggle<WalkingState>(); else if (input.down) player.stateMachine.Toggle<CrouchingEnterState>(); else if (input.commandPressed) player.stateMachine.Toggle<JumpingState>(); } } } }<file_sep>/Assets/Scripts/Players/Mario/States/MarioUpwardSpecialAttackState.cs using State.Attack.Special; using State.Grounded.Stationary; using UnityEngine; namespace Players.Mario.States { // TODO there is no upward boost if velocity.y > 0 before entering state public class MarioUpwardSpecialAttackState : UpwardSpecialAttackState { [Header("Jump Parameters")] public float timeToHeight; public float maxHeight; public float horizontalSpeed; public float horizontalAcceleration; private float maxJumpSpeed; private float gravity; private float counter = 0f; private void Start() { CalculateJumpParameters(); } private void CalculateJumpParameters() { gravity = 2 * maxHeight / Mathf.Pow (timeToHeight, 2); maxJumpSpeed = gravity * timeToHeight; } public override void Enter(Player player) { base.Enter(player); var physics = player.physics; physics.gravity = gravity; physics.velocity.x = physics.facingDirection * horizontalSpeed; physics.velocity.y = maxJumpSpeed; } public override void Resume(Player player) { var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (counter < animationClip.length) counter += Time.deltaTime; else if (counter >= animationClip.length) { if (physics.isGrounded) stateMachine.Toggle<IdleState>(); } if (physics.isGrounded) stateMachine.Toggle<IdleState>(); else if (physics.velocity.y < 0f) { var input = player.input; if (input.left) physics.AccelerateX(-horizontalAcceleration, -horizontalSpeed); else if (input.right) physics.AccelerateX(horizontalAcceleration, horizontalSpeed); if (physics.velocity.y < -physics.maxVelocity.y * 0.75f) physics.velocity.y = -physics.maxVelocity.y * 0.75f; } } } }<file_sep>/Assets/Scripts/State/State.cs // ReSharper disable All namespace State { public interface State { void Enter(Player player); void Resume(Player player); void Exit(Player player); } }<file_sep>/Assets/Scripts/State/Grounded/Stationary/Crouching/CrouchingExitState.cs using State.Grounded.Mobile; using UnityEngine; namespace State.Grounded.Stationary.Crouching { public class CrouchingExitState : CrouchingState { private float counter; public override void Enter(Player player) { base.Enter(player); counter = 0; } public override void Resume(Player player) { base.Resume(player); var stateMachine = player.stateMachine; var input = player.input; if (input.left || input.right) stateMachine.Toggle<WalkingState>(); else if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) stateMachine.Toggle<IdleState>(); } } } }<file_sep>/Assets/Scripts/Physics/Collisions/CollisionDetection.cs using UnityEngine; namespace Physics.Collisions { public class CollisionDetection : RayProjector { [Header("Collisions")] public LayerMask collisionLayers; public CollisionInfo collisionInfo; public int mode; public void Translate(Vector2 displacement) { UpdateRayOrigins(); collisionInfo.Reset(); collisionInfo.inputDisplacement = displacement; if (displacement.y < 0) CheckToDescendSlope(ref displacement); if (Mathf.Abs(displacement.x) > 0f) CheckForHorizontalCollision(ref displacement); if (Mathf.Abs(displacement.y) > 0f) CheckForVerticalCollision(ref displacement); transform.Translate(displacement); // if (collisionInfo.ascendingSlope) { // if (collisionInfo.currentSurfaceAngle > 45f) // transform.rotation = Quaternion.Euler(0, 0, transform.rotation.eulerAngles.z + 90f * Mathf.Sign(displacement.x)); // } } private void CheckToDescendSlope(ref Vector2 displacement) { var dx = (int) Mathf.Sign (displacement.x); var dy = (int) Mathf.Sign (displacement.y); var rayOrigin = dx < 0 ? rayOrigins.bottomRight : rayOrigins.bottomLeft; var ray = Physics2D.Raycast (rayOrigin, -transform.up, Mathf.Infinity, collisionLayers); Debug.DrawRay(rayOrigin, -transform.up, Color.magenta); if (ray) { var surfaceAngle = Vector2.Angle (ray.normal, transform.up); if (Mathf.Abs(surfaceAngle) > 0.00001f) { if (mode == 0) { var rayNormalXSign = (int) Mathf.Sign(ray.normal.x); if (rayNormalXSign == dx) { var verticalDistanceFromSlope = ray.distance - skinWidth; var distanceToDescend = Mathf.Tan(surfaceAngle * Mathf.Deg2Rad) * Mathf.Abs(displacement.x); if (verticalDistanceFromSlope <= distanceToDescend) { var distance = Mathf.Abs(displacement.x); displacement.x = Mathf.Cos(surfaceAngle * Mathf.Deg2Rad) * distance * Mathf.Sign(displacement.x); displacement.y -= Mathf.Sin(surfaceAngle * Mathf.Deg2Rad) * distance; collisionInfo.currentSurfaceAngle = surfaceAngle; collisionInfo.currentSurfaceNormal = ray.normal; collisionInfo.descendingSlope = true; collisionInfo.below = true; } } } else if (mode == 1) { var rayNormalYSign = (int) Mathf.Sign(ray.normal.y); if (rayNormalYSign == dy) { var verticalDistanceFromSlope = ray.distance - skinWidth; var distanceToDescend = Mathf.Tan(surfaceAngle * Mathf.Deg2Rad) * Mathf.Abs(displacement.y); if (verticalDistanceFromSlope <= distanceToDescend) { var distance = Mathf.Abs(displacement.y); displacement.x += Mathf.Sign(surfaceAngle * Mathf.Deg2Rad) * distance; displacement.y = Mathf.Cos(surfaceAngle * Mathf.Deg2Rad) * distance * Mathf.Sign(displacement.y); collisionInfo.currentSurfaceAngle = surfaceAngle; collisionInfo.currentSurfaceNormal = ray.normal; collisionInfo.descendingSlope = true; collisionInfo.below = true; } } } } } } private void CheckForHorizontalCollision(ref Vector2 displacement) { var element = transform; var up = (Vector2) element.up; var right = (Vector2) element.right; var dx = (int) Mathf.Sign(displacement.x); var length = Mathf.Abs(displacement.x) + skinWidth; for (var i = 0; i < horizontalRayCount; i++) { var origin = dx < 0 ? rayOrigins.bottomLeft : rayOrigins.bottomRight; origin += up * (horizontalRaySpacing * i); var destination = right * dx; var ray = Physics2D.Raycast(origin, destination, length, collisionLayers); if (!ray) continue; if (i >= horizontalRayCount / 4 && displacement.y < 0f && ray.collider.gameObject.tag.Equals("Ledge")) { collisionInfo.ledge = true; var ledge = ray.collider.gameObject; var playerTop = transform.position.y + boxCollider.bounds.extents.y; var ledgeTop = ledge.transform.position.y + ledge.GetComponent<BoxCollider2D>().bounds.extents.y; var heightDifference = ledgeTop - playerTop; transform.Translate(new Vector3(0f, heightDifference, 0f)); displacement.y = 0f; } var surfaceAngle = Vector2.Angle(ray.normal, transform.up); if (i == 0 && surfaceAngle > 0f && surfaceAngle < 90f) { var distanceXToSlope = 0f; if (Mathf.Abs(surfaceAngle - collisionInfo.previousSurfaceAngle) > 0.00001f) { distanceXToSlope = ray.distance - skinWidth; displacement.x -= distanceXToSlope * dx; } AscendSlope(ref displacement, surfaceAngle, ray.normal); displacement.x += distanceXToSlope * dx; } if (!collisionInfo.ascendingSlope) { length = ray.distance; displacement.x = (ray.distance - skinWidth) * dx; if (collisionInfo.ascendingSlope) displacement.y = Mathf.Abs(displacement.x) * Mathf.Tan(collisionInfo.currentSurfaceAngle * Mathf.Deg2Rad); collisionInfo.left = dx < 0f; collisionInfo.right = dx > 0f; } } } private void AscendSlope(ref Vector2 displacement, float surfaceAngle, Vector2 rayNormal) { var angle = surfaceAngle * Mathf.Deg2Rad; var distance = Mathf.Abs(displacement.x); var displacementY = distance * Mathf.Sin(angle); if (displacement.y <= displacementY) { displacement.y = displacementY; displacement.x = distance * Mathf.Cos(angle) * Mathf.Sign(displacement.x); collisionInfo.currentSurfaceAngle = surfaceAngle; collisionInfo.currentSurfaceNormal = rayNormal; collisionInfo.ascendingSlope = true; collisionInfo.below = true; } } private void CheckForVerticalCollision(ref Vector2 displacement) { var element = transform; var up = (Vector2) element.up; var right = (Vector2) element.right; var dy = (int) Mathf.Sign(displacement.y); var length = Mathf.Abs(displacement.y) + skinWidth; for (var i = 0; i < verticalRayCount; i++) { var origin = dy < 0 ? rayOrigins.bottomLeft : rayOrigins.topLeft; origin += right * (verticalRaySpacing * i + displacement.x); var destination = up * dy; var ray = Physics2D.Raycast(origin, destination, length, collisionLayers); if (!ray) continue; var surfaceAngle = Vector2.Angle(ray.normal, ray.normal.x > 0 ? right : -right); if (mode == 0 && dy > 0 && (i == 0 || i == verticalRayCount - 1) && surfaceAngle < 90) { var distanceYToSlope = 0f; if (Mathf.Abs(surfaceAngle - collisionInfo.previousSurfaceAngle) > 0.00001f) { distanceYToSlope = ray.distance - skinWidth; displacement.y -= distanceYToSlope * dy; } AscendSlopeVertically(ref displacement, surfaceAngle, ray.normal); displacement.y += distanceYToSlope * dy; } if (!collisionInfo.ascendingSlope) { length = ray.distance; displacement.y = (ray.distance - skinWidth) * dy; if (collisionInfo.ascendingSlope) displacement.x = displacement.y / Mathf.Tan(collisionInfo.currentSurfaceAngle * Mathf.Deg2Rad) * Mathf.Sign(displacement.x); collisionInfo.below = dy < 0f; collisionInfo.above = dy > 0f; } } if (collisionInfo.ascendingSlope) { var dx = (int) Mathf.Sign(displacement.x); length = Mathf.Abs(displacement.x) + skinWidth; var rayOrigin = (dx < 0 ? rayOrigins.bottomLeft : rayOrigins.bottomRight) + Vector2.up * displacement.y; var ray = Physics2D.Raycast(rayOrigin,Vector2.right * dx, length, collisionLayers); if (ray) { var slopeAngle = Vector2.Angle(ray.normal,Vector2.up); if (Mathf.Abs(slopeAngle - collisionInfo.currentSurfaceAngle) > 0.00001f) { displacement.x = (ray.distance - skinWidth) * dx; collisionInfo.currentSurfaceAngle = slopeAngle; collisionInfo.currentSurfaceNormal = ray.normal; } } } } private void AscendSlopeVertically (ref Vector2 displacement, float surfaceAngle, Vector2 rayNormal) { var angle = surfaceAngle * Mathf.Deg2Rad; var distance = Mathf.Abs(displacement.y); displacement.x = distance * Mathf.Sin(angle) * Mathf.Sign(rayNormal.x); displacement.y = distance * Mathf.Cos(angle) * Mathf.Sign(displacement.y); collisionInfo.currentSurfaceAngle = surfaceAngle; collisionInfo.currentSurfaceNormal = rayNormal; collisionInfo.ascendingSlope = true; } public struct CollisionInfo { public bool above; public bool below; public bool right; public bool left; public bool ledge; public bool descendingSlope; public bool ascendingSlope; public float previousSurfaceAngle; public float currentSurfaceAngle; public Vector2 currentSurfaceNormal; public Vector2 inputDisplacement; public void Reset() { above = false; below = false; right = false; left = false; ledge = false; ascendingSlope = false; descendingSlope = false; previousSurfaceAngle = currentSurfaceAngle; currentSurfaceAngle = 0f; currentSurfaceNormal = Vector2.zero; } } // public override void Update() { // base.Update(); // if (Input.GetKeyDown(KeyCode.Alpha1)) // ToggleBounds(0); // else if (Input.GetKeyDown(KeyCode.Alpha2)) // ToggleBounds(1); // } } } <file_sep>/Assets/Scripts/State/Grounded/Stationary/Crouching/CrouchingState.cs namespace State.Grounded.Stationary.Crouching { public abstract class CrouchingState : StationaryState {} }<file_sep>/Assets/Scripts/Physics/Collisions/CollisionBounds.cs using System; using UnityEngine; namespace Physics.Collisions { [Serializable] public class CollisionBounds { public Bounds bounds; public Vector2 offset; } }<file_sep>/Assets/Scripts/State/Attack/Special/UpwardSpecialAttackState.cs namespace State.Attack.Special{ public abstract class UpwardSpecialAttackState : SpecialAttackState {} }<file_sep>/Assets/Scripts/State/Airborne/AirborneDodgingState.cs using System.Collections; using State.Grounded.Mobile; using State.Grounded.Stationary; using UnityEngine; namespace State.Airborne { public class AirborneDodgingState : AirborneState { private float counter; public override void Enter(Player player) { base.Enter(player); counter = 0f; } public override void Resume(Player player) { var input = player.input; var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (input.left) { var acceleration = physics.velocity.x < 0 ? horizontalAcceleration : horizontalDeceleration; physics.AccelerateX(input.x * acceleration, -physics.maxVelocity.x); } else if (input.right) { var acceleration = physics.velocity.x > 0 ? horizontalAcceleration : horizontalDeceleration; physics.AccelerateX(input.x * acceleration, physics.maxVelocity.x); } if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) { stateMachine.Toggle<FallingState>(); return; } } if (physics.isGrounded) { if (Mathf.Abs(physics.velocity.x) > 0) stateMachine.Toggle<WalkingState>(); else stateMachine.Toggle<IdleState>(); } } public override void Exit(Player player) { base.Exit(player); spriteRenderer.enabled = true; } } }<file_sep>/Assets/Scripts/State/BaseState.cs using System.Collections; using JetBrains.Annotations; using UnityEngine; namespace State { public abstract class BaseState : MonoBehaviour, State { [Header("Audio & Animation")] public AudioClip audioClip; public AnimationClip animationClip; [HideInInspector] public SpriteRenderer spriteRenderer; [HideInInspector] [CanBeNull] public Animator animator; [HideInInspector] [CanBeNull] public AudioSource audioSource; public virtual void Awake() { var spriteContainer = transform.parent.parent.GetChild(0); spriteRenderer = spriteContainer.GetComponent<SpriteRenderer>(); animator = spriteContainer.GetComponent<Animator>(); audioSource = spriteContainer.GetComponent<AudioSource>(); } public virtual void Enter(Player player) { PlayAnimation(); } public void PlayAnimation() { if (audioSource && audioClip) { audioSource.clip = audioClip; audioSource.Play(); } if (animator && animationClip) { animator.enabled = true; animator.Play(animationClip.name); } } public virtual void Resume(Player player) { CheckToFlipLocalScale(player); } public virtual void Exit(Player player) {} protected void ContinueAnimation(bool state = true) { if (animator) animator.enabled = state; } protected static void CheckToFlipLocalScale(Player player) { var directionFacing = player.physics.facingDirection; var directionMoving = player.physics.movingDirection; if (Mathf.Abs(player.input.x) > 0 && directionFacing == -directionMoving) { player.physics.facingDirection = -directionFacing; var element = player.transform; var localScale = element.localScale; localScale = new Vector3(-localScale.x, localScale.y, 0f); element.localScale = localScale; } } protected static void FlipScale(Player player) { var directionFacing = player.physics.facingDirection; player.physics.facingDirection = -directionFacing; var element = player.transform; var localScale = element.localScale; localScale = new Vector3(-localScale.x, localScale.y, 0f); element.localScale = localScale; } protected IEnumerator Squeeze(Vector2 amount, float duration) { var originalSize = Vector2.one; var squeezeSize = new Vector2(amount.x, amount.y); transform.parent.parent.GetChild(0).transform.localScale = squeezeSize; var time = 0f; while (time <= 1.0f) { time += Time.deltaTime / duration; transform.parent.parent.GetChild(0).transform.localScale = Vector2.Lerp(squeezeSize, originalSize, time); yield return null; } } } }<file_sep>/Assets/Scripts/State/Interactive/Lifting/CarryingState.cs using UnityEngine; namespace State.Interactive.Lifting { public class CarryingState : BaseState { [Header("Horizontal Motion")] public float deceleration; public override void Resume(Player player) { base.Resume(player); var input = player.input; var physics = player.physics; physics.ApplyGravity(); if (physics.isGrounded) { if (Input.GetKeyDown(KeyCode.K)) player.stateMachine.Toggle<ThrowingState>(); else if (input.left) physics.velocity.x = -physics.maxVelocity.x * 0.65f; else if (input.right) physics.velocity.x = physics.maxVelocity.x * 0.65f; else { if (physics.velocity.x > 0) physics.AccelerateX(-deceleration, 0); else if (physics.velocity.x < 0) physics.AccelerateX(deceleration, 0); } } } } }<file_sep>/Assets/Scripts/State/Airborne/BackflipState.cs using State.Airborne.Jumping; using State.Grounded.Stationary; using UnityEngine; namespace State.Airborne { public class BackflipState : JumpingState { [Header("Speed Parameters")] public float horizontalSpeed; public float maxHorizontalSpeed; public float minHorizontalSpeed; [Header("Squeeze Parameters")] public Vector2 squeezeAmount; public float squeezeDuration; public override void Enter(Player player) { base.Enter(player); var physics = player.physics; var direction = physics.facingDirection; physics.velocity = new Vector2(horizontalSpeed * -direction, maxJumpSpeed); StartCoroutine(Squeeze(squeezeAmount, squeezeDuration)); } public override void Resume(Player player) { var input = player.input; var physics = player.physics; var stateMachine = player.stateMachine; physics.ApplyGravity(gravity); if (physics.isGrounded) stateMachine.Toggle<HardLandingState>(); else { if (input.left) { if (physics.velocity.x > 0) physics.AccelerateX(-horizontalDeceleration, minHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(-horizontalAcceleration, -maxHorizontalSpeed); } else if (input.right) { if (physics.velocity.x > 0) physics.AccelerateX(horizontalAcceleration, maxHorizontalSpeed); else if (physics.velocity.x < 0) physics.AccelerateX(horizontalDeceleration, -minHorizontalSpeed); } } } } }<file_sep>/Assets/Scripts/Interactive/Climbable.cs using UnityEngine; namespace Interactive { public class Climbable : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { var playerPhysics = other.GetComponent<Physics.Physics>(); if (playerPhysics) playerPhysics.canClimb = true; } private void OnTriggerExit2D(Collider2D other) { var playerPhysics = other.GetComponent<Physics.Physics>(); if (playerPhysics) playerPhysics.canClimb = false; } } } <file_sep>/Assets/Scripts/Physics/PlayerPhysics.cs using Physics.Collisions; using UnityEngine; namespace Physics { public class PlayerPhysics : Physics { [HideInInspector] public CollisionDetection collisionDetection; [HideInInspector] public ControllerInput controllerInput; public override void Awake() { base.Awake(); collisionDetection = GetComponent<CollisionDetection>(); controllerInput = GetComponent<ControllerInput>(); } private void Start() { facingDirection = 1; movingDirection = wallDirection = ledgeDirection = 0; } public override void Simulate() { collisionDetection.Translate(velocity * Time.deltaTime); var collisionInfo = collisionDetection.collisionInfo; if (collisionInfo.below || collisionInfo.above) { velocityBeforeCollision.y = velocity.y; velocity.y = 0f; } if (collisionInfo.left || collisionInfo.right) { velocityBeforeCollision.x = velocity.x; velocity.x = 0f; if (controllerInput.dx != 0) wallDirection = collisionInfo.left ? -1 : 1; if (collisionInfo.ledge) ledgeDirection = collisionInfo.left ? -1 : 1; } isGrounded = collisionInfo.below; if (isGrounded) { coyoteTimeCounter = coyoteTime; ledgeDirection = 0; } movingDirection = velocity.x > 0 ? 1 : velocity.x < 0 ? -1 : 0; if (movingDirection == -wallDirection) wallDirection = 0; } public override void ApplyGravity() { if (simulating && gravityEnabled) velocity.y -= gravity * Time.deltaTime; } public override void ApplyGravity(float grv) { if (simulating && gravityEnabled) velocity.y -= grv * Time.deltaTime; } public override void AccelerateX(float acceleration, float boundingValue) { velocity.x += acceleration * Time.deltaTime; velocity.x = acceleration > 0 ? Mathf.Min(velocity.x, boundingValue) : Mathf.Max(velocity.x, boundingValue); } } }<file_sep>/Assets/Scripts/State/Ledge/LedgeRollRecoverState.cs namespace State.Ledge { public class LedgeRollRecoverState : LedgeState { } }<file_sep>/Assets/Scripts/State/Underwater/SurfaceSwimmingState.cs namespace State.Underwater { public class SurfaceSwimmingState { } }<file_sep>/Assets/Scripts/Players/Mario/States/MarioNeutralSpecialAttackState.cs using State.Airborne; using State.Attack.Special; using State.Grounded.Stationary; using UnityEngine; namespace Players.Mario.States { public class MarioNeutralSpecialAttackState : NeutralSpecialAttackState { [Header("Projectile Parameters")] public GameObject projectile; public Vector2 offset; private int facingDirection; private float counter; public override void Enter(Player player) { base.Enter(player); var position = (Vector2) transform.position; var physics = player.physics; if (physics.isGrounded) physics.velocity.x = 0f; counter = 0f; } public override void Resume(Player player) { var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (counter < animationClip.length) { counter += Time.deltaTime; if (counter >= animationClip.length) { if (physics.isGrounded) stateMachine.Toggle<IdleState>(); else stateMachine.Toggle<FallingState>(); } } } } } <file_sep>/Assets/Scripts/State/MotionState.cs using State.Attack.Special; using UnityEngine; namespace State { public abstract class MotionState : BaseState { public override void Resume(Player player) { base.Resume(player); var physics = player.physics; var input = player.input; var stateMachine = player.stateMachine; if (Input.GetKeyDown(KeyCode.U)) { if(input.left || input.right) stateMachine.Toggle<ForwardSpecialAttackState>(); else if (input.down) stateMachine.Toggle<DownwardSpecialAttackState>(); else if (input.up) stateMachine.Toggle<UpwardSpecialAttackState>(); else stateMachine.Toggle<NeutralSpecialAttackState>(); } } } }<file_sep>/Assets/Scripts/State/Airborne/AirborneState.cs using State.Airborne.Jumping; using State.Attack.Special; using State.Grounded.Mobile; using State.Grounded.Stationary; using State.Interactive; using State.Ledge; using State.WallStates; using UnityEngine; namespace State.Airborne { public abstract class AirborneState : MotionState { [Header("Airborne Acceleration")] public float horizontalAcceleration; public float horizontalDeceleration; public override void Enter(Player player) { base.Enter(player); player.physics.isGrounded = false; } public override void Resume(Player player) { base.Resume(player); var input = player.input; var stateMachine = player.stateMachine; var physics = player.physics; physics.ApplyGravity(); if (physics.isGrounded) { if (physics.jumpCounter > 0) { physics.jumpCounter = 0f; stateMachine.Toggle<BaseJumpingState>(); } else if (!input.left && !input.right && physics.velocityBeforeCollision.y <= -physics.maxVelocity.y) stateMachine.Toggle<HardLandingState>(); else if (Mathf.Abs(physics.velocity.x) >= physics.maxVelocity.x) stateMachine.Toggle<RunningState>(); else if (Mathf.Abs(physics.velocity.x) > 0f) stateMachine.Toggle<WalkingState>(); else stateMachine.Toggle<IdleState>(); } else if (physics.canClimb && input.up) stateMachine.Toggle<ClimbingState>(); else if (physics.ledgeDirection != 0) stateMachine.Toggle<LedgeHangingState>(); else if (physics.wallDirection != 0 && input.dx == physics.wallDirection) stateMachine.Toggle<WallStickingState>(); else if (input.left) { var acceleration = physics.velocity.x < 0 ? horizontalAcceleration : horizontalDeceleration; physics.AccelerateX(input.x * acceleration, -physics.maxVelocity.x); } else if (input.right) { var acceleration = physics.velocity.x > 0 ? horizontalAcceleration : horizontalDeceleration; physics.AccelerateX(input.x * acceleration, physics.maxVelocity.x); } else { if (Mathf.Abs(physics.velocity.x) > 0f) { var dragDeceleration = physics.velocity.x > 0 ? -physics.drag : physics.velocity.x < 0 ? physics.drag : 0f; physics.AccelerateX(dragDeceleration, 0f); } } if (Input.GetKeyDown(KeyCode.Y)) { stateMachine.Toggle<AirborneDodgingState>(); return; } if (input.commandPressed) physics.jumpCounter = physics.jumpBuffer; if (physics.jumpCounter > 0f) { physics.jumpCounter -= Time.deltaTime; if (physics.jumpCounter < 0f) physics.jumpCounter = 0f; } } public override void Exit(Player player) {} } }<file_sep>/Assets/Scripts/State/Ledge/LedgeClimbRecoverState.cs namespace State.Ledge { public class LedgeClimbRecoverState : LedgeState { } }
e47ab6e8c2eb7084144fc3f97632e5ff86ee212d
[ "C#" ]
65
C#
pwez/Unity2D
92eac0bee84c52b38ff3c8aad1b9617dd073d484
8de5b5f71cc73e6a1c23f6f4700ec06a74b71023
refs/heads/master
<repo_name>ale4motions/Car-Quiz<file_sep>/app/src/main/java/com/ale/carquiz/Level4CompletedActivity.java package com.ale.carquiz; import android.content.Intent; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Level4CompletedActivity extends AppCompatActivity { private TextView textScreen, textQuestion, textTitle, textBtn; private ImageView bigboss; private Animation smalltobig; private TextView homeBtn; private Button continueButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_boss); smalltobig = AnimationUtils.loadAnimation(this, R.anim.smalltobig); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/FredokaOneRegular.ttf"); textQuestion = (TextView) findViewById(R.id.textQuestion); textScreen = (TextView) findViewById(R.id.textScreen); textTitle = (TextView) findViewById(R.id.textTitle); textBtn = (TextView) findViewById(R.id.textBtn); bigboss = (ImageView) findViewById(R.id.bigboss); bigboss.startAnimation(smalltobig); textQuestion.setTypeface(typeface); textScreen.setTypeface(typeface); // textTitle.setTypeface(typeface); homeBtn = (TextView) findViewById(R.id.textBtn); homeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Level4CompletedActivity.this, HomeActivity.class)); } }); continueButton = (Button) findViewById(R.id.continueButton); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Level4CompletedActivity.this, Level5.class)); } }); } }
745221cc5a2e2f387e06d072403547ad93f9ad6b
[ "Java" ]
1
Java
ale4motions/Car-Quiz
579e4f608cc0fbaf18b543832928fc0e621c7996
8745680f4c6266306ee5229bd112c98a95b07eea
refs/heads/master
<repo_name>abada/classifieds<file_sep>/app/Category.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Category extends Model { use SoftDeletes; /** * date attributes to be used by Carbon * @var array */ protected $dates = ['deleted_at']; /** * setting the slug of the category * @param $value */ public function setNameAttribute($value) { $this->attributes['name'] = $value; if (!$this->exists) { $this->attributes['slug'] = str_slug($value); } } /** * getting all the posts for the category * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function posts() { return $this->hasMany('App\Post'); } /** * getting the sub categories for the category * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function sub_categories() { return $this->hasMany('App\Category', 'parent_id', 'id'); } /** * getting the parent category of the category * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function parent_category() { return $this->belongsTo('App\Category', 'parent_id', 'id'); } } <file_sep>/public/assets/js/classifieds.js (function(){ $('#category-filter').metisMenu(); $('#user-posts-table').DataTable(); }());<file_sep>/app/PostImage.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class PostImage extends Model { /** * get the parent post * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function post() { return $this->belongsTo('App\Post'); } }
3ac13e4a6d61d2ec939425a727c1f6f611e1f365
[ "JavaScript", "PHP" ]
3
PHP
abada/classifieds
c7b356bcf699413f216d2f8b6317435485fab0ff
59f05ce2b00a910a789d61da3d8eab2a5f3ac6b6
refs/heads/master
<repo_name>zanane-meritis/SecondTrade-Business-DAO<file_sep>/src/main/java/fr/secondtrade/businessdao/repositories/IssuerRepository.java package fr.secondtrade.businessdao.repositories; import org.springframework.data.repository.CrudRepository; import fr.secondtrade.businessdao.entities.Issuer; public interface IssuerRepository extends CrudRepository<Issuer, Long>{ } <file_sep>/src/main/java/fr/secondtrade/businessdao/business/Business.java package fr.secondtrade.businessdao.business; import java.util.List; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import fr.secondtrade.businessdao.entities.Agent; import fr.secondtrade.businessdao.entities.Investor; import fr.secondtrade.businessdao.entities.Issuer; import fr.secondtrade.businessdao.repositories.AgentRepository; import fr.secondtrade.businessdao.repositories.InvestorRepository; import fr.secondtrade.businessdao.repositories.IssuerRepository; @Service("Business") public class Business implements IBusiness{ // répositories @Autowired private AgentRepository agentRepository; @Autowired private InvestorRepository investorRepository; @Autowired private IssuerRepository issuerRepository; @Override public List<Agent> getAllAgents() { return Lists.newArrayList(agentRepository.findAll()); } @Override public Agent getAgentById(long id) { return agentRepository.findOne(id); } @Override public List<Investor> getAllInverstors() { return Lists.newArrayList(investorRepository.findAll()); } @Override public Investor getInvestorById(long id) { return investorRepository.findOne(id); } @Override public List<Issuer> getAllIssuers() { return Lists.newArrayList(issuerRepository.findAll()); } @Override public Issuer getIssuerById(long id) { return issuerRepository.findOne(id); } } <file_sep>/src/main/java/fr/secondtrade/businessdao/repositories/InvestorRepository.java package fr.secondtrade.businessdao.repositories; import org.springframework.data.repository.CrudRepository; import fr.secondtrade.businessdao.entities.Investor;; public interface InvestorRepository extends CrudRepository<Investor, Long>{ } <file_sep>/src/main/java/fr/secondtrade/businessdao/repositories/AgentRepository.java package fr.secondtrade.businessdao.repositories; import org.springframework.data.repository.CrudRepository; import fr.secondtrade.businessdao.entities.Agent; public interface AgentRepository extends CrudRepository<Agent, Long>{ }
5c8925b2fc078147af5b45cf39587df2d24340bf
[ "Java" ]
4
Java
zanane-meritis/SecondTrade-Business-DAO
36ab9196eb25994aa7361f08b31a77a85fe4692b
7c8abbe914fa52aca9a27a8f9a7cd417f6e39ec8
refs/heads/master
<file_sep>#!/usr/bin/env python3 # <NAME> # Project 2 import socket import sys import argparse import os # Socket Wrapper class SocketInterface(): # Store socket information def __init__(self, port): self.socket = None self.connection = None self.host = '' self.port = port self.buffer_size = 8192 self.max_conns = 10 # Open socket method def open(self): assert self.socket is None, "Socket has already been opened" # Initialize socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Reuse socket if possible self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: # Bind the socket self.socket.bind((self.host, self.port)) except: self.close() raise # Close socket method def close(self): assert self.socket is not None, "Socket has already been closed" # Check if connection is open if self.connection: # Close the connection self.connection.close() self.connection = None # Close the socket itself self.socket.close() self.socket = None # Listen socket method def listen(self): assert self.socket is not None, "Socket needs to be opened first" # Listen with set ammount of maximum queued connections self.socket.listen(self.max_conns) # Store current connection and keep socket open self.connection, _ = self.socket.accept() data = self.connection.recv(self.buffer_size) return data # Send socket method def send(self, data: bytes): assert self.socket is not None, "Socket must be open to send data" self.connection.sendall(data) self.connection.close() # Request Parser class HTTPParser(): def __init__(self): self.data = None self.method = None self.path = None self.httpVersion = None self.headers = None def parse(self, data: bytes): lines = None try: # Get the first line of the request lines = [d.strip() for d in data.decode('ascii').split("\n") if d.strip()] # Get the method, path, and http version self.method, self.path, self.httpVersion = lines.pop(0).split(" ") # Get the headers self.headers = {k: v for k, v in (l.split(': ') for l in lines)} except: # The above failed somewhere # None indicates a bad request return None # Print the Request Method, Path, and HTTP Version print("Method: {}\nPath: {}\nHTTP Version: {}".format(self.method, self.path, self.httpVersion)) # Print the Request Headers for header in self.headers: print("{}: {}".format(header, self.headers[header])) print("\n") # Request object request = { 'method': self.method, 'path': self.path, 'version': self.httpVersion, 'headers': self.headers } return request # HTTP Server class Server(): # Store server information def __init__(self): # Args self.args = self.parseArgs() if not self.args.port or not self.args.basedir: self.args.port = 8080 self.args.basedir = './' self.port = self.args.port # Create a new socket self.socket = SocketInterface(self.port) # Save Base Directory path self.basedir = os.path.abspath(self.args.basedir) # HTTP Methods self.methods = [ 'GET' ] self.request = None self.response = None self.version = "HTTP/1.1" self.defaultFile = "index.html" self.mimeTypes = { 'jpeg': 'image/jpeg', 'jpg': 'image/jpg', 'gif': 'image/gif', 'png': 'image/png', 'svg': 'image/svg+xml', 'html': 'text/html', 'css': 'text/css', 'js': 'application/javascript', 'tff': 'application/font-sfnt', 'woff': 'application/font-woff', 'otf': 'application/font-sfnt', 'eot': 'application/vnd.ms-fontobject' } self.defaultContentType = 'application/octet-stream' def parseArgs(self): parser = argparse.ArgumentParser(description='HTTP Web Server for COMP 177') parser.add_argument('--port', dest='port', action='store', help='Port Number', type=int) parser.add_argument('--base', dest='basedir', action='store', help='Base Directory', type=str) return parser.parse_args() # Server logging method def logger(self, msg: str): print(msg) # Server start method def start(self): # Open the socket self.socket.open() self.logger(("Socket Info: 127.0.0.1:{}").format(self.socket.port)) self.logger("Server Base Dir: %s" % self.basedir) # Listen and Serve HTTP Requests while True: self.listenAndServe() # Server stop method def stop(self): # Close the socket self.socket.close() # Server listen and serve method def listenAndServe(self): # Get data from client data = self.socket.listen() #body = [] parser = HTTPParser() # Parse the request self.request = parser.parse(data) if self.request is None: self.socket.send(self.badRequest()) self.request = None self.response = None return self.decodeRequest() # Send response self.socket.send(self.response) self.request = None self.response = None def decodeRequest(self): if self.request['method'] not in self.methods: self.badRequest() return if self.request['version'] != self.version: self.badRequest() return # TODO:(mcervco) Do something with the headers later if self.request['method'] == 'GET': self.GET() return def GET(self): self.response = [] if self.request['path'] == "/" or self.request['path'] == "/index.html": data = None try: with open(self.basedir + "/" + self.defaultFile, 'r') as indexFile: data = indexFile.read() except: self.notFound() return size = os.path.getsize(self.basedir + "/" + self.defaultFile) print("Size: %s " % size) print("Len: %s" % len(data)) self.response.append("HTTP/1.1 200 OK\r\n") self.response.append("Server: ECPE-177 Server\r\n") #self.response.append("Content-Length: " + str(size) + "\r\n") self.response.append("Content-Type: text/html\r\n") self.response.append("Connection: Close\r\n") self.response.append("\r\n") self.response.append(data) self.response = bytes(("".join(self.response)), 'utf-8') return data = None found = "" _, fileExt = os.path.splitext(self.basedir + self.request['path']) fileExt = fileExt.replace(".", "") if fileExt in self.mimeTypes: found = fileExt else: found = self.defaultContentType if found == "html" or found == "js" or found == "css": try: with open(self.basedir + self.request['path'], 'r') as text: data = text.read() except: self.notFound() return size = os.path.getsize(self.basedir + self.request['path']) self.response.append("HTTP/1.1 200 OK\r\n") self.response.append("Server: ECPE-177 Server\r\n") #self.response.append("Content-Length: " + str(size) + "\r\n") self.response.append("Content-Type: " + str(self.mimeTypes[found]) + "\r\n") self.response.append("Connection: Close\r\n") self.response.append("\r\n") self.response.append(data) self.response = bytes((''.join(self.response)), 'utf-8') return else: try: with open(self.basedir + self.request['path'], 'rb') as binary: data = binary.read() except: self.notFound() return size = os.path.getsize(self.basedir + self.request['path']) self.response.append("HTTP/1.1 200 OK\r\n") self.response.append("Server: ECPE-177 Server\r\n") #self.response.append("Content-Length: " + str(size) + "\r\n") self.response.append("Content-Type: " + str(found) + "\r\n") self.response.append("Connection: Close\r\n") self.response.append("\r\n") self.response = bytes((''.join(self.response)), 'utf-8') self.response = b"".join([self.response,data]) return def notFound(self): self.response = [] responseHTML = """<!DOCTYPE HTML><html><head><title>404</title></head><body>404 Not Found</body></html>""" self.response.append("HTTP/1.1 404 Not Found\r\n") self.response.append("Server: ECPE-177 Server\r\n") self.response.append("Content-Length: " + str(len(responseHTML)) + "\r\n") self.response.append("Content-Type: text/html\r\n") self.response.append("Connection: Close\r\n") self.response.append("\r\n") self.response.append(responseHTML) self.response = bytes(("".join(self.response)), 'utf-8') def badRequest(self): self.response = [] responseHTML = """<!DOCTYPE HTML><html><head><title>400</title></head><body>Bad Request</body></html>""" self.response.append("HTTP/1.1 400 Bad Request\r\n") self.response.append("Server: ECPE-177 Server\r\n") self.response.append("Content-Length: " + str(len(responseHTML)) + "\r\n") self.response.append("Content-Type: text/html\r\n") self.response.append("Connection: Close\r\n") self.response.append("\r\n") self.response.append(responseHTML) self.response = bytes(("".join(self.response)), 'utf-8') if __name__ == '__main__': # Python version checking if not sys.version_info[:2] == (3,5): print("Error: need Python 3.5 to run program") sys.exit(1) else: print("Using Python 3.5 to run program") server = Server() try: server.start() finally: server.stop()
63e282459bca61a41daf4b7465187c10df7fc96d
[ "Python" ]
1
Python
mcervco/Pyrum
b85b0b4a7af847e52950b7ea906ea2322e9bcb53
d85f966a75c411980a1be154eb851d34331ab072
refs/heads/main
<file_sep>import "./styles.css"; import writer, * as HtmlPrint from "./DomWriter.js"; import RandomNumberCache from "./RandomNumberCache.js"; const writeToApp = writer(document.getElementById("app")); writeToApp( HtmlPrint.h1("Hello - Random Number Cache"), HtmlPrint.p("Test promise caching using random number generator"), HtmlPrint.div( HtmlPrint.button("Get Cached", { onclick: "getCached()" }), HtmlPrint.button("Get New", { onclick: "getNewCached()" }) ), HtmlPrint.hr() ); const rndCache = new RandomNumberCache(); function writeRndToApp(data) { writeToApp(HtmlPrint.div(data)); } function getCached() { rndCache.get().then(writeRndToApp); } function getNewCached() { rndCache.getNew().then(writeRndToApp); } <file_sep>import Cache from "./Cache.js"; let cacheKeyCount = 0; function createRandomNumber() { return Math.random(); } function createRandomNumberPromise() { return new Promise((resolve) => setTimeout(() => resolve(createRandomNumber()), 500) ); } class RandomNumberCache { constructor() { this.cache = new Cache(); this.cacheKey = Symbol(`RandomNumberPromise-${++cacheKeyCount}`); } get() { let promise = this.cache.get(this.cacheKey); if (!promise) { promise = createRandomNumberPromise(); this.cache.put(this.cacheKey, promise); } return promise; } getNew() { let promise = createRandomNumberPromise(); this.cache.put(this.cacheKey, promise); return promise; } } export default RandomNumberCache; <file_sep># cached-promises Created with CodeSandbox
1784e67b28561684f4ee28b950b35f8dbcde6c5a
[ "JavaScript", "Markdown" ]
3
JavaScript
myramoki/cached-promises
76add4c381e4f7580b5708b402c5c00bc672e340
6dab8b731abc84480cfa4505711455d9fe260646
refs/heads/main
<file_sep>// import express module const express = require("express"); // import body-parser module const bodyParser = require("body-parser"); // import mongoose module const mongoose = require("mongoose"); // import Bcrypt module const bcrypt = require("bcrypt"); // import nodemailer const nodemailer = require('nodemailer'); // import nodemailer const jwt = require("jsonwebtoken"); // import module path predefini en node js const path = require('path'); // import multer module const multer = require('multer'); mongoose.connect("mongodb://localhost:27017/projetDB", { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }); const app = express(); // Configure body-parser app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // configure path app.use('/images', express.static(path.join('backend/images'))); // cofiguration d'image const MIME_TYPE = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/jpg': 'jpg' }; const storage = multer.diskStorage({ // destination destination: (req, file, cb) => { const isValid = MIME_TYPE[file.mimetype]; let error = new Error('Mime type is invalid'); if (isValid) { error = null; } cb(null, 'backend/images'); }, filename: (req, file, cb) => { const name = file.originalname.toLowerCase().split(' ').join('-'); const extension = MIME_TYPE[file.mimetype]; const imgName = name + '-' + Date.now() + '-projet-' + '.' + extension; cb(null, imgName); } }); // Security configuration app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Headers", "Origin, Accept, Content-Type, X-Requested-with, Authorization" ); res.setHeader( "Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, PATCH, PUT" ); next(); }); const User = require("./models/user.js"); const Product = require("./models/product.js"); const File = require("./models/files.js"); app.post("/users/signup", (req, res) => { bcrypt.hash(req.body.pwd, 10).then((cryptedPwd) => { console.log("Here in signup", req.body); const user = new User({ userName: req.body.userName, email: req.body.email, pwd: <PASSWORD>, role: req.body.role, }); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'votre adrees gmail', pass: '<PASSWORD>' } }); var mailOptions = { from: '<EMAIL>', to: req.body.email, subject: 'Sending Email using Node.js', text: 'That was easy!' }; transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); user.save((err, result) => { console.log("Here into signup ERROR", err); console.log("Here into signup RESULT", result); if (result) { console.log("here into 1"); res.status(200).json({ message: "1" }); } if (err) { if (err.name == "ValidationError") { console.log('here into 0'); res.status(200).json({ message: "0" }); } } }); }); }); app.post("/users/signin", (req, res, next) => { let fetchedUser; User.findOne({ email: req.body.email }).then(user => { if (!user) { return res.status(401).json({ message: "Auth failed no such user" }) } fetchedUser = user; return bcrypt.compare(req.body.pwd, user.pwd); }).then(result => { if (!result) { return res.status(401).json({ message: "Auth failed inccorect password" }) } const token = jwt.sign( { email: fetchedUser.email, userId: fetchedUser._id, userRole: fetchedUser.userRole }, "secret_this_should_be_longer", { expiresIn: "1min" } ); res.status(200).json({ token: token, expiresIn: 60, userId: fetchedUser._id, userRole: fetchedUser.role }); console.log('here role', fetchedUser.role); }) .catch(e => { console.log(e) }) }) app.get('/users/getAll', (req, res) => { console.log('here get all users'); User.find((err, docs) => { if (err) { console.log('error widh DB'); } else { res.status(200).json({ users: docs }); } }); }); // product app.post('/product', multer({ storage: storage }).single('image'), (req, res) => { console.log('req.file', req.file); url = req.protocol + '://' + req.get('host'); console.log('here url', url); product = new Product({ nom: req.body.nom, categorie: req.body.categorie, prix: req.body.prix, description: req.body.description, image: url + '/images/' + req.file.filename }); product.save().then( res.status(200).json({ message: 'product Added successfully' }) ); }); app.get('/product', (req, res) => { console.log('here get all product'); Product.find((err, docs) => { if (err) { console.log('error widh DB'); } else { res.status(200).json({ product: docs }); } }); }); app.delete('/product/:id', (req, res) => { console.log('here product is deleted', req.params.id); Product.deleteOne({ _id: req.params.id }).then( res.status(200).json({ message: 'product deleted successfully' }) ); }); app.put('/product/:id', (req, res) => { console.log('here product is update'); const product = new Product({ _id: req.body._id, nom: req.body.nom, categorie: req.body.categorie, prix: req.body.prix, description: req.body.description, image: req.body.image }); Product.updateOne({ _id: req.params.id }, product).then((result) => { if (result) { res.status(200).json({ message: 'product updated' }); } }); }); app.get('/product/:id', (req, res) => { console.log('here product id', req.params.id); Product.findOne({ _id: req.params.id }).then((findedObject) => { if (findedObject) { res.status(200).json({ product: findedObject }); } }); }); app.post("/multifiles/upload", multer({ storage: storage }).array("file", 12), function (req, res) { console.log('files', req.files); url = req.protocol + '://' + req.get('host'); file = new File({ file: url + '/images/' + req.files[0].filename }); file.save().then( res.status(200).json({ message: 'files Added successfully' }) ); }); app.get('/multifiles/files', (req, res) => { console.log('here get all File'); File.find((err, docs) => { if (err) { console.log('error widh DB'); } else { res.status(200).json({ files: docs }); } }); }); module.exports = app; <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService, FacebookLoginProvider, SocialUser } from 'angularx-social-login'; import { UserService } from '../services/user.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { login: any = {}; loginForm: FormGroup; user: SocialUser; loggedIn: boolean; constructor(private fb: FormBuilder, private userService: UserService, private authService: AuthService) { } ngOnInit() { this.loginForm = this.fb.group({ email: [''], pwd: [''] }); this.authService.authState.subscribe((user) => { this.user = user; this.loggedIn = (user != null); console.log(this.user); }); } signInWithFB(): void { this.authService.signIn(FacebookLoginProvider.PROVIDER_ID); } signOut(): void { this.authService.signOut(); } validateLogin() { this.userService.signIn(this.login.email, this.login.pwd); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { PERFECT_SCROLLBAR_CONFIG, PerfectScrollbarConfigInterface, PerfectScrollbarModule } from 'ngx-perfect-scrollbar'; import { ClickOutsideModule } from 'ng-click-outside'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = { suppressScrollX: true }; @NgModule({ imports: [CommonModule, PerfectScrollbarModule, ClickOutsideModule, ReactiveFormsModule, FormsModule], exports: [CommonModule, PerfectScrollbarModule, ClickOutsideModule, ReactiveFormsModule, FormsModule], declarations: [], providers: [ { provide: PERFECT_SCROLLBAR_CONFIG, useValue: DEFAULT_PERFECT_SCROLLBAR_CONFIG } ] }) export class SharedModule { } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ProductService { productUrl = 'http://localhost:3000/product'; constructor(private httpClient: HttpClient) { } addProduct(product: any, image: File) { const formdata = new FormData(); formdata.append('nom', product.nom); formdata.append('categorie', product.categorie); formdata.append('prix', product.prix); formdata.append('description', product.description); formdata.append('image', image); return this.httpClient.post<{ message: string }>(this.productUrl, formdata); } getProductById(id: any) { return this.httpClient.get<{ product: any }>(`${this.productUrl}/${id}`); } updateProduct(product: any) { return this.httpClient.put<{ message: string }>(`${this.productUrl}/${product._id}`, product); } deleteProduct(id: any) { return this.httpClient.delete<{ message: string }>(`${this.productUrl}/${id}`); } getAllProduct() { return this.httpClient.get<{ product: any }>(this.productUrl); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AdminComponent } from './admin/admin.component'; import { ClientComponent } from './client/client.component'; import { NavItemComponent } from './admin/navigation/nav-content/nav-item/nav-item.component'; import { NavGroupComponent } from './admin/navigation/nav-content/nav-group/nav-group.component'; import { NavCollapseComponent } from './admin/navigation/nav-content/nav-collapse/nav-collapse.component'; import { NavRightComponent } from './admin/nav-bar/nav-right/nav-right.component'; import { NavLeftComponent } from './admin/nav-bar/nav-left/nav-left.component'; import { NavContentComponent } from './admin/navigation/nav-content/nav-content.component'; import { NavigationComponent } from './admin/navigation/navigation.component'; import { NavBarComponent } from './admin/nav-bar/nav-bar.component'; import { ClientModule } from './client/client.module'; import { AdminModule } from './admin/admin.module'; import { SharedModule } from './shared/shared.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NavigationItem } from './admin/navigation/navigation'; import { NavSearchComponent } from './admin/nav-bar/nav-left/nav-search/nav-search.component'; import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { SignupComponent } from './signup/signup.component'; import { LoginComponent } from './login/login.component'; import { HeaderComponent } from './client/header/header.component'; import { FooterComponent } from './client/footer/footer.component'; import { AuthServiceConfig, FacebookLoginProvider, SocialLoginModule } from 'angularx-social-login'; const config = new AuthServiceConfig([ { id: FacebookLoginProvider.PROVIDER_ID, provider: new FacebookLoginProvider('584028956313938') } ]); export function provideConfig() { return config; } @NgModule({ declarations: [ AppComponent, AdminComponent, ClientComponent, NavBarComponent, NavigationComponent, NavContentComponent, NavLeftComponent, NavRightComponent, NavCollapseComponent, NavGroupComponent, NavItemComponent, NavSearchComponent, SignupComponent, LoginComponent, HeaderComponent, FooterComponent ], imports: [ BrowserModule, AppRoutingModule, SharedModule, AdminModule, ClientModule, FormsModule, ReactiveFormsModule, HttpClientModule, BrowserAnimationsModule, NgbDropdownModule, SocialLoginModule ], providers: [NavigationItem, { provide: AuthServiceConfig, useFactory: provideConfig } ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AdminRoutingModule } from './admin-routing.module'; import { AddProductComponent } from './add-product/add-product.component'; import { ProductTableComponent } from './product-table/product-table.component'; import { SharedModule } from '../shared/shared.module'; import { ModalContentComponent } from './modal-content/modal-content.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { DataTableComponent } from './data-table/data-table.component'; import { DataTableModule } from '../modules/data-table/data-table.module'; import { UploadFilesComponent } from './upload-files/upload-files.component'; @NgModule({ declarations: [AddProductComponent, ProductTableComponent, ModalContentComponent, DataTableComponent, UploadFilesComponent], imports: [ CommonModule, AdminRoutingModule, SharedModule, NgbModule, DataTableModule, ], entryComponents: [ModalContentComponent] }) export class AdminModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ProductService } from 'src/app/services/product.service'; import { ModalContentComponent } from '../modal-content/modal-content.component'; @Component({ selector: 'app-product-table', templateUrl: './product-table.component.html', styleUrls: ['./product-table.component.scss'] }) export class ProductTableComponent implements OnInit { product: any constructor(private productService: ProductService, private router: Router, public modalService: NgbModal) { } ngOnInit() { this.getAllProduct() } getAllProduct() { this.productService.getAllProduct().subscribe((data) => { this.product = data.product }) } // deleteProduct(id: any) { // this.productService.deleteProduct(id).subscribe((res) => { // this.getAllProduct() // console.log(res.message); // }) // } goToEdit(id: any) { this.router.navigate([`admin/add-product/${id}`]) } openModal(id) { this.productService.getProductById(id).subscribe((res) => { const modalRef = this.modalService.open(ModalContentComponent); modalRef.componentInstance.productId = res.product._id; modalRef.result.then((result) => { if (result) { console.log(result); } }); }); // modalRef.componentInstance.passEntry.subscribe((receivedEntry) => { // console.log(receivedEntry); // }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { UserService } from '../services/user.service'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignupComponent implements OnInit { signupForm: FormGroup; url: string; constructor( private formBuilder: FormBuilder, private userService: UserService, private router: Router) { } ngOnInit() { this.url = this.router.url; this.signupForm = this.formBuilder.group({ userName: ['', Validators.minLength(4)], email: ['', [Validators.email, Validators.required]], pwd: ['', Validators.required], }) } signup(user) { user.role = (this.url == '/signup') ? 'user' : 'admin'; this.userService.signup(user).subscribe( (data) => { if (data.message == "0") { document.getElementById("errorMsg").innerHTML = "User exixts into DB"; } else { this.router.navigate(['']); } } ) } } <file_sep>const mongoose = require('mongoose'); const fileSchema = mongoose.Schema({ file: String, }); const file = mongoose.model('File', fileSchema); module.exports = file;<file_sep> const mongoose = require('mongoose') const Schema = mongoose.Schema const userFbSchema = new Schema({ uid: String, token: String, email: String, name: String, gender: String, pic: String }); const UserFb = mongoose.model('userFb', userFbSchema) module.exports = UserFb<file_sep>import { Component, OnInit } from '@angular/core'; import { UserService } from 'src/app/services/user.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent implements OnInit { userIsAuthenticated = false; profile: any; username: string profileisSet = false constructor(private userService: UserService) { } ngOnInit(): void { this.userIsAuthenticated = this.userService.getIsAuth(); console.log('here auth', this.userIsAuthenticated); } onLogout() { this.userService.logout(); } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material'; import { UserService } from 'src/app/services/user.service'; export interface User { userName: String, email: String, pwd: String, role: String, } @Component({ selector: 'app-data-table', templateUrl: './data-table.component.html', styleUrls: ['./data-table.component.scss'] }) export class DataTableComponent implements OnInit { displayedColumns = ['userName', 'email', 'pwd', 'role']; dataSource; user; users: User[]; searchText: string items = []; pageOfItems: Array<any>; @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; @ViewChild(MatSort, { static: true }) sort: MatSort; constructor(private userService: UserService) { } ngOnInit() { this.getAllUsers() } getAllUsers() { this.userService.getAllUsers().subscribe((data) => { this.users = data.users; this.dataSource = new MatTableDataSource(data.users); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; }) } applyFilter(filterValue: string) { filterValue = filterValue.trim(); // Remove whitespace filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches this.dataSource.filter = filterValue; } onChangePage(pageOfItems: Array<any>) { // update current page of items this.pageOfItems = pageOfItems; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ProductService } from 'src/app/services/product.service'; @Component({ selector: 'app-add-product', templateUrl: './add-product.component.html', styleUrls: ['./add-product.component.scss'] }) export class AddProductComponent implements OnInit { addEditProductForm: FormGroup product: any = {} id: any; title: String; imagePreview: String; constructor( private formBuilder: FormBuilder, private activatedRoute: ActivatedRoute, private productService: ProductService, private router: Router ) { } ngOnInit() { this.id = this.activatedRoute.snapshot.paramMap.get('id'); if (this.id) { this.title = 'Éditer'; this.productService.getProductById(this.id).subscribe((data) => { this.product = data.product }) } else { this.title = 'Ajouter'; } this.addEditProductForm = this.formBuilder.group({ nom: [''], categorie: [''], prix: [''], description: [''], image: [''] }); } onImageSelected(event: Event) { const file = (event.target as HTMLInputElement).files[0]; this.addEditProductForm.patchValue({ image: file }); this.addEditProductForm.updateValueAndValidity(); const reader = new FileReader(); reader.onload = () => { this.imagePreview = reader.result as string; }; reader.readAsDataURL(file); } addEditproduct() { if (this.id) { this.productService.updateProduct(this.product).subscribe((data) => { console.log(data.message); }); this.router.navigate(['admin/products-table']); } else { this.productService.addProduct(this.product, this.addEditProductForm.value.image).subscribe((data) => { console.log(data.message); }); this.router.navigate(['admin/products-table']); } } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AddProductComponent } from './add-product/add-product.component'; import { DataTableComponent } from './data-table/data-table.component'; import { ProductTableComponent } from './product-table/product-table.component'; import { UploadFilesComponent } from './upload-files/upload-files.component'; const routes: Routes = [ { path: 'add-product', component: AddProductComponent }, { path: 'add-product/:id', component: AddProductComponent }, { path: 'products-table', component: ProductTableComponent }, { path: 'data-table', component: DataTableComponent }, { path: 'upload', component: UploadFilesComponent }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class AdminRoutingModule { } <file_sep>import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core'; import { Router } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ProductService } from 'src/app/services/product.service'; @Component({ selector: 'app-modal-content', templateUrl: './modal-content.component.html', styleUrls: ['./modal-content.component.scss'] }) export class ModalContentComponent implements OnInit { @Input() public productId; @Output() passEntry: EventEmitter<any> = new EventEmitter(); constructor( public activeModal: NgbActiveModal, private productService: ProductService, private router: Router ) { } ngOnInit() { console.log(this.productId); } passBack() { this.passEntry.emit(this.productId); this.activeModal.close(this.productId); } deleteProduct() { this.productService.deleteProduct(this.productId).subscribe((res) => { console.log(res.message); this.passBack(); this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => { this.router.navigate(['admin/products-table']); }); }) } } <file_sep>import { HttpClient, HttpEvent, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UploadFilesService { fileUrl = 'http://localhost:3000/multifiles'; constructor(private httpClient: HttpClient) { } upload(file: File): Observable<HttpEvent<any>> { const formdata = new FormData(); formdata.append('file', file); const req = new HttpRequest('POST', `${this.fileUrl}/upload`, formdata, { reportProgress: true, responseType: 'json' }); return this.httpClient.request(req); } getFiles() { return this.httpClient.get<{ files: any }>(`${this.fileUrl}/files`); } }
59059cd454db1e830a60b6dc6cccdd457222bfbb
[ "JavaScript", "TypeScript" ]
16
JavaScript
houssem-amri/Auth-Using-JWT-facebook-login-multi-file-upload
6d3bb6e5b18ffd210de7db55a36b55f4099ca0cd
fc6ccf32b895c219d7d929f737fb15481c2315d4
refs/heads/master
<repo_name>AndreasSummer/lokad-shared-libraries<file_sep>/Source/Lokad.Shared/Settings/DictionarySettingsProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Lokad.Quality; namespace Lokad.Settings { /// <summary> /// Settings provider based on a simple dictionary /// </summary> [Immutable] public sealed class DictionarySettingsProvider : ISettingsProvider { readonly IDictionary<string, string> _dictionary; /// <summary> /// Initializes a new instance of the <see cref="DictionarySettingsProvider"/> class. /// </summary> /// <param name="dictionary">The dictionary.</param> public DictionarySettingsProvider([NotNull] IDictionary<string, string> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } Maybe<string> ISettingsProvider.GetValue([NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); return _dictionary.GetValue(name); } ISettingsProvider ISettingsProvider.Filtered([NotNull] ISettingsKeyFilter acceptor) { if (acceptor == null) throw new ArgumentNullException("acceptor"); var dict = new Dictionary<string, string>(); foreach (var pair in _dictionary) { var v = pair.Value; acceptor .Filter(pair.Key) .Apply(f => dict.Add(f, v)); } return dict.AsSettingsProvider(); } } }<file_sep>/Source/Lokad.Testing/Testing/Assert.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Testing { static class Assert { public static void Fail(string message, params object[] args) { throw new FailedAssertException(string.Format(message, args)); } public static void IsTrue(bool expression, string message, params object[] args) { if (!expression) throw new FailedAssertException(string.Format(message, args)); } public static void IsFalse(bool expression, string message, params object[] args) { if (expression) throw new FailedAssertException(string.Format(message, args)); } } }<file_sep>/Sample/Sdk/ManageDataAndTasks/Program.cs using System; using System.Linq; using Lokad.Api; namespace ManageDataAndTasks { class Program { const string serviceUrl = "http://sandbox-ws.lokad.com/TimeSeries2.asmx"; static void Main() { Output.Write("Connecting to '{0}'", serviceUrl); Output.Info("Please enter your Lokad username and press [Enter]"); var login = Console.ReadLine(); Output.Info("Please enter the corresponding password and press [Enter]"); var pwd = Console.ReadLine(); try { var lokadService = ServiceFactory.GetConnectorForTesting(login, pwd, serviceUrl); Output.Info("Reading tasks..."); DisplayTasks(lokadService); Output.Info("Reading series..."); DisplaySeries(lokadService); Output.Info("Adding new series..."); var newSeries = CreateSampleSeries(lokadService); DisplaySeries(lokadService); Output.Info("Cleaning up..."); lokadService.DeleteSeries(newSeries); } catch (Exception ex) { Output.Error(ex); } Output.Info("Press any key to exit"); Output.Wait(); } static void DisplayTasks(ILokadService service) { var tasks = service.GetTasks(); var series = service.GetSeries().ToDictionary(s => s.SerieID); foreach (var task in tasks) { var serieForTask = series[task.SerieID]; Console.WriteLine("Task for {0}: {1} x {2}", serieForTask.Name, task.FuturePeriods, task.Period); } } static SerieInfo[] CreateSampleSeries(ILokadService lokadService) { var series = TestHelper.CreateSeries(10); lokadService.AddSeries(series); lokadService.UpdateSerieSegments(TestHelper.CreateValues(series, 100)); lokadService.SetTags(TestHelper.CreateTags(series)); lokadService.SetEvents(TestHelper.CreateEvents(series,4)); var tasks = TestHelper.CreateTasks(series); lokadService.AddTasks(tasks); return series; } public static void DisplaySeries(ILokadService api) { var series = api.GetSeries(); var tags = api.GetTags(series).ToDictionary(t => t.SerieID); var events = api.GetEvents(series).ToDictionary(t => t.SerieID); series.ForEach(s => { Console.WriteLine(s.Name); if (tags.ContainsKey(s.SerieID)) Console.WriteLine(" Tagged: {0}", tags[s.SerieID].Tags.Join(", ")); if (events.ContainsKey(s.SerieID)) Console.WriteLine(" With {0} events", events[s.SerieID].Events.Length); }); } } }<file_sep>/Source/Lokad.Shared/Utils/ArrayUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Utility class to manipulate arrays /// </summary> public static class ArrayUtil { /// <summary> /// Returns <em>True</em> if the provided array is null or empty /// </summary> /// <param name="array"></param> /// <returns></returns> public static bool IsNullOrEmpty(Array array) { return array == null || array.Length == 0; } /// <summary> /// Empty array of <see cref="Guid"/> /// </summary> public static readonly Guid[] EmptyGuid = Empty<Guid>(); /// <summary> /// Empty array of <see cref="int"/> /// </summary> public static readonly int[] EmptyInt32 = Empty<int>(); /// <summary> /// Empty array of <see cref="string"/> /// </summary> public static readonly string[] EmptyString = Empty<string>(); /// <summary> /// Returns empty array instance /// </summary> /// <typeparam name="T">type of the item for the array</typeparam> /// <returns>empty array singleton</returns> public static T[] Empty<T>() { return ArrayUtil<T>.Empty; } } static class ArrayUtil<T> { internal static readonly T[] Empty = new T[0]; } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/AssertionConditionAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates the condition parameter of the assertion method. /// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute. /// The mandatory argument of the attribute is the assertion type. /// </summary> /// <seealso cref="AssertionConditionType"/> /// <remarks>This attribute helps R# in code analysis</remarks> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class AssertionConditionAttribute : Attribute { readonly AssertionConditionType _conditionType; /// <summary> /// Initializes new instance of AssertionConditionAttribute /// </summary> /// <param name="conditionType">Specifies condition type</param> public AssertionConditionAttribute(AssertionConditionType conditionType) { _conditionType = conditionType; } /// <summary> /// Gets condition type /// </summary> public AssertionConditionType ConditionType { get { return _conditionType; } } } }<file_sep>/Test/Lokad.Shared.Test/RangeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class RangeTests { // ReSharper disable InconsistentNaming [Test] public void Test_Create() { var array = Range.Create(5).ToArray(); CollectionAssert.AreEqual(new[] {0, 1, 2, 3, 4}, array); } [Test] public void Generator() { var array = Range.Create(4, i => i + 1).ToArray(); CollectionAssert.AreEqual(new[] {1, 2, 3, 4}, array); } [Test] public void Array() { CollectionAssert.AreEqual(new[] {1, 2, 3, 4}, Range.Array(4, i => i + 1)); } [Test] public void Test_Simple_Array() { CollectionAssert.AreEqual(Range.Array(5), new[] {0, 1, 2, 3, 4}); } [Test] public void Empty() { CollectionAssert.IsEmpty(Range.Empty<int>().ToArray()); Assert.AreSame(Range.Empty<int>(), Range.Empty<int>()); } } }<file_sep>/Source/Lokad.Shared/Tuples/Pair.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Tuple class with 2 items /// </summary> /// <typeparam name="TKey">The type of the first item.</typeparam> /// <typeparam name="TValue">The type of the second item.</typeparam> [Serializable] [Immutable] public sealed class Pair<TKey, TValue> : Tuple<TKey, TValue> { /// <summary> /// Initializes a new instance of the <see cref="Pair{T1, T2}"/> class. /// </summary> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> public Pair(TKey first, TValue second) : base(first, second) { } /// <summary> /// Gets the key (or Item1). /// </summary> /// <value>The key.</value> public TKey Key { get { return Item1; } } /// <summary> /// Gets the value (or Item2). /// </summary> /// <value>The value.</value> public TValue Value { get { return Item2; } } } }<file_sep>/Test/Lokad.Quality.Test/CodebaseTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad.Quality.Test { [TestFixture] public sealed class CodebaseTests { sealed class C { } [Test] public void Find_Works_With_Nested_Classes() { var find = GlobalSetup.Codebase.Find<C>(); Assert.IsTrue(find.IsNestedPrivate); } } }<file_sep>/Source/Lokad.Shared/Settings/ISettingsProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Settings { /// <summary> /// Simple settings reader /// </summary> public interface ISettingsProvider { /// <summary> /// Gets the value, using the given key name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// value for the specified key name, or empty result /// </returns> Maybe<string> GetValue(string name); /// <summary> /// Creates new provider that contains only values filtered by the acceptor /// </summary> /// <param name="acceptor">The acceptor.</param> /// <returns> /// new settings provider that had been filtered /// </returns> ISettingsProvider Filtered(ISettingsKeyFilter acceptor); } }<file_sep>/Source/Lokad.Shared/Threading/ReaderWriterLockSlimExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Threading; #if !SILVERLIGHT2 namespace Lokad.Threading { /// <summary> /// Helper class that simplifies <see cref="ReaderWriterLockSlim"/> usage /// </summary> public static class ReaderWriterLockSlimExtensions { /// <summary> /// Gets the read lock object, that is released when the object is disposed. /// </summary> /// <param name="slimLock">The slim lock object.</param> /// <returns></returns> public static IDisposable GetReadLock(this ReaderWriterLockSlim slimLock) { slimLock.EnterReadLock(); return new DisposableAction(slimLock.ExitReadLock); } /// <summary> /// Gets the write lock, that is released when the object is disposed. /// </summary> /// <param name="slimLock">The slim lock.</param> /// <returns></returns> public static IDisposable GetWriteLock(this ReaderWriterLockSlim slimLock) { slimLock.EnterWriteLock(); return new DisposableAction(slimLock.ExitWriteLock); } /// <summary> /// Gets the upgradeable read lock, that is released, when the object is disposed /// </summary> /// <param name="slimLock">The slim lock.</param> /// <returns></returns> public static IDisposable GetUpgradeableReadLock(this ReaderWriterLockSlim slimLock) { slimLock.EnterUpgradeableReadLock(); return new DisposableAction(slimLock.ExitUpgradeableReadLock); } } } #endif<file_sep>/Source/Lokad.Shared/Monads/Result.1.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class that allows to pass out method call results without using exceptions /// </summary> /// <typeparam name="T">type of the associated data</typeparam> [Immutable] public sealed class Result<T> : IEquatable<Result<T>> { readonly bool _isSuccess; readonly T _value; readonly string _error; Result(bool isSuccess, T value, string error) { _isSuccess = isSuccess; _value = value; _error = error; } /// <summary> /// Error message associated with this failure /// </summary> [Obsolete("Use Error instead"), UsedImplicitly] public string ErrorMessage { get { return _error; } } /// <summary> Creates failure result </summary> /// <param name="errorFormatString">format string for the error message</param> /// <param name="args">The arguments.</param> /// <returns>result that is a failure</returns> /// <exception cref="ArgumentNullException">if format string is null</exception> public static Result<T> CreateError([NotNull] string errorFormatString, params object[] args) { if (errorFormatString == null) throw new ArgumentNullException("errorFormatString"); return CreateError(string.Format(errorFormatString, args)); } /// <summary> /// Creates the success result. /// </summary> /// <param name="value">The value.</param> /// <returns>result encapsulating the success value</returns> /// <exception cref="ArgumentNullException">if value is a null reference type</exception> public static Result<T> CreateSuccess(T value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<T>(true, value, default(string)); } /// <summary> /// Converts value of this instance /// using the provided <paramref name="converter"/> /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns>Converted result</returns> /// <exception cref="ArgumentNullException"> if <paramref name="converter"/> is null</exception> public Result<TTarget> Convert<TTarget>([NotNull] Func<T, TTarget> converter) { if (converter == null) throw new ArgumentNullException("converter"); if (!_isSuccess) return Result<TTarget>.CreateError(_error); return converter(_value); } /// <summary> /// Creates the error result. /// </summary> /// <param name="error">The error.</param> /// <returns>result encapsulating the error value</returns> /// <exception cref="ArgumentNullException">if error is null</exception> public static Result<T> CreateError(string error) { if (null == error) throw new ArgumentNullException("error"); return new Result<T>(false, default(T), error); } /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Result{T}"/>. /// </summary> /// <param name="value">The item.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">if <paramref name="value"/> is a reference type that is null</exception> public static implicit operator Result<T>(T value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<T>(true, value, null); } /// <summary> /// Combines this <see cref="Result{T}"/> with the result returned /// by <paramref name="converter"/>. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns>Combined result.</returns> public Result<TTarget> Combine<TTarget>(Func<T, Result<TTarget>> converter) { if (!_isSuccess) return Result<TTarget>.CreateError(_error); return converter(_value); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Result<T>)) return false; return Equals((Result<T>) obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { unchecked { int result = _isSuccess.GetHashCode(); result = (result*397) ^ _value.GetHashCode(); result = (result*397) ^ (_error != null ? _error.GetHashCode() : 0); return result; } } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(Result<T> other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._isSuccess.Equals(_isSuccess) && Equals(other._value, _value) && Equals(other._error, _error); } /// <summary> /// Applies the specified <paramref name="action"/> /// to this <see cref="Result{T}"/>, if it has value. /// </summary> /// <param name="action">The action to apply.</param> /// <returns>returns same instance for inlining</returns> /// <exception cref="ArgumentNullException">if <paramref name="action"/> is null</exception> public Result<T> Apply([NotNull] Action<T> action) { if (action == null) throw new ArgumentNullException("action"); if (_isSuccess) action(_value); return this; } /// <summary> /// Handles the specified handler. /// </summary> /// <param name="handler">The handler.</param> /// <returns>same instance for the inlining</returns> public Result<T> Handle([NotNull] Action<string> handler) { if (handler == null) throw new ArgumentNullException("handler"); if (!_isSuccess) handler(_error); return this; } /// <summary> /// Gets a value indicating whether this result is valid. /// </summary> /// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value> public bool IsSuccess { get { return _isSuccess; } } /// <summary> /// item associated with this result /// </summary> public T Value { get { if (!_isSuccess) throw new InvalidOperationException(string.Format("Code should not access value when the result has failed. Error is: \'{0}\'.", _error)); return _value; } } /// <summary> /// Error message associated with this failure /// </summary> public string Error { get { if (_isSuccess) throw new InvalidOperationException("Code should not access error message when the result is valid."); return _error; } } /// <summary> /// Converts this <see cref="Result{T}"/> to <see cref="Maybe{T}"/>, /// using the <paramref name="converter"/> to perform the value conversion. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The reflector.</param> /// <returns><see cref="Maybe{T}"/> that represents the original value behind the <see cref="Result{T}"/> after the conversion</returns> public Maybe<TTarget> ToMaybe<TTarget>([NotNull] Func<T, TTarget> converter) { if (converter == null) throw new ArgumentNullException("converter"); if (!_isSuccess) return Maybe<TTarget>.Empty; return converter(_value); } /// <summary> /// Converts this <see cref="Result{T}"/> to <see cref="Maybe{T}"/>, /// with the original value reference, if there is any. /// </summary> /// <returns><see cref="Maybe{T}"/> that represents the original value behind the <see cref="Result{T}"/>.</returns> public Maybe<T> ToMaybe() { if (!_isSuccess) return Maybe<T>.Empty; return _value; } /// <summary> /// Exposes result failure as the exception (providing compatibility, with the exception -expecting code). /// </summary> /// <param name="exception">The function to generate exception, provided the error string.</param> /// <returns>result value</returns> public T ExposeException([NotNull] Func<string, Exception> exception) { if (exception == null) throw new ArgumentNullException("exception"); if (!IsSuccess) throw exception(Error); // abdullin: we can return value here, since failure chain ends here return Value; } /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Lokad.Result&lt;T&gt;"/>. /// </summary> /// <param name="error">The error.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">If value is a null reference type</exception> public static implicit operator Result<T>(string error) { if (null == error) throw new ArgumentNullException("error"); return CreateError(error); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (!_isSuccess) return "<Error: '" + _error + "'>"; return "<Value: '" + _value + "'>"; } } }<file_sep>/Source/Lokad.Logging/Diagnostics/TraceLog.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using System; using System.Diagnostics; using Lokad.Quality; namespace Lokad.Diagnostics { /// <summary> /// Simple <see cref="ILog"/> that writes to the <see cref="Trace.Listeners"/> /// </summary> /// <remarks>Use Logging stack, if more flexibility is needed</remarks> [Serializable] [NoCodeCoverage, Immutable, UsedImplicitly] public sealed class TraceLog : ILog { /// <summary> Singleton instance </summary> [UsedImplicitly] public static readonly ILog Instance = new TraceLog(""); /// <summary> /// Named provider for the <see cref="TraceLog"/> /// </summary> [UsedImplicitly] public static readonly ILogProvider Provider = new LambdaLogProvider(s => new TraceLog(s)); readonly string _logName; /// <summary> /// Initializes a new instance of the <see cref="TraceLog"/> class. /// </summary> /// <param name="logName">Name of the log.</param> public TraceLog(string logName) { _logName = logName; } void ILog.Log(LogLevel level, object message) { Trace.WriteLine("[" + level + "] " + message, _logName); Trace.Flush(); } void ILog.Log(LogLevel level, Exception ex, object message) { Trace.WriteLine("[" + level + "] " + message, _logName); Trace.WriteLine("[" + level + "] " + ex, _logName); Trace.Flush(); } bool ILog.IsEnabled(LogLevel level) { return true; } } } #endif<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/ValidationScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class ValidationScopeTests { [Test, Expects.RuleException] public void All_Problems_Are_Collected_Properly() { try { using (var t = Scope.ForValidation("Test", Scope.WhenError)) { ScopeTestHelper.FireErrors(t); } } catch (RuleException ex) { ScopeTestHelper.ShouldBeClean(ex); ScopeTestHelper.ShouldHave(ex, "ErrA", "ErrB", "ErrC"); throw; } } [Test, Expects.RuleException] public void Test_Nesting() { try { using (var t = Scope.ForValidation("Test", Scope.WhenError)) { ScopeTestHelper.RunNesting(0, t); } } catch (RuleException ex) { ScopeTestHelper.ShouldBeClean(ex); ScopeTestHelper.ShouldHave(ex, "None1", "Warn1", "Group1", "Group2", "None3"); throw; } } } }<file_sep>/Source/Lokad.Stack/ReadMe.txt === License === Copyright (c) Lokad 2009 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. * Neither the name of Lokad 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. === Lokad.Stack === Lokad.Stack extends Lokad.Shared and contains Lokad-specific bindings to specific Open Source libraries that form up the public stack of the http://lokad.com: * Autofac IoC Container (and some extension modules) * log4net logging SVN repository is located at: http://lokad.svn.sourceforge.net/svnroot/lokad/Platform/Trunk/Shared<file_sep>/Source/Lokad.Logging/Rules/LogScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad.Rules { /// <summary> <see cref="IScope"/> that maintains scope path and writes inner messages /// to the log with the proper path /// </summary> [Serializable] [UsedImplicitly] public sealed class LogScope : IScope { readonly string _name; readonly ILogProvider _logProvider; readonly ILog _log; RuleLevel _level; readonly Action<RuleLevel> _dispose = level => { }; void IDisposable.Dispose() { _dispose(_level); } internal LogScope(string name, ILogProvider provider, Action<RuleLevel> dispose) { _name = name; _dispose = dispose; _logProvider = provider; _log = _logProvider.Get(name); } /// <summary> /// Initializes a new instance of the <see cref="LogScope"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="logProvider">The log provider.</param> public LogScope(string name, ILogProvider logProvider) { _name = name; _logProvider = logProvider; _dispose = level => { }; _log = _logProvider.Get(name); } IScope IScope.Create(string name) { return new LogScope(Scope.ComposePath(_name, name), _logProvider, level => { if (level > _level) _level = level; }); } void IScope.Write(RuleLevel level, string message) { if (level > _level) _level = level; _log.Log(MatchLevel(level), message); } static LogLevel MatchLevel(RuleLevel level) { switch (level) { case RuleLevel.None: return LogLevel.Info; case RuleLevel.Warn: return LogLevel.Warn; case RuleLevel.Error: return LogLevel.Error; default: throw new ArgumentOutOfRangeException("level"); } } RuleLevel IScope.Level { get { return _level; } } } }<file_sep>/Source/Lokad.Quality/CecilExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; using Mono.Cecil; namespace Lokad.Quality { using Provider = IProvider<TypeReference, TypeDefinition>; /// <summary> /// Helper methods to simplify the usage of Mono.Cecil /// </summary> public static class CecilExtensions { /// <summary> /// Gets all methods for the provided <see cref="TypeDefinition"/>. /// This includes walking all the way up the inheritance chain, excluding /// the <see cref="object"/> /// </summary> /// <param name="self">The <see cref="TypeDefinition"/> to check.</param> /// <param name="provider">The resolution provider.</param> /// <returns>lazy collection of methods</returns> /// <seealso cref="Codebase"/> public static IEnumerable<MethodDefinition> GetAllMethods(this TypeDefinition self, IProvider<TypeReference, TypeDefinition> provider) { return self.GetInheritance(provider).SelectMany(p => TypeDefinitionExtensions.GetMethods(p)); } /// <summary> /// Gets the inheritance tree of the provided type. /// </summary> /// <param name="definition">The definition.</param> /// <param name="provider">The provider.</param> /// <returns>lazy enumerator</returns> public static IEnumerable<TypeDefinition> GetInheritance(this TypeDefinition definition, IProvider<TypeReference, TypeDefinition> provider) { var current = definition; var interfaces = new HashSet<TypeReference>(); while (true) { yield return current; interfaces.AddRange(current.GetInterfaces()); if (current.BaseType == null) break; if (current.BaseType.FullName == typeof (object).FullName) break; current = provider.Get(current.BaseType); } foreach (var reference in interfaces) { yield return provider.Get(reference); } } /// <summary> /// Gets all fields for the provided <see cref="TypeDefinition"/>. /// This includes walking all the way up the inheritance chain, excluding /// the <see cref="object"/> /// </summary> /// <param name="self">The <see cref="TypeDefinition"/> to check.</param> /// <param name="provider">The resolution provider.</param> /// <returns>lazy collection of fields</returns> /// <seealso cref="Codebase"/> public static IEnumerable<FieldDefinition> GetAllFields(this TypeDefinition self, IProvider<TypeReference, TypeDefinition> provider) { return self.GetInheritance(provider).SelectMany(p => p.GetFields()); } } }<file_sep>/Source/Lokad.Shared/Currency/CurrencyMismatchException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; namespace Lokad { /// <summary> /// Exception related to the situations when currency logic is violated. /// </summary> /// <remarks> /// All currency conversion operations should be handled by the /// appropriate currency manager, that will take care of fetching the /// proper conversion rates /// </remarks> [Serializable] public class CurrencyMismatchException : Exception { /// <summary> /// Initializes a new instance of the /// <see cref="CurrencyMismatchException" /> /// class. /// </summary> public CurrencyMismatchException() { } /// <summary> /// Initializes a new instance of the /// <see cref="CurrencyMismatchException" /> /// class. /// </summary> /// <param name="message">The message.</param> public CurrencyMismatchException(string message) : base(message) { } #if !SILVERLIGHT2 CurrencyMismatchException( SerializationInfo info, StreamingContext context) : base(info, context) { } #endif internal static CurrencyMismatchException Create(string format, params object[] args) { var text = string.Format(format, args); return new CurrencyMismatchException(text); } } }<file_sep>/Test/Lokad.Shared.Test/Result1Tests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; using Lokad.Rules; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class Result1Tests { // ReSharper disable InconsistentNaming [Test, Expects.InvalidOperationException] public void Access_Error() { var result = Result<int>.CreateError("Failed"); Assert.IsFalse(result.IsSuccess); Assert.AreEqual(result.Error, "Failed"); Assert.IsNull(result.Value, "This should fail"); } [Test, Expects.ArgumentNullException] public void Reference_Value_Is_Checked_For_Null() { // if you have R#, this should be highlighted Result.CreateSuccess(default(object)); } [Test] public void Value_can_be_default() { Result.CreateSuccess(default(int)); } [Test] public void Implicit_value_conversion() { Result<int> result = 10; RuleAssert.IsTrue(() => result.IsSuccess); } readonly Result<int> ResultSuccess = 10; readonly Result<int> ResultError = Result<int>.CreateError("Error"); [Test] public void Apply() { ResultError.Apply(i => Assert.Fail()); int applied = 0; ResultSuccess.Apply(i => applied = i); Assert.AreEqual(10, applied); } [Test] public void Convert() { Assert.AreEqual(Result.CreateSuccess("10"), ResultSuccess.Convert(i => i.ToString()), "#1"); Assert.AreEqual(Result<string>.CreateError("Error"), ResultError.Convert(i => i.ToString()),"#2"); } [Test] public void Combine() { var error1 = Result<int>.CreateError("E1"); var error1s = Result<string>.CreateError("E1"); Func<int, Result<string>> fails = i => { throw new InvalidOperationException(); }; Assert.AreEqual(error1s, error1.Combine(fails)); Assert.AreEqual(error1s, ResultSuccess.Combine(i => error1s)); Assert.AreEqual(Result.CreateSuccess("10"), ResultSuccess.Combine(i => Result.CreateSuccess(i.ToString()))); } [Test] public void ToMaybe() { Assert.AreEqual(Maybe<int>.Empty, ResultError.ToMaybe()); Assert.AreEqual(Maybe.From(10), ResultSuccess.ToMaybe()); Assert.AreEqual(Maybe<int>.Empty, ResultError.ToMaybe(i => i)); Assert.AreEqual(Maybe.From(10), ResultSuccess.ToMaybe(i => i)); } [Test] public void Create_formatted_error() { var result = Result<int>.CreateError("Error {0}", 1); Assert.AreEqual("Error 1", result.Error); } [Test] public void Equality_members() { // Silverlight does not contain Hashset var hashset = new[] { ResultSuccess }.ToDictionary(r => r); Assert.IsTrue(hashset.ContainsKey(ResultSuccess)); Assert.IsFalse(hashset.ContainsKey(ResultError)); Assert.IsTrue(hashset.ContainsKey(10)); } static void Throw(string message) { throw new InvalidOperationException(); } [Test] public void Success_with_apply_handle() { var val = 0; ResultSuccess .Apply(x => val = x) .Handle(Throw) .Apply(x => val += x); Assert.AreEqual(ResultSuccess.Value * 2, val); } [Test, Expects.InvalidOperationException] public void Failure_with_apply_handle() { ResultError .Apply(x => Assert.Fail()) .Handle(Throw); } [Test] public void ExposeException() { var exception = ResultSuccess.ExposeException(s => new InvalidOperationException("should not fail")); Assert.AreEqual(exception, ResultSuccess.Value); } [Test, Expects.InvalidOperationException] public void ExposeException_with_failure() { ResultError.ExposeException(s => new InvalidOperationException(s)); } } }<file_sep>/Sample/Shared/ReadMe.txt Copyright (c) 2006-2009 LOKAD SAS. All rights reserved. Distributed under the new BSD License. This folder contains samples and reference implementations for the Lokad Shared Libraries. Rules UI -------- This is a sample on DDD and rule-driven UI Validation in .NET with Lokad Shared Libraries. Article for this sample is available at: http://abdullin.com/journal/2009/1/29/ddd-and-rule-driven-ui-validation-in-net.html<file_sep>/Source/Lokad.Shared/Quality/ImmutableAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// <para>Class is considered to be immutable, when all fields are read-only. /// This makes the class safe for the multi-threaded operations.</para> /// <para>This attribute is used as a marker for code validation that actually enforced the rule</para> /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] [NoCodeCoverage] public sealed class ImmutableAttribute : ClassDesignAttribute { /// <summary> /// Initializes a new instance of the <see cref="ImmutableAttribute"/> class. /// </summary> public ImmutableAttribute() : base(DesignTag.ImmutableWithFields) { } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/SimpleScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class SimpleScopeTests { [Test] public void Nesting_Works() { IScope t = new SimpleScope("Test", (path, level, message) => { Assert.AreEqual("Test.Child", path); Assert.AreEqual(RuleLevel.Error, level); Assert.AreEqual("Message", message); }, level => { }); using (var scope = t.Create("Child")) { scope.Error("Message"); Assert.AreEqual(RuleLevel.Error, scope.Level); } Assert.AreEqual(RuleLevel.Error, t.Level); } } }<file_sep>/Source/Lokad.Shared/Reflection/ReflectCache.cs namespace Lokad.Reflection { static class ReflectCache<T> { public static string ReferenceName = "{" + typeof (T).Name + "}"; public static string SequenceName = "{" + typeof(T).Name + "}[]"; } } <file_sep>/Source/Lokad.Testing/ExtendIEquatable.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Testing { /// <summary> /// Extends <see cref="IEquatable{T}"/> for the purposes of testing /// </summary> public static class ExtendIEquatable { /// <summary> /// Ensures that the specified equals to a value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="value">The value.</param> /// <param name="compare">The compare.</param> /// <returns>same instance for inlining</returns> public static IEquatable<TValue> ShouldBeEqualTo<TValue>(this IEquatable<TValue> value, TValue compare) { Assert.IsTrue(value.EqualsTo(compare), "Value should be equal to '{0}'", compare); return value; } } }<file_sep>/Source/Lokad.Quality/Extensions/ModuleDefinitionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Extensions for the <see cref="ModuleDefinition"/> /// </summary> public static class ModuleDefinitionExtensions { /// <summary> /// Gets the assembly references. /// </summary> /// <param name="moduleDefinition">The module definition.</param> /// <returns>lazy enumerator over the results</returns> public static IEnumerable<AssemblyNameReference> GetAssemblyReferences(this ModuleDefinition moduleDefinition) { return moduleDefinition.AssemblyReferences.Cast<AssemblyNameReference>(); } } }<file_sep>/Source/Lokad.Shared/Errors.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using System.Reflection; using Lokad.Quality; using Lokad.Reflection; namespace Lokad { /// <summary> /// Helper class for generating exceptions /// </summary> [NoCodeCoverage] [UsedImplicitly] public class Errors { [NotNull] internal static Exception ArgumentNull<T>([NotNull] Func<T> argumentReference) { var message = StringUtil.FormatInvariant("Parameter of type '{0}' can't be null", typeof (T)); var paramName = Reflect.VariableName(argumentReference); return new ArgumentNullException(paramName, message); } [NotNull] internal static Exception Argument<T>([NotNull] Func<T> argumentReference, [NotNull] string message) { var paramName = Reflect.VariableName(argumentReference); return new ArgumentException(message, paramName); } static readonly MethodInfo InternalPreserveStackTraceMethod; static Errors() { InternalPreserveStackTraceMethod = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); } /// <summary> /// Returns inner exception, while preserving the stack trace /// </summary> /// <param name="e">The target invocation exception to unwrap.</param> /// <returns>inner exception</returns> [NotNull, UsedImplicitly] public static Exception Inner([NotNull] TargetInvocationException e) { if (e == null) throw new ArgumentNullException("e"); InternalPreserveStackTraceMethod.Invoke(e.InnerException, new object[0]); return e.InnerException; } } }<file_sep>/Source/Lokad.Stack/Logging/LoggingModule.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Autofac; using Autofac.Builder; using Autofac.Core; namespace Lokad.Logging { /// <summary> /// Autofac extension module that provides integration with the log4net /// </summary> public sealed class LoggingModule : IModule { LoggingMode _mode = LoggingMode.Console; /// <summary> /// Informs the module to use the config file /// </summary> public bool UseConfig { get { return _mode == LoggingMode.Config; } set { _mode = value ? LoggingMode.Config : LoggingMode.Console; } } string _fileName; /// <summary> /// Informs the module to use the provided file /// </summary> public string FileName { get { return _fileName; } set { if (string.IsNullOrEmpty(value)) throw new InvalidOperationException(); _fileName = value; _mode = LoggingMode.File; } } /// <summary> /// <see cref="IModule.Configure"/> /// </summary> /// <param name="container"></param> public void Configure(IComponentRegistry container) { switch (_mode) { case LoggingMode.Console: LoggingStack.UseConsoleLog(); break; case LoggingMode.Config: LoggingStack.UseConfig(); break; case LoggingMode.File: LoggingStack.ConfigureFromFile(_fileName); break; default: throw new ArgumentOutOfRangeException(); } var builder = new ContainerBuilder(); // register log provider builder.RegisterInstance(LoggingStack.GetLogProvider()).As<ILogProvider, INamedProvider<ILog>>(); builder.Register(c => c.Resolve<INamedProvider<ILog>>().Get("Default")); builder.Update(container); } } }<file_sep>/Source/Lokad.Shared/Settings/PrefixTruncatingKeyFilter.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Settings { /// <summary> /// Simple prefix-based path acceptor, that removes prefix from the path after match /// </summary> public sealed class PrefixTruncatingKeyFilter : ISettingsKeyFilter { readonly string _prefix; /// <summary> /// Initializes a new instance of the /// <see cref="PrefixTruncatingKeyFilter" /> /// class. /// </summary> /// <param name="prefix">The prefix.</param> public PrefixTruncatingKeyFilter(string prefix) { Enforce.ArgumentNotEmpty(() => prefix); _prefix = prefix; } Maybe<string> ISettingsKeyFilter.Filter(string keyPath) { if (!keyPath.StartsWith(_prefix, StringComparison.InvariantCulture)) return Maybe<string>.Empty; var filter = keyPath.Remove(0, _prefix.Length); return filter; } } }<file_sep>/Source/Lokad.ActionPolicy/Exceptions/RetryState.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad.Exceptions { [Immutable] sealed class RetryState : IRetryState { readonly Action<Exception> _onRetry; public RetryState(Action<Exception> onRetry) { _onRetry = onRetry; } bool IRetryState.CanRetry(Exception ex) { _onRetry(ex); return true; } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendArray.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Shortcuts for some common array operations /// </summary> public static class ExtendArray { /// <summary> /// Shorthand extension method for converting the arrays /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> /// <typeparam name="TTarget">The type of the target array.</typeparam> /// <param name="source">The array to convert.</param> /// <param name="converter">The converter.</param> /// <returns>target array instance</returns> public static TTarget[] Convert<TSource, TTarget>(this TSource[] source, Converter<TSource, TTarget> converter) { if (source == null) throw new ArgumentNullException("source"); if (converter == null) throw new ArgumentNullException("converter"); var outputArray = new TTarget[source.Length]; for (int i = 0; i < source.Length; i++) { outputArray[i] = converter(source[i]); } return outputArray; } /// <summary> /// Shorthand extension method for converting the arrays /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> /// <typeparam name="TTarget">The type of the target array.</typeparam> /// <param name="source">The array to convert.</param> /// <param name="converter">The converter, where the second parameter is an index of item being converted.</param> /// <returns>target array instance</returns> public static TTarget[] Convert<TSource, TTarget>(this TSource[] source, Func<TSource, int, TTarget> converter) { if (source == null) throw new ArgumentNullException("source"); if (converter == null) throw new ArgumentNullException("converter"); var outputArray = new TTarget[source.Length]; int i = 0; foreach (var input in source) { outputArray[i] = converter(input, i++); } return outputArray; } /// <summary> /// Applies the action to each item in the array /// </summary> /// <typeparam name="T">type of the items in the array</typeparam> /// <param name="self">The array to walk through.</param> /// <param name="action">The action.</param> /// <returns>Same array instance</returns> public static T[] ForEach<T>(this T[] self, Action<T> action) { if (self == null) throw new ArgumentNullException("self"); if (action == null) throw new ArgumentNullException("action"); foreach (var t in self) { action(t); } return self; } /// <summary> /// Slices array into array of arrays of length up to <paramref name="sliceLength"/> /// </summary> /// <typeparam name="T">Type of the items int the array</typeparam> /// <param name="array">The array.</param> /// <param name="sliceLength">Length of the slice.</param> /// <returns>array of sliced arrays</returns> /// <exception cref="ArgumentNullException">When source array is null</exception> /// <exception cref="ArgumentOutOfRangeException">When <paramref name="sliceLength"/> is invalid</exception> public static T[][] SliceArray<T>(this T[] array, int sliceLength) { if (array == null) throw new ArgumentNullException("array"); if (sliceLength <= 0) { throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); } if (array.Length == 0) return new T[0][]; int segments = array.Length/sliceLength; int last = array.Length%sliceLength; int totalSegments = segments + (last == 0 ? 0 : 1); var result = new T[totalSegments][]; for (int i = 0; i < segments; i++) { var item = result[i] = new T[sliceLength]; Array.Copy(array, i*sliceLength, item, 0, sliceLength); } if (last > 0) { var item = result[totalSegments - 1] = new T[last]; Array.Copy(array, segments*sliceLength, item, 0, last); } return result; } /// <summary> /// Converts this array to a jagged array, while bringing indexing to zero-based. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="array">The array.</param> /// <returns>jagged array</returns> public static TValue[][] ToJaggedArray<TValue>([NotNull] this TValue[,] array) { if (array == null) throw new ArgumentNullException("array"); var aMin = array.GetLowerBound(0); var aMax = array.GetUpperBound(0); var rows = aMax - aMin + 1; var bMin = array.GetLowerBound(1); var bMax = array.GetUpperBound(1); var cols = bMax - bMin + 1; var result = new TValue[rows][]; for (int row = 0; row < rows; row++) { result[row] = new TValue[cols]; for (int col = 0; col < cols; col++) { result[row][col] = array[row + aMin, col + bMin]; } } return result; } } }<file_sep>/Source/Lokad.Stack/Logging/ConfiguratorHelper.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using log4net.Appender; using log4net.Core; using log4net.Layout; namespace Lokad.Logging { using Colors = ColoredConsoleAppender.Colors; static class ConfiguratorHelper { internal static Level ToLog4Net(this LogLevel level) { switch (level) { case LogLevel.Min: return Level.All; case LogLevel.Debug: return Level.Debug; case LogLevel.Info: return Level.Info; case LogLevel.Warn: return Level.Warn; case LogLevel.Error: return Level.Error; case LogLevel.Fatal: return Level.Fatal; case LogLevel.Max: return Level.Off; default: throw new ArgumentOutOfRangeException("level"); } } internal static RollingFileAppender GetDailyLog(string path) { var layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); layout.ActivateOptions(); var log = new RollingFileAppender { File = path, AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Date, DatePattern = "yyyyMMdd", Layout = layout }; log.ActivateOptions(); return log; } internal static EventLogAppender GetEventLogAppender(string logName, string applicationName) { var layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); layout.ActivateOptions(); var appender = new EventLogAppender { ApplicationName = applicationName, LogName = logName, Layout = layout, }; appender.ActivateOptions(); return appender; } internal static RollingFileAppender GetRollingLog(string path, int numberOfBackups, long size) { var layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); layout.ActivateOptions(); var log = new RollingFileAppender { File = path, AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Size, MaxSizeRollBackups = numberOfBackups, StaticLogFileName = true, MaxFileSize = size, Layout = layout }; log.ActivateOptions(); return log; } internal static ConsoleAppender BuildConsoleLog(LogOptions options) { var layout = new PatternLayout { ConversionPattern = options.Pattern }; layout.ActivateOptions(); var appender = new ConsoleAppender { Layout = layout }; appender.ActivateOptions(); return appender; } internal static TraceAppender BuildTraceLog(ListeningLogOptions options) { var layout = new PatternLayout { ConversionPattern = options.Pattern }; layout.ActivateOptions(); var appender = new TraceAppender { Layout = layout, ImmediateFlush = options.ImmediateFlush }; appender.ActivateOptions(); return appender; } internal static DebugAppender BuildDebugLog(ListeningLogOptions options) { var layout = new PatternLayout { ConversionPattern = options.Pattern }; layout.ActivateOptions(); var appender = new DebugAppender { Layout = layout, ImmediateFlush = options.ImmediateFlush }; appender.ActivateOptions(); return appender; } internal static LogOptions GetDefaultOptions() { return new LogOptions { Pattern = PatternLayout.DetailConversionPattern }; } internal static ListeningLogOptions GetDefaultListeningOptions() { return new ListeningLogOptions() { Pattern = PatternLayout.DetailConversionPattern }; } internal static ColoredConsoleAppender BuildColoredConsoleLog(LogOptions options) { var layout = new PatternLayout { ConversionPattern = options.Pattern }; layout.ActivateOptions(); var appender = new ColoredConsoleAppender { Layout = layout }; Map(appender, Colors.Red | Colors.HighIntensity, Level.Alert, Level.Critical, Level.Emergency, Level.Error, Level.Fatal, Level.Severe); Map(appender, Colors.Cyan | Colors.HighIntensity, Level.Info, Level.Notice); Map(appender, Colors.Yellow | Colors.HighIntensity, Level.Warn); appender.ActivateOptions(); return appender; } static void Map(ColoredConsoleAppender appender, Colors fore, params Level[] levels) { foreach (var level in levels) { appender.AddMapping(new ColoredConsoleAppender.LevelColors() { ForeColor = fore, Level = level }); } } } }<file_sep>/Test/Lokad.Shared.Test/Rules/EnforceTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class EnforceTests { // ReSharper disable InconsistentNaming static void ClassUsagePatterns<T>(T param, IEnumerable<T> collection, Rule<T> rule) where T : class { Enforce.Argument(() => param); Enforce.Argument(() => param, rule); Enforce.Argument(() => collection, rule); Enforce.Arguments(() => param, () => param); Enforce.Arguments(() => param, () => param, () => param); Enforce.Arguments(() => param, () => param, () => param, () => param); Enforce.Arguments(() => param, () => param, () => param, () => param, () => param); Enforce.That(() => param); Enforce.That(() => param, rule); Enforce.That(() => collection, rule); Enforce.That(param, rule); Enforce.That(collection, rule); var local = param; Enforce.NotNull(() => local); } [Test] public void Simple_usage_patterns() { Enforce.That(true); Enforce.That(true, "Check"); Enforce.That(true, "Format {0}", 1); var value = new object(); Enforce.NotNull(value); Enforce.NotNull(value, "value"); } static void ValueUsagePatterns<T>(T param, IEnumerable<T> collection, Rule<T> rule) { Enforce.Argument(() => param, rule); Enforce.Argument(() => collection, rule); Enforce.That(() => param); Enforce.That(() => param, rule); Enforce.That(() => collection, rule); Enforce.That(param, rule); Enforce.That(collection, rule); } static void StringUsagePatterns(string param, Rule<string> rule) { Enforce.ArgumentNotEmpty(() => param); Enforce.Argument(() => param, rule); } [Test] public void Test() { var i = new { Value = 10 }; ClassUsagePatterns(i, Enumerable.Repeat(i, 4), (p, scope) => scope.Validate(i.Value, "Value", Is.AtLeast(10))); ValueUsagePatterns(1, Range.Create(30), (int1, scope) => { }); StringUsagePatterns("1", StringIs.Without('+')); } [Test, Expects.ArgumentException] public void ArgumentNotEmpty_On_Null() { var v = string.Empty; Enforce.ArgumentNotEmpty(() => v); } [Test, Expects.ArgumentNullException] public void ArgumentNotEmpty_On_Empty() { // ReSharper disable ConvertToConstant string v = null; // ReSharper restore ConvertToConstant Enforce.ArgumentNotEmpty(() => v); } [Test, Expects.InvalidOperationException] public void NotNull_variable() { object arg = null; Enforce.NotNull(() => arg); } const string Value = null; [Test, Expects.InvalidOperationException] public void NotNull_handles_bad_arguments() { Enforce.NotNull(() => Value); } [Test, Expects.ArgumentNullException] public void Argument_handles_bad_references() { Enforce.Argument(() => Value); } [Test, Expects.ArgumentNullException] public void ArgumentNotEmpty_handles_bad_references() { Enforce.ArgumentNotEmpty(() => Value); } } }<file_sep>/Test/Lokad.Shared.Test/NamedProviderTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class NamedProviderTests { static readonly INamedProvider<int> _provider = new Dictionary<string, int> {{"1", 1}, {"2", 2}}.AsProvider(); [Test, Expects.ResolutionException] public void Exception() { _provider.Get("0"); } [Test] public void Resolution() { Assert.AreEqual(1, _provider.Get("1")); } } }<file_sep>/Source/Lokad.Stack/Logging/LogOptions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using log4net.Layout; namespace Lokad.Logging { /// <summary> /// Log options /// </summary> public class LogOptions { /// <summary> /// Gets or sets the conversion pattern. /// </summary> /// <value>The conversion pattern.</value> /// <seealso cref="PatternLayout.DefaultConversionPattern"/> /// <seealso cref="PatternLayout.DetailConversionPattern"/> public string Pattern { get; set; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/MessageScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class MessageScopeTests { [Test] public void Test() { var messages = Scope.GetMessages(0, "item", ScopeTestHelper.RunNesting); Assert.AreEqual(6, messages.Count); var check = messages[3]; Assert.AreEqual(RuleLevel.Error, check.Level); Assert.AreEqual("Error1", check.Message); Assert.AreEqual("item.Group1.Group2", check.Path); Assert.IsTrue(messages.IsError, "IsError"); Assert.IsTrue(messages.IsWarn, "IsWarn"); Assert.IsFalse(messages.IsSuccess, "IsSuccess"); } [Test] public void Empty() { var messages = Scope.GetMessages(0, "item"); Assert.IsNotNull(messages); CollectionAssert.IsEmpty(messages); Assert.IsFalse(messages.IsError, "IsError"); Assert.IsFalse(messages.IsWarn, "IsWarn"); Assert.IsTrue(messages.IsSuccess, "IsSuccess"); } } }<file_sep>/Source/Lokad.Shared/Syntax/Syntax.TTarget.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.ComponentModel; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class for creating fluent APIs /// </summary> /// <typeparam name="TTarget">underlying type</typeparam> [Immutable] [Serializable] [NoCodeCoverage] public sealed class Syntax<TTarget> : Syntax, ISyntax<TTarget> { readonly TTarget _inner; /// <summary> /// Initializes a new instance of the <see cref="Syntax{T}"/> class. /// </summary> /// <param name="inner">The underlying instance.</param> public Syntax(TTarget inner) { _inner = inner; } #region ISyntax<TTarget> Members /// <summary> /// Gets the underlying object. /// </summary> /// <value>The underlying object.</value> [EditorBrowsable(EditorBrowsableState.Advanced)] public TTarget Target { get { return _inner; } } #endregion internal static Syntax<TTarget> For(TTarget item) { return new Syntax<TTarget>(item); } } }<file_sep>/Source/Lokad.Shared/Utils/EnumUtil.TEnum.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; namespace Lokad { /// <summary> /// Strongly-typed enumeration util /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> public static class EnumUtil<TEnum> where TEnum : struct, IComparable { /// <summary> /// Values of the <typeparamref name="TEnum"/> /// </summary> public static readonly TEnum[] Values; /// <summary> /// Values of the <typeparamref name="TEnum"/> without the default value. /// </summary> public static readonly TEnum[] ValuesWithoutDefault; // enum parsing performance is horrible! internal static readonly IDictionary<string, TEnum> CaseDict; internal static readonly IDictionary<string, TEnum> IgnoreCaseDict; internal static readonly string EnumPrefix = typeof (TEnum).Name + "_"; /// <summary> /// Efficient comparer for the enum /// </summary> public static readonly IEqualityComparer<TEnum> Comparer; static EnumUtil() { Values = GetValues(); var def = default(TEnum); ValuesWithoutDefault = Values.Where(x => !def.Equals(x)).ToArray(); Comparer = EnumComparer<TEnum>.Instance; IgnoreCaseDict = new Dictionary<string, TEnum>(StringComparer.InvariantCultureIgnoreCase); CaseDict = new Dictionary<string, TEnum>(StringComparer.InvariantCulture); foreach (var value in Values) { var item = value.ToString(); IgnoreCaseDict[item] = value; CaseDict[item] = value; } } /// <summary> /// Converts the specified enum safely from the target enum. Matching is done /// via the efficient <see cref="Comparer"/> initialized with <see cref="MaybeParse.Enum{TEnum}(string)"/> /// </summary> /// <typeparam name="TSourceEnum">The type of the source enum.</typeparam> /// <param name="enum">The @enum to convert from.</param> /// <returns>converted enum</returns> /// <exception cref="ArgumentException"> when conversion is not possible</exception> public static TEnum ConvertSafelyFrom<TSourceEnum>(TSourceEnum @enum) where TSourceEnum : struct, IComparable { return EnumUtil<TSourceEnum, TEnum>.Convert(@enum); } static TEnum[] GetValues() { Type enumType = typeof (TEnum); if (!enumType.IsEnum) { throw new ArgumentException("Type is not an enum: '" + enumType.Name); } #if !SILVERLIGHT2 return Enum .GetValues(enumType) .Cast<TEnum>() .ToArray(); #else return enumType .GetFields() .Where(field => field.IsLiteral) .ToArray(f => (TEnum) f.GetValue(enumType)); #endif } } }<file_sep>/Source/Lokad.Stack/ExtendISupportSyntaxForLogging.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using Lokad.Logging; using Lokad.Quality; namespace Lokad { /// <summary> /// Extends logging syntax /// </summary> public static class ExtendISupportSyntaxForLogging { /// <summary> /// Registers the log provider from the current log4net stack <see cref="LoggingStack.GetLogProvider"/>. /// See <see cref="LoggingStack"/> for options on configuring Apache log4net options. /// </summary> /// <param name="module">The module to extend.</param> [UsedImplicitly] public static void LogToStack(this ISupportSyntaxForLogging module) { module.RegisterLogProvider(LoggingStack.GetLogProvider()); } } }<file_sep>/Source/Lokad.Shared/Provider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using Lokad.Quality; namespace Lokad { /// <summary> /// This class provides short-cut for creating providers /// out of lambda expressions. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [Serializable] [Immutable] public class Provider<TKey, TValue> : IProvider<TKey, TValue> { readonly Func<TKey, TValue> _resolver; /// <summary> /// Initializes a new instance of the <see cref="Provider{TKey, TValue}"/> class. /// </summary> /// <param name="resolver">The resolver.</param> /// <exception cref="ArgumentNullException">When /// <paramref name="resolver"/> is null</exception> public Provider(Func<TKey, TValue> resolver) { if (resolver == null) throw new ArgumentNullException("resolver"); _resolver = resolver; } /// <summary> /// Retrieves <typeparamref name="TValue"/> given the /// </summary> /// <param name="key"></param> /// <returns></returns> /// <exception cref="ResolutionException">when the key is invalid for /// the provider</exception> public TValue Get(TKey key) { try { return _resolver(key); } catch (Exception ex) { Type valueType = typeof (TValue); throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0} with key '{1}'", valueType, (object) key), ex); } } } /// <summary> /// Helper class that simplifies creation of <see cref="Provider{TKey,TValue}"/> /// </summary> /// <typeparam name="TKey">type of the Key items</typeparam> [NoCodeCoverage] public static class Provider<TKey> { /// <summary> /// Creates the provider, letting compiler to figure out /// the value type. This allows to use anonymous types locally as well /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="func">The function that is the provider.</param> /// <returns>new provider instance</returns> public static IProvider<TKey, TValue> For<TValue>(Func<TKey, TValue> func) { return new Provider<TKey, TValue>(func); } } }<file_sep>/Test/Lokad.Shared.Test/Utils/FormatUtilTests.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class FormatUtilTests { // ReSharper disable InconsistentNaming [Test] public void Formatting_large_interval() { StringAssert.Contains("years from now", FormatUtil.TimeOffsetUtc(DateTime.MaxValue)); StringAssert.Contains("years ago", FormatUtil.TimeOffsetUtc(DateTime.MinValue)); } [Test] public void Formatting_large_size() { Assert.AreEqual("8 EB", FormatUtil.SizeInBytes(long.MaxValue)); } } }<file_sep>/Source/Lokad.Shared/Settings/ISettingsRepository.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Settings { /// <summary> /// Simple repository that merely loads all available /// and applicable settings for this instance. /// Tenant filtering and other options, if applicable, /// would be hidden behind this interface /// </summary> public interface ISettingsRepository { /// <summary> /// Loads the currently active settings from the repo. /// </summary> /// <returns> /// dictionary containing settings /// </returns> ISettingsProvider LoadSettings(); } }<file_sep>/Source/Lokad.Quality/Properties/AssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; [assembly : AssemblyTitle("Lokad.Quality")] [assembly : AssemblyDescription("Lokad Code Quality routines")] [assembly: AssemblyCopyright(GlobalAssemblyInfo.Copyright)] [assembly: AssemblyTrademark(GlobalAssemblyInfo.Trademark)] [assembly: CLSCompliant(false)]<file_sep>/Source/Lokad.Stack/Logging/LoggingMode.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Logging { /// <summary> /// Defines log modes for the <see cref="LoggingModule"/> /// </summary> enum LoggingMode { /// <summary> /// Initializes logging system to write to the console. /// </summary> Console, /// <summary> /// All logging is configured via lognet config /// </summary> Config, /// <summary> /// Logging is configured from file /// </summary> File } }<file_sep>/Resource/Tool/ILMerge/ReadMe.txt Due to the Licensing restrictions ILMerge can't be distributed with this project. If you want to run the merge task, download and place ILMerge.exe in this folder http://www.microsoft.com/downloads/details.aspx?familyid=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en<file_sep>/Source/Lokad.Shared/Utils/DebugUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper utility for debugging /// </summary> [NoCodeCoverage, UsedImplicitly] public static class DebugUtil { static readonly BinaryFormatter Formatter = new BinaryFormatter(); /// <summary> /// Saves the object graph to the specified path. /// </summary> /// <param name="graph">The graph.</param> /// <param name="path">The path to save to.</param> public static void SaveTo(object graph, string path) { if (graph == null) throw new ArgumentNullException("graph"); if (path == null) throw new ArgumentNullException("path"); using (var stream = File.Create(path)) { Formatter.Serialize(stream, graph); } } /// <summary> /// Loads the graph from the specified path. /// </summary> /// <param name="path">The path to load from.</param> /// <returns>graph loaded from the specified path</returns> public static object LoadFrom(string path) { if (path == null) throw new ArgumentNullException("path"); using (var stream = File.OpenRead(path)) { return Formatter.Deserialize(stream); } } /// <summary> /// Loads the graph from the specified path. /// </summary> /// <typeparam name="TGraph">The type of the item.</typeparam> /// <param name="path">The path to load from.</param> /// <returns>graph loaded from the specified path</returns> public static TGraph LoadFrom<TGraph>(string path) { if (path == null) throw new ArgumentNullException("path"); return (TGraph) LoadFrom(path); } } } #endif<file_sep>/Source/Lokad.Stack/Logging/LogWrapper.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using log4net; using Lokad.Quality; namespace Lokad.Logging { /// <summary> /// Wrapper around <see cref="log4net.ILog"/> /// </summary> [NoCodeCoverage] public sealed class LogWrapper : ILog { readonly log4net.ILog _inner; internal static ILog GetByName(string logName) { return new LogWrapper(LogManager.GetLogger(logName)); } LogWrapper(log4net.ILog inner) { _inner = inner; } void ILog.Log(LogLevel level, Exception exception, object message) { switch (level) { case LogLevel.Debug: _inner.Debug(message, exception); break; case LogLevel.Info: _inner.Info(message, exception); break; case LogLevel.Warn: _inner.Warn(message, exception); break; case LogLevel.Error: _inner.Error(message, exception); break; case LogLevel.Fatal: _inner.Fatal(message, exception); break; default: throw new ArgumentOutOfRangeException("level"); } } bool ILog.IsEnabled(LogLevel level) { switch (level) { case LogLevel.Debug: return _inner.IsDebugEnabled; case LogLevel.Info: return _inner.IsInfoEnabled; case LogLevel.Warn: return _inner.IsWarnEnabled; case LogLevel.Error: return _inner.IsErrorEnabled; case LogLevel.Fatal: return _inner.IsFatalEnabled; default: throw new ArgumentOutOfRangeException("level"); } } void ILog.Log(LogLevel level, object message) { switch (level) { case LogLevel.Debug: _inner.Debug(message); break; case LogLevel.Info: _inner.Info(message); break; case LogLevel.Warn: _inner.Warn(message); break; case LogLevel.Error: _inner.Error(message); break; case LogLevel.Fatal: _inner.Fatal(message); break; default: throw new ArgumentOutOfRangeException("level"); } } } }<file_sep>/Source/Lokad.Logging/Diagnostics/LambdaLogProvider.cs using System; namespace Lokad { /// <summary> /// Log provider, that uses lambda expression /// </summary> public sealed class LambdaLogProvider : ILogProvider { readonly Func<string, ILog> _factory; /// <summary> /// Initializes a new instance of the <see cref="LambdaLogProvider"/> class. /// </summary> /// <param name="factory">The factory.</param> public LambdaLogProvider(Func<string, ILog> factory) { _factory = factory; } ILog IProvider<string, ILog>.Get(string key) { return _factory(key); } } }<file_sep>/Source/Lokad.Testing/ExtendResult1.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq.Expressions; using Lokad.Quality; namespace Lokad.Testing { /// <summary> /// Extends <see cref="Result{T}"/> for the purposes of testing /// </summary> [UsedImplicitly] public static class ExtendResult1 { /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <returns>same result instance for further inlining</returns> public static Result<TValue> ShouldFail<TValue>(this Result<TValue> result) { Assert.IsFalse(result.IsSuccess, "Result should be a failure"); return result; } /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="error">The error.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue> ShouldFailWith<TValue>(this Result<TValue> result, string error) { Assert.IsFalse(result.IsSuccess, "result should be a failure"); Assert.IsTrue(result.Error == error, "Error should be equal to '{0}'", error); return result; } /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TEnum">The type of the enum describing the failure.</typeparam> /// <param name="result">The result.</param> /// <param name="enum">The @enum.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue> ShouldFailWith<TValue, TEnum>(this Result<TValue> result, TEnum @enum) where TEnum : struct, IComparable { var s = EnumUtil.ToIdentifier(@enum); return result.ShouldFailWith(s); } ///// <summary> ///// Asserts that the result is equal to some error ///// </summary> ///// <typeparam name="TValue">The type of the value.</typeparam> ///// <typeparam name="TError">The type of the error.</typeparam> ///// <param name="result">The result.</param> ///// <param name="error">The error.</param> ///// <returns>same result instance for further inlining</returns> //public static Result<TValue> ShouldFail<TValue, TError>(this Result<TValue> result, TError error) // where TError : struct //{ // Assert.IsFalse(result.IsSuccess, "Result should be a failure"); // var unwrappedError = typeof(TError).Name + "_" + error; // Assert.IsTrue(result.Error.Equals(unwrappedError), // "Result should have expected failure{0}Expected: {1}.{0}Was: {2}.", // Environment.NewLine, error, result.Error); // return result; //} /// <summary> /// Asserts that the result is valid and equal to some value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="value">The value.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue> ShouldPassWith<TValue>(this Result<TValue> result, TValue value) { if (!result.IsSuccess) Assert.Fail("Result should be valid. It had error instead: '{0}'", result.Error); var equatable = value as IEquatable<TValue>; if (equatable != null) { Assert.IsTrue(equatable.EqualsTo(result.Value), "Result should be equal to: '{0}'", value); } else { Assert.IsTrue(result.Value.Equals(value), "Result should be equal to: '{0}'", value); } return result; } /// <summary> /// Asserts that the result is valid and equal to some value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="value">The value.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue> ShouldBe<TValue>(this Result<TValue> result, TValue value) { return ShouldPassWith(result, value); } /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="error">The error.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue> ShouldBe<TValue>(this Result<TValue> result, string error) { return ShouldFailWith(result, error); } /// <summary> /// Checks that the result has a value matching to the provided expression in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="expression">The expression.</param> /// <returns>same result instance for inlining</returns> public static Result<TValue> ShouldPassCheck<TValue>(this Result<TValue> result, Expression<Func<TValue, bool>> expression) { if (!result.IsSuccess) Assert.Fail("Result should be valid. It had error instead: '{0}'", result.Error); var check = expression.Compile(); Assert.IsTrue(check(result.Value), "Expression should be true: '{0}'.", expression.Body.ToString()); return result; } /// <summary> /// Checks that the result has a value matching to the provided expression in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <returns>same result instance for inlining</returns> public static Result<TValue> ShouldPass<TValue>(this Result<TValue> result) { if (!result.IsSuccess) Assert.Fail("Result should be valid. It had error instead: '{0}'", result.Error); return result; } /// <summary> /// Ensures that the specified collections are equal in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="collection">The collection.</param> /// <param name="anotherCollection">Another collection.</param> /// <returns>same instance for inlining</returns> public static ICollection<TValue> ShouldBeEqualTo<TValue>(this ICollection<TValue> collection, ICollection<TValue> anotherCollection) where TValue : IEquatable<TValue> { Assert.IsTrue(collection.EqualsTo(anotherCollection), "Collections should be equal"); return collection; } /// <summary> /// Ensures that the specified collection is empty in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="collection">The collection.</param> /// <returns>same instance for inlining</returns> public static ICollection<TValue> ShouldBeEmpty<TValue>(this ICollection<TValue> collection) where TValue : IEquatable<TValue> { Assert.IsTrue(collection.Count == 0, "collection should be empty"); return collection; } } }<file_sep>/Source/Lokad.Testing/Testing/MockContainer/RegistrationSource.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Globalization; using Autofac; using Autofac.Core; using Autofac.Core.Activators.Delegate; using Autofac.Core.Lifetime; using Autofac.Core.Registration; using Rhino.Mocks; namespace Lokad.Testing { sealed class RhinoRegistrationSource : IRegistrationSource { public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); var typedService = service as TypedService; if ((typedService == null)) yield break; var newGuid = Guid.NewGuid(); var registration = new ComponentRegistration( newGuid, new DelegateActivator(typedService.ServiceType, (c, p) => { try { return MockRepository.GenerateStub(typedService.ServiceType); } catch (Exception ex) { Type valueType = typedService.ServiceType; throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0}", valueType), ex); } }), new RootScopeLifetime(), InstanceSharing.Shared, InstanceOwnership.OwnedByLifetimeScope, new Service[] { new UniqueService(newGuid), typedService}, new Dictionary<string, object>()); yield return registration; } public bool IsAdapterForIndividualComponents { get { return false; } } } }<file_sep>/Test/Lokad.Shared.Test/Utils/StringUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class StringUtilTests { [Test] public void Test_MemberNameToCaption() { Assert.AreEqual("Lokad - Account Id", StringUtil.MemberNameToCaption("Lokad.AccountId")); } } }<file_sep>/Source/Lokad.Logging/ISupportSyntaxForLogging.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion namespace Lokad { /// <summary> /// Syntax extensions for Logging configurations /// </summary> public interface ISupportSyntaxForLogging { /// <summary> /// Registers the specified log provider instance as singleton. /// </summary> /// <param name="provider">The provider.</param> void RegisterLogProvider(ILogProvider provider); } }<file_sep>/Source/Lokad.Shared/Utils/EnumUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Enum helper class from xLim /// </summary> public static class EnumUtil { /// <summary> /// Parses the specified string into the <typeparamref name="TEnum"/>, ignoring the case /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The value.</param> /// <returns>Parsed enum</returns> /// <exception cref="ArgumentNullException">If <paramref name="value"/> is null</exception> public static TEnum Parse<TEnum>([NotNull] string value) where TEnum : struct, IComparable { if (value == null) throw new ArgumentNullException("value"); return Parse<TEnum>(value, true); } /// <summary> /// Parses the specified string into the <typeparamref name="TEnum"/>, ignoring the case /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The value.</param> /// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param> /// <returns>Parsed enum</returns> /// <exception cref="ArgumentNullException">If <paramref name="value"/> is null</exception> public static TEnum Parse<TEnum>([NotNull] string value, bool ignoreCase) where TEnum : struct, IComparable { if (value == null) throw new ArgumentNullException("value"); var dict = ignoreCase ? EnumUtil<TEnum>.IgnoreCaseDict : EnumUtil<TEnum>.CaseDict; TEnum @enum; if (!dict.TryGetValue(value, out @enum)) { throw new ArgumentException(string.Format("Can't find enum for '{0}'", value)); } return @enum; } /// <summary> /// Unwraps the enum by creating a string usable for identifiers and resource lookups. /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="enumItem">The enum item.</param> /// <returns>a string usable for identifiers and resource lookups</returns> public static string ToIdentifier<TEnum>(TEnum enumItem) where TEnum : struct, IComparable { return EnumUtil<TEnum>.EnumPrefix + enumItem; } /// <summary> /// Gets the values associated with the specified enum. /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <returns>array instance of the enum values</returns> public static TEnum[] GetValues<TEnum>() where TEnum : struct, IComparable { return EnumUtil<TEnum>.Values; } /// <summary> /// Gets the values associated with the specified enum, /// with the exception of the default value /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <returns>array instance of the enum values</returns> public static TEnum[] GetValuesWithoutDefault<TEnum>() where TEnum : struct, IComparable { return EnumUtil<TEnum>.ValuesWithoutDefault; } } }<file_sep>/Source/Lokad.Shared/Collections/Generic/ProjectionComparer.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; namespace Lokad.Collections.Generic { sealed class ProjectionComparer<TValue, TProjection> : IEqualityComparer<TValue> { readonly Func<TValue, TProjection> _projection; public ProjectionComparer(Func<TValue, TProjection> projection) { _projection = projection; } bool IEqualityComparer<TValue>.Equals(TValue x, TValue y) { var projectedX = _projection(x); var projectedY = _projection(y); return projectedX.Equals(projectedY); } int IEqualityComparer<TValue>.GetHashCode(TValue obj) { var projectedObj = _projection(obj); return projectedObj.GetHashCode(); } } }<file_sep>/Source/Lokad.Logging/Properties/AssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; [assembly : AssemblyTitle("Lokad.Logging")] [assembly : AssemblyDescription("Lokad Logging abstraction")] [assembly: AssemblyCopyright(GlobalAssemblyInfo.Copyright)] [assembly: AssemblyTrademark(GlobalAssemblyInfo.Trademark)] [assembly: CLSCompliant(true)]<file_sep>/Source/Lokad.Shared/INamedProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Shortcut interface for <see cref="IProvider{TKey,TValue}"/> that uses <see cref="string"/> as the key. /// </summary> /// <typeparam name="TValue"></typeparam> [CLSCompliant(true)] public interface INamedProvider<TValue> : IProvider<string, TValue> { } }<file_sep>/Source/Lokad.Shared/Serialization/IKnowSerializationTypes.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using System; using System.Collections.Generic; namespace Lokad.Serialization { /// <summary> /// Provides collection of known serialization types (for prebuilt serializers) /// </summary> public interface IKnowSerializationTypes { /// <summary> /// Gets the known serialization types. /// </summary> /// <returns></returns> IEnumerable<Type> GetKnownTypes(); } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/AssertionMethodAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied. /// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute /// </summary> /// <seealso cref="AssertionConditionAttribute"/> /// <remarks>This attribute helps R# in code analysis</remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class AssertionMethodAttribute : Attribute { } }<file_sep>/Source/Lokad.Shared/Resolver.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using Lokad.Quality; namespace Lokad { /// <summary> /// Implementation of the <see cref="IResolver"/> that uses delegates /// to wire up the resolution logics and wraps all exceptions with the /// <see cref="ResolutionException"/> /// </summary> [Serializable] [Immutable] public sealed class Resolver : IResolver { readonly Func<Type, object> _resolver; readonly Func<Type, string, object> _namedResolver; /// <summary> /// Initializes a new instance of the <see cref="Resolver"/> class. /// </summary> /// <param name="resolver">The resolver.</param> /// <param name="namedResolver">The named resolver.</param> public Resolver(Func<Type, object> resolver, Func<Type, string, object> namedResolver) { if (resolver == null) throw new ArgumentNullException("resolver"); if (namedResolver == null) throw new ArgumentNullException("namedResolver"); _resolver = resolver; _namedResolver = namedResolver; } /// <summary> /// Resolves this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns> /// requested instance of <typeparamref name="TService"/> /// </returns> /// <exception cref="ResolutionException">if there is some resolution problem</exception> public TService Get<TService>() { try { return (TService) _resolver(typeof (TService)); } catch (Exception ex) { Type valueType = typeof (TService); throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0}", valueType), ex); } } /// <summary> /// Resolves the specified service type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="name">The name.</param> /// <returns> /// requested instance of <typeparamref name="TService"/> /// </returns> /// <exception cref="ResolutionException">if there is resolution problem</exception> public TService Get<TService>(string name) { try { return (TService) _namedResolver(typeof (TService), name); } catch (Exception ex) { Type valueType = typeof (TService); throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0} with key '{1}'", valueType, (object) name), ex); } } } }<file_sep>/Source/Lokad.Shared/Quality/DesignUtil.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; namespace Lokad.Quality { /// <summary> /// Helper class for managing designs /// </summary> public static class DesignUtil { /// <summary> /// Converts the tag to string. /// </summary> /// <param name="tag">The tag.</param> /// <returns>string representation for the tag</returns> public static string ConvertTagToString(DesignTag tag) { return "Lokad.Class." + tag; } /// <summary> /// Converts multiple tags to strings. /// </summary> /// <param name="tags">The tags to convert.</param> /// <returns>array of string representations for the design tags</returns> public static string[] ConvertTagsToStrings(params DesignTag[] tags) { return tags.Convert(ConvertTagToString); } /// <summary> /// Gets the class design tags. /// </summary> /// <param name="type">The type.</param> /// <param name="inherit"> /// if set to /// <c>true</c> /// [inherit]. /// </param> /// <returns> /// array of class design tags /// </returns> /// <remarks> /// it is advised to cache the results, if performance is important /// </remarks> public static string[] GetClassDesignTags(Type type, bool inherit) { // we are using unbound search, since property implementations might change var returnType = typeof (string[]); var attributes = type .GetCustomAttributes(inherit) .Cast<Attribute>(); return attributes .Select(a => new { Attribute = a, Property = a.GetType().GetProperty("ClassDesignTags", returnType) }).Where(x => null != x.Property) .SelectMany(x => (string[]) x.Property.GetValue(x.Attribute, null)) .Distinct() .ToArray(); } /// <summary> /// Simple type cache /// </summary> /// <typeparam name="T"></typeparam> public static class ClassCache<T> { /// <summary> /// Tags for the specified class /// </summary> public readonly static string[] Tags; /// <summary> /// If this class contains a model design tag /// </summary> public static readonly bool IsModel; static ClassCache() { Tags = GetClassDesignTags(typeof (T), false); IsModel = Tags.Contains(ConvertTagToString(DesignTag.Model)); } } } }<file_sep>/Source/Lokad.Testing/ExtendMaybe.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq.Expressions; using Lokad.Quality; namespace Lokad.Testing { /// <summary> /// Extends <see cref="Maybe{T}"/> for the purposes of testing /// </summary> [UsedImplicitly] public static class ExtendMaybe { /// <summary> /// Checks that optional has value matching to the provided value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="expression">The expression.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldPassCheck<TValue>(this Maybe<TValue> result, Expression<Func<TValue, bool>> expression) { Assert.IsTrue(result.HasValue, "Maybe should have value"); var check = expression.Compile(); Assert.IsTrue(check(result.Value), "Expression should be true: '{0}'.", expression.Body.ToString()); return result; } /// <summary> /// Checks that optional has value matching to the provided value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <param name="value">The value.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldPassWith<TValue>(this Maybe<TValue> result, TValue value) { Assert.IsTrue(result.HasValue, "Maybe should have value"); Assert.IsTrue(value.Equals(result.Value), "Value should be equal to: '{0}'.", value); return result; } /// <summary> /// Checks that optional has value matching to the provided value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="result">The result.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldPass<TValue>(this Maybe<TValue> result) { Assert.IsTrue(result.HasValue, "Maybe should have value"); return result; } /// <summary> /// Checks that the optional does not have any value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="maybe">The maybe.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldFail<TValue>(this Maybe<TValue> maybe) { Assert.IsFalse(maybe.HasValue, "Maybe should not have value"); return maybe; } /// <summary> /// Checks that optional has value matching to the provided value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="maybe">The maybe.</param> /// <param name="value">The value.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldBe<TValue>(this Maybe<TValue> maybe, TValue value) { return ShouldPassWith(maybe, value); } /// <summary> /// Checks that optional has value matching to the provided value in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="maybe">The maybe.</param> /// <param name="value">The value.</param> /// <returns>same instance for inlining</returns> public static Maybe<TValue> ShouldBe<TValue>(this Maybe<TValue> maybe, bool value) { Assert.IsTrue(maybe.HasValue == value, "Value.HasValue should be: {0}", value); return maybe; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/MaybeIsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class MaybeIsTests { // ReSharper disable InconsistentNaming [Test] public void EmptyOr() { RuleAssert.For(MaybeIs.EmptyOr(StringIs.WithoutUppercase)) .ExpectNone(Maybe<string>.Empty, "lowercase") .ExpectError(null, "UpperCase"); } [Test] public void ValidAnd() { RuleAssert.For(MaybeIs.ValidAnd(StringIs.WithoutUppercase)) .ExpectNone("lowercase") .ExpectError(null, Maybe.String, "Uppercase"); } } }<file_sep>/Source/Lokad.Shared/Utils/GuidUtil.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Guid comb generator as in NHibernate /// </summary> public static class GuidUtil { /// <summary> /// Generates new COMB Guid /// </summary> /// <returns>new comb guid</returns> public static Guid NewComb() { var guidArray = Guid.NewGuid().ToByteArray(); var baseDate = new DateTime(0x76c, 1, 1); var now = DateTime.UtcNow; var days = new TimeSpan(now.Ticks - baseDate.Ticks); var msecs = now.TimeOfDay; var daysArray = BitConverter.GetBytes(days.Days); var msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds/3.333333)); Array.Reverse(daysArray); Array.Reverse(msecsArray); Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new Guid(guidArray); } /// <summary> /// Creates GUIDs that have same uniqueness as COMB, but are string-sortable /// </summary> /// <returns>String-sortable GUID</returns> public static Guid NewStringSortable() { var guidArray = Guid.NewGuid().ToByteArray(); var baseDate = new DateTime(0x76c, 1, 1); var now = DateTime.UtcNow; var days = new TimeSpan(now.Ticks - baseDate.Ticks); var msecs = now.TimeOfDay; var daysArray = BitConverter.GetBytes(days.Days); var msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); var g = new byte[16]; Array.Copy(guidArray, 0, g, 6, 10); g[3] = daysArray[1]; g[2] = daysArray[0]; g[1] = msecsArray[3]; g[0] = msecsArray[2]; g[5] = msecsArray[1]; g[4] = msecsArray[0]; return new Guid(g); } } }<file_sep>/Test/Lokad.Shared.Test/CodeQualityTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using Lokad.Quality; using Lokad.Rules; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class CodeQualityTests { internal static readonly Codebase Codebase = new Codebase("Lokad.Shared.dll"); [Test] public void Maintainability() { Scope.Validate(Codebase, MaintainabilityRules.Immutable_Types_Should_Be_Immutable, MaintainabilityRules.Ncca_Is_Used_Properly(38)); } } } #endif<file_sep>/Source/Lokad.Shared/Rules/Common/StringIs.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using System.Text.RegularExpressions; namespace Lokad.Rules { /// <summary> /// Common string rules /// </summary> public static class StringIs { /// <summary> /// Originally http://fightingforalostcause.net/misc/2006/compare-email-regex.php, /// but modified to have less negative results /// </summary> static readonly Regex EmailRegex = new Regex( @"^[a-z0-9](([_\.\-\'\+]?[a-z0-9]+)*)" + @"@(([a-z0-9]{1,64})(([\.\-][a-z0-9]{1,64})*)\.([a-z]{2,})" + @"|(\d{1,3}(\.\d{1,3}){3}))$", #if !SILVERLIGHT2 RegexOptions.Compiled | #endif RegexOptions.Singleline | RegexOptions.IgnoreCase); static readonly Regex ServerConnectionRegex = new Regex( @"^(([a-z0-9]{1,64})(([\.\-][a-z0-9]{1,64})*)(\:\d{1,5})?)$", RegexOptions.Singleline | #if !SILVERLIGHT2 RegexOptions.Compiled | #endif RegexOptions.IgnoreCase); /// <summary> /// Determines whether the string is valid email address /// </summary> /// <param name="email">string to validate</param> /// <param name="scope">validation scope.</param> public static void ValidEmail(string email, IScope scope) { if (!EmailRegex.IsMatch(email)) scope.Error("String should be a valid email address."); } /// <summary> /// Determines whether the string is valid server connection (with optional port) /// </summary> /// <param name="host">The host name to validate.</param> /// <param name="scope">The validation scope.</param> public static void ValidServerConnection(string host, IScope scope) { if (!ServerConnectionRegex.IsMatch(host)) scope.Error("String should be a valid host name."); } /// <summary> /// Composes the string validator ensuring string length is within the supplied rangs /// </summary> /// <param name="minLength">Min string length.</param> /// <param name="maxLength">Max string length.</param> /// <returns>new validator instance</returns> public static Rule<string> Limited(int minLength, int maxLength) { Enforce.Argument(() => maxLength, Is.GreaterThan(0)); Enforce.Argument(() => minLength, Is.Within(0, maxLength)); return (s, scope) => { if (s.Length < minLength) scope.Error("String should not be shorter than {0} characters.", minLength); if (s.Length > maxLength) scope.Error("String should not be longer than {0} characters.", maxLength); }; } /// <summary> /// Composes the string validator ensuring string length is shorter than /// <paramref name="maxLength"/> /// </summary> /// <param name="maxLength">Max string length.</param> /// <returns>new validator instance</returns> public static Rule<string> Limited(int maxLength) { Enforce.Argument(() => maxLength, Is.GreaterThan(0)); return (s, scope) => { if (s.Length > maxLength) scope.Error("String should not be longer than {0} characters.", maxLength); }; } /// <summary> /// Reports error if the associated string is empty /// </summary> public static readonly Rule<string> NotEmpty = (s, scope) => { if (string.IsNullOrEmpty(s)) scope.Error("String should not be empty."); }; /// <summary> /// String validator that ensures absence of any illegal characters /// </summary> /// <param name="illegalCharacters">The illegal characters.</param> /// <returns>new validator instance</returns> public static Rule<string> Without(params char[] illegalCharacters) { var joined = illegalCharacters.Select(c => "'" + c + "'").Join(", "); return (s, scope) => { if (s.IndexOfAny(illegalCharacters) >= 0) scope.Error("String should not contain following characters: {0}.", joined); }; } /// <summary> /// String validator that detects possible issues /// for passing strings through the ASP.NET Web services /// </summary> public static readonly Rule<string> ValidForXmlSerialization = (s, scope) => { for (int i = 0; i < s.Length; i++) { if (char.IsControl(s[i])) scope.Error("String should not contain unicode control characters."); } }; /// <summary> String validator checking for presence of /// white-space characters in the beginning of string </summary> public static readonly Rule<string> WithoutLeadingWhiteSpace = (s, scope) => { if (s.Length > 0 && char.IsWhiteSpace(s[0])) scope.Error("String should not start with white-space character."); }; /// <summary> String validator checking for presence of /// white-space characters in the end of string </summary> public static readonly Rule<string> WithoutTrailingWhiteSpace = (s, scope) => { if (s.Length > 0 && char.IsWhiteSpace(s.Last())) scope.Error("String should not end with trailing white-space character."); }; /// <summary> String validator checking for presence of uppercase /// characters </summary> public static readonly Rule<string> WithoutUppercase = (s, scope) => { for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s, i)) { scope.Error("String should not have uppercase characters."); return; } } }; } }<file_sep>/Source/Lokad.Logging/ExtendILogProvider.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Extension methods for the <see cref="INamedProvider{TValue}"/> /// of <see cref="ILog"/> /// </summary> [NoCodeCoverage, UsedImplicitly] public static class ExtendILogProvider { /// <summary> /// Creates new log using the type as name. /// </summary> /// <typeparam name="T"></typeparam> [Obsolete("Obsolete, Use LogForType overrides to specify log name precisely")] public static ILog CreateLog<T>(this INamedProvider<ILog> logProvider) where T : class { return logProvider.Get(typeof (T).Name); } /// <summary> /// Creates new log with using <see cref="Type.FullName"/> for the name. /// </summary> /// <typeparam name="T">type to use for naming</typeparam> /// <param name="logProvider">The log provider.</param> /// <returns>new instance of the log</returns> public static ILog LogForType<T>(this ILogProvider logProvider) { return logProvider.Get(typeof (T).FullName); } /// <summary> /// Creates new log with using <see cref="Type.FullName"/> for the name. /// </summary> /// <param name="logProvider">The log provider.</param> /// <param name="instance">The instance to retrieve type for naming from.</param> /// <returns>new instance of the log</returns> public static ILog LogForType(this ILogProvider logProvider, object instance) { return logProvider.Get(instance.GetType().FullName); } /// <summary> /// Creates new log with named with class name. /// </summary> /// <typeparam name="T">type to use for naming</typeparam> /// <param name="logProvider">The log provider.</param> /// <returns>new instance of the log</returns> public static ILog LogForName<T>(this ILogProvider logProvider) { return logProvider.Get(typeof (T).Name); } /// <summary> /// Creates new log with named with the class name. /// </summary> /// <param name="logProvider">The log provider.</param> /// <param name="instance">The instance to retrieve type for naming from.</param> /// <returns>new instance of the log</returns> public static ILog LogForName(this ILogProvider logProvider, object instance) { return logProvider.Get(instance.GetType().Name); } /// <summary> /// Creates new log with using <see cref="Type.Namespace"/> for the name. /// </summary> /// <typeparam name="T">type to use for naming</typeparam> /// <param name="logProvider">The log provider.</param> /// <returns>new instance of the log</returns> public static ILog LogForNamespace<T>(this ILogProvider logProvider) { return logProvider.Get(typeof (T).Namespace); } /// <summary> /// Creates new log with using <see cref="Type.Namespace"/> for the name. /// </summary> /// <param name="logProvider">The log provider.</param> /// <param name="instance">The instance to retrieve type for naming from.</param> /// <returns>new instance of the log</returns> public static ILog LogForNamespace(this ILogProvider logProvider, object instance) { return logProvider.Get(instance.GetType().Namespace); } } }<file_sep>/Source/Lokad.Shared/Tuples/ExtendTuple.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper extensions for tuples /// </summary> [NoCodeCoverage] public static class ExtendTuple { /// <summary> /// Appends the specified <paramref name="item"/> to the <paramref name="tuple"/>. /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <param name="tuple">The tuple to append to.</param> /// <param name="item">The item to append.</param> /// <returns>New tuple instance</returns> public static Triple<T1, T2, T3> Append<T1, T2, T3>(this Tuple<T1, T2> tuple, T3 item) { return Tuple.From(tuple.Item1, tuple.Item2, item); } /// <summary> /// Appends the specified <paramref name="item"/> to the <paramref name="tuple"/>. /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <param name="tuple">The tuple to append to.</param> /// <param name="item">The item to append.</param> /// <returns>New tuple instance</returns> public static Quad<T1, T2, T3, T4> Append<T1, T2, T3, T4>(this Tuple<T1, T2, T3> tuple, T4 item) { return Tuple.From(tuple.Item1, tuple.Item2, tuple.Item3, item); } /// <summary> /// Appends the specified <paramref name="item"/> to the <paramref name="tuple"/>. /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <param name="tuple">The tuple to append to.</param> /// <param name="item">The item to append.</param> /// <returns>New tuple instance</returns> public static Tuple<T1, T2, T3, T4, T5> Append<T1, T2, T3, T4, T5>(this Tuple<T1, T2, T3, T4> tuple, T5 item) { return Tuple.From(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, item); } /// <summary> /// Appends the specified <paramref name="item"/> to the <paramref name="tuple"/>. /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <typeparam name="T6">The type of the sixth item.</typeparam> /// <param name="tuple">The tuple to append to.</param> /// <param name="item">The item to append.</param> /// <returns>New tuple instance</returns> public static Tuple<T1, T2, T3, T4, T5, T6> Append<T1, T2, T3, T4, T5, T6>(this Tuple<T1, T2, T3, T4, T5> tuple, T6 item) { return Tuple.From(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, tuple.Item5, item); } /// <summary> /// Appends the specified <paramref name="item"/> to the <paramref name="tuple"/>. /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <typeparam name="T6">The type of the sixth item.</typeparam> /// <typeparam name="T7">The type of the seventh item.</typeparam> /// <param name="tuple">The tuple to append to.</param> /// <param name="item">The item to append.</param> /// <returns>New tuple instance</returns> public static Tuple<T1, T2, T3, T4, T5, T6, T7> Append<T1, T2, T3, T4, T5, T6, T7>(this Tuple<T1, T2, T3, T4, T5, T6> tuple, T7 item) { return Tuple.From(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, tuple.Item5, tuple.Item6, item); } /// <summary> Shortcut to create and add tuple to the collection </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <param name="collection">The collection to add to.</param> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> public static void AddTuple<T1, T2>(this ICollection<Tuple<T1, T2>> collection, T1 first, T2 second) { collection.Add(Tuple.From(first, second)); } /// <summary> Shortcut to create and add tuple to the collection </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <param name="collection">The collection to add to.</param> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> public static void AddTuple<T1, T2>(this ICollection<Pair<T1, T2>> collection, T1 first, T2 second) { collection.Add(Tuple.From(first, second)); } /// <summary> Shortcut to create and add tuple to the collection </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <param name="collection">The collection to add to.</param> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> public static void AddTuple<T1, T2, T3>(this ICollection<Tuple<T1, T2, T3>> collection, T1 first, T2 second, T3 third) { collection.Add(Tuple.From(first, second, third)); } /// <summary> Shortcut to create and add tuple to the collection </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <param name="collection">The collection to add to.</param> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> public static void AddTuple<T1, T2, T3, T4>(this ICollection<Tuple<T1, T2, T3, T4>> collection, T1 first, T2 second, T3 third, T4 fourth) { collection.Add(Tuple.From(first, second, third, fourth)); } /// <summary> Shortcut to create and add tuple to the collection </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <param name="collection">The collection to add to.</param> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <param name="fifth">The fifth item.</param> public static void AddTuple<T1, T2, T3, T4, T5>(this ICollection<Tuple<T1, T2, T3, T4, T5>> collection, T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { collection.Add(Tuple.From(first, second, third, fourth, fifth)); } } }<file_sep>/Test/Lokad.Shared.Test/Utils/GuidUtilTests.cs using System; using System.Collections.Generic; using Lokad.Data.SqlClient; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class GuidUtilTests { // ReSharper disable InconsistentNaming [Test] public void Combs_are_SQL_Ordered() { var initial = Range.Array(50, n => { SystemUtil.Sleep(20.Milliseconds()); return GuidUtil.NewComb(); }); var copy = new List<Guid>(initial); copy.Sort(new SqlServerGuidComparer()); CollectionAssert.AreEqual(initial, copy); } [Test] public void Sortables_are_string_ordered() { var initial = Range.Array(1000, n => { SystemUtil.Sleep(20.Milliseconds()); return GuidUtil.NewStringSortable().ToString(); }); var copy = new List<String>(initial); copy.Sort(); CollectionAssert.AreEqual(initial, copy); } } }<file_sep>/Source/Lokad.Shared/DesignOfClass.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Class design markers for the Lokad namespace /// </summary> public static class DesignOfClass { /// <summary> /// Indicates that a class is an immutable model with fields /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class ImmutableFieldsModel : ClassDesignAttribute { /// <summary> /// Initializes a new instance of the /// <see cref="ImmutableFieldsModel" /> /// class. /// </summary> public ImmutableFieldsModel() : base(DesignTag.Model, DesignTag.ImmutableWithFields) { } } /// <summary> /// Indicates that a class is an immutable model with properties /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class ImmutablePropertiesModel : ClassDesignAttribute { /// <summary> /// Initializes a new instance of the /// <see cref="ImmutablePropertiesModel" /> /// class. /// </summary> public ImmutablePropertiesModel() : base(DesignTag.Model, DesignTag.ImmutableWithProperties) { } } } }<file_sep>/Source/Lokad.Shared/Rules/Common/Is.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq.Expressions; namespace Lokad.Rules { /// <summary> /// Generic rules /// </summary> public static class Is { /// <summary> /// Composes the validator ensuring that the provided value does not equal to <paramref name="item"/> /// </summary> /// <typeparam name="T">type of the item to compare</typeparam> /// <param name="item">The item.</param> /// <returns>new rule instance</returns> public static Rule<T> NotEqual<T>(IEquatable<T> item) { return (t, scope) => { if (item.Equals(t)) scope.Error("Value should not be equal to \'{0}\'.", item); }; } /// <summary> /// Composes the validator ensuring that the provided value equals to <paramref name="item"/> /// </summary> /// <typeparam name="T">type of the item to compare</typeparam> /// <param name="item">The item.</param> /// <returns>new rule instance</returns> public static Rule<T> Equal<T>(IEquatable<T> item) { return (t, scope) => { if (!item.Equals(t)) scope.Error("Value should be equal to \'{0}\'.", item); }; } /// <summary> /// Composes the validator ensuring that the provided value equals to <paramref name="item"/> /// </summary> /// <typeparam name="T">type of the item to compare</typeparam> /// <param name="item">The item.</param> /// <returns>new rule instance</returns> public static Rule<T> Value<T>(T item) where T : struct { return (t, scope) => { if (!item.Equals(t)) scope.Error("Value should be equal to \'{0}\'.", item); }; } /// <summary> /// Composes the validator ensuring that the provided object is same as <paramref name="item"/> /// </summary> /// <typeparam name="T">type of the item to compare</typeparam> /// <param name="item">The item.</param> /// <returns>new rule instance</returns> public static Rule<T> SameAs<T>(T item) where T : class { return (t, scope) => { if (!ReferenceEquals(item, t)) scope.Error("Object should be same as the provided reference."); }; } /// <summary> /// Returns error if the provided value type has default value /// </summary> /// <typeparam name="T">value type to check</typeparam> /// <param name="item">The item.</param> /// <param name="scope">The scope.</param> public static void NotDefault<T>(T item, IScope scope) where T : struct { if (default(T).Equals(item)) { scope.Error("Value should not be equal to \'{0}\'.", default(T)); } } /// <summary> /// Returns error if provided value type has been initialized /// </summary> /// <typeparam name="T"></typeparam> /// <param name="item">The item.</param> /// <param name="scope">The scope.</param> public static void Default<T>(T item, IScope scope) where T : struct { if (!default(T).Equals(item)) { scope.Error("Value should be equal to \'{0}\'.", default(T)); } } /// <summary> /// Composes the range validator that ensures that the supplied value belongs /// to the interval from <paramref name="minValue"/> to <paramref name="maxValue"/> /// (inclusive). /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="minValue">The min value.</param> /// <param name="maxValue">The max value.</param> /// <returns>new validator instance</returns> public static Rule<T> Within<T>(IComparable<T> minValue, IComparable<T> maxValue) { return (value, scope) => { if (minValue.CompareTo(value) > 0) scope.Error("Value should not be less than \'{0}\'.", minValue); if (maxValue.CompareTo(value) < 0) scope.Error("Value should not be greater than \'{0}\'.", maxValue); }; } /// <summary> /// Composes the range validator that ensures that the supplied value belongs /// to the interval between <paramref name="lowerBound"/> and <paramref name="upperBound"/> /// (exclusive) /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="lowerBound">The lower bound.</param> /// <param name="upperBound">The upper bound.</param> /// <returns>new rule instance</returns> public static Rule<T> Between<T>(IComparable<T> lowerBound, IComparable<T> upperBound) { return (value, scope) => { if (lowerBound.CompareTo(value) >= 0) scope.Error("Value should be greater than \'{0}\'.", lowerBound); if (upperBound.CompareTo(value) <= 0) scope.Error("Value should be less than \'{0}\'.", upperBound); }; } /// <summary> /// Creates the rule to ensure that the validated value is greater than /// the specified <paramref name="comparable"/> /// </summary> /// <typeparam name="T">type of the item to run rule against</typeparam> /// <param name="comparable">The comparable.</param> /// <returns>new rule instance</returns> public static Rule<T> GreaterThan<T>(IComparable<T> comparable) { return (t, scope) => { if (comparable.CompareTo(t) >= 0) scope.Error("Value should be greater than \'{0}\'.", comparable); }; } /// <summary> /// Creates the rule to ensure that the validated value is greater than /// or equal to the specified <paramref name="comparable"/> /// </summary> /// <typeparam name="T">type of the item to run rule against</typeparam> /// <param name="comparable">The comparable.</param> /// <returns>new rule instance</returns> public static Rule<T> AtLeast<T>(IComparable<T> comparable) { return (t, scope) => { if (comparable.CompareTo(t) > 0) scope.Error("Value should not be less than \'{0}\'.", comparable); }; } /// <summary> /// Creates the rule to ensure that the validated value is less than /// or equal to the specified <paramref name="comparable"/> /// </summary> /// <typeparam name="T">type of the item to run rule against</typeparam> /// <param name="comparable">The comparable.</param> /// <returns>new rule instance</returns> public static Rule<T> AtMost<T>(IComparable<T> comparable) { return (t, scope) => { if (comparable.CompareTo(t) < 0) scope.Error("Value should not be greater than \'{0}\'.", comparable); }; } /// <summary> /// Creates the rule to ensure that the validated value is less than /// the specified <paramref name="comparable"/> /// </summary> /// <typeparam name="T">type of the item to run rule against</typeparam> /// <param name="comparable">The comparable.</param> /// <returns>new rule instance</returns> public static Rule<T> LessThan<T>(IComparable<T> comparable) { return (t, scope) => { if (comparable.CompareTo(t) <= 0) scope.Error("Value should be less than \'{0}\'.", comparable); }; } /// <summary> /// <para>Compiles the rule out of the specified expression.</para> /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="expression">The expression.</param> /// <returns>compiled rule instance</returns> public static Rule<TTarget> True<TTarget>(Expression<Predicate<TTarget>> expression) { var stringRepresentation = expression.ToString(); var check = expression.Compile(); return (t, scope) => { if (!check(t)) scope.Error("Expression should be true: {0}.", stringRepresentation); }; } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/UsedImplicitlyAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the marked symbol is used implicitly (ex. reflection, external library), /// so this symbol will not be marked as unused (as well as by other usage inspections) /// </summary> /// <remarks>This attribute helps R# in code analysis</remarks> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] [MeansImplicitUse(ImplicitUseFlags.ALL_MEMBERS_USED)] public sealed class UsedImplicitlyAttribute : Attribute { } }<file_sep>/Source/Lokad.Testing/Testing/FailedAssertException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; namespace Lokad.Testing { /// <summary> /// Failed assertion exception /// </summary> [Serializable] public sealed class FailedAssertException : Exception { /// <summary> /// Initializes a new instance of the <see cref="FailedAssertException"/> class. /// </summary> public FailedAssertException() { } /// <summary> /// Initializes a new instance of the <see cref="FailedAssertException"/> class. /// </summary> /// <param name="message">The message.</param> public FailedAssertException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="FailedAssertException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public FailedAssertException(string message, Exception inner) : base(message, inner) { } FailedAssertException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/Source/Lokad.ActionPolicy/Properties/AssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly : AssemblyTitle("Lokad.ActionPolicy")] [assembly : AssemblyDescription("Action Policies and reliability")] [assembly: AssemblyCopyright(GlobalAssemblyInfo.Copyright)] [assembly: AssemblyTrademark(GlobalAssemblyInfo.Trademark)] [assembly: CLSCompliant(true)] [assembly: InternalsVisibleTo("Lokad.ActionPolicy.Test, PublicKey = " + GlobalAssemblyInfo.PublicKey)]<file_sep>/Sample/Shared/RulesUI/ScopePending.cs using System; using System.Linq.Expressions; namespace RulesUI { /// <summary> /// Simple helper class that allows to make rule paths strongly-typed /// instead of resorting to string literals /// </summary> internal static class ScopePending { public static string GetPath<TTarget, TProperty>(Expression<Func<TTarget, TProperty>> prop) { // slow binding for now Enforce.Argument(() => prop); var lambda = prop as LambdaExpression; Enforce.That(lambda != null, "Must be a lambda expression"); Enforce.That(lambda.Body.NodeType == ExpressionType.MemberAccess, "Must be member access"); var memberExpr = lambda.Body as MemberExpression; if (null == memberExpr) throw new InvalidOperationException("memberExpr"); string path = memberExpr.Member.Name; while (null != (memberExpr.Expression as MemberExpression)) { memberExpr = (MemberExpression)memberExpr.Expression; path = Compose(memberExpr.Member.Name, path); } return path; } public static string Compose(string prefix, string postfix) { return prefix + "." + postfix; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/ScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; // ReSharper disable InconsistentNaming namespace Lokad.Rules { [TestFixture] public sealed class ScopeTests { static readonly Rule<int> Error = Is.AtLeast(0); static readonly Rule<int> MustBeLucky = (i, scope) => { if (i == 13) scope.Warn("Unlucky number"); }; [Test] public void Test() { RuleAssert.IsTrue(() => Scope.IsValid(1, MustBeLucky, Error)); RuleAssert.IsTrue(() => Scope.IsWarn(13, MustBeLucky, Error)); RuleAssert.IsTrue(() => Scope.IsError(-1, MustBeLucky, Error)); } [Test] public void UseCases() { var one = 12; var many = new[] {12, 14}; Scope.Validate(one, MustBeLucky, Error); Scope.ValidateMany(many, MustBeLucky, Error); Scope.GetMessages(one, "one", MustBeLucky, Error); Scope.GetMessagesForMany(many, "many", MustBeLucky, Error); Scope.GetMessages(() => one, MustBeLucky, Error); Scope.GetMessagesForMany(() => many, MustBeLucky, Error); const RuleLevel level = RuleLevel.None; Scope.WhenNone(level); Scope.WhenWarn(level); Scope.WhenError(level); Scope.WhenAny(level); } [Test] public void Messaging_UseCases() { Scope.GetMessages(string.Empty, scope => { scope.Error("Message"); scope.Error("Message {0}", 1); scope.Warn("Message"); scope.Warn("Message {0}", 1); scope.Info("Message"); scope.Info("Message {0}", 1); }); } } }<file_sep>/Source/Lokad.Testing/Testing/MockContainer/MockContainer.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Autofac; using Autofac.Builder; using Autofac.Core; using Lokad.Quality; using Rhino.Mocks; using Rhino.Mocks.Interfaces; namespace Lokad.Testing { /// <summary> /// Container that automatically resolves all unknown dependencies as stubs /// </summary> [Immutable, UsedImplicitly] public class MockContainer : IDisposable { readonly IContainer _container = new Container(); /// <summary> /// Creates strongly-typed mocking container /// </summary> /// <typeparam name="TSubject">The type of the subject.</typeparam> /// <returns>new container instance</returns> public static MockContainer<TSubject> For<TSubject>() { return new MockContainer<TSubject>(); } /// <summary> /// Gets the actial container. /// </summary> /// <value>The container.</value> public IContainer Container { get { return _container; } } /// <summary> /// Initializes a new instance of the <see cref="MockContainer"/> class. /// </summary> public MockContainer() { var builder = new ContainerBuilder(); builder.RegisterSource(new RhinoRegistrationSource()); _container = builder.Build(); } /// <summary> /// Registers the specified component in this container. /// </summary> /// <typeparam name="TComponent">The type of the component.</typeparam> public void Register<TComponent>() { Build(builder => builder.RegisterType<TComponent>()); } /// <summary> /// Registers the specified component instance in this container. /// </summary> /// <typeparam name="TComponent">The type of the component.</typeparam> /// <param name="instance">The actual instance.</param> public void Register<TComponent>(TComponent instance) where TComponent : class { Build(builder => builder.RegisterInstance(instance).ExternallyOwned()); } /// <summary> /// Builds the specified registration into the container. /// </summary> /// <param name="registration">The registration.</param> public void Build(Action<ContainerBuilder> registration) { var builder = new ContainerBuilder(); registration(builder); builder.Update(_container); } /// <summary> /// Resolves the specified service from the container /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns></returns> public TService Resolve<TService>() { return _container.Resolve<TService>(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _container.Dispose(); } /// <summary> /// Stubs the specified action against the specified service. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="action">The action.</param> /// <returns>method options for the additional configuration</returns> public IMethodOptions<TResult> Stub<TService, TResult>(Func<TService, TResult> action) where TService : class { return _container.Resolve<TService>().Stub(t => action(t)); } /// <summary> /// Raises the specified event on the <typeparamref name="TEventSource"/> resolved from the container. /// </summary> /// <typeparam name="TEventSource">The type of the service.</typeparam> /// <param name="eventSubscription">The event subscription that specifies the event to be called.</param> /// <param name="args">The optional arguments to be passed to the event.</param> /// <returns>same instance of the mock container</returns> /// <seealso cref="RhinoMocksExtensions.GetEventRaiser{TEventSource}"/> /// <seealso cref="IEventRaiser.Raise(object[])"/> public MockContainer RaiseEventOn<TEventSource>(Action<TEventSource> eventSubscription, params object[] args) where TEventSource : class { _container .Resolve<TEventSource>() .GetEventRaiser(eventSubscription).Raise(args); return this; } /// <summary> /// Asserts that a particular method was called on the specified mock object /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="action">The action.</param> /// <seealso cref="RhinoMocksExtensions.AssertWasCalled{T}(T,System.Action{T})"/> /// <returns>same instance of the mock container</returns> public MockContainer AssertWasCalled<TService>(Action<TService> action) { var resolve = _container .Resolve<TService>(); resolve.AssertWasCalled(action); return this; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/RuleExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; using Lokad.Testing; using NUnit.Framework; // ReSharper disable InconsistentNaming namespace Lokad.Rules { [TestFixture] public sealed class RuleExtensionsTests { [Test] public void Test_Valid_Nested_Object() { Enforce.That(Visitor.CreateValid(), BusinessRules.VisitorRules); } [Test] public void Test_Valid_Collection() { var array = Range.Array(10, i => Program.CreateValid()); Enforce.That(array, BusinessRules.ProgramRules); } [Test, Expects.RuleException] public void Nested_Object_Throws_On_Invalid_Collection() { var v = Visitor.CreateValid(); v.Programs = v.Programs.Append(new Program()); Enforce.That(v, BusinessRules.VisitorRules); } [Test, Expects.ArgumentException] public void Null_Collection_Is_Detected() { var v = Visitor.CreateValid(); v.Programs = null; Enforce.Argument(() => v, BusinessRules.VisitorRules); } [Test, Expects.RuleException] public void Null_Object_Is_Detected() { var v = Visitor.CreateValid(); v.Programs[0] = null; Enforce.That(v, BusinessRules.VisitorRules); } public class Domain { public string[] Properties { get; set; } public double[] Values { get; set; } public string Property { get; set; } public double Value { get; set; } } [Test] public void Usage_patterns_for_building_rules() { var domain = new Domain { Properties = Range.Array(10, i => i.ToString()), Values = Range.Array(10, i => (double) (i + 1)), Property = "Something", Value = Math.PI }; Enforce.That(() => domain, Usage_Rule); Scope.GetMessages(new Domain(), "domain", Usage_Rule); } static void Usage_Rule(Domain domain, IScope scope) { scope.Validate(domain.Property, "Property", StringIs.NotEmpty); scope.Validate(domain.Value, "Value", Is.NotDefault); scope.ValidateMany(domain.Properties, "Properties", StringIs.NotEmpty); //scope.ValidateMany(domain.Values, "Values", 100, Is.NotDefault); scope.ValidateMany(domain.Values, "Values", Is.NotDefault); //scope.ValidateMany(domain.Values, "Values", 100, Is.NotDefault); scope.Validate(() => domain.Property, StringIs.NotEmpty); scope.Validate(() => domain.Value, Is.NotDefault); // medium trust scope.Validate(domain, d => d.Property, StringIs.NotEmpty); scope.Validate(domain, d => d.Value, Is.NotDefault); scope.ValidateMany(() => domain.Properties, StringIs.NotEmpty); scope.ValidateMany(() => domain.Values, Is.NotDefault); // medium trust scope.ValidateMany(domain, d => d.Properties, StringIs.NotEmpty); scope.ValidateMany(domain, d => d.Values, Is.NotDefault); scope.ValidateInScope(domain, (domain1, scope1) => { }); scope.ValidateInScope(new[] {domain}, (domain1, scope1) => { }); } } }<file_sep>/Source/Lokad.Shared/DisposableAction.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Class that allows action to be executed, when it is disposed /// </summary> [Serializable] [Immutable] public sealed class DisposableAction : IDisposable { readonly Action _action; /// <summary> /// Initializes a new instance of the <see cref="DisposableAction"/> class. /// </summary> /// <param name="action">The action.</param> public DisposableAction(Action action) { _action = action; } /// <summary> /// Executes the action /// </summary> public void Dispose() { _action(); } } }<file_sep>/Source/Lokad.Shared/Rules/Rule.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Rules { ///<summary> /// Typed delegate for holding the validation logics ///</summary> ///<param name="obj">Object to validate</param> ///<param name="scope">Scope that will hold all validation results</param> ///<typeparam name="T">type of the item to validate</typeparam> public delegate void Rule<T>(T obj, IScope scope); }<file_sep>/Source/Lokad.Shared/Diagnostics/ExecutionCounter.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Diagnostics; using System.Linq; using System.Threading; #if !SILVERLIGHT2 namespace Lokad.Diagnostics { /// <summary> <para> /// Class to provide simple measurement of some method calls. /// This class has been designed to provide light performance monitoring /// that could be used for instrumenting methods in production. It does /// not use any locks and uses design to avoid 90% of concurrency issues. /// </para><para> /// Counters are designed to be "cheap" and throwaway, so we basically we /// don't care about the remaining 10% /// </para><para> /// The usage idea is simple - data is captured from the counters at /// regular intervals of time (i.e. 5-10 minutes). Counters are reset /// after that. Data itself is aggregated on the monitoring side. /// If there are some bad values (i.e. due to some rare race condition /// between multiple threads and monitoring scan) then the counter data /// is simply discarded. /// </para></summary> public sealed class ExecutionCounter { long _openCount; long _closeCount; long _runningTime; readonly long[] _openCounters; readonly long[] _closeCounters; readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="ExecutionCounter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> public ExecutionCounter(string name, int openCounterCount, int closeCounterCount) { _name = name; _openCounters = new long[openCounterCount]; _closeCounters = new long[closeCounterCount]; } /// <summary> /// Open the specified counter and adds the provided values to the openCounters collection /// </summary> /// <param name="openCounters">The open counters.</param> /// <returns>timestamp for the operation</returns> public long Open(params long[] openCounters) { // abdullin: this is not really atomic and precise, // but we do not care that much unchecked { Interlocked.Increment(ref _openCount); for (int i = 0; i < openCounters.Length; i++) { Interlocked.Add(ref _openCounters[i], openCounters[i]); } } return Stopwatch.GetTimestamp(); } /// <summary> /// Closes the specified timestamp. /// </summary> /// <param name="timestamp">The timestamp.</param> /// <param name="closeCounters">The close counters.</param> public void Close(long timestamp, params long[] closeCounters) { var runningTime = Stopwatch.GetTimestamp() - timestamp; // this counter has been reset after opening - discard if ((_openCount == 0) || (runningTime < 0)) return; // abdullin: this is not really atomic and precise, // but we do not care that much unchecked { Interlocked.Add(ref _runningTime, runningTime); Interlocked.Increment(ref _closeCount); for (int i = 0; i < closeCounters.Length; i++) { Interlocked.Add(ref _closeCounters[i], closeCounters[i]); } } } /// <summary> /// Resets this instance. /// </summary> public void Reset() { _runningTime = 0; _openCount = 0; _closeCount = 0; for (int i = 0; i < _closeCounters.Length; i++) { _closeCounters[i] = 0; } for (int i = 0; i < _openCounters.Length; i++) { _openCounters[i] = 0; } } /// <summary> /// Converts this instance to <see cref="ExecutionStatistics"/> /// </summary> /// <returns></returns> public ExecutionStatistics ToStatistics() { long dateTimeTicks = _runningTime; if (Stopwatch.IsHighResolution) { double num2 = dateTimeTicks; num2 *= 10000000.0/Stopwatch.Frequency; dateTimeTicks = (long) num2; } return new ExecutionStatistics( _name, _openCount, _closeCount, _openCounters.Append(_closeCounters), dateTimeTicks); } } } #endif<file_sep>/Source/Lokad.Shared/ResolutionException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; using Lokad.Quality; namespace Lokad { /// <summary> /// Exception that is thrown by <see cref="IResolver"/> or <see cref="IProvider{TKey,TValue}"/> /// </summary> [Serializable] [NoCodeCoverage] public class ResolutionException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ResolutionException"/> class. /// </summary> public ResolutionException() { } /// <summary> /// Initializes a new instance of the <see cref="ResolutionException"/> class. /// </summary> /// <param name="message">The message related to this exception.</param> public ResolutionException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ResolutionException"/> class. /// </summary> /// <param name="message">The message related to this exception.</param> /// <param name="inner">The inner exception.</param> public ResolutionException(string message, Exception inner) : base(message, inner) { } #if !SILVERLIGHT2 /// <summary> /// Initializes a new instance of the <see cref="ResolutionException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="info"/> parameter is null. /// </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException"> /// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). /// </exception> protected ResolutionException( SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }<file_sep>/Source/Lokad.Testing/Testing/Models/TestModelEqualityCache.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Globalization; namespace Lokad.Testing { /// <summary> /// Simple dictionary-based cache for the equality providers /// </summary> sealed class TestModelEqualityCache : ITestModelEqualityProvider { readonly IDictionary<Type, TestModelEqualityDelegate> _dictionary = new Dictionary<Type, TestModelEqualityDelegate>(); public Func<Type, TestModelEqualityDelegate> UnknownType { get; set; } public TestModelEqualityCache() { UnknownType = type => { throw new KeyInvalidException(string.Format(CultureInfo.InvariantCulture, "Key has invalid value '{0}'", (object) type)); }; } public TestModelEqualityDelegate GetEqualityTester(Type type) { TestModelEqualityDelegate value; if (!_dictionary.TryGetValue(type, out value)) { value = UnknownType(type); _dictionary.Add(type, value); } return value; } } }<file_sep>/Source/Lokad.Shared/Linq/ExtendIEnumerable.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using Lokad; using Lokad.Collections.Generic; using Lokad.Quality; namespace System.Linq { /// <summary> /// Helper methods for the <see cref="IEnumerable{T}"/> /// </summary> public static class ExtendIEnumerable { /// <summary> /// Performs the specified <see cref="Action{T}"/> against every element of <see cref="IEnumerable{T}"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable">Enumerable to extend</param> /// <param name="action">Action to perform</param> /// <exception cref="ArgumentNullException">When any parameter is null</exception> public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (action == null) throw new ArgumentNullException("action"); foreach (var t in enumerable) { action(t); } } /// <summary> /// Performs the specified <see cref="Action{T}"/> against every element of <see cref="IEnumerable{T}"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable">Enumerable to extend</param> /// <param name="action">Action to perform; second parameter represents the index</param> /// <exception cref="ArgumentNullException">When any parameter is null</exception> public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (action == null) throw new ArgumentNullException("action"); int i = 0; foreach (var t in enumerable) { action(t, i); i += 1; } } /// <summary> /// Applies the specified action to the target <paramref name="enumerable"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="action">The action to execute against every item.</param> /// <returns>enumerator</returns> /// <exception cref="ArgumentNullException">when one of the values is null</exception> public static IEnumerable<T> Apply<T>(this IEnumerable<T> enumerable, Action<T> action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (action == null) throw new ArgumentNullException("action"); foreach (var t in enumerable) { action(t); yield return t; } } /// <summary> /// Applies the specified action to the target <paramref name="enumerable"/>. /// </summary> /// <typeparam name="TSource">Type of the elements in <paramref name="enumerable"/></typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="action">The action to execute against every item; second /// parameter represents the index.</param> /// <returns>enumerator</returns> /// <exception cref="ArgumentNullException">when one of the values is null</exception> public static IEnumerable<TSource> Apply<TSource>(this IEnumerable<TSource> enumerable, Action<TSource, int> action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (action == null) throw new ArgumentNullException("action"); int i = 0; foreach (var t in enumerable) { action(t, i); yield return t; i += 1; } } /// <summary> /// Returns <em>True</em> as soon as the first member of <paramref name="enumerable"/> /// mathes <paramref name="predicate"/> /// </summary> /// <typeparam name="TSource">Type of the elements in <paramref name="enumerable"/></typeparam> /// <param name="enumerable">The enumerable</param> /// <param name="predicate">The predicate.</param> /// <returns>true if the <paramref name="enumerable"/> contains any elements /// matching <paramref name="predicate"/></returns> public static bool Exists<TSource>(this IEnumerable<TSource> enumerable, Predicate<TSource> predicate) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (predicate == null) throw new ArgumentNullException("predicate"); foreach (var t in enumerable) { if (predicate(t)) { return true; } } return false; } /// <summary> /// Checks if the provided enumerable has anything /// </summary> /// <typeparam name="TSource">Type of the elements in <paramref name="enumerable"/></typeparam> /// <param name="enumerable">The enumerable.</param> /// <returns>true if the sequence contains any elements</returns> public static bool Exists<TSource>(this IEnumerable<TSource> enumerable) { if (enumerable == null) throw new ArgumentNullException("enumerable"); return enumerable.Any(); } /// <summary> /// Appends the <paramref name="items"/> to the <paramref name="enumerable"/>. /// </summary> /// <typeparam name="TSource">type of the elements in <paramref name="enumerable"/></typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="items">The item.</param> /// <returns>new sequence</returns> public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> enumerable, params TSource[] items) { if (enumerable == null) throw new ArgumentNullException("enumerable"); foreach (TSource t in enumerable) { yield return t; } foreach (var t in items) { yield return t; } } /// <summary> /// Appends the specified <paramref name="range"/> to the <paramref name="enumerable"/>. /// </summary> /// <typeparam name="T">type of the item to operate with</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="range">The range.</param> /// <returns>new enumerator instance</returns> public static IEnumerable<T> Append<T>(this IEnumerable<T> enumerable, IEnumerable<T> range) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (range == null) throw new ArgumentNullException("range"); foreach (T t in enumerable) { yield return t; } foreach (T t in range) { yield return t; } } /// <summary> /// Prepends the specified <paramref name="enumerable"/> with the <paramref name="items"/>. /// </summary> /// <typeparam name="T">type of the item to operate with</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="items">The item.</param> /// <returns>new enumerator instance</returns> public static IEnumerable<T> Prepend<T>(this IEnumerable<T> enumerable, params T[] items) { if (enumerable == null) throw new ArgumentNullException("enumerable"); foreach (var t in items) { yield return t; } foreach (T t in enumerable) { yield return t; } } #if !SILVERLIGHT2 /// <summary> /// Converts the enumerable to <see cref="HashSet{T}"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable">The enumerable.</param> /// <returns>hashset instance</returns> public static HashSet<T> ToSet<T>(this IEnumerable<T> enumerable) { if (enumerable == null) throw new ArgumentNullException("enumerable"); return new HashSet<T>(enumerable); } /// <summary> /// Converts the enumerable to <see cref="HashSet{T}"/> /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="selector">The selector.</param> /// <returns>hashset instance</returns> public static HashSet<TKey> ToSet<TKey, TItem>(this IEnumerable<TItem> enumerable, Func<TItem, TKey> selector) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (selector == null) throw new ArgumentNullException("selector"); return new HashSet<TKey>(enumerable.Select(selector)); } #endif /// <summary> /// Returns the minimum value in a generic sequence, using the provided comparer /// </summary> /// <typeparam name="T">Type of the elements of <paramref name="source"/></typeparam> /// <param name="source">Original sequence.</param> /// <param name="comparer">The comparer.</param> /// <returns>Maximum value</returns> public static T Min<T>(this IEnumerable<T> source, IComparer<T> comparer) { if (source == null) throw new ArgumentNullException("source"); if (comparer == null) throw new ArgumentNullException("comparer"); var val = default(T); // ReSharper disable CompareNonConstrainedGenericWithNull if (val == null) { foreach (var t in source) { if ((t != null) && ((val == null) || (comparer.Compare(t, val) < 0))) { val = t; } } return val; } // ReSharper restore CompareNonConstrainedGenericWithNull bool set = false; foreach (var t in source) { if (set) { if (comparer.Compare(t, val) < 0) { val = t; } } else { val = t; set = true; } } if (!set) throw new ArgumentException("Collection can't be empty", "source"); return val; } /// <summary> /// Returns the maximum value in a generic sequence using the provided comparer. /// </summary> /// <typeparam name="T">Type of the elements of <paramref name="source"/></typeparam> /// <param name="source">Original sequence.</param> /// <param name="comparer">The comparer.</param> /// <returns>Maximum value</returns> public static T Max<T>(this IEnumerable<T> source, IComparer<T> comparer) { if (source == null) throw new ArgumentNullException("source"); if (comparer == null) throw new ArgumentNullException("comparer"); var val = default(T); // ReSharper disable CompareNonConstrainedGenericWithNull if (val == null) { foreach (var t in source) { if ((t != null) && ((val == null) || (comparer.Compare(t, val) > 0))) { val = t; } } return val; } // ReSharper restore CompareNonConstrainedGenericWithNull bool set = false; foreach (var t in source) { if (set) { if (comparer.Compare(t, val) > 0) { val = t; } } else { val = t; set = true; } } if (!set) throw new ArgumentException("Collection can't be empty", "source"); return val; } /// <summary> /// Concatenates a specified separator between each element of a specified <paramref name="strings"/>, /// yielding a single concatenated string. /// </summary> /// <param name="strings">The strings.</param> /// <param name="separator">The separator.</param> /// <returns>concatenated string</returns> public static string Join(this IEnumerable<string> strings, string separator) { if (strings == null) throw new ArgumentNullException("strings"); return string.Join(separator, strings.ToArray()); } /// <summary> /// <para>Performs lazy splitting of the provided collection into collections of <paramref name="sliceLength"/>.</para> /// <para>Each collection will have total <em>weight</em> equal or less than <paramref name="maxSliceWeight"/></para> /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="source">The source collection to slice.</param> /// <param name="sliceLength">Length of the slice.</param> /// <param name="weightDelegate">Function to calculate <em>weight</em> of each item in the collection</param> /// <param name="maxSliceWeight">The max item weight.</param> /// <returns>enumerator over the results</returns> public static IEnumerable<TItem[]> Slice<TItem>(this IEnumerable<TItem> source, int sliceLength, Func<TItem, int> weightDelegate, int maxSliceWeight) { if (source == null) throw new ArgumentNullException("source"); if (weightDelegate == null) throw new ArgumentNullException("weightDelegate"); if (sliceLength <= 0) throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); if (maxSliceWeight <= 0) throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); var list = new List<TItem>(sliceLength); var accumulatedWeight = 0; foreach (var item in source) { var currentWeight = weightDelegate(item); if (currentWeight > maxSliceWeight) throw new InvalidOperationException("Impossible to slice this collection"); var weightOverload = (currentWeight + accumulatedWeight) > maxSliceWeight; if ((sliceLength == list.Count) || weightOverload) { accumulatedWeight = 0; yield return list.ToArray(); list.Clear(); } list.Add(item); accumulatedWeight += currentWeight; } if (list.Count > 0) yield return list.ToArray(); } /// <summary> /// Performs lazy splitting of the provided collection into collections of <paramref name="sliceLength"/> /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="source">The source.</param> /// <param name="sliceLength">Maximum length of the slice.</param> /// <returns>lazy enumerator of the collection of arrays</returns> public static IEnumerable<TItem[]> Slice<TItem>(this IEnumerable<TItem> source, int sliceLength) { if (source == null) throw new ArgumentNullException("source"); if (sliceLength <= 0) throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); var list = new List<TItem>(sliceLength); foreach (var item in source) { list.Add(item); if (sliceLength == list.Count) { yield return list.ToArray(); list.Clear(); } } if (list.Count > 0) yield return list.ToArray(); } /// <summary> /// Converts collection of collections to jagged array /// </summary> /// <typeparam name="T">type of the items in collection</typeparam> /// <param name="collection">The collection.</param> /// <returns>jagged array</returns> public static T[][] ToJaggedArray<T>(this IEnumerable<IEnumerable<T>> collection) { if (collection == null) throw new ArgumentNullException("collection"); return collection.Select(i => i.ToArray()).ToArray(); } /// <summary> /// Shorthand extension method for converting enumerables into the arrays /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> /// <typeparam name="TTarget">The type of the target array.</typeparam> /// <param name="self">The collection to convert.</param> /// <param name="converter">The converter.</param> /// <returns>target array instance</returns> public static TTarget[] ToArray<TSource, TTarget>(this IEnumerable<TSource> self, Func<TSource, TTarget> converter) { if (self == null) throw new ArgumentNullException("self"); if (converter == null) throw new ArgumentNullException("converter"); return self.Select(converter).ToArray(); } /// <summary> /// Shorthand extension method for converting enumerables into the arrays /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> /// <typeparam name="TTarget">The type of the target array.</typeparam> /// <param name="self">The collection to convert.</param> /// <param name="converter">The converter, where the second parameter is an index of item being converted.</param> /// <returns>target array instance</returns> public static TTarget[] ToArray<TSource, TTarget>(this IEnumerable<TSource> self, Func<TSource, int, TTarget> converter) { if (self == null) throw new ArgumentNullException("self"); if (converter == null) throw new ArgumentNullException("converter"); return self.Select(converter).ToArray(); } /// <summary> /// returns distinct values from a sequence by using projecting each item to a new /// sequence with <paramref name="projection"/> and then selecting /// distinct values from it. /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <typeparam name="TProjected">The type of the projected item.</typeparam> /// <param name="enumerable">The sequence to work with.</param> /// <param name="projection">The projection function.</param> /// <returns>sequence of distinct values</returns> public static IEnumerable<TItem> Distinct<TItem, TProjected>(this IEnumerable<TItem> enumerable, Func<TItem, TProjected> projection) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (projection == null) throw new ArgumentNullException("projection"); return enumerable .Select(p => Tuple.From(p, projection(p))) .Distinct(new ProjectionComparer<Pair<TItem, TProjected>, TProjected>(p => p.Value)) .Select(pair => pair.Key); } /// <summary> /// Retrieves first value from the <paramref name="sequence"/> /// </summary> /// <typeparam name="TSource">The type of the source sequence.</typeparam> /// <param name="sequence">The source.</param> /// <param name="predicate">The predicate.</param> /// <returns>first value</returns> public static Maybe<TSource> FirstOrEmpty<TSource>( [NotNull] this IEnumerable<TSource> sequence, [NotNull] Func<TSource, bool> predicate) { if (sequence == null) throw new ArgumentNullException("sequence"); if (predicate == null) throw new ArgumentNullException("predicate"); foreach (var source in sequence) { if (predicate(source)) return source; } return Maybe<TSource>.Empty; } /// <summary> /// Retrieves first value from the <paramref name="sequence"/> /// </summary> /// <typeparam name="TSource">The type of the source sequence.</typeparam> /// <param name="sequence">The source.</param> /// <returns>first value or empty result, if it is not found</returns> public static Maybe<TSource> FirstOrEmpty<TSource>([NotNull] this IEnumerable<TSource> sequence) { if (sequence == null) throw new ArgumentNullException("sequence"); foreach (var source in sequence) { return source; } return Maybe<TSource>.Empty; } /// <summary> /// Applies the integral indexer to the sequence in a lazy manner /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The sequence.</param> /// <returns>indexed sequence</returns> /// <exception cref="ArgumentNullException"> if <paramref name="source"/> is null</exception> public static IEnumerable<Indexer<TSource>> ToIndexed<TSource>([NotNull] this IEnumerable<TSource> source) { if (source == null) throw new ArgumentNullException("source"); var index = 0; foreach (var item in source) { yield return new Indexer<TSource>(index, item); index += 1; } } /// <summary> /// Enumerates and returns a mapping that associated the items with their respective /// indices (positions) within the enumeration. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The source.</param> /// <returns>a dictionary</returns> /// <remarks><para>Typical usage is <c>coll.ToIndex()["foo"]</c> that returns /// the position of the item <c>"foo"</c> in the initial collection.</para> /// <para>if multiple similar entries are present in the original collection, /// index of the first entry is recorded. /// </para> /// /// </remarks> /// public static IDictionary<TSource, int> ToIndexDictionary<TSource>([NotNull] this IEnumerable<TSource> source) { if (source == null) throw new ArgumentNullException("source"); var dic = new Dictionary<TSource, int>(source.Count()); var index = 0; foreach (var x in source) { if (!dic.ContainsKey(x)) { dic.Add(x, index); } index += 1; } return dic; } /// <summary> /// Selects the values from a sequence of optionals. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="sequence">The sequence.</param> /// <returns>enumerable that contains values</returns> public static IEnumerable<TValue> SelectValues<TValue>(this IEnumerable<Maybe<TValue>> sequence) { return sequence.Where(s => s.HasValue).Select(s => s.Value); } } }<file_sep>/Sample/Shared/RulesUI/Address.cs namespace RulesUI { public sealed class Address { readonly string _street1; readonly string _street2; readonly string _zip; readonly Country _country; public Country Country { get { return _country; } } public Address(string street1, string street2, string zip, Country country) { _street1 = street1; _country = country; _street2 = street2; _zip = zip; } public string Street1 { get { return _street1; } } public string Street2 { get { return _street2; } } public string Zip { get { return _zip; } } } }<file_sep>/Test/Lokad.Shared.Test/Utils/BufferUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Security.Cryptography; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class BufferUtilTests { // ReSharper disable InconsistentNaming [Test] public void Test_Zeroes() { var bytes1 = new byte[101]; var bytes2 = new byte[100]; var hash1 = BufferUtil.CalculateSimpleHashCode(bytes1); var hash2 = BufferUtil.CalculateSimpleHashCode(bytes2); Assert.AreNotEqual(0, hash1); Assert.AreNotEqual(0, hash2); Assert.AreNotEqual(hash1, hash2); } [Test] public void Hash_random() { var length = Rand.Next(1, 100); var b = new byte[length]; new RNGCryptoServiceProvider().GetBytes(b); var hash1 = BufferUtil.CalculateSimpleHashCode(b); var hash2 = BufferUtil.CalculateSimpleHashCode(b); Assert.AreEqual(hash1, hash2); unchecked { b[Rand.Next(length)] += 1; } Assert.AreNotEqual(hash1, BufferUtil.CalculateSimpleHashCode(b)); } [Test] public void Hashing_short() { var b = new byte[] {1, 2}; BufferUtil.CalculateSimpleHashCode(b); } [Test] public void Mess_detection() { var length = Rand.Next(1, 100); var b = new byte[length]; new RNGCryptoServiceProvider().GetBytes(b); var hash = BufferUtil.CalculateSimpleHashCode(b); for (int i = 0; i < length; i++) { unchecked { b[i] ^= 1; Assert.AreNotEqual(hash, BufferUtil.CalculateSimpleHashCode(b), "Messing at {0} of {1}", i, length); b[i] ^= 1; Assert.AreEqual(hash, BufferUtil.CalculateSimpleHashCode(b), "Restoring at {0} of {1}", i, length); } } } [Test, Expects.ArgumentNullException] public void Null() { // ReSharper disable AssignNullToNotNullAttribute BufferUtil.CalculateSimpleHashCode(null); // ReSharper restore AssignNullToNotNullAttribute } } }<file_sep>/Sample/Sdk/Tutorial/Program.cs using System; using Lokad.Api; namespace Tutorial { class Program { static void Main() { var serviceUrl = "http://ws.lokad.com/TimeSeries2.asmx"; var login = "<EMAIL>"; // your Sandbox login here var pwd = "<PASSWORD>"; // your Sandbox password here var service = ServiceFactory .GetConnectorForTesting(login, pwd, serviceUrl); var existingSeries = service.GetSeries(); service.DeleteSeries(existingSeries); var serie1 = new SerieInfo { Name = "MySerie1" }; var serie2 = new SerieInfo { Name = "MySerie2" }; var mySeries = new[] {serie1, serie2}; Console.WriteLine("Saving series..."); service.AddSeries(mySeries); // add values var value1 = new TimeValue { Time = new DateTime(2008, 7, 1), Value = 10 }; var value2 = new TimeValue { Time = new DateTime(2008, 7, 2), Value = 12 }; var value3 = new TimeValue { Time = new DateTime(2008, 7, 3), Value = 11 }; // create association between serie1 and values 1,2,3 var segment1 = new SegmentForSerie(serie1, new[] {value1, value2, value3}); // create association between serie2 and values 1,2 var segment2 = new SegmentForSerie(serie2, new[] {value1, value2}); Console.WriteLine("Saving values..."); service.UpdateSerieSegments(new[] {segment1, segment2}); // create new forecasting task // to create 3 days forecast with daily interval var task = new TaskInfo(serie1) { FuturePeriods = 3, Period = Period.Day }; Console.WriteLine("Saving Tasks..."); service.AddTasks(new[] {task}); Console.WriteLine("Retrieving forecasts..."); var forecasts = service.GetForecasts(new[] {task}); foreach (var forecast in forecasts) { Console.WriteLine("Forecast for task {0}", forecast.TaskID); foreach (var value in forecast.Values) { Console.WriteLine(" {0} - {1}", value.Time.ToShortDateString(), value.Value); } } Console.WriteLine("Press any key to continue"); Console.ReadKey(true); } } }<file_sep>/Source/Lokad.Shared/Testing/Equatable.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; namespace Lokad.Testing { /// <summary> /// Helper extensions for the <see cref="IEquatable{T}"/> used in testing of models. /// </summary> public static class Equatable { /// <summary> /// Checks if the specified object instance is equal to another instance /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="self">The object to check.</param> /// <param name="other">The other object to compare with.</param> /// <returns><c>True</c> if the object instances are equal</returns> public static bool EqualsTo<TObject>(this IEquatable<TObject> self, TObject other) { return self.Equals(other); } ///// <summary> ///// Checks if the specified array of object instances is equal to another similar array ///// </summary> ///// <typeparam name="TObject">The type of the object.</typeparam> ///// <param name="self">The array to cehck.</param> ///// <param name="other">The other array.</param> ///// <returns><c>True</c> if all object instances are equal</returns> //public static bool EqualsTo<TObject>(this IEquatable<TObject>[] self, TObject[] other) //{ // if (self.Length != other.Length) return false; // for (int i = 0; i < self.Length; i++) // { // if (!self[i].Equals(other[i])) // return false; // } // return true; //} ///// <summary> ///// Checks if the specified array of object instances is equal to another similar array ///// </summary> ///// <typeparam name="TObject">The type of the object.</typeparam> ///// <param name="self">The array to check.</param> ///// <param name="other">The other array.</param> ///// <returns><c>True</c> if all object instances are equal</returns> //public static bool EqualsTo<TObject>(this TObject[] self, TObject[] other) // where TObject : IEquatable<TObject> //{ // if (self.Length != other.Length) return false; // for (int i = 0; i < self.Length; i++) // { // if (!self[i].Equals(other[i])) // return false; // } // return true; //} /// <summary> /// Checks if the specified collection of object instances is equal to another similar collection /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="self">The collection to check.</param> /// <param name="other">The other collection.</param> /// <returns><c>True</c> if all object instances are equal</returns> public static bool EqualsTo<TObject>(this ICollection<TObject> self, ICollection<TObject> other) where TObject : IEquatable<TObject> { if (self.Count != other.Count) return false; var e2 = other.GetEnumerator(); foreach (var item in self) { e2.MoveNext(); if (!item.Equals(e2.Current)) return false; } return true; } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/ImplicitUseFlags.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Used by <see cref="MeansImplicitUseAttribute"/> /// </summary> [Flags] public enum ImplicitUseFlags { /// <summary> /// Standard /// </summary> STANDARD = 0, /// <summary> /// All members used /// </summary> ALL_MEMBERS_USED = 1 } }<file_sep>/Source/Lokad.Stack/Logging/LogProviderWrapper.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Logging { /// <summary> /// Uses <see cref="log4net"/> as the logging backend /// </summary> public sealed class LogProviderWrapper : ILogProvider { /// <summary> /// Singleton instance of the <see cref="INamedProvider{TValue}"/> for <see cref="ILog"/> /// </summary> public static readonly ILogProvider Instance = new LogProviderWrapper(); LogProviderWrapper() { } /// <summary> /// Creates new named log /// </summary> /// <param name="key">Name of the log to use</param> /// <returns></returns> public ILog Get(string key) { return LogWrapper.GetByName(key); } } }<file_sep>/Test/Lokad.Shared.Test/Extensions/ExtendActionTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ExtendActionTests { [Test] public void Test() { bool flag = false; Action act = () => { flag = true; }; using (act.AsDisposable()) { Assert.IsFalse(flag); } Assert.IsTrue(flag); } } }<file_sep>/Test/Lokad.Shared.Test/Utils/EnumUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; using Lokad.Testing; namespace Lokad { [TestFixture] public sealed class EnumUtilTests { // ReSharper disable InconsistentNaming enum Tri { None, True, False } enum Quad { None, True,False, Other } [Test] public void Conversion_is_good() { var quad = EnumUtil<Quad>.ConvertSafelyFrom(Tri.None); Assert.AreEqual(Quad.None, quad); } [Test, Expects.ArgumentException] public void Conversion_possible_but_unsafe() { EnumUtil<Tri>.ConvertSafelyFrom(Quad.False); } [Test, Expects.ArgumentException] public void Conversion_impossible() { EnumUtil<Tri>.ConvertSafelyFrom(Quad.Other); } [Test] public void Test_Parse() { Assert.AreEqual(Tri.True, EnumUtil.Parse<Tri>("true")); Assert.AreEqual(Tri.False, EnumUtil.Parse<Tri>("False")); } [Test] public void Test_Values() { Assert.AreEqual(new[] {Tri.None, Tri.True, Tri.False}, EnumUtil<Tri>.Values); } [Test] public void ToIdentifier() { Assert.AreEqual("Tri_None", EnumUtil.ToIdentifier(Tri.None)); } } }<file_sep>/Source/Lokad.Quality/Extensions/MethodDefinitionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; namespace Lokad.Quality { /// <summary> /// Extensions for the <see cref="MethodDefinition"/> /// </summary> public static class MethodDefinitionExtensions { /// <summary> /// Gets the instructions for the specified method. /// </summary> /// <param name="method">The method.</param> /// <returns>enumerator over the instructions within the method</returns> public static IEnumerable<Instruction> GetInstructions(this MethodDefinition method) { if (!method.HasBody) return Enumerable.Empty<Instruction>(); return method.Body.Instructions.Cast<Instruction>(); } /// <summary> /// Gets the methods referenced from this <paramref name="definition"/>. /// </summary> /// <param name="definition">The definition.</param> /// <returns>enumerator over the method references</returns> public static IEnumerable<MethodReference> GetReferencedMethods(this MethodDefinition definition) { return definition .GetInstructions() .Select(i => i.Operand as MethodReference) .Where(r => r != null); } //public static bool Exists(this MethodDefinition method, Predicate<Instruction> instructionCheck) //{ // return method.GetInstructions().Exists(instructionCheck); //} /// <summary> /// Gets the parameters from the specified <paramref name="definition"/>. /// </summary> /// <param name="definition">The definition to explore.</param> /// <returns>enumerator over the parameters</returns> public static IEnumerable<ParameterDefinition> GetParameters(this MethodDefinition definition) { return definition.Parameters.Cast<ParameterDefinition>(); } /// <summary> /// Determines whether the provided <see cref="MethodDefinition"/> /// has specified attribute (matching is done by full name) /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="reference">The <see cref="MethodDefinition"/> to check.</param> /// <returns> /// <c>true</c> if the specified attribute is found otherwise, <c>false</c>. /// </returns> public static bool Has<TAttribute>(this MethodDefinition reference) where TAttribute : Attribute { foreach (CustomAttribute attribute in reference.CustomAttributes) { if (attribute.Constructor.DeclaringType.Is<TAttribute>()) return true; } return false; } /// <summary> /// Verifies that the specified <paramref name="check"/> is satisfied /// </summary> /// <param name="definitions">The definitions.</param> /// <param name="check">The check.</param> /// <returns>the same enumerable</returns> /// <exception cref="QualityException">if any definitions do not pass the check</exception> public static IEnumerable<MethodDefinition> Should(this IEnumerable<MethodDefinition> definitions, Predicate<MethodDefinition> check) { QualityAssert.MethodsPass(definitions, check); return definitions; } } }<file_sep>/Source/Lokad.Shared/Silverlight/AllowPartiallyTrustedCallerAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if SILVERLIGHT2 using System; namespace System.Security { /// <summary> /// Attribute marker to make code compatible with Silverlight /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class AllowPartiallyTrustedCallersAttribute : Attribute { } } #endif<file_sep>/Source/Lokad.Shared/ReadMe.txt === License === Copyright (c) Lokad 2009 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. * Neither the name of Lokad 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. === Lokad.Shared === This Open Source library contains common helper methods and routines that have proved themselves useful in different applications and projects. Partially inspiration and ideas come from the usage of: * Lokad.Common * Microsoft Enterprise Library Application Block * Composite Application Block * Microsoft Smart Client Software Factory * Autofac Inversion of Control Container * xLim Lokad.Shared aims for efficient reuse and flexibility. It does not reference any 3rd party applications or libraries(only BCL). Instead, it provides some generic interfaces the could be used to decouple business logic from the cross-cutting concerns, while still leveraging specific functionality. Currently abstraction points are provided for: * Logging * Exception Handling * Reliability Layers * Monitoring and performance counters * IoC Container auto-registration routines SVN repository is located at: http://lokad.svn.sourceforge.net/svnroot/lokad/Platform/Trunk/Shared<file_sep>/Sample/Sdk/ManageDataAndTasks/Output.cs using System; namespace ManageDataAndTasks { static class Output { public static void Wait() { Console.ReadKey(true); } public static void Error(Exception ex) { Error("Exception encountered"); Exception inner = ex; while (inner.InnerException != null) { inner = inner.InnerException; } Write(ex.Message); Info("Press any key to view full exception informaiton"); Wait(); Write(ex.ToString()); } static void Error(string message, params object[] args) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(message, args); Console.ForegroundColor = color; } public static void Warn(string message, params object[] args) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(message, args); Console.ForegroundColor = color; } public static void Write(string message, params object[] args) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(message, args); Console.ForegroundColor = color; } public static void Info(string message, params object[] args) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(message, args); Console.ForegroundColor = color; } } }<file_sep>/Test/Lokad.Shared.Test/Currency/CurrencyAmountTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class CurrencyAmountTests { // ReSharper disable InconsistentNaming // ReSharper disable EqualExpressionComparison [Test] public void Use_cases() { var eur10 = 10m.In(CurrencyType.Eur); var eur1 = 1m.In(CurrencyType.Eur); Assert.AreEqual(11m.In(CurrencyType.Eur), eur1 + eur10, "X+Y"); Assert.AreEqual(9m.In(CurrencyType.Eur), eur10 - eur1, "X-Y"); Assert.IsTrue(eur10 > eur1, ">"); Assert.IsTrue(eur10 >= eur1, ">="); Assert.IsTrue(eur1 < eur10, "<"); Assert.IsTrue(eur1 <= eur10, "<="); Assert.IsTrue(eur1 != eur10, "!="); Assert.IsFalse(eur1 == eur10, "=="); Assert.AreEqual(eur1, eur1, "Eq"); Assert.AreNotEqual(eur1, eur10, "!Eq"); Assert.AreEqual(-1m, -eur1.Value, "-"); } [Test, ExpectCurrencyMismatch] public void Subtract_mismatched() { var result = 10m.In(CurrencyType.Aud) - 1m.In(CurrencyType.Cad); } [Test, ExpectCurrencyMismatch] public void Add_mismatched() { var result = 10m.In(CurrencyType.Aud) - 1m.In(CurrencyType.Cad); } [Test, ExpectCurrencyMismatch] public void Less_mismatched() { var result = 10m.In(CurrencyType.Aud) < 1m.In(CurrencyType.Cad); } [Test, ExpectCurrencyMismatch] public void Greater_mismatched() { var result = 10m.In(CurrencyType.Aud) > 1m.In(CurrencyType.Cad); } [Test] public void Format_zero() { Assert.AreEqual("0.00", CurrencyAmount.Zero.ToString()); } [Test] public void Format_negative() { Assert.AreEqual("-1.12", (-1.123m.In(CurrencyType.None)).ToString()); } [Test] public void Format_zero_aud() { Assert.AreEqual("0.00 AUD", 0m.In(CurrencyType.Aud).ToString()); } [Test] public void Format_posizitive_aud() { Assert.AreEqual("10.00 AUD", 10m.In(CurrencyType.Aud).ToString()); } [Test] public void Format_positive_with_rounding() { Assert.AreEqual("12.35 USD", 12.347m.In(CurrencyType.Usd).ToString()); } sealed class ExpectCurrencyMismatchAttribute : ExpectedExceptionAttribute { public ExpectCurrencyMismatchAttribute() : base(typeof (CurrencyMismatchException)) { } } } }<file_sep>/Test/Lokad.Testing.Test/ModelAssertTests.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Quality; using NUnit.Framework; namespace Lokad.Testing.Test { [TestFixture] public sealed class ModelAssertTests { // ReSharper disable InconsistentNaming [DesignOfClass.ImmutableFieldsModel] public sealed class WithFields { public readonly string Field1; public readonly int Field2; public WithFields(string field1, int field2) { Field1 = field1; Field2 = field2; } } [Test] public void With_fields_valid() { var m1 = new WithFields("F1", 2); var m2 = new WithFields("F1", 2); ModelAssert.AreEqual(m1, m2); } [Test, ExpectAssert] public void With_fields_invalid() { var m1 = new WithFields("F1", 2); var m2 = new WithFields("F1", 3); ModelAssert.AreEqual(m1, m2); } [Test, ExpectAssert] public void With_fields_nullable_invalid() { var m1 = new WithFields("F1", 2); ModelAssert.AreEqual(m1, null); } [Test] public void With_properties_nullable_valid() { var m1 = new WithProperties("F1", 2); ModelAssert.AreNotEqual(m1, null); } [DesignOfClass.ImmutableFieldsModel] public sealed class WithNested { public readonly WithFields Model; public readonly Guid Unique; public WithNested(WithFields model, Guid unique) { Model = model; Unique = unique; } } [Test] public void Should_be_equal_valid_complex() { var guid = Guid.NewGuid(); var m21 = new WithNested(new WithFields("F1", 2), guid); var m22 = new WithNested(new WithFields("F1", 2), guid); ModelAssert.AreEqual(m21, m22); } [DesignOfClass.ImmutablePropertiesModel] public sealed class WithArrayProperty { public WithFields[] Property { get; set; } public WithArrayProperty(params WithFields[] property) { Property = property; } } [Test] public void With_array_property_valid() { var m11 = new WithFields("F1", 2); var m12 = new WithFields("F1", 2); var m31 = new WithArrayProperty(m11, m11); var m32 = new WithArrayProperty(m12, m12); ModelAssert.AreEqual(m31, m32); } [Test] public void With_array_property_nullable_entry_valid() { var m11 = new WithFields("F1", 2); var m12 = new WithFields("F1", 2); var m31 = new WithArrayProperty(m11, m11,null); var m32 = new WithArrayProperty(m12, m12, null); ModelAssert.AreEqual(m31, m32); } [Test, ExpectAssert] public void With_array_property_null_array_invalid() { var m11 = new WithFields("F1", 2); var m12 = new WithFields("F1", 2); var m31 = new WithArrayProperty { Property = null }; var m32 = new WithArrayProperty(m12, m12, null); ModelAssert.AreEqual(m31,m32); } [Test, ExpectAssert] public void With_array_property_invalid_length() { var m11 = new WithFields("F1", 2); var m12 = new WithFields("F1", 2); var m31 = new WithArrayProperty(m11, m11); var m32 = new WithArrayProperty(m12); ModelAssert.AreEqual(m31, m32); } [Test, ExpectAssert] public void With_array_property_mismatch() { var m11 = new WithFields("F1", 2); var m12 = new WithFields("F1", 2); var m13 = new WithFields("F2", 2); var m31 = new WithArrayProperty(m11, m11); var m32 = new WithArrayProperty(m12, m13); ModelAssert.AreEqual(m31, m32); } [DesignOfClass.ImmutablePropertiesModel] public sealed class WithProperties { public string Property1 { get; private set; } public int Property2 { get; private set; } public WithProperties(string property1, int property2) { Property1 = property1; Property2 = property2; } } [Test] public void With_properties_valid() { var m1 = new WithProperties("F1", 32); var m2 = new WithProperties("F1", 32); ModelAssert.AreEqual(m1, m2); } [Test, ExpectAssert] public void With_properties_valid_reversed() { var m1 = new WithProperties("F1", 32); var m2 = new WithProperties("F1", 32); ModelAssert.AreNotEqual(m1, m2); } [Test] public void With_properties_invalid_reversed() { var m1 = new WithProperties("F1", 33); var m2 = new WithProperties("F1", 32); ModelAssert.AreNotEqual(m1, m2); } [Test, ExpectedException(typeof (FailedAssertException))] public void With_properties_invalid() { var m1 = new WithProperties("F1", 32); var m2 = new WithProperties("F1", 33); ModelAssert.AreEqual(m1, m2); } [Test] public void Collection_of_models() { var m1 = new List<WithProperties> { new WithProperties("F1", 1), new WithProperties("F2", 3) }; var m2 = new List<WithProperties> { new WithProperties("F1", 1), new WithProperties("F2", 3) }; ModelAssert.AreEqualMany(m1, m2); } [Test] public void Array_of_models_valid() { var m1 = new [] { new WithProperties("F1", 1), new WithProperties("F2", 3) }; var m2 = new [] { new WithProperties("F1", 1), new WithProperties("F2", 3) }; ModelAssert.AreEqualMany(m1, m2); } [Test, ExpectAssert] public void Array_of_models_invalid() { var m1 = new[] { new WithProperties("F1", 1), new WithProperties("F2", 4) }; var m2 = new[] { new WithProperties("F1", 1), new WithProperties("F2", 3) }; ModelAssert.AreEqualMany(m1, m2); } public sealed class ExpectAssertAttribute : ExpectedExceptionAttribute { public ExpectAssertAttribute() : base(typeof (FailedAssertException)) { } } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/EnforceArgumentScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class EnforceArgumentScopeTests { [Test, Expects.ArgumentException] public void Test() { try { using (var scope = Scope.ForEnforceArgument("Test", Scope.WhenError)) { ScopeTestHelper.FireErrors(scope); } } catch (ArgumentException ex) { ScopeTestHelper.ShouldBeClean(ex); ScopeTestHelper.ShouldHave(ex, "ErrA"); ScopeTestHelper.ShouldNotHave(ex, "ErrB", "ErrC"); throw; } } [Test] [ExpectedException(typeof (ArgumentException))] public void Test2() { try { var arg = 0; Enforce.Argument(() => arg, ScopeTestHelper.RunNesting); } catch (ArgumentException ex) { ScopeTestHelper.ShouldBeClean(ex); ScopeTestHelper.ShouldHave(ex, "Error1", "Group1", "Group2"); throw; } } } }<file_sep>/Source/Lokad.Shared/Monads/Maybe.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper routines for <see cref="Maybe{T}"/> /// </summary> [UsedImplicitly] public static class Maybe { //public static T? ToNullable<T>(this Maybe<T> maybe) where T : struct //{ // return maybe.HasValue // ? maybe.Value // : new T?(); //} //public static Maybe<T> ToMaybe<T>(this T? nullable) where T : struct //{ // return nullable.HasValue // ? nullable.Value // : Maybe<T>.Empty; //} /// <summary> /// Creates new <see cref="Maybe{T}"/> from the provided value /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="item">The item.</param> /// <returns><see cref="Maybe{T}"/> that matches the provided value</returns> /// <exception cref="ArgumentNullException">if argument is a null reference</exception> public static Maybe<TSource> From<TSource>([NotNull] TSource item) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == item) throw new ArgumentNullException("item"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Maybe<TSource>(item); } /// <summary> /// Optional empty boolean /// </summary> public static readonly Maybe<bool> Bool = Maybe<bool>.Empty; /// <summary> /// Optional empty string /// </summary> public static readonly Maybe<string> String = Maybe<string>.Empty; } }<file_sep>/Test/Lokad.Shared.Test/Reflection/ReflectTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using System; using NUnit.Framework; namespace Lokad.Reflection { [TestFixture] public sealed class ReflectTests { // ReSharper disable InconsistentNaming static void AssertVariable<T>(Func<T> func, string name) { var info = Reflect.Variable(func); Assert.AreSame(typeof (T), info.FieldType); Assert.AreEqual(name, info.Name); } static void AssertProperty<T>(Func<T> func, string name) { var info = Reflect.Property(func); Assert.AreSame(typeof (T), info.ReturnType); Assert.AreEqual("get_" + name, info.Name); } [Test] public void Variable_Works_With_Primitives() { var myVar = "Test"; AssertVariable(() => myVar, "myVar"); } [Test] public void Variable_Works_With_Arguments() { Check("argument", 3); } static void Check(string arg1, int arg2) { AssertVariable(() => arg1, "arg1"); AssertVariable(() => arg2, "arg2"); } [Test] public void Variable_Works_With_Multiple_Items_Per_Scope() { { var i1 = 1; var i2 = 2; AssertVariable(() => i1, "i1"); AssertVariable(() => i2, "i2"); } { var i1 = "A"; var i2 = "B"; AssertVariable(() => i1, "i1"); AssertVariable(() => i2, "i2"); } } [Test] public void Variable_Works_With_Anonymous() { var myVar = new { i = 1 }; AssertVariable(() => myVar, "myVar"); } [Test, ExpectedException(typeof(ReflectLambdaException))] public void Variable_Fails_On_Property() { var i = new { i = 1 }; Reflect.Variable(() => i.i); } [Test, ExpectedException(typeof(ReflectLambdaException))] public void Variable_Fails_On_Constant() { Reflect.Variable(() => 1); } [Test] public void Variable() { var t = new Test<string>("Test"); AssertVariable(() => t, "t"); } public sealed class Test<T> { public readonly T Field; public Test(T property) { Field = property; } public T Property { get { return Field; } } } [Test] public void Property() { var i = new Test<string>("Value"); var i2 = new { Property = "Value" }; AssertProperty(() => i.Property, "Property"); AssertProperty(() => i2.Property, "Property"); } [Test] public void Variable_with_generic_method() { TestGenericMethod<Model>(null); } [Test] public void Variable_with_generic_class() { new GenericClass<Model>(null); } [Test] public void MemberName() { var i = new Test<string>("Value"); var i2 = new { Property = "Value" }; Assert.AreEqual(Reflect.MemberName(() => i.Property), "Property"); Assert.AreEqual(Reflect.MemberName(() => i2.Property), "Property"); Assert.AreEqual(Reflect.MemberName(() => i.Field), "Field"); } static void TestGenericMethod<TModel>(IModel<TModel> model) { var name = Reflect.Variable(() => model).Name; Assert.AreEqual("model", name); } sealed class Model : IModel<Model> { } interface IModel<T> { } class GenericClass<TModel> where TModel : class, IModel<TModel> { public GenericClass(IModel<TModel> model) { Assert.AreEqual("model", Reflect.VariableName(() => model)); } } [Test] public void Can_reflect_property_of_class_with_constraints() { var reflect = new ClassWithConstraints<ClassToReflect>(); string propertyName = reflect.GetNameOfProperty(); Assert.AreEqual("get_SomeProperty", propertyName); } class ClassWithConstraints<T> where T : ClassToReflect, new() { public T Target = default(T); public string GetNameOfProperty() { return Reflect.Property(() => Target.SomeProperty).Name; } } class ClassToReflect { public string SomeProperty { get; set; } } } } #endif<file_sep>/Source/Lokad.Shared/Quality/ReSharper/AssertionConditionType.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Quality { /// <summary> /// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues. /// Otherwise, execution is assumed to be halted /// </summary> public enum AssertionConditionType { /// <summary> /// Indicates that the marked parameter should be evaluated to true /// </summary> IS_TRUE = 0, /// <summary> /// Indicates that the marked parameter should be evaluated to false /// </summary> IS_FALSE = 1, /// <summary> /// Indicates that the marked parameter should be evaluated to null value /// </summary> IS_NULL = 2, /// <summary> /// Indicates that the marked parameter should be evaluated to not null value /// </summary> IS_NOT_NULL = 3, } }<file_sep>/Sample/Sdk/ReadMe.txt Copyright (c) 2006-2009 LOKAD SAS. All rights reserved. Distributed under the new BSD License. This folder contains samples for the Lokad SDK Product page: http://www.lokad.com/sdk-dot-net.ashx TestConnection -------------- The project shows how to connect to the Lokad Services and retrieve information for the current account. ManageDataAndTasks ------------------ This project demonstrates how to: * Connect to the Lokad Services * List all tasks * List all series with associated events and tags * Create new series and update them with values * Add events, tags and tasks to the series Tutorial Source Code -------------------- Sources for the tutorial on Lokad SDK for .NET http://www.lokad.com/sdk-dot-net-tutorial.ashx<file_sep>/Source/Lokad.ActionPolicy/Exceptions/RetryStateWithCount.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Exceptions { sealed class RetryStateWithCount : IRetryState { int _errorCount; readonly Action<Exception, int> _onRetry; readonly Predicate<int> _canRetry; public RetryStateWithCount(int retryCount, Action<Exception, int> onRetry) { _onRetry = onRetry; _canRetry = i => _errorCount <= retryCount; } public bool CanRetry(Exception ex) { _errorCount += 1; bool result = _canRetry(_errorCount); if (result) { _onRetry(ex, _errorCount - 1); } return result; } } }<file_sep>/Source/Lokad.Shared/IResolver.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad { /// <summary> /// Generic resolution interface for the applications, /// where proper infrastructure could not be setup /// </summary> /// <remarks>There are no Generic resolution methods /// (like Resolve(Type service)), for the purpose of enforcing /// explicit resolution logics </remarks> public interface IResolver { /// <summary> /// Resolves this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns>requested instance of <typeparamref name="TService"/></returns> /// <exception cref="ResolutionException">if there is some resolution problem</exception> TService Get<TService>(); /// <summary> /// Resolves the specified service type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="name">The name.</param> /// <returns>requested instance of <typeparamref name="TService"/></returns> /// <exception cref="ResolutionException">if there is resolution problem</exception> TService Get<TService>(string name); } }<file_sep>/Test/Lokad.ActionPolicy.Test/RetryPolicyTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class RetryPolicyTests { // ReSharper disable InconsistentNaming [Test] public void Stack_trace_is_preserved() { var policy = ActionPolicy .Handle<InvalidOperationException>() .Retry(2); StackTest<InvalidOperationException>.Check(policy); } } }<file_sep>/Source/Lokad.Shared/Reflection/ILHelper.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; #if DEBUG && !SILVERLIGHT2 namespace Lokad.Reflection { static class ILHelper { static OpCode[] _multiByteCodes; static OpCode[] _singleByteCodes; static ILHelper() { LoadOpCodes(); } static void LoadOpCodes() { _singleByteCodes = new OpCode[0x100]; _multiByteCodes = new OpCode[0x100]; var fields = typeof (OpCodes) .GetFields() .Where(i => i.FieldType == typeof (OpCode)); foreach (var info in fields) { if (info.FieldType == typeof (OpCode)) { var code = (OpCode) info.GetValue(null); var value = (ushort) code.Value; if (value < 0x100) { _singleByteCodes[value] = code; } else { if ((value & 0xff00) != 0xfe00) { throw new InvalidOperationException("Invalid OpCode."); } _multiByteCodes[value & 0xff] = code; } } } } internal sealed class ILInstruction<T> : ILInstruction { readonly OpCode _code; readonly T _operand; readonly long _position; public ILInstruction(OpCode code, T operand, long position) { _code = code; _operand = operand; _position = position; } public override string ToString() { return string.Format("{2:000} Code: {0}, Operand: {1} ({3})", _code, _operand, _position, _operand.GetType().Name); } } public static ILInstruction<T> From<T>(OpCode item, T operand, long position) { return new ILInstruction<T>(item, operand, position); } public abstract class ILInstruction { } static ILInstruction ReadInstruction(BinaryReader il, Module module, Type[] genericTypeArguments, Type[] genericMethodArguments) { OpCode code; var position = il.BaseStream.Position; ushort value = il.ReadByte(); if (value != 0xfe) { code = _singleByteCodes[value]; } else { value = il.ReadByte(); code = _multiByteCodes[value]; } switch (code.OperandType) { case OperandType.InlineBrTarget: return From(code, il.ReadInt32(), position); case OperandType.InlineField: return From(code, module.ResolveField(il.ReadInt32(), genericTypeArguments, genericMethodArguments), position); case OperandType.InlineMethod: try { return From(code, module.ResolveMethod(il.ReadInt32(), genericTypeArguments, genericMethodArguments), position); } catch { return From(code, module.ResolveMember(il.ReadInt32()), position); } case OperandType.InlineSig: return From(code, module.ResolveSignature(il.ReadInt32()), position); case OperandType.InlineType: return From(code, module.ResolveType(il.ReadInt32(), genericTypeArguments, genericMethodArguments), position); //instruction.Operand = module.ResolveType(metadataToken, this.mi.DeclaringType.GetGenericArguments(), this.mi.GetGenericArguments()); case OperandType.InlineI: return From(code, il.ReadInt32(), position); case OperandType.InlineI8: return From(code, il.ReadInt64(), position); case OperandType.InlineNone: return From(code, 0, position); case OperandType.InlineR: return From(code, il.ReadDouble(), position); case OperandType.InlineString: var stringToken = il.ReadInt32(); return From(code, module.ResolveString(stringToken), position); case OperandType.InlineSwitch: int count = il.ReadInt32(); var addresses = Range.Array(count, i => il.ReadInt32()); return From(code, addresses, position); case OperandType.InlineVar: return From(code, il.ReadUInt16(), position); case OperandType.ShortInlineBrTarget: return From(code, il.ReadSByte(), position); case OperandType.ShortInlineI: return From(code, il.ReadSByte(), position); case OperandType.ShortInlineR: return From(code, il.ReadSingle(), position); case OperandType.ShortInlineVar: return From(code, il.ReadByte(), position); default: throw new InvalidOperationException(code.OperandType.ToString()); } } public static ILInstruction[] Read(Delegate d) { var method = d.Method; var il = method.GetMethodBody().GetILAsByteArray(); using (var stream = new MemoryStream(il)) using (var reader = new BinaryReader(stream)) { var list = new List<ILInstruction>(); while (stream.Position < il.Length) { list.Add(ReadInstruction(reader, method.Module, method.DeclaringType.GetGenericArguments(), method.GetGenericArguments())); } return list.ToArray(); } } } } #endif<file_sep>/Sample/Shared/RulesUI/CustomerView.cs using System; using System.Rules; using System.Windows.Forms; namespace RulesUI { public partial class CustomerView : Form, IEditorView<Customer> { public CustomerView() { InitializeComponent(); _validator = new Validator<Customer>(_name, errorProvider1); _validator .Bind(_name, i => i.Name) .Bind(_email, i => i.Email) .Bind(_street1, i => i.Address.Street1) .Bind(_street2, i => i.Address.Street2) .Bind(_country, i=> i.Address.Country) .Bind(_zip, i=> i.Address.Zip); EnumUtil<Country>.Values.ForEach(c => _country.Items.Add(c)); _country.SelectedIndex = 0; } Rule<Customer>[] _rules; readonly Validator<Customer> _validator; public Result<Customer> GetData(params Rule<Customer>[] rules) { _rules = rules; // we pretend to ask workspace (retrieved from IoC) // for the current presentation framework (windows.forms) // to display us if (DialogResult.OK == ShowDialog()) { return Result.Success(GetData()); } return Result<Customer>.Error("User gave up."); } public void BindData(Customer customer) { _name.Text = customer.Name; _email.Text = customer.Email; // logically this could be moved to a nested address control _street1.Text = customer.Address.Street1; _street2.Text = customer.Address.Street2; _country.SelectedItem = customer.Address.Country; _zip.Text = customer.Address.Zip; } public void SetTitle(string text) { Text = text; } Customer GetData() { var address = new Address(_street1.Text, _street2.Text, _zip.Text, EnumUtil.Parse<Country>(_country.Text)); return new Customer(_name.Text, address, _email.Text); } private void _ok_Click(object sender, EventArgs e) { var customer = GetData(); if (_validator.RunRules(customer, _rules) == RuleLevel.None) { DialogResult = DialogResult.OK; Close(); } } } }<file_sep>/Test/Lokad.Shared.Test/ProviderTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ProviderTests { static readonly IProvider<int, int> _provider = new Dictionary<int, int> {{1, 1}, {2, 4}}.AsProvider(); [Test, Expects.ResolutionException] public void Exception() { _provider.Get(0); } [Test] public void Resolution() { Assert.AreEqual(4, _provider.Get(2)); } } }<file_sep>/Source/Lokad.Shared/Rules/Scopes/ModifierScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// Simple <see cref="IScope"/> implementation that allows to /// modify the behavior of the underlying scopes /// </summary> [Serializable] sealed class ModifierScope : IScope { public delegate void Modifier(IScope scope, RuleLevel ruleLevel, string message); readonly Modifier _modifier; readonly IScope _inner; public ModifierScope(IScope inner, Modifier modifier) { _modifier = modifier; _inner = inner; } void IDisposable.Dispose() { //_inner.Dispose(); } IScope IScope.Create(string name) { return new ModifierScope(_inner.Create(name), _modifier); } void IScope.Write(RuleLevel level, string message) { _modifier(_inner, level, message); } RuleLevel IScope.Level { get { return _inner.Level; } } public static void Lower(IScope scope, RuleLevel ruleLevel, string message) { switch (ruleLevel) { case RuleLevel.Warn: scope.Write(RuleLevel.None, message); break; case RuleLevel.None: break; case RuleLevel.Error: scope.Write(RuleLevel.Warn, message); break; default: throw new ArgumentOutOfRangeException("level"); } } public static void Raise(IScope scope, RuleLevel ruleLevel, string message) { switch (ruleLevel) { case RuleLevel.None: scope.Write(RuleLevel.Warn, message); break; case RuleLevel.Warn: case RuleLevel.Error: scope.Write(RuleLevel.Error, message); break; default: throw new ArgumentOutOfRangeException("level"); } } } }<file_sep>/Source/Lokad.Shared/Diagnostics/ExecutionCounterGroup.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using System; using System.Collections.Generic; using System.Linq.Expressions; using Lokad.Quality; using Lokad.Reflection; namespace Lokad.Diagnostics { /// <summary> /// Helper class to simplify counter creation syntax /// </summary> public abstract class ExecutionCounterGroup { readonly List<ExecutionCounter> _counters = new List<ExecutionCounter>(); /// <summary> /// Registers the counters in the global cache /// </summary> protected void Register() { ExecutionCounters.Default.RegisterRange(_counters); } /// <summary> /// Registers the counters in the specified cache /// </summary> protected void Register(ExecutionCounters context) { context.RegisterRange(_counters); } /// <summary> /// Creates the counter and adds it to the internal collection. /// </summary> /// <param name="name">The name for the new counter.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> /// <returns>instance of the created counter</returns> protected ExecutionCounter CreateCounter(string name, int openCounterCount, int closeCounterCount) { var counter = new ExecutionCounter(name, openCounterCount, closeCounterCount); _counters.Add(counter); return counter; } /// <summary> Creates the counter and adds it to the internal collection. </summary> /// <param name="expression">The expression to derive counter name from.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> /// <returns>instance of the new counter</returns> protected ExecutionCounter CreateCounter(Expression<Action> expression, int openCounterCount, int closeCounterCount) { var methodInfo = Express.Method(expression); string counterName = StringUtil.FormatInvariant("{0}.{1}", methodInfo.DeclaringType.Name, methodInfo.Name); return CreateCounter(counterName, openCounterCount, closeCounterCount); } /// <summary> Creates the counter and adds it to the internal collection. </summary> /// <param name="expression">The expression to derive counter name from.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> /// <returns>instance of the new counter</returns> protected ExecutionCounter CreateCounterForCtor<T>(Expression<Func<T>> expression, int openCounterCount, int closeCounterCount) { var methodInfo = Express.Constructor(expression); string counterName = StringUtil.FormatInvariant("{0}.{1}", methodInfo.DeclaringType.Name, methodInfo.Name); return CreateCounter(counterName, openCounterCount, closeCounterCount); } } /// <summary> /// Helper class to simplify counter creation syntax /// </summary> [NoCodeCoverage] public abstract class ExecutionCounterGroup<T> : ExecutionCounterGroup { /// <summary> /// Creates new counter and adds it to the internal collection /// </summary> /// <param name="call">The call to derive counter name from.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> /// <returns>instance of the created counter</returns> protected ExecutionCounter CreateCounter(Expression<Action<T>> call, int openCounterCount, int closeCounterCount) { var methodInfo = Express.MethodWithLambda(call); string counterName = StringUtil.FormatInvariant("{0}.{1}", typeof (T).Name, methodInfo.Name); return CreateCounter(counterName, openCounterCount, closeCounterCount); } } } #endif<file_sep>/Source/Lokad.Shared/Extensions/ExtendInt32.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> Extensions to the <see cref="int"/> </summary> public static class ExtendInt32 { /// <summary> /// Returns kilobytes /// </summary> /// <param name="value"></param> /// <returns></returns> public static int Kb(this int value) { return value*1024; } /// <summary> /// Returns megabytes /// </summary> /// <param name="value"></param> /// <returns></returns> public static int Mb(this int value) { return value*1024*1024; } /// <summary>Returns a <see cref="TimeSpan"/> that represents a specified number of minutes.</summary> /// <param name="minutes">number of minutes</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> /// <example>3.Minutes()</example> public static TimeSpan Minutes(this int minutes) { return TimeSpan.FromMinutes(minutes); } /// <summary> /// Returns a <see cref="TimeSpan"/> that represents a specified number of seconds. /// </summary> /// <param name="seconds">number of seconds</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> /// <example>2.Seconds()</example> public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } /// <summary> /// Returns a <see cref="TimeSpan"/> that represents a specified number of milliseconds. /// </summary> /// <param name="milliseconds">milliseconds for this timespan</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> public static TimeSpan Milliseconds(this int milliseconds) { return TimeSpan.FromMilliseconds(milliseconds); } /// <summary> /// Returns a <see cref="TimeSpan"/> that represents a specified number of days. /// </summary> /// <param name="days">Number of days.</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> public static TimeSpan Days(this int days) { return TimeSpan.FromDays(days); } /// <summary> /// Returns a <see cref="TimeSpan"/> that represents a specified number of hours. /// </summary> /// <param name="hours">Number of hours.</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> public static TimeSpan Hours(this int hours) { return TimeSpan.FromHours(hours); } } }<file_sep>/Test/Lokad.Shared.Test/Utils/XmlUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.IO; using NUnit.Framework; #if !SILVERLIGHT2 namespace Lokad { [TestFixture] public sealed class XmlUtilTests { public sealed class Item { } [Test] public void Use_Cases() { var item = new Item(); var items = new Item[0]; // strings XmlUtil.Serialize(item); XmlUtil.SerializeArray(items); XmlUtil<string[]>.Serialize(new string[0]); using (var stream = new MemoryStream()) { XmlUtil.Serialize(item, stream); XmlUtil.SerializeArray(items, stream); XmlUtil<string[]>.Serialize(new string[0], stream); } using (var stream = new StringWriter()) { XmlUtil.Serialize(item, stream); XmlUtil.SerializeArray(items, stream); XmlUtil<string[]>.Serialize(new string[0], stream); } } } } #endif<file_sep>/Source/Lokad.Shared/Rules/Scopes/ScopeFactory.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Reflection; namespace Lokad.Rules { static class ScopeFactory { public static IScope ForEnforceArgument(string name, Predicate<RuleLevel> throwIf) { return new SimpleScope(name, (path, level, message) => { if (throwIf(level)) throw new ArgumentException(message, path); }); } public static IScope ForEnforceArgument<T>(Func<T> argumentReference, Predicate<RuleLevel> predicate) { return new DelayedScope( () => Reflect.VariableName(argumentReference), (func, level, s) => { if (predicate(level)) throw new ArgumentException(s, func()); } ); } public static IScope ForEnforce(string name, Predicate<RuleLevel> throwIf) { return new SimpleScope(name, (path, level, message) => { if (throwIf(level)) throw new RuleException(message, path); }); } public static IScope ForEnforce<T>(Func<T> reference, Predicate<RuleLevel> predicate) { return new DelayedScope( () => Reflect.VariableName(reference), (func, level, s) => { if (predicate(level)) throw new RuleException(s, func()); } ); } public static IScope ForMessages(string name, Action<RuleMessages> action) { var messages = new List<RuleMessage>(); return new SimpleScope(name, (path, level, message) => messages.Add(new RuleMessage(path, level, message)), level => action(new RuleMessages(messages, level))); } public static IScope ForMessages<T>(Func<T> reference, Action<RuleMessages> action) { var messages = new List<RuleMessage>(); return new DelayedScope( () => Reflect.VariableName(reference), (func, level, message) => messages.Add(new RuleMessage(func(), level, message)), level => action(new RuleMessages(messages, level))); } public static IScope ForValidation(string name, Predicate<RuleLevel> throwIf) { return ForMessages(name, messages => { if (throwIf(messages.Level)) throw new RuleException(messages); }); } public static RuleMessages GetMessages<T>(Func<T> reference, Action<IScope> action) { var messages = RuleMessages.Empty; using (var scope = ForMessages(reference, m => messages = m)) { action(scope); } return messages; } } }<file_sep>/Source/Lokad.Quality/MaintainabilityRules.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using Lokad.Quality; using Lokad.Rules; namespace Lokad.Quality { /// <summary> /// Shared maintainability rules /// </summary> public static class MaintainabilityRules { /// <summary> /// Ensures that <see cref="NoCodeCoverageAttribute"/> is not used on complex methods. /// </summary> /// <param name="maxInstructions">Method is considered to be complex when number /// of IL instructions in it exceeds the <paramref name="maxInstructions"/>.</param> /// <returns>new rule instance</returns> public static Rule<Codebase> Ncca_Is_Used_Properly(int maxInstructions) { return (codebase, scope) => Ncca_Is_Used_Properly(codebase, scope, maxInstructions); } static void Ncca_Is_Used_Properly(Codebase codebase, IScope scope, int maxInstructions) { var methods = codebase.Methods .Where(m => m.HasBody && m.Body.Instructions.Count > maxInstructions) .Where(m => m.Has<NoCodeCoverageAttribute>() || m.DeclaringType.Has<NoCodeCoverageAttribute>()); foreach (var method in methods) { scope.Error("Method is too complex to be marked with NCCA: {0}", method); } } /// <summary> /// Ensures that classes marked with <see cref="ImmutableAttribute"/> have only /// readonly fields /// </summary> /// <param name="codebase">The codebase to run against.</param> /// <param name="scope">The scope to report to.</param> public static void Immutable_Types_Should_Be_Immutable(Codebase codebase, IScope scope) { var decorated = codebase.Types .Where(t => t.Has<ImmutableAttribute>()); var failing = decorated .Where(t => t.GetAllFields(codebase) .Count(f => !f.IsInitOnly && !f.IsStatic) > 0); foreach (var definition in failing) { scope.Error("Type should be immutable: {0}", definition); } } } }<file_sep>/Source/Lokad.Shared/Serialization/DataContractMessageSerializer.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Xml; using Lokad.Quality; using System.Linq; namespace Lokad.Serialization { /// <summary> /// Message serializer for the <see cref="DataContractSerializer"/> /// </summary> [UsedImplicitly] public class DataContractMessageSerializer : IMessageSerializer { readonly IDictionary<string, Type> _contract2Type = new Dictionary<string, Type>(); readonly ICollection<Type> _knownTypes; readonly IDictionary<Type, string> _type2Contract = new Dictionary<Type, string>(); /// <summary> /// Initializes a new instance of the <see cref="DataContractMessageSerializer"/> class. /// </summary> /// <param name="knownTypes">The known types.</param> public DataContractMessageSerializer(ICollection<Type> knownTypes) { if (knownTypes.Count == 0) throw new InvalidOperationException("DataContractMessageSerializer requires some known types to serialize. Have you forgot to supply them?"); _knownTypes = knownTypes; DataContractUtil.ThrowOnMessagesWithoutDataContracts(_knownTypes); foreach (var type in _knownTypes) { var reference = DataContractUtil.GetContractReference(type); _contract2Type.Add(reference, type); _type2Contract.Add(type, reference); } } /// <summary> /// Initializes a new instance of the <see cref="DataContractMessageSerializer"/> class. /// </summary> /// <param name="know">The know.</param> public DataContractMessageSerializer(IKnowSerializationTypes know) : this(know.GetKnownTypes().ToSet()) { } /// <summary> /// Serializes the object to the specified stream /// </summary> /// <param name="instance">The instance.</param> /// <param name="destination">The destination stream.</param> public void Serialize(object instance, Stream destination) { var serializer = new DataContractSerializer(instance.GetType(), _knownTypes); //using (var compressed = destination.Compress(true)) using (var writer = XmlDictionaryWriter.CreateBinaryWriter(destination, null, null, false)) { serializer.WriteObject(writer, instance); } } /// <summary> /// Deserializes the object from specified source stream. /// </summary> /// <param name="sourceStream">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> public object Deserialize(Stream sourceStream, Type type) { var serializer = new DataContractSerializer(type, _knownTypes); using (var reader = XmlDictionaryReader.CreateBinaryReader(sourceStream, XmlDictionaryReaderQuotas.Max)) { return serializer.ReadObject(reader); } } /// <summary> /// Gets the contract name by the type /// </summary> /// <param name="messageType">Type of the message.</param> /// <returns>contract name (if found)</returns> public Maybe<string> GetContractNameByType(Type messageType) { return _type2Contract.GetValue(messageType); } /// <summary> /// Gets the type by contract name. /// </summary> /// <param name="contractName">Name of the contract.</param> /// <returns>type that could be used for contract deserialization (if found)</returns> public Maybe<Type> GetTypeByContractName(string contractName) { return _contract2Type.GetValue(contractName); } } }<file_sep>/Sample/Shared/RulesUI/Country.cs namespace RulesUI { public enum Country { Undefined, USA, France, Russia } }<file_sep>/Source/Lokad.Shared/Range.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class with shortcut methods for managing enumerations. /// Useful for inlining object generation in tests /// </summary> public static class Range { /// <summary> Returns empty enumerator </summary> /// <typeparam name="T">type of the item to enumerate</typeparam> /// <returns>singleton instance of the empty enumerator</returns> public static IEnumerable<T> Empty<T>() { return Enumerable.Empty<T>(); } /// <summary> /// returns enumeration from 0 with <paramref name="count"/> numbers /// </summary> /// <param name="count">Number of items to create</param> /// <returns>enumerable</returns> [NoCodeCoverage] public static IEnumerable<int> Create(int count) { return Enumerable.Range(0, count); } /// <summary> /// Creates sequence of the integral numbers within the specified range /// </summary> /// <param name="start">The value of the first integer in sequence.</param> /// <param name="count">The number of values in the sequence.</param> /// <returns>sequence of the integral numbers within the specified range</returns> [NoCodeCoverage] public static IEnumerable<int> Create(int start, int count) { return Enumerable.Range(start, count); } /// <summary> /// Creates sequence that consists of a repeated value. /// </summary> /// <typeparam name="TResult">The type of the value to repeat.</typeparam> /// <param name="item">The value to repeat.</param> /// <param name="count">The number of times to repeat.</param> /// <returns>sequence that consists of a repeated value</returns> [NoCodeCoverage] public static IEnumerable<TResult> Repeat<TResult>(TResult item, int count) { return Enumerable.Repeat(item, count); } /// <summary> /// Creates the generator to iterate from 1 to <see cref="int.MaxValue"/>. /// </summary> /// <typeparam name="T">type of the item to generate</typeparam> /// <param name="generator">The generator.</param> /// <returns>new enumerator</returns> public static IEnumerable<T> Create<T>(Func<int, T> generator) { for (int i = 0; i < int.MaxValue; i++) { yield return generator(i); } throw new InvalidOperationException("Generator has reached the end"); } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<int, T> generator) { for (int i = 0; i < count; i++) { yield return generator(i); } } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<T> generator) { for (int i = 0; i < count; i++) { yield return generator(); } } /// <summary> /// Creates the array populated with the provided generator /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>array</returns> public static TValue[] Array<TValue>(int count, Func<int, TValue> generator) { if (generator == null) throw new ArgumentNullException("generator"); var array = new TValue[count]; for (int i = 0; i < array.Length; i++) { array[i] = generator(i); } return array; } /// <summary> /// Creates the array of integers /// </summary> /// <param name="count">The count.</param> /// <returns></returns> public static int[] Array(int count) { var array = new int[count]; for (int i = 0; i < array.Length; i++) { array[i] = i; } return array; } } }<file_sep>/Test/Lokad.Stack.Test/Logging/LoggingModuleTests.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Autofac; using NUnit.Framework; namespace Lokad.Logging { [TestFixture] public sealed class LoggingModuleTests { // ReSharper disable InconsistentNaming [Test] public void Test_Console() { var builder = new ContainerBuilder(); builder.RegisterModule<LoggingModule>(); using (var build = builder.Build()) { Assert.IsNotNull(build.Resolve<ILog>()); Assert.IsNotNull(build.Resolve<INamedProvider<ILog>>()); } } [TearDown] public void TearDown() { LoggingStack.Reset(); } } }<file_sep>/Source/Lokad.Testing/Properties/AssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Lokad.Testing")] [assembly: AssemblyDescription("Testing helpers")] [assembly: CLSCompliant(true)] [assembly: InternalsVisibleTo("Lokad.Stack.Test, PublicKey = " + GlobalAssemblyInfo.PublicKey)] [assembly: AssemblyCopyright(GlobalAssemblyInfo.Copyright)] [assembly: AssemblyTrademark(GlobalAssemblyInfo.Trademark)] <file_sep>/Sample/Shared/RulesUI/AddressIs.cs using System; using System.Rules; namespace RulesUI { static class AddressIs { // simple static rule public static void Valid(Address address, IScope scope) { scope.Validate(() => address.Street1, StringIs.Limited(10, 256)); scope.Validate(() => address.Street2, StringIs.Limited(256)); scope.Validate(() => address.Country, Is.NotDefault); scope.Validate(() => address.Zip, StringIs.Limited(10)); switch (address.Country) { case Country.USA: scope.Validate(() => address.Zip, StringIs.Limited(5, 10)); break; case Country.France: break; case Country.Russia: scope.Validate(() => address.Zip, StringIs.Limited(6, 6)); break; default: scope.Validate(() => address.Zip, StringIs.Limited(1, 64)); break; } } // another dynamic rule public static Rule<Address> In(Country country) { return (address, scope) => scope.Validate(() => address.Country, (c, s) => { if (c != country) s.Error("We are working only in {0} now.", country); }); } } }<file_sep>/Source/Lokad.ActionPolicy/ExceptionHandler.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> This delegate represents <em>catch</em> block /// </summary> /// <param name="ex">Exception to handle</param> /// <returns><em>true</em> if we can handle exception</returns> public delegate bool ExceptionHandler(Exception ex); }<file_sep>/Test/Lokad.Testing.Test/ContainerFixture.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Testing.Test { public abstract class ContainerFixture<TSubject, TInterface> where TSubject : TInterface { MockContainer<TSubject> _container; protected MockContainer<TSubject> Container { get { return _container; } } protected TInterface Interface { get { return _container.Subject; } } protected TSubject Implementation { get { return _container.Subject; } } [SetUp] public void SetUp() { _container = new MockContainer<TSubject>(); } [TearDown] public void TearDown() { ((IDisposable) _container).Dispose(); } } }<file_sep>/Source/Lokad.Shared/Linq/Indexer.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace System.Linq { /// <summary> /// Indexing wrapper that contains value and its integral position. /// </summary> /// <typeparam name="TSource">type of the underlying item</typeparam> public struct Indexer<TSource> { readonly int _index; readonly TSource _value; readonly bool _isFirst; /// <summary> /// Gets the integral position of the item. /// </summary> /// <value>The integral position of the item.</value> public int Index { get { return _index; } } /// <summary> /// Gets a value indicating whether this instance is first. /// </summary> /// <value><c>true</c> if this instance is first; otherwise, <c>false</c>.</value> public bool IsFirst { get { return _isFirst; } } /// <summary> /// Gets the value. /// </summary> /// <value>The value.</value> public TSource Value { get { return _value; } } internal Indexer(int index, TSource value) { _index = index; _isFirst = index == 0; _value = value; } } }<file_sep>/Source/Lokad.Serialization/Serialization/ProtoBufUtil.cs using System; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Xml.Serialization; using ProtoBuf; namespace Lokad.Serialization { public static class ProtoBufUtil { public static string GetContractReference(Type type) { var attribs = type.GetCustomAttributes(false); var helper = new AttributeHelper(attribs); var name = Maybe.String .GetValue(() => helper.GetString<ProtoContractAttribute>(p => p.Name)) .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Name)) .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.TypeName)) .GetValue(() => type.Name); var ns = Maybe.String .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Namespace)) .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.Namespace)) .Convert(s => s.Trim() + "/", ""); return ns + name; } public static IFormatter CreateFormatter(Type type) { try { typeof(Serializer) .GetMethod("PrepareSerializer") .MakeGenericMethod(type) .Invoke(null, null); } catch (TargetInvocationException tie) { var message = string.Format("Failed to prepare ProtoBuf serializer for '{0}'.", type); throw new InvalidOperationException(message, tie.InnerException); } try { return (IFormatter)typeof(Serializer) .GetMethod("CreateFormatter") .MakeGenericMethod(type) .Invoke(null, null); } catch (TargetInvocationException tie) { var message = string.Format("Failed to create ProtoBuf formatter for '{0}'.", type); throw new InvalidOperationException(message, tie.InnerException); } } } } <file_sep>/Sample/Sdk/TestConnection/Program.cs #region (c)2008 Lokad - New BSD license // Copyright (c) Lokad 2008 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Api; namespace TestConnection { class Program { const string serviceUrl = "http://sandbox-ws.lokad.com/TimeSeries2.asmx"; static void Main() { var login = ""; // put your Lokad login here var password = ""; // put your Lokad password here try { var service = ServiceFactory.GetConnectorForTesting(login, password, serviceUrl); var info = service.GetAccountInfo(); Console.WriteLine("My account HR ID is {0}", info.AccountHRID); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("Press any key to exit"); Console.ReadKey(true); } } }<file_sep>/Test/Lokad.ActionPolicy.Test/StackTest.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { static class StackTest<TException> where TException : Exception, new() { static void InternalStack() { throw new TException(); } static void Fire() { InternalStack(); } internal static void Check(ActionPolicy policy) { try { policy.Do(Fire); } catch (TException ex) { StringAssert.Contains("InternalStack", ex.StackTrace); } } } }<file_sep>/Source/Lokad.Shared/Utils/StringUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Globalization; using System.Text; namespace Lokad { /// <summary> /// Helper methods for <see cref="string"/> /// </summary> public static class StringUtil { /// <summary> /// Formats the string using InvariantCulture /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> /// <returns>formatted string</returns> public static string FormatInvariant(string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format, args); } /// <summary> /// Converts "Class.SomeName" to "Class - Some Name" /// </summary> public static string MemberNameToCaption(string source) { Enforce.ArgumentNotEmpty(() => source); var cleanedSource = source.Replace(".", " - "); var sb = new StringBuilder(); bool lastWasUpper = false; bool lastWasEmpty = true; foreach (var c in cleanedSource) { if (char.IsUpper(c) && !lastWasUpper && !lastWasEmpty) { sb.Append(' '); } lastWasUpper = char.IsUpper(c); lastWasEmpty = char.IsWhiteSpace(c); sb.Append(c); } return sb.ToString(); } } }<file_sep>/Test/Lokad.Shared.Test/Extensions/ExtendIDictionaryTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ExtendIDictionaryTests { [Test] public void GetValue() { var d = new Dictionary<int, int> { {1, 2} }; Assert.AreEqual(2, d.GetValue(1, 0)); Assert.AreEqual(0, d.GetValue(2, 0)); Assert.AreEqual(Maybe<int>.Empty, d.GetValue(10)); Assert.AreEqual(2, d.GetValue(1).Value); } } }<file_sep>/Source/Lokad.Shared/Silverlight/Stopwatch.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if SILVERLIGHT2 namespace System.Diagnostics { /// <summary> /// Replacement for missing stopwatch, based on the article from /// http://blog.tiaan.com/link/2009/02/03/stopwatch-silverlight /// This is a low-precision stop-watch /// </summary> public class Stopwatch { /// <summary> /// Determines if the stopwatch is high or low resolution /// (always false for this implementation) /// </summary> public static readonly bool IsHighResolution = false; /// <summary> /// Polling frequency /// </summary> public static readonly long Frequency = TimeSpan.TicksPerSecond; /// <summary> /// Gets the time elapsedsince the stopwatch has been started. /// </summary> /// <value>The elapsed.</value> public TimeSpan Elapsed { get { if (!_startUtc.HasValue) { return TimeSpan.Zero; } if (!_endUtc.HasValue) { return (DateTime.UtcNow - _startUtc.Value); } return (_endUtc.Value - _startUtc.Value); } } /// <summary> /// Gets the elapsed time in milliseconds. /// </summary> /// <value>The elapsed time inmilliseconds.</value> public long ElapsedMilliseconds { get { return ElapsedTicks/TimeSpan.TicksPerMillisecond; } } /// <summary> /// Gets the elapsed time in ticks. /// </summary> /// <value>The elapsed time in ticks.</value> public long ElapsedTicks { get { return Elapsed.Ticks; } } /// <summary> /// Gets or sets a value indicating whether this instance is running. /// </summary> /// <value> /// <c>true</c> if this instance is running; otherwise, <c>false</c>. /// </value> public bool IsRunning { get; private set; } DateTime? _startUtc; DateTime? _endUtc; /// <summary> /// Gets the timestamp. /// </summary> /// <returns>current timestamp</returns> public static long GetTimestamp() { return DateTime.UtcNow.Ticks; } /// <summary> /// Resets this instance. /// </summary> public void Reset() { Stop(); _endUtc = null; _startUtc = null; } /// <summary> /// Starts this instance. /// </summary> public void Start() { if (IsRunning) { return; } if ((_startUtc.HasValue) && (_endUtc.HasValue)) { // Resume the timer from its previous state _startUtc = _startUtc.Value + (DateTime.UtcNow - _endUtc.Value); } else { // Start a new time-interval from scratch _startUtc = DateTime.UtcNow; } IsRunning = true; _endUtc = null; } /// <summary> /// Stops this instance. /// </summary> public void Stop() { if (IsRunning) { IsRunning = false; _endUtc = DateTime.UtcNow; } } /// <summary> /// Creates and starts a new stopwatch instance /// </summary> /// <returns>new stopwatch instance</returns> public static Stopwatch StartNew() { var stopwatch = new Stopwatch(); stopwatch.Start(); return stopwatch; } } } #endif<file_sep>/Test/Lokad.Quality.Test/GlobalSetup.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Quality.Test { static class GlobalSetup { public static readonly Codebase Codebase = new Codebase("Lokad.Quality.Test.dll"); } }<file_sep>/Test/Lokad.Shared.Test/Diagnostics/ExecutionCounterTests.cs using Lokad.Rules; using Lokad.Testing; using NUnit.Framework; using Lokad.Diagnostics.Persist; #if !SILVERLIGHT2 namespace Lokad.Diagnostics { [TestFixture] public sealed class ExecutionCounterTests { // ReSharper disable InconsistentNaming [Test] public void Async_counter_reset_is_handled() { var c = Create(); var timer = c.Open(); c.Reset(); c.Close(timer); Assert.AreEqual(0, c.ToStatistics().CloseCount); } [Test] public void Normal_flow() { var c = Create(1,1); var timer = c.Open(5); SystemUtil.Sleep(1.Milliseconds()); c.Close(timer,5); var statistics = c.ToStatistics(); RuleAssert.That(() => statistics, s => s.CloseCount == 1, s => s.OpenCount == 1, s => s.RunningTime > 0, s => s.Counters[0] == 5, s => s.Counters[1] == 5); } [Test] public void Conversion() { var c = Create(); var timer = c.Open(); var statistics = new[]{c.ToStatistics()}; XmlUtil.TestXmlSerialization(statistics.ToPersistence()); } static ExecutionCounter Create() { return new ExecutionCounter("null", 0, 0); } static ExecutionCounter Create(int openGroup, int closeGroup) { return new ExecutionCounter("null", openGroup, closeGroup); } } } #endif<file_sep>/Source/Lokad.ActionPolicy/Exceptions/CircuitBreakerPolicy.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Exceptions { static class CircuitBreakerPolicy { internal static void Implementation(Action action, ExceptionHandler canHandle, ICircuitBreakerState breaker) { if (breaker.IsBroken) throw breaker.LastException; try { action(); breaker.Reset(); return; } catch (Exception ex) { if (!canHandle(ex)) { throw; } breaker.TryBreak(ex); throw; } } } }<file_sep>/Source/Lokad.Shared/Quality/NoCodeCoverageAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Attribute used to inform code coverage tool to ignore marked code block /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] [NoCodeCoverage] public sealed class NoCodeCoverageAttribute : Attribute { /// <summary> Gets or sets the justification for removing /// the member from the unit test code coverage. </summary> /// <value>The justification.</value> public string Justification { get; set; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/DelayedScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class DelayedScopeTests { [Test] public void Test() { int nameCounter = 0; int runCounter = 0; Func<string> func = () => (nameCounter++).ToString(); var t = new DelayedScope(func, (func1, level, s) => { func1(); runCounter++; }); Assert.AreEqual(0, nameCounter); ScopeTestHelper.RunNesting(0, t); Assert.AreEqual(1, nameCounter); Assert.AreEqual(6, runCounter); } [Test] public void Nesting() { IScope s = new DelayedScope(() => "Name", (provider, level, message) => { Assert.AreEqual("Name.Child", provider()); Assert.AreEqual(level, RuleLevel.Warn); Assert.AreEqual("Message", message); }); using (var child = s.Create("Child")) { child.Warn("Message"); Assert.AreEqual(RuleLevel.Warn, child.Level); } Assert.AreEqual(RuleLevel.Warn, s.Level); } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendICollection.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; namespace Lokad { /// <summary> /// Simple helper extensions for <see cref="ICollection{T}"/> /// </summary> public static class ExtendICollection { /// <summary> /// Adds all items to the target collection /// </summary> /// <typeparam name="T">type of the item within the collection</typeparam> /// <param name="collection">The collection</param> /// <param name="items">items to add to the collection</param> /// <returns>same collection instance</returns> public static ICollection<T> AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) { if (collection == null) throw new ArgumentNullException("collection"); if (items == null) throw new ArgumentNullException("items"); foreach (var item in items) { collection.Add(item); } return collection; } /// <summary> /// Removes all items from the target collection /// </summary> /// <typeparam name="T">type of the item within the collection</typeparam> /// <param name="collection">The collection.</param> /// <param name="items">The items.</param> /// <returns>same collection instance</returns> public static ICollection<T> RemoveRange<T>(this ICollection<T> collection, IEnumerable<T> items) { if (collection == null) throw new ArgumentNullException("collection"); if (items == null) throw new ArgumentNullException("items"); foreach (var item in items) { collection.Remove(item); } return collection; } /// <summary> /// Shortcut to determine whether the specified <see cref="ICollection{T}"/> is empty. /// </summary> /// <typeparam name="T">items in the collection</typeparam> /// <param name="self">The collection.</param> /// <returns> /// <c>true</c> if the specified self is empty; otherwise, <c>false</c>. /// </returns> public static bool IsEmpty<T>(this ICollection<T> self) { if (self == null) throw new ArgumentNullException("self"); return self.Count == 0; } } }<file_sep>/Source/Lokad.Shared/Rules/Common/DoubleIs.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// Rules for the <see cref="double"/> /// </summary> public static class DoubleIs { /// <summary> /// Checks if the specified double is valid. /// </summary> /// <param name="value">The value.</param> /// <param name="scope">The scope.</param> public static void Valid(double value, IScope scope) { if (Double.IsNaN(value) || Double.IsInfinity(value)) scope.Error("Double should represent a valid value."); } } }<file_sep>/Source/Lokad.Shared/Rules/RuleLevel.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Rules { /// <summary> /// Levels leveraged by the <see cref="Rule{T}"/> implementations /// </summary> public enum RuleLevel { /// <summary> Default value for the purposes of good citizenship </summary> None = 0, /// <summary> The rule raises a warning </summary> Warn, /// <summary> The rule raises an error </summary> Error } }<file_sep>/Sample/Shared/RulesUI/Validator.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Rules; using System.Windows.Forms; namespace RulesUI { /// <summary> /// Allows to bind validation results to <see cref="ErrorProvider"/> /// in a strongly-typed manner </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> public sealed class Validator<TTarget> { private readonly Control _defaultControl; private readonly ErrorProvider _provider; private readonly string _scope = Guid.NewGuid().ToString(); private readonly IList<Tuple<Control, string>> _bindings = new List<Tuple<Control, string>>(); public Validator(Control defaultControl, ErrorProvider provider) { _defaultControl = defaultControl; _provider = provider; } public RuleLevel RunRules(TTarget item, params Rule<TTarget>[] rules) { _provider.Clear(); var messages = Scope.GetMessages(item, _scope, rules); if (messages.Level != RuleLevel.None) { Display(messages); } return messages.Level; } public Validator<TTarget> Bind<TProperty>(Control control, Expression<Func<TTarget, TProperty>> expression) { var path = ScopePending.GetPath(expression); var fullPath = ScopePending.Compose(_scope, path); _bindings.Add(control, fullPath); return this; } private void Display(IEnumerable<RuleMessage> messages) { var used = messages.ToList(); foreach (var binding in _bindings) { var binding1 = binding; var match = messages .Where(m => m.Path == binding1.Item2); DisplayErrors(binding.Item1, match); foreach (var message in match) { used.Remove(message); } } if (used.Count > 0) { DisplayErrors(_defaultControl, used); } } private void DisplayErrors(Control control, IEnumerable<RuleMessage> match) { var join = match .Select(m => m.Message); if (match.Count() != 0) { _provider.SetError(control, join.Join(Environment.NewLine)); } } } }<file_sep>/Test/Lokad.Shared.Test/Tuples/TupleTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class TupleTests { // ReSharper disable InconsistentNaming [Test] public void Test_tuple5() { var t1 = CreateTuple5(); var copy = Tuple.From(t1.Item1, t1.Item2, t1.Item3, t1.Item4, t1.Item5); var t2 = CreateTuple5(); Assert.AreEqual(t1, copy); Assert.AreNotEqual(t1, t2); Assert.AreEqual(t1.GetHashCode(), copy.GetHashCode()); Assert.AreNotEqual(t1.GetHashCode(), t2.GetHashCode()); Assert.AreEqual(t1.ToString(), copy.ToString()); Assert.AreNotEqual(t1.ToString(), t2.ToString()); Assert.IsTrue(t1 == copy); Assert.IsTrue(t1 != t2); } [Test] public void Test_tuple6() { var t1 = CreateTuple6(); var copy = Tuple.From(t1.Item1, t1.Item2, t1.Item3, t1.Item4, t1.Item5, t1.Item6); var t2 = CreateTuple6(); Assert.AreEqual(t1, copy); Assert.AreNotEqual(t1, t2); Assert.AreEqual(t1.GetHashCode(), copy.GetHashCode()); Assert.AreNotEqual(t1.GetHashCode(), t2.GetHashCode()); Assert.AreEqual(t1.ToString(), copy.ToString()); Assert.AreNotEqual(t1.ToString(), t2.ToString()); Assert.IsTrue(t1 == copy); Assert.IsTrue(t1 != t2); } [Test] public void Test_tuple7() { var t1 = CreateTuple7(); var copy = Tuple.From(t1.Item1, t1.Item2, t1.Item3, t1.Item4, t1.Item5, t1.Item6, t1.Item7); var t2 = CreateTuple7(); Assert.AreEqual(t1, copy); Assert.AreNotEqual(t1, t2); Assert.AreEqual(t1.GetHashCode(), copy.GetHashCode()); Assert.AreNotEqual(t1.GetHashCode(), t2.GetHashCode()); Assert.AreEqual(t1.ToString(), copy.ToString()); Assert.AreNotEqual(t1.ToString(), t2.ToString()); Assert.IsTrue(t1 == copy); Assert.IsTrue(t1 != t2); } [Test] public void Test_appending() { var tuple = CreateTuple7(); var appended = Tuple .From(tuple.Item1, tuple.Item2) .Append(tuple.Item3) .Append(tuple.Item4) .Append(tuple.Item5) .Append(tuple.Item6) .Append(tuple.Item7); Assert.AreEqual(tuple, appended); } static Tuple<bool, DateTime, object, string, double, Guid, Guid> CreateTuple7() { return Tuple.From( Rand.NextBool(), Rand.NextDate(), (object) null, Rand.NextString(10, 23), Rand.NextDouble(), Rand.NextGuid(), Rand.NextGuid()); } static Tuple<object, bool, DateTime, string, double, Guid> CreateTuple6() { return Tuple.From( (object) null, Rand.NextBool(), Rand.NextDate(), Rand.NextString(10, 23), Rand.NextDouble(), Rand.NextGuid()); } static Tuple<object, bool, DateTime, string, double> CreateTuple5() { return Tuple.From( (object) null, Rand.NextBool(), Rand.NextDate(), Rand.NextString(10, 23), Rand.NextDouble()); } } }<file_sep>/Source/Lokad.Shared/Enforce.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Lokad.Quality; using Lokad.Reflection; using Lokad.Rules; namespace Lokad { /// <summary> /// Helper class allows to follow the principles defined by Microsoft P&amp;P team. /// </summary> public static class Enforce { // refactored methods go here. /// <summary> /// <para>Throws exception if the provided object is null. </para> /// <code>Enforce.Argument(() => args);</code> /// </summary> /// <typeparam name="TValue">type of the class to check</typeparam> /// <param name="argumentReference">The argument reference to check.</param> /// <exception cref="ArgumentNullException">If the class reference is null.</exception> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] public static void Argument<TValue>(Func<TValue> argumentReference) where TValue : class { if (null == argumentReference()) throw Errors.ArgumentNull(argumentReference); } /// <summary> /// <para>Throws exception if one of the provided objects is null. </para> /// <code>Enforce.Arguments(() =&gt; controller, () =&gt; service);</code> /// </summary> /// <param name="first">The first argument to check for</param> /// <param name="second">The second argument to check for.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] public static void Arguments<T1, T2>(Func<T1> first, Func<T2> second) where T1 : class where T2 : class { if (null == first()) throw Errors.ArgumentNull(first); if (null == second()) throw Errors.ArgumentNull(second); } /// <summary> /// <para>Throws exception if one of the provided objects is null. </para> /// <code>Enforce.Arguments(() =&gt; controller, () =&gt; service, () =&gt; parameters);</code> /// </summary> /// <typeparam name="T1">The type of the first argument.</typeparam> /// <typeparam name="T2">The type of the second argument.</typeparam> /// <typeparam name="T3">The type of the third argument.</typeparam> /// <param name="first">The first argument to check</param> /// <param name="second">The second argument to check.</param> /// <param name="third">The third argument to check.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] public static void Arguments<T1, T2, T3>(Func<T1> first, Func<T2> second, Func<T3> third) where T1 : class where T2 : class where T3 : class { if (null == first()) throw Errors.ArgumentNull(first); if (null == second()) throw Errors.ArgumentNull(second); if (null == third()) throw Errors.ArgumentNull(third); } /// <summary> /// <para>Throws exception if one of the provided objects is null. </para> /// <code>Enforce.Arguments(() =&gt; controller, () =&gt; service, () =&gt; parameters);</code> /// </summary> /// <typeparam name="T1">The type of the first argument.</typeparam> /// <typeparam name="T2">The type of the second argument.</typeparam> /// <typeparam name="T3">The type of the third argument.</typeparam> /// <typeparam name="T4">The type of the fourth argument.</typeparam> /// <param name="first">The first argument to check.</param> /// <param name="second">The second argument to check.</param> /// <param name="third">The third argument to check.</param> /// <param name="fourth">The fourth argument to check.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] public static void Arguments<T1, T2, T3, T4>(Func<T1> first, Func<T2> second, Func<T3> third, Func<T4> fourth) where T1 : class where T2 : class where T3 : class where T4 : class { if (null == first()) throw Errors.ArgumentNull(first); if (null == second()) throw Errors.ArgumentNull(second); if (null == third()) throw Errors.ArgumentNull(third); if (null == fourth()) throw Errors.ArgumentNull(fourth); } /// <summary> /// <para>Throws exception if one of the provided objects is null. </para> /// <code>Enforce.Arguments(() =&gt; controller, () =&gt; service, () =&gt; parameters);</code> /// </summary> /// <typeparam name="T1">The type of the first argument.</typeparam> /// <typeparam name="T2">The type of the second argument.</typeparam> /// <typeparam name="T3">The type of the third argument.</typeparam> /// <typeparam name="T4">The type of the fourth argument.</typeparam> /// <typeparam name="T5">The type of the fifth argument.</typeparam> /// <param name="first">The first argument to check.</param> /// <param name="second">The second argument to check.</param> /// <param name="third">The third argument to check.</param> /// <param name="fourth">The fourth argument to check.</param> /// <param name="fifth">The fifth argument to check.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] public static void Arguments<T1, T2, T3, T4, T5>(Func<T1> first, Func<T2> second, Func<T3> third, Func<T4> fourth, Func<T5> fifth) where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { if (null == first()) throw Errors.ArgumentNull(first); if (null == second()) throw Errors.ArgumentNull(second); if (null == third()) throw Errors.ArgumentNull(third); if (null == fourth()) throw Errors.ArgumentNull(fourth); if (null == fifth()) throw Errors.ArgumentNull(fifth); } /// <summary> /// Throws proper exception if the provided string argument is null or empty. /// </summary> /// <returns>Original string.</returns> /// <exception cref="ArgumentException">If the string argument is null or empty.</exception> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] [AssertionMethod] public static void ArgumentNotEmpty(Func<string> argumentReference) { var value = argumentReference(); if (null == value) throw Errors.ArgumentNull(argumentReference); if (0 == value.Length) throw Errors.Argument(argumentReference, "String can't be empty"); } /// <summary> /// Throws exception if the check does not pass. /// </summary> /// <param name="check">if set to <c>true</c> then check will pass.</param> /// <param name="name">The name of the assertion.</param> /// <exception cref="InvalidOperationException">If the assertion has failed.</exception> [DebuggerNonUserCode] [AssertionMethod] public static void That( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool check, [NotNull] string name) { if (!check) { throw new InvalidOperationException(string.Format("Failed assertion '{0}'", name)); } } /// <summary> /// Throws exception if the check does not pass. /// </summary> /// <param name="check">if set to <c>true</c> then check will pass.</param> /// <param name="message">The message.</param> /// <param name="arguments">The format arguments.</param> /// <exception cref="InvalidOperationException">If the assertion has failed.</exception> [DebuggerNonUserCode] [AssertionMethod] public static void That( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool check, [NotNull] string message, params object[] arguments) { if (!check) { throw new InvalidOperationException(string.Format(message, arguments)); } } /// <summary> /// Throws exception if the check does not pass. /// </summary> /// <exception cref="InvalidOperationException">If the assertion has failed.</exception> [DebuggerNonUserCode] [AssertionMethod] public static void That( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool check) { if (!check) { throw new InvalidOperationException(); } } /// <summary> /// Throws <typeparamref name="TException"/> if the <paramref name="check"/> /// failes /// </summary> /// <typeparam name="TException">The type of the exception.</typeparam> /// <param name="check">Check that should be true.</param> /// <param name="message">The message.</param> /// <param name="args">String arguments.</param> /// <exception cref="Exception">of <typeparamref name="TException"/> type</exception> [DebuggerNonUserCode] [AssertionMethod] [StringFormatMethod("message")] public static void With<TException>( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool check, [NotNull] string message, params object[] args) where TException : Exception { if (!check) { var msg = args.Length == 0 ? message : string.Format(CultureInfo.InvariantCulture, message, args); throw (TException) Activator.CreateInstance(typeof (TException), msg); } } /// <summary> Throws exception if the argument fails the <paramref name="check"/> </summary> /// <param name="check">Throw exception if false.</param> /// <param name="paramName">Name of the param.</param> /// <param name="checkName">Name of the check.</param> /// <exception cref="ArgumentException">When the argument fails the check</exception> [DebuggerNonUserCode] [AssertionMethod] public static void Argument( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool check, [InvokerParameterName] string paramName, [NotNull] string checkName) { if (!check) { throw new ArgumentException(string.Format("Argument '{0}' has failed check '{1}'.", paramName, checkName), paramName); } } /// <summary> /// Throws proper exception if the class reference is null. /// </summary> /// <typeparam name="TValue"></typeparam> /// <param name="value">Class reference to check.</param> /// <exception cref="InvalidOperationException">If class reference is null.</exception> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] [AssertionMethod] public static void NotNull<TValue>(Func<TValue> value) where TValue : class { if (value() == null) { throw new InvalidOperationException(string.Format("'{0}' can not be null.", Reflect.VariableName(value))); } } /// <summary> /// Throws proper exception if the class reference is null. /// </summary> /// <typeparam name="TValue"></typeparam> /// <param name="value">Class reference to check.</param> /// <exception cref="InvalidOperationException">If class reference is null.</exception> [DebuggerNonUserCode] [AssertionMethod] public static void NotNull<TValue>(TValue value) where TValue : class { if (value == null) { throw new InvalidOperationException(string.Format("Value of type '{0}' can not be null.", typeof(TValue).Name)); } } /// <summary> /// Throws proper exception if the class reference is null. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="value">Class reference to check.</param> /// <param name="name">The name.</param> /// <exception cref="InvalidOperationException">If class reference is null.</exception> [DebuggerNonUserCode] [AssertionMethod] public static void NotNull<TValue>(TValue value, [NotNull] string name) where TValue : class { if (name == null) throw new ArgumentNullException("name"); if (value == null) { var message = string.Format("Value '{1}' of type '{0}' can not be null.", typeof(TValue).Name, name); throw new InvalidOperationException(message); } } /// <summary> /// Throws proper exception if the provided class reference is null. /// Can be used for inline checks. /// </summary> /// <typeparam name="TValue">Class type</typeparam> /// <param name="value">Class reference to check.</param> /// <param name="argumentName">Name of the argument.</param> /// <returns>Original reference.</returns> /// <exception cref="ArgumentNullException">If the class reference is null.</exception> [DebuggerNonUserCode] [AssertionMethod] [Obsolete("Use Enforce.Argument() instead", true)] public static TValue ArgumentNotNull<TValue>( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] TValue value, [InvokerParameterName] string argumentName) where TValue : class { if (value == null) { throw new ArgumentNullException(argumentName); } return value; } /// <summary> /// Runs the rules against single argument, using scope that fails on <see cref="Scope.WhenError"/> /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="argumentReference">The argument reference.</param> /// <param name="rules">The rules.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> /// <exception cref="ArgumentException">When any rule fails</exception> [DebuggerNonUserCode] [AssertionMethod] public static void Argument<T>(Func<T> argumentReference, params Rule<T>[] rules) { using (var scope = ScopeFactory.ForEnforceArgument(argumentReference, Scope.WhenError)) { scope.ValidateInScope(argumentReference(), rules); } } /// <summary> /// Runs the rules against single collection, using scope that fails on <see cref="Scope.WhenError"/> /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="items">The items to validate.</param> /// <param name="rules">The rules.</param> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> /// <exception cref="ArgumentException">When any rule fails</exception> [DebuggerNonUserCode] public static void Argument<T>(Func<IEnumerable<T>> items, params Rule<T>[] rules) { using (var scope = ScopeFactory.ForEnforceArgument(items, Scope.WhenError)) { scope.ValidateInScope(items(), rules); } } /// <summary> Runs the rules against single argument, /// using scope that fails on <see cref="Scope.WhenError"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="item">The item to validate.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException">When check fails</exception> [DebuggerNonUserCode] [AssertionMethod] public static void That<T>( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] T item, params Rule<T>[] rules) { using (var scope = Scope.ForEnforce(typeof (T).Name, Scope.WhenError)) { scope.ValidateInScope(item, rules); } } /// <summary> Runs the rules against single collection, using /// scope that fails on <see cref="Scope.WhenError"/>.</summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="items">The items to validate.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException">When check fails</exception> [DebuggerNonUserCode] [AssertionMethod] public static void That<T>( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] IEnumerable<T> items, params Rule<T>[] rules) { using (var scope = Scope.ForEnforce(typeof (T).Name, Scope.WhenError)) { scope.ValidateInScope(items, rules); } } /// <summary> Runs the rules against single item, using /// scope that fails on <see cref="Scope.WhenError"/>.</summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="argumentReference">The item to validate.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException">When check fails</exception> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] [AssertionMethod] public static void That<T>( Func<T> argumentReference, params Rule<T>[] rules) { var name = Reflection.Reflect.VariableName(argumentReference); using (var scope = Scope.ForEnforce(name, Scope.WhenError)) { scope.ValidateInScope(argumentReference(), rules); } } /// <summary> Runs the rules against collection, /// using scope that fails on <see cref="Scope.WhenError"/> </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="collectionReference">The items to validate.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException">When check fails</exception> /// <remarks>Silverlight 2.0 does not support fast resolution of variable names, yet</remarks> [DebuggerNonUserCode] [AssertionMethod] public static void That<T>( Func<IEnumerable<T>> collectionReference, params Rule<T>[] rules) { var name = Reflection.Reflect.VariableName(collectionReference); using (var scope = Scope.ForEnforce(name, Scope.WhenError)) { scope.ValidateInScope(collectionReference(), rules); } } } }<file_sep>/Source/Lokad.Shared/Lambda.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class for creating lambda expressions that return /// anonymous types /// </summary> /// <typeparam name="T1">The type of the first argument.</typeparam> [NoCodeCoverage] public static class Lambda<T1> { /// <summary> /// Returns the provided function. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="func">The func.</param> /// <returns>returns the same function instance</returns> public static Func<T1, TResult> Func<TResult>(Func<T1, TResult> func) { return func; } } /// <summary> /// Helper class for creating lambda expressions that return /// anonymous types /// </summary> [NoCodeCoverage] public static class Lambda { /// <summary> /// Returns the provided function /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="func">The function.</param> /// <returns>returns same function instance</returns> public static Func<TResult> Func<TResult>(Func<TResult> func) { return func; } /// <summary> /// Returns the provided action /// </summary> /// <param name="action">The action.</param> /// <returns>returns same action instance</returns> public static Action<T1> Action<T1>(Action<T1> action) { return action; } } }<file_sep>/Source/Lokad.Shared/Utils/AssemblyUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; namespace Lokad { /// <summary> /// Helper class for the managing .NET assemblies /// </summary> public static class AssemblyUtil { /// <summary> /// Retrieves value of the <see cref="AssemblyConfigurationAttribute"/> for the current assembly /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">When the attribute is missing</exception> public static Result<string> GetAssemblyConfiguration() { var callingAssembly = Assembly.GetCallingAssembly(); return GetAssemblyConfiguration(callingAssembly); } // ReSharper disable SuggestBaseTypeForParameter internal static Result<string> GetAssemblyConfiguration(Assembly callingAssembly) // ReSharper restore SuggestBaseTypeForParameter { var attributes = callingAssembly .GetAttributes<AssemblyConfigurationAttribute>(true); if (attributes.Length == 0) return Result<string>.CreateError("Attribute is not present"); return Result.CreateSuccess(attributes[0].Configuration); } /// <summary> /// If <see cref="AssemblyDescriptionAttribute"/> is present in the calling assembly, /// then its value is retrieved. <see cref="string.Empty"/> is returned otherwise. /// </summary> /// <returns></returns> public static Result<string> GetAssemblyDescription() { var attributes = Assembly .GetCallingAssembly() .GetAttributes<AssemblyDescriptionAttribute>(true); if (attributes.Length == 0) return Result<string>.CreateError("Attribute was not found"); return Result.CreateSuccess(attributes[0].Description); } } }<file_sep>/Source/Lokad.Quality/CecilUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { static class CecilUtil<T> { internal static readonly string MonoName = CecilUtil.GetMonoName(typeof(T)); } static class CecilUtil { internal static string GetMonoName(Type type) { return (type.FullName).Replace('+', '/'); } } }<file_sep>/Test/Lokad.Shared.Test/Tuples/QuadTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class QuadTests { static readonly Tuple<DateTime, int, double, long> _t1 = new Tuple<DateTime, int, double, long>(DateTime.MinValue, 1, Math.PI, 1L); static readonly Tuple<DateTime, int, double, long> _t2 = Tuple.From(DateTime.MinValue, 1, Math.PI, 1L); static readonly Quad<DateTime, int, double, long> _t3 = Tuple.From(DateTime.MinValue, 1, Math.PI, 0L); [Test] public void Test_Equality() { Assert.AreEqual(_t1, _t2); Assert.AreNotEqual(_t1, _t3); } [Test] public void Test_Operators() { Assert.IsTrue(_t1 == _t2, "#1"); Assert.IsTrue(_t1 != _t3, "#2"); } [Test] public void Test_Hash() { var h1 = _t1.GetHashCode(); var h2 = _t2.GetHashCode(); var h3 = _t3.GetHashCode(); Assert.AreNotEqual(0, h1, "#1"); Assert.AreNotEqual(0, h3, "#2"); Assert.AreEqual(h1, h2, "#3"); Assert.AreNotEqual(h2, h3, "#4"); } } }<file_sep>/Source/Lokad.Shared/Currency/ExtendDecimal.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Extensions around /// <see cref="CurrencyAmount" /> /// </summary> public static class ExtendDecimal { /// <summary> /// Converts the specified deimal to a currency. /// </summary> /// <param name="value">The value.</param> /// <param name="currency">The currency.</param> /// <returns> /// new instance of the currency amount /// </returns> public static CurrencyAmount In(this decimal value, CurrencyType currency) { return new CurrencyAmount(currency, value); } /// <summary> /// Rounds the specified decimal with the provided number /// of fractional digits. /// </summary> /// <param name="value">The value to round.</param> /// <param name="digits">The digits.</param> /// <returns>rounded value</returns> /// <remarks>We can't use "Round" since it will collide with <see cref="decimal.Round(decimal,int)"/></remarks> public static Decimal RoundTo(this Decimal value, int digits) { return Math.Round(value, digits); } } }<file_sep>/Source/Lokad.Testing/Testing/Models/ITestModelEqualityProvider.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Testing { /// <summary> /// Provides model equality testers, given their type /// </summary> interface ITestModelEqualityProvider { TestModelEqualityDelegate GetEqualityTester(Type type); } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/RuleAssertTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class RuleAssertTests { // ReSharper disable InconsistentNaming [Test] public void UseCases() { RuleAssert.IsNone(1, Is.NotDefault); RuleAssert.IsError(1, Is.Default); RuleAssert.IsWarn(1, (i, scope) => scope.Warn("Warning")); } [Test, Expects.RuleException] public void UseCase_For_That() { var visitor = new Visitor { Programs = new[] { new Program { Name = "Some" }, new Program { Active = false }, } }; //Assert.IsTrue(visitor.Programs.Exists(p => p.Active), // "visitor should have at least one active program"); RuleAssert.That(() => visitor, v => v.Programs.Exists(p => p.Active), v => v.Programs.Length > 1); RuleAssert.That(visitor, v => v.Programs.Exists(p => p.Active), v => v.Programs.Length > 1); } [Test, Expects.RuleException] public void Expect() { RuleAssert.For<int>(Is.Default).ExpectNone(1); } } }<file_sep>/Test/Lokad.ActionPolicy.Test/HandlingProviderTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class HandlingProviderTests { readonly IProvider<int, int> _failing = Provider<int>.For<int>(i => { throw new UnauthorizedAccessException(); }); [Test, Expects.ResolutionException] public void Exception_Is_Wrapped_Properly() { HandlingProvider .For(_failing, ActionPolicy.Null) .Get(1); } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendDouble.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Some helper shortcuts for the <see cref="double"/> /// </summary> public static class ExtendDouble { /// <summary> /// Rounds the specified double with the provided number /// of fractional digits. /// </summary> /// <param name="value">The value to round.</param> /// <param name="digits">The digits.</param> /// <returns>rounded value</returns> public static double Round(this double value, int digits) { return Math.Round(value, digits); } /// <summary>Returns a <see cref="TimeSpan"/> that represents a specified number of minutes.</summary> /// <param name="minutes">number of minutes</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> /// <example>3D.Minutes()</example> public static TimeSpan Minutes(this double minutes) { return TimeSpan.FromMinutes(minutes); } /// <summary>Returns a <see cref="TimeSpan"/> that represents a specified number of hours.</summary> /// <param name="hours">number of hours</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> /// <example>3D.Hours()</example> public static TimeSpan Hours(this double hours) { return TimeSpan.FromHours(hours); } /// <summary>Returns a <see cref="TimeSpan"/> that represents a specified number of seconds.</summary> /// <param name="seconds">number of seconds</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> /// <example>2D.Seconds()</example> public static TimeSpan Seconds(this double seconds) { return TimeSpan.FromSeconds(seconds); } /// <summary>Returns a <see cref="TimeSpan"/> that represents a specified number of milliseconds.</summary> /// <param name="milliseconds">milliseconds for this timespan</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> public static TimeSpan Milliseconds(this double milliseconds) { return TimeSpan.FromMilliseconds(milliseconds); } /// <summary> /// Returns a <see cref="TimeSpan"/> that represents a specified number of days. /// </summary> /// <param name="days">Number of days, accurate to the milliseconds.</param> /// <returns>A <see cref="TimeSpan"/> that represents a value.</returns> public static TimeSpan Days(this double days) { return TimeSpan.FromDays(days); } } }<file_sep>/Test/Lokad.Shared.Test/Expects.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad.Testing { /// <summary> /// <para>Helper class that simplifies definition of NUnit exception expectations.</para> /// <para>Usage:</para> /// <code>[Expects.ArgumentNullException]</code> /// </summary> public static class Expects { #pragma warning disable 1591 public sealed class ArgumentNullException : ExpectedExceptionAttribute { public ArgumentNullException() : base(typeof (System.ArgumentNullException)) { } } public sealed class InvalidOperationException : ExpectedExceptionAttribute { public InvalidOperationException() : base(typeof (System.InvalidOperationException)) { } } public sealed class TimeoutException : ExpectedExceptionAttribute { public TimeoutException() : base(typeof (System.TimeoutException)) { } } public sealed class ArgumentException : ExpectedExceptionAttribute { public ArgumentException() : base(typeof (System.ArgumentException)) { } } public sealed class RuleException : ExpectedExceptionAttribute { public RuleException() : base(typeof (Rules.RuleException)) { } } public sealed class ResolutionException : ExpectedExceptionAttribute { public ResolutionException() : base(typeof (Lokad.ResolutionException)) { } } public sealed class ArgumentOutOfRangeException : ExpectedExceptionAttribute { public ArgumentOutOfRangeException() : base(typeof (System.ArgumentOutOfRangeException)) { } } } }<file_sep>/Source/Lokad.Logging/ILogExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; namespace Lokad { /// <summary> /// Helper extensions for any class that implements <see cref="ILog"/> /// </summary> public static class ILogExtensions { static readonly CultureInfo _culture = CultureInfo.InvariantCulture; /// <summary> /// Determines whether the specified log is recording debug messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording debug messages; otherwise, <c>false</c>. /// </returns> public static bool IsDebugEnabled(this ILog log) { return log.IsEnabled(LogLevel.Debug); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Debug(this ILog log, object message) { log.Log(LogLevel.Debug, message); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void DebugFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Debug, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Debug(this ILog log, Exception ex, object message) { log.Log(LogLevel.Debug, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void DebugFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Debug, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording info messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording info messages; otherwise, <c>false</c>. /// </returns> public static bool IsInfoEnabled(this ILog log) { return log.IsEnabled(LogLevel.Info); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Info(this ILog log, object message) { log.Log(LogLevel.Info, message); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void InfoFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Info, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Info(this ILog log, Exception ex, object message) { log.Log(LogLevel.Info, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void InfoFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Info, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording warning messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording warning messages; otherwise, <c>false</c>. /// </returns> public static bool IsWarnEnabled(this ILog log) { return log.IsEnabled(LogLevel.Warn); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Warn(this ILog log, object message) { log.Log(LogLevel.Warn, message); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void WarnFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Warn, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Warn(this ILog log, Exception ex, object message) { log.Log(LogLevel.Warn, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void WarnFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Warn, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording error messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording error messages; otherwise, <c>false</c>. /// </returns> public static bool IsErrorEnabled(this ILog log) { return log.IsEnabled(LogLevel.Error); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Error(this ILog log, object message) { log.Log(LogLevel.Error, message); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void ErrorFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Error, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Error(this ILog log, Exception ex, object message) { log.Log(LogLevel.Error, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void ErrorFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Error, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording Fatal messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording datal messages; otherwise, <c>false</c>. /// </returns> public static bool IsFatalEnabled(this ILog log) { return log.IsEnabled(LogLevel.Fatal); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Fatal(this ILog log, object message) { log.Log(LogLevel.Fatal, message); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void FatalFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Fatal, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Fatal(this ILog log, Exception ex, object message) { log.Log(LogLevel.Fatal, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void FatalFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Fatal, ex, string.Format(_culture, format, args)); } } }<file_sep>/Test/Lokad.Testing.Test/ExtendOptionalTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Testing.Test { [TestFixture] public sealed class ExtendOptionalTests { static readonly IEquatable<string> Text = "Text"; // ReSharper disable InconsistentNaming static readonly Result<string, int> ResultGood = "Good"; static readonly Result<string, int> Result11 = 11; static readonly Result<int> Result10 = 10; static readonly Result<int> ResultError = "Error"; static readonly Maybe<int> Maybe10 = 10; static readonly Maybe<int> MaybeNot = Maybe<int>.Empty; [Test] public void Use_cases_1() { ResultGood .ShouldPass() .ShouldPassCheck(i => i == "Good") .ShouldPassWith("Good") .ShouldBe("Good"); Result11 .ShouldFailWith(11) .ShouldFail() .ShouldBe(11); Result10 .ShouldPass() .ShouldPassWith(10) .ShouldPassCheck(i => i == 10) .ShouldBe(10); ResultError .ShouldFail() .ShouldFailWith("Error") .ShouldBe("Error"); Maybe10 .ShouldPass() .ShouldPassCheck(i => i == 10) .ShouldPassWith(10) .ShouldBe(10) .ShouldBe(true); MaybeNot .ShouldFail() .ShouldBe(false); } [Test] public void Test() { Text .ShouldBeEqualTo("Text").ShouldBeEqualTo("Text"); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/BufferIsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Security.Cryptography; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class BufferIsTests { // ReSharper disable InconsistentNaming [Test] public void Check_hash_roundtrips() { var buffer = new byte[Rand.Next(2, 64)]; var prov = new RNGCryptoServiceProvider(); prov.GetBytes(buffer); var hash = BufferUtil.CalculateSimpleHashCode(buffer); Enforce.That(() => buffer, BufferIs.WithValidHash(hash)); unchecked { buffer[Rand.Next(buffer.Length)] += 1; } Assert.IsFalse(Scope.IsValid(buffer, BufferIs.WithValidHash(hash))); } [Test] public void Limited() { RuleAssert.For(BufferIs.Limited(10)) .ExpectNone(new byte[10], new byte[9]) .ExpectError(null, new byte[11], new byte[12]); } } }<file_sep>/Source/Lokad.Quality/Codebase.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Base class that serves as validation target for the Lokad /// quality rules /// </summary> [Immutable] public sealed class Codebase : IProvider<TypeReference, TypeDefinition> { /// <summary> /// Methods declared in the assemblies being checked /// </summary> /// <value>The collection of methods.</value> public MethodDefinition[] Methods { get { return _methods; } } /// <summary> /// Types declared in the assemblies being checked /// </summary> /// <value>The collection of types.</value> public TypeDefinition[] Types { get { return _types; } } /// <summary> /// Gets the assemblies being checked. /// </summary> /// <value>The assemblies.</value> public AssemblyDefinition[] Assemblies { get { return _assemblies.Convert(a => a.Value); } } readonly TypeDefinition[] _types; readonly MethodDefinition[] _methods; readonly IDictionary<string, TypeDefinition> _typeDictionary; readonly AssemblyDefinition[] _references; readonly Pair<string, AssemblyDefinition>[] _assemblies; /// <summary> /// Saves the entire codebase to the specified folder. /// </summary> /// <param name="path">The path.</param> public void SaveTo(string path) { foreach (var def in _assemblies) { var fileName = Path.GetFileName(def.Key); var fullName = Path.Combine(path, fileName); AssemblyFactory.SaveAssembly(def.Value, fullName); } } /// <summary> /// Initializes a new instance of the <see cref="Codebase"/> class. /// </summary> /// <param name="assembliesToAnalyze">The assemblies to load.</param> public Codebase(params string[] assembliesToAnalyze) { _assemblies = assembliesToAnalyze .Convert(n => Tuple.From(Path.GetFileName(n), AssemblyFactory.GetAssembly(n))); var defs = _assemblies.Convert(p => p.Value); _types = defs .SelectMany(m => m.GetTypes()) .ToArray(); _methods = _types .SelectMany(t => t.GetMethods()) .ToArray(); _references = defs .SelectMany(m => m .GetAssemblyReferences() .Select(nr => m.Resolver.Resolve(nr))) .ToArray(); var referencedTypes = _references .SelectMany(r => r.GetAllTypes()) .Where(t => t.IsPublic) .ToArray(); _typeDictionary = new Dictionary<string, TypeDefinition>(); _types .Append(referencedTypes) .ForEach(t => _typeDictionary[t.FullName] = t); } /// <summary> /// Gets all the external type references in the codebase. /// </summary> /// <returns>lazy enumerator over the results.</returns> public IEnumerable<TypeReference> GetAllTypeReferences() { return _assemblies.SelectMany(a => a.Value.GetTypeReferences()); } TypeDefinition IProvider<TypeReference, TypeDefinition>.Get(TypeReference key) { if (key is GenericInstanceType) { key = (key as GenericInstanceType).ElementType; } var name = key.FullName; TypeDefinition definition; if (!_typeDictionary.TryGetValue(name, out definition)) { throw new KeyInvalidException(string.Format(CultureInfo.InvariantCulture, "Key has invalid value '{0}'", (object) key)); } return definition; } /// <summary> /// Gets the type based on the .NET type. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public TypeDefinition Find<T>() { return _typeDictionary[CecilUtil<T>.MonoName]; } /// <summary> /// Looks up the type based on the .NET type. /// </summary> /// <param name="type">The type.</param> /// <returns>matching type definition</returns> public Maybe<TypeDefinition> Find(Type type) { return _typeDictionary.GetValue(CecilUtil.GetMonoName(type)); } /// <summary> /// Finds the specified reference. /// </summary> /// <param name="reference">The reference.</param> /// <returns>matching type definition</returns> public Maybe<TypeDefinition> Find(TypeReference reference) { return _typeDictionary.GetValue(reference.FullName); } } }<file_sep>/Source/Lokad.Shared/Settings/ExtendISettingsProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Quality; namespace Lokad.Settings { /// <summary> /// Adds extensions for the simplicity of settings use. /// </summary> public static class ExtendISettingsProvider { /// <summary> /// Converts given dictionary to the settings provider. /// </summary> /// <param name="dict">The dict.</param> /// <returns> /// new instance of the settings provider /// </returns> public static ISettingsProvider AsSettingsProvider([NotNull] this IDictionary<string, string> dict) { if (dict == null) throw new ArgumentNullException("dict"); return new DictionarySettingsProvider(dict); } /// <summary> /// Creates new settings provider, using the /// <see cref="PrefixTruncatingKeyFilter" /> /// for the path filtering logic /// </summary> /// <param name="settingsProvider"> /// The settings provider. /// </param> /// <param name="prefix"> /// The prefix to look for and then truncate. /// </param> /// <returns> /// new instance of the settings provider, created by filtering and applying transformations /// </returns> public static ISettingsProvider FilteredByPrefix([NotNull] this ISettingsProvider settingsProvider, [NotNull] string prefix) { Enforce.Argument(() => settingsProvider); Enforce.ArgumentNotEmpty(() => prefix); return settingsProvider.Filtered(new PrefixTruncatingKeyFilter(prefix)); } } }<file_sep>/Source/Lokad.Shared/Rules/Common/DateIs.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> Rules for the <see cref="DateTime"/> </summary> public static class DateIs { static readonly DateTime SqlMinDateTime = new DateTime(1753, 1, 1); /// <summary> /// Verifies that it is ok to send this date directly into the MS SQL DB /// </summary> /// <param name="dateTime">The dateTime to validate.</param> /// <param name="scope">validation scope</param> public static void SqlCompatible(DateTime dateTime, IScope scope) { if (dateTime < SqlMinDateTime) scope.Error("Date must be greater than \'{0}\'.", SqlMinDateTime); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/ModifierScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class ModifierScopeTests { static readonly RuleLevel[] _levels = EnumUtil<RuleLevel>.Values; [Test] public void Test_Lower_Modifier() { var levels = new List<RuleLevel>(); var scope = new SimpleScope("T", (path, level, message) => levels.Add(level)).Lower(); _levels.ForEach(l => scope.Write(l, "test")); Assert.AreEqual(RuleLevel.Warn, scope.Level); Assert.AreEqual(levels.Count, 2); CollectionAssert.DoesNotContain(levels, RuleLevel.Error); } [Test] public void Test_Raise_Modifier() { var levels = new List<RuleLevel>(); var scope = new SimpleScope("T", (path, level, message) => levels.Add(level)).Raise(); _levels.ForEach(l => scope.Write(l, "test")); Assert.AreEqual(RuleLevel.Error, scope.Level); Assert.AreEqual(_levels.Length, levels.Count); CollectionAssert.DoesNotContain(levels, RuleLevel.None); } } }<file_sep>/Source/Lokad.Shared/Rules/Common/MaybeIs.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Rules { /// <summary> /// Common rules for handling Maybe{T} values. /// </summary> public static class MaybeIs { /// <summary> /// Generates rule that is valid if the provided optional /// is either empty or passes the supplied value rules /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="valueRules">The value rules.</param> /// <returns>new validation rule</returns> public static Rule<Maybe<TValue>> EmptyOr<TValue>(params Rule<TValue>[] valueRules) { return (maybe, scope) => maybe.Apply(v => scope.ValidateInScope(v, valueRules)); } /// <summary> /// Generates the rule that ensures the provided optional to be /// valid and passing the provided rules /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="valueRules">The value rules.</param> /// <returns>new validation rules</returns> public static Rule<Maybe<TValue>> ValidAnd<TValue>(params Rule<TValue>[] valueRules) { return (maybe, scope) => maybe .Handle(() => scope.Error("Optional \'{0}\' should not be empty.", typeof (Maybe<TValue>).Name)) .Apply(value => scope.ValidateInScope(value, valueRules)); } } }<file_sep>/Source/Lokad.Shared/Rand.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class that allows to implement non-deterministic /// reproducible testing. /// </summary> /// <remarks> /// Keep in mind, that this implementation is not thread-safe. /// </remarks> public static partial class Rand { static Func<int, int> NextInt; static Func<Func<int, int>> Activator; /// <summary> /// Resets everything to the default, using <see cref="Random"/> generator and random seed. /// </summary> public static void ResetToDefault() { ResetToDefault(new Random().Next()); } /// <summary> /// Resets everything to the default, using <see cref="Random"/> generator and the specified /// rand seed. /// </summary> /// <param name="randSeed">The rand seed.</param> [UsedImplicitly] public static void ResetToDefault(int randSeed) { Activator = () => { var r = new Random(randSeed); return i => r.Next(i); }; NextInt = Activator(); } static Rand() { ResetToDefault(); } /// <summary> /// Resets the random generator, using the provided activator /// </summary> [UsedImplicitly] public static void Reset() { NextInt = Activator(); } /// <summary> /// Overrides with the current activator /// </summary> /// <param name="activator">The activator.</param> public static void Reset(Func<Func<int, int>> activator) { Activator = activator; NextInt = Activator(); } /// <summary> /// Generates random value between 0 and <see cref="int.MaxValue"/> (exclusive) /// </summary> /// <returns>random integer</returns> public static int Next() { return NextInt(int.MaxValue); } /// <summary> /// Generates random value between 0 and <paramref name="upperBound"/> (exclusive) /// </summary> /// <param name="upperBound">The upper bound.</param> /// <returns>random integer</returns> public static int Next(int upperBound) { return NextInt(upperBound); } /// <summary> /// Generates random value between <paramref name="lowerBound"/> /// and <paramref name="upperBound"/> (exclusive) /// </summary> /// <param name="lowerBound">The lower bound.</param> /// <param name="upperBound">The upper bound.</param> /// <returns>random integer</returns> public static int Next(int lowerBound, int upperBound) { var range = upperBound - lowerBound; return NextInt(range) + lowerBound; } /// <summary> Picks random item from the provided array </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="items">The items.</param> /// <returns>random item from the array</returns> public static TItem NextItem<TItem>(TItem[] items) { var index = NextInt(items.Length); return items[index]; } /// <summary> Picks random <see cref="Enum"/> </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <returns>random Enum value</returns> public static TEnum NextEnum<TEnum>() where TEnum : struct, IComparable { return NextItem(EnumUtil<TEnum>.Values); } /// <summary> Picks random <see cref="Enum"/> where the item is not equal to /// default(TEnum)</summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <returns>random Enum value</returns> public static TEnum NextEnumExceptDefault<TEnum>() where TEnum : struct, IComparable { return NextItem(EnumUtil<TEnum>.ValuesWithoutDefault); } /// <summary> /// Returns <em>true</em> with the specified probability. /// </summary> /// <param name="probability">The probability (between 0 and 1).</param> /// <returns><em>true</em> with the specified probability</returns> public static bool NextBool(double probability) { return NextDouble() < probability; } /// <summary> /// Returns either <em>true</em> or <em>false</em> /// </summary> /// <returns>either <em>true</em> or <em>false</em></returns> public static bool NextBool() { return NextBool(0.5D); } /// <summary> /// Creates random optional that might have the value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="value">The value.</param> /// <returns>optional that might have the value</returns> public static Maybe<TValue> NextMaybe<TValue>(TValue value) { return NextBool() ? Maybe<TValue>.Empty : value; } /// <summary> Picks random <see cref="Guid"/> </summary> /// <returns>random value</returns> public static Guid NextGuid() { return new Guid(Range.Array(16, i => (byte) Next(byte.MaxValue + 1))); } /// <summary> /// Creates an array of random <see cref="Guid"/> /// </summary> /// <param name="count">Number of items in the array.</param> /// <returns>random value</returns> public static Guid[] NextGuids(int count) { return Range.Array(count, x => NextGuid()); } /// <summary> /// Creates an array of random <see cref="Guid"/> and random length. /// </summary> /// <param name="lowerBound">The lower bound.</param> /// <param name="upperBound">The upper bound.</param> /// <returns></returns> public static Guid[] NextGuids(int lowerBound, int upperBound) { int count = Rand.Next(lowerBound, upperBound); return Range.Array(count, x => NextGuid()); } /// <summary> Returns random double value with lowered precision </summary> /// <returns>random double value</returns> public static double NextDouble() { return (double) NextInt(int.MaxValue)/int.MaxValue; } static readonly DateTime MinDate = new DateTime(1700, 1, 1); /// <summary> /// Returns a random date between 1700-01-01 and 2100-01-01 /// </summary> /// <returns>random value</returns> public static DateTime NextDate() { return MinDate .AddYears(Next(500)) .AddDays(NextDouble()*24D*365.25D); } /// <summary> /// Returns a random date between the specified range. /// </summary> /// <param name="minYear">The min year.</param> /// <param name="maxYear">The max year.</param> /// <returns>new random date</returns> public static DateTime NextDate(int minYear, int maxYear) { var days = NextDouble()*356*(maxYear - minYear); return new DateTime(minYear, 1, 1).AddDays(days); } static readonly char[] Symbols = "!\"#%&'()*,-./:;?@[\\]_{} ".ToCharArray(); /// <summary> /// Generates random string with the length between /// <paramref name="lowerBound"/> and <paramref name="upperBound"/> (exclusive) /// </summary> /// <param name="lowerBound">The lower bound for the string length.</param> /// <param name="upperBound">The upper bound for the string length.</param> /// <returns>new random string</returns> public static string NextString(int lowerBound, int upperBound) { //const int surrogateStartsAt = 55296; int count = Next(lowerBound, upperBound); var array = Range.Array(count, i => Next(5) == 1 ? NextItem(Symbols) : (char) Next(48, 122)); return new string(array); } /// <summary> /// Gets a random subset from the array /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="items">The items.</param> /// <param name="count">The count.</param> /// <returns>array that contains <paramref name="count"/> items from the original array</returns> /// <exception cref="ArgumentOutOfRangeException">when <paramref name="count"/> /// is bigger than the length of <paramref name="items"/></exception> public static TValue[] NextItems<TValue>(TValue[] items, int count) { if (items == null) throw new ArgumentNullException("items"); if (count > items.Length) throw new ArgumentOutOfRangeException(); if (count == 0) return ArrayUtil<TValue>.Empty; var indexes = Range.Array(items.Length).ToList(); var result = new TValue[count]; for (int i = 0; i < count; i++) { var next = Next(indexes.Count); var index = indexes[next]; indexes.RemoveAt(next); result[i] = items[index]; } return result; } } }<file_sep>/Source/Lokad.Serialization/Serialization/AttributeHelper.cs using System; using System.Linq; namespace Lokad.Serialization { sealed class AttributeHelper { readonly object[] _attributes; public AttributeHelper(object[] attributes) { _attributes = attributes; } public Maybe<string> GetString<TAttribute>(Func<TAttribute, string> retriever) where TAttribute : Attribute { var v = _attributes .OfType<TAttribute>() .FirstOrEmpty() .Convert(retriever, ""); if (string.IsNullOrEmpty(v)) return Maybe<string>.Empty; return v; } } }<file_sep>/Source/Lokad.Shared/Monads/MaybeParse.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; namespace Lokad { /// <summary> /// Helper routines for converting strings into Maybe /// </summary> public static class MaybeParse { /// <summary> /// Tries to parse the specified string into the enum, returning empty result /// on failure. We ignore case in this scenario. /// </summary> /// <typeparam name="TEnum"> /// The type of the enum. /// </typeparam> /// <param name="value">The value.</param> /// <returns> /// either enum or an empty result /// </returns> public static Maybe<TEnum> Enum<TEnum>(string value) where TEnum : struct, IComparable { return Enum<TEnum>(value, true); } /// <summary> /// Tries to parse the specified string into the enum, returning empty result /// on failure /// </summary> /// <typeparam name="TEnum"> /// The type of the enum. /// </typeparam> /// <param name="value">The value.</param> /// <param name="ignoreCase"> /// if set to /// <c>true</c> /// then parsing will ignore case. /// </param> /// <returns> /// either enum or an empty result /// </returns> public static Maybe<TEnum> Enum<TEnum>(string value, bool ignoreCase) where TEnum : struct, IComparable { if (string.IsNullOrEmpty(value)) return Maybe<TEnum>.Empty; try { return EnumUtil.Parse<TEnum>(value, ignoreCase); } catch (Exception) { return Maybe<TEnum>.Empty; } } /// <summary> /// Tries to parse the specified value into Decimal, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Decimal or an empty result /// </returns> /// <seealso cref="decimal.TryParse(string,out decimal)" /> public static Maybe<decimal> Decimal(string value) { decimal result; if (!decimal.TryParse(value, out result)) return Maybe<decimal>.Empty; return result; } /// <summary> /// Tries to parse the specified value into decimal, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <param name="numberStyles"> /// The number styles to use. /// </param> /// <param name="formatProvider"> /// The format provider to use. /// </param> /// <returns> /// either parsed decimal or an empty result /// </returns> /// <seealso cref="decimal.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out decimal)" /> public static Maybe<decimal> Decimal(string value, NumberStyles numberStyles, IFormatProvider formatProvider) { decimal result; if (!decimal.TryParse(value, numberStyles, formatProvider, out result)) return Maybe<decimal>.Empty; return result; } /// <summary> /// Tries to parse the specified value into decimal, using the invariant culture /// info and returning empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed decimal or an empty result /// </returns> public static Maybe<decimal> DecimalInvariant(string value) { return Decimal(value, NumberStyles.Number, CultureInfo.InvariantCulture); } /// <summary> /// Tries to parse the specified value into Int32, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Int32 or an empty result /// </returns> /// <seealso cref="System.Int32.TryParse(string,out int)" /> public static Maybe<Int32> Int32(string value) { Int32 result; if (!System.Int32.TryParse(value, out result)) return Maybe<Int32>.Empty; return result; } /// <summary> /// Tries to parse the specified value into Int32, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <param name="numberStyles"> /// The number styles to use. /// </param> /// <param name="formatProvider"> /// The format provider to use. /// </param> /// <returns> /// either parsed Int32 or an empty result /// </returns> /// <seealso cref="System.Int32.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out int)" /> public static Maybe<Int32> Int32(string value, NumberStyles numberStyles, IFormatProvider formatProvider) { Int32 result; if (!System.Int32.TryParse(value, numberStyles, formatProvider, out result)) return Maybe<Int32>.Empty; return result; } /// <summary> /// Tries to parse the specified string value into Int32, /// using an invariant culture and returning empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Int32 or an empty result /// </returns> /// <seealso cref="System.Int32.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out int)" /> public static Maybe<Int32> Int32Invariant(string value) { return Int32(value, NumberStyles.Integer, CultureInfo.InvariantCulture); } /// <summary> /// Tries to parse the specified value into Int64, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Int64 or an empty result /// </returns> /// <seealso cref="System.Int64.TryParse(string,out long)" /> public static Maybe<Int64> Int64(string value) { Int64 result; if (!System.Int64.TryParse(value, out result)) return Maybe<Int64>.Empty; return result; } /// <summary> /// Tries to parse the specified value into Int64, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <param name="numberStyles"> /// The number styles to use. /// </param> /// <param name="formatProvider"> /// The format provider to use. /// </param> /// <returns> /// either parsed Int64 or an empty result /// </returns> /// <seealso cref="System.Int64.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out long)" /> public static Maybe<Int64> Int64(string value, NumberStyles numberStyles, IFormatProvider formatProvider) { Int64 result; if (!System.Int64.TryParse(value, numberStyles, formatProvider, out result)) return Maybe<Int64>.Empty; return result; } /// <summary> /// Tries to parse the specified string value into Int64, /// using an invariant culture and returning empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Int64 or an empty result /// </returns> /// <seealso cref="System.Int64.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out long)" /> public static Maybe<Int64> Int64Invariant(string value) { return Int64(value, NumberStyles.Integer, CultureInfo.InvariantCulture); } /// <summary> /// Tries to parse the specified value into Double, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Double or an empty result /// </returns> /// <seealso cref="System.Double.TryParse(string,out double)" /> public static Maybe<Double> Double(string value) { Double result; if (!System.Double.TryParse(value, out result)) return Maybe<Double>.Empty; return result; } /// <summary> /// Tries to parse the specified value into Double, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <param name="numberStyles"> /// The number styles to use. /// </param> /// <param name="formatProvider"> /// The format provider to use. /// </param> /// <returns> /// either parsed Double or an empty result /// </returns> /// <seealso cref="System.Double.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out double)" /> public static Maybe<Double> Double(string value, NumberStyles numberStyles, IFormatProvider formatProvider) { Double result; if (!System.Double.TryParse(value, numberStyles, formatProvider, out result)) return Maybe<Double>.Empty; return result; } /// <summary> /// Attempts to parse the specified value into Double, /// using invariant culture and returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Double or an empty result /// </returns> /// <seealso cref="System.Double.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out double)" /> public static Maybe<Double> DoubleInvariant(string value) { return Double(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture); } /// <summary> /// Tries to parse the specified value into Single, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Single or an empty result /// </returns> /// <seealso cref="System.Single.TryParse(string,out float)" /> public static Maybe<Single> Single(string value) { Single result; if (!System.Single.TryParse(value, out result)) return Maybe<Single>.Empty; return result; } /// <summary> /// Tries to parse the specified value into Single, returning /// empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <param name="numberStyles"> /// The number styles to use. /// </param> /// <param name="formatProvider"> /// The format provider to use. /// </param> /// <returns> /// either parsed Single or an empty result /// </returns> /// <seealso cref="System.Single.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out float)" /> public static Maybe<Single> Single(string value, NumberStyles numberStyles, IFormatProvider formatProvider) { Single result; if (!System.Single.TryParse(value, numberStyles, formatProvider, out result)) return Maybe<Single>.Empty; return result; } /// <summary> /// Tries to parse the specified value into Single, using invariant culture /// and returning empty result on failure. /// </summary> /// <param name="value">The value.</param> /// <returns> /// either parsed Single or an empty result /// </returns> /// <seealso cref="System.Single.TryParse(string,System.Globalization.NumberStyles,System.IFormatProvider,out float)" /> public static Maybe<Single> SingleInvariant(string value) { return Single(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture); } } }<file_sep>/Test/Lokad.Quality.Test/RuleUseCases.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Mono.Cecil; using Mono.Cecil.Cil; using NUnit.Framework; namespace Lokad.Quality.Test { public sealed class ElementAttribute : Attribute { } [Element] public static class Fire { public static void Extend(this object self) { throw new NotImplementedException(); } } class ExceptionClass { public void Run() { InnerCall(); throw new NotSupportedException(); } void InnerCall() { throw new NotImplementedException(); } } [TestFixture] public class RuleUseCases { // ReSharper disable InconsistentNaming [Test] public void Count_Methods_With_Exceptions() { var codebase = GlobalSetup.Codebase; var throwingMethods = codebase.Methods .Where(m => m .GetInstructions() .Exists(i => i.Creates<NotImplementedException>())) .ToArray(); Assert.AreEqual(2, throwingMethods.Length); } [Test] public void Get_created_exceptions() { var type = GlobalSetup.Codebase.Find<ExceptionClass>(); var method = type.GetMethods().First(md => md.Name == "Run"); var exceptions = GetCreatedExceptions(method) .ToArray(); Assert.AreEqual(1, exceptions.Length); Assert.AreEqual("NotSupportedException", exceptions[0].Name); } static IEnumerable<TypeReference> GetCreatedExceptions(MethodDefinition method) { return method.GetInstructions() .Where(i => i.OpCode == OpCodes.Newobj) .Select(i => ((MemberReference) i.Operand).DeclaringType) .Where(tr => tr.Name.EndsWith("Exception")) .Distinct(); } [Test] public void Count_Methods_That_Extend_Object() { var codebase = GlobalSetup.Codebase; var methods = codebase.Methods .Where(m => m.Has<ExtensionAttribute>()) .Where(m => m.Parameters[0].Is<object>()); Assert.AreEqual(1, methods.Count()); //CollectionAssert.IsEmpty(methods.ToArray()); } } }<file_sep>/Test/Lokad.ActionPolicy.Test/ActionPolicyTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ActionPolicyTests { // ReSharper disable InconsistentNaming #region Setup/Teardown [TearDown] public void TearDown() { SystemUtil.Reset(); } #endregion static void Expect<T>(Action action) where T : Exception { try { action(); Assert.Fail("Exception expected"); } catch (T) { } } static void RaiseTimeout() { throw new TimeoutException(); } static void RaiseArgument() { throw new ArgumentException(); } static void Nothing() { } [Test] public void WaitAndRetry() { TimeSpan slept = TimeSpan.Zero; SystemUtil.SetSleep(span => slept += span); var policy = ActionPolicy .Handle<TimeoutException>() .WaitAndRetry(Range.Create(5, i => i.Seconds())); Expect<ArgumentException>(() => policy.Do(RaiseArgument)); Assert.AreEqual(TimeSpan.Zero, slept); Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); Assert.AreEqual(10.Seconds(), slept); } [Test] public void WaitAndRetry_WithAction() { TimeSpan slept = TimeSpan.Zero; SystemUtil.SetSleep(span => slept += span); int count = 0; var policy = ActionPolicy .Handle<TimeoutException>() .WaitAndRetry(Range.Create(5, i => i.Seconds()), (ex, s) => count += 1); // non-handled Expect<ArgumentException>(() => policy.Do(RaiseArgument)); Assert.AreEqual(TimeSpan.Zero, slept); Assert.AreEqual(0, count); // handled succeeds Raise<TimeoutException>(5, policy); Assert.AreEqual(10.Seconds(), slept); Assert.AreEqual(5, count); // handled fails Expect<TimeoutException>(6, policy); Assert.AreEqual(20.Seconds(), slept); Assert.AreEqual(10, count); } [Test] public void Retry() { var policy = ActionPolicy .Handle<TimeoutException>() .Retry(2); // non-handled exception Expect<ArgumentException>(() => policy.Do(RaiseArgument)); // handled succeeds Raise<TimeoutException>(2, policy); // handled fails Expect<TimeoutException>(3, policy); } [Test] public void From_is_similar_to_With() { var policy = ActionPolicy .From(e => true) .Retry(2); // handled succeeds Raise<TimeoutException>(2, policy); // handled fails Expect<TimeoutException>(3, policy); } [Test] public void Retry_Once() { var policy = ActionPolicy.Handle<TimeoutException>().Retry(0); // non-handled exception Expect<ArgumentException>(() => policy.Do(RaiseArgument)); Raise<TimeoutException>(0, policy); Expect<TimeoutException>(1, policy); } [Test] public void Retry_With_Action() { int counter = 0; var policy = ActionPolicy .Handle<TimeoutException>() .Retry(2, (ex, i) => counter += 1); // non-handled exception Expect<ArgumentException>(() => policy.Do(RaiseArgument)); Assert.AreEqual(0, counter); // handled succeeds Raise<TimeoutException>(2, policy); Assert.AreEqual(2, counter); // handled fails Expect<TimeoutException>(3, policy); Assert.AreEqual(4, counter); } [Test] public void RetryForever() { int counter = 0; var policy = ActionPolicy .Handle<TimeoutException>() .RetryForever(ex => counter += 1); // non-handled exception Expect<ArgumentException>(() => policy.Do(RaiseArgument)); Assert.AreEqual(0, counter); // handled succeeds Raise<TimeoutException>(11, policy); Assert.AreEqual(11, counter); } #if !SILVERLIGHT2 [Test] public void CircuitBreaker() { var policy = ActionPolicy .Handle<TimeoutException>() .CircuitBreaker(1.Minutes(), 2); var time = new DateTime(2008, 1, 1); SystemUtil.SetTime(time); // non-handled policy.Do(Nothing); Expect<ArgumentException>(() => policy.Do(RaiseArgument)); // handled below // Raise Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); // Trigger Expect<TimeoutException>(() => policy.Do(RaiseArgument)); Expect<TimeoutException>(() => policy.Do(Nothing)); // Elapse and pass SystemUtil.SetTime(time.AddMinutes(1)); policy.Do(Nothing); // Raise Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); // Elapse and rearm SystemUtil.SetTime(time.AddMinutes(1)); Expect<TimeoutException>(() => policy.Do(RaiseTimeout)); // Non-elapse and trigger SystemUtil.SetTime(time.AddSeconds(119)); Expect<TimeoutException>(() => policy.Do(Nothing)); // Elapse and pass SystemUtil.SetTime(time.AddMinutes(2)); policy.Do(Nothing); } #endif static void Expect<TException>(int count, ActionPolicy policy) where TException : Exception, new() { Expect<TException>(() => Raise<TException>(count, policy)); } static void Raise<TException>(int count, ActionPolicy policy) where TException : Exception, new() { int counter = 0; policy.Do(() => { if (counter < count) { counter++; throw new TException(); } }); } [Test, Expects.TimeoutException] public void Null_Policy() { ActionPolicy.Null.Do(RaiseTimeout); } } }<file_sep>/Source/Lokad.Quality/QualityException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; namespace Lokad.Quality { /// <summary> /// Exception thrown by rules checking code quality /// </summary> [Serializable, NoCodeCoverage] public sealed class QualityException : Exception { /// <summary> /// Initializes a new instance of the <see cref="QualityException"/> class. /// </summary> public QualityException() { } /// <summary> /// Initializes a new instance of the <see cref="QualityException"/> class. /// </summary> /// <param name="message">The message.</param> public QualityException(string message) : base(message) { } QualityException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/Test/Lokad.Shared.Test/Extensions/ExtendNumberTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; using Lokad; namespace Lokad { [TestFixture] public sealed class ExtendNumberTests { [Test] public void UseCases() { 1.Milliseconds(); 1.Seconds(); 1.Minutes(); 1.Hours(); 1.Days(); 1.Kb(); 1.Mb(); 1D.Milliseconds(); 1D.Seconds(); 1D.Minutes(); 1D.Hours(); 1D.Days(); 1D.Round(3); 1m.RoundTo(2); } } }<file_sep>/Source/Lokad.Shared/Serialization/IDataSerializer.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; namespace Lokad.Serialization { /// <summary> /// Generic data serializer interface. /// </summary> public interface IDataSerializer { /// <summary> /// Serializes the object to the specified stream /// </summary> /// <param name="instance">The instance.</param> /// <param name="destinationStream">The destination stream.</param> void Serialize(object instance, Stream destinationStream); /// <summary> /// Deserializes the object from specified source stream. /// </summary> /// <param name="sourceStream">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> object Deserialize(Stream sourceStream, Type type); } }<file_sep>/Source/Lokad.Logging/ExtendISupportSyntaxForLogging.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Lokad.Diagnostics; using Lokad.Quality; namespace Lokad { /// <summary> /// Extends logging syntax /// </summary> public static class ExtendISupportSyntaxForLogging { /// <summary> /// Registers the <see cref="TraceLog"/> /// </summary> /// <typeparam name="TModule">The type of the module.</typeparam> /// <param name="module">The module.</param> /// <returns>same module for the inlining</returns> [UsedImplicitly] public static TModule LogToTrace<TModule>(this TModule module) where TModule : ISupportSyntaxForLogging { module.RegisterLogProvider(TraceLog.Provider); return module; } /// <summary> /// Registers the <see cref="NullLog"/> /// </summary> /// <typeparam name="TModule">The type of the module.</typeparam> /// <param name="module">The module.</param> /// <returns>same module for the inlining</returns> [UsedImplicitly] public static TModule LogToNull<TModule>(this TModule module) where TModule : ISupportSyntaxForLogging { module.RegisterLogProvider(TraceLog.Provider); return module; } } }<file_sep>/Test/Lokad.Shared.Test/Utils/ResourceUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.IO; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ResourceUtilTests { [Test, Expects.ArgumentNullException] public void Test_Null() { ResourceUtil<ResourceUtilTests>.GetStream(null); } [Test] public void Test_Stream() { var stream = ResourceUtil<ResourceUtilTests>.GetStream("Hello.txt"); using (stream) { var end = new StreamReader(stream).ReadToEnd(); Assert.AreEqual("Lokad.Shared.Test", end); } } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/TerminatesProgramAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class TerminatesProgramAttribute : Attribute { } }<file_sep>/Source/Lokad.Testing/Rules/RuleAssert.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using Lokad.Quality; namespace Lokad.Rules { /// <summary> /// Helper class to simplify testing of rules. /// </summary> /// <typeparam name="TTarget"> /// The type of the target for rules. /// </typeparam> [Immutable] public sealed class RuleAssert<TTarget> { readonly Rule<TTarget>[] _rules; /// <summary> /// Initializes a new instance of the /// <see cref="RuleAssert{TTarget}" /> /// class. /// </summary> /// <param name="rules">The rules.</param> public RuleAssert(params Rule<TTarget>[] rules) { Enforce.Argument(() => rules); _rules = rules; } /// <summary> /// Expects that every single item in /// <paramref name="testCases" /> /// returns /// <see cref="RuleLevel.Error" /> /// . /// </summary> /// <param name="testCases">The test cases.</param> /// <returns> /// same instance for inlining /// </returns> /// <exception cref="RuleException"> /// when expectation is not met /// </exception> public RuleAssert<TTarget> ExpectError(params TTarget[] testCases) { Expect(RuleLevel.Error, testCases); return this; } /// <summary> /// Expects that every single item in /// <paramref name="testCases" /> /// returns /// <see cref="RuleLevel.Warn" /> /// . /// </summary> /// <param name="testCases">The test cases.</param> /// <returns> /// same instance for inlining /// </returns> /// <exception cref="RuleException"> /// when expectation is not met /// </exception> public RuleAssert<TTarget> ExpectWarn(params TTarget[] testCases) { Expect(RuleLevel.Warn, testCases); return this; } /// <summary> /// Expects that every single item in /// <paramref name="testCases" /> /// returns /// <see cref="RuleLevel.None" /> /// . /// </summary> /// <param name="testCases">The test cases.</param> /// <returns> /// same instance for inlining /// </returns> /// <exception cref="RuleException"> /// when expectation is not met /// </exception> public RuleAssert<TTarget> ExpectNone(params TTarget[] testCases) { Expect(RuleLevel.None, testCases); return this; } void Expect(RuleLevel level, IEnumerable<TTarget> testCases) { foreach (var testCase in testCases) { var messages = Scope.GetMessages(testCase, "testCase", _rules); if (level != messages.Level) { var builder = new StringBuilder(); builder.AppendFormat("Expected '{0}', but got '{1}'.{2}", level, messages.Level, Environment.NewLine); builder.AppendFormat("Value: {0}{1}", testCase, Environment.NewLine); if (messages.Count > 0) { builder.Append("Messages:"); foreach (var message in messages) { builder.AppendLine().Append(message); } } throw new RuleException(builder.ToString(), "rule"); } } } } /// <summary> /// Helper class to simplify testing with rules. /// </summary> public static class RuleAssert { /// <summary> /// Initializes a new instance of the /// <see cref="RuleAssert{TTarget}" /> /// class. /// </summary> /// <param name="rules">The rules.</param> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <returns> /// new instance of the rule tester. /// </returns> public static RuleAssert<TTarget> For<TTarget>(params Rule<TTarget>[] rules) { Enforce.Argument(() => rules); return new RuleAssert<TTarget>(rules); } /// <summary> /// Expects that the /// <paramref name="rules" /> /// return /// <see cref="RuleLevel.Error" /> /// , /// when executed against the /// <paramref name="testCase" /> /// . /// </summary> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <param name="testCase">The test case.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException"> /// when the expectation is not met. /// </exception> public static void IsError<TTarget>(TTarget testCase, params Rule<TTarget>[] rules) { For(rules).ExpectError(testCase); } /// <summary> /// Expects that the /// <paramref name="rules" /> /// return /// <see cref="RuleLevel.None" /> /// , /// when executed against the /// <paramref name="testCase" /> /// . /// </summary> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <param name="testCase">The test case.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException"> /// when the expectation is not met. /// </exception> public static void IsNone<TTarget>(TTarget testCase, params Rule<TTarget>[] rules) { For(rules).ExpectNone(testCase); } /// <summary> /// Expects that the /// <paramref name="rules" /> /// return /// <see cref="RuleLevel.Warn" /> /// , /// when executed against the /// <paramref name="testCase" /> /// . /// </summary> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <param name="testCase">The test case.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException"> /// when the expectation is not met. /// </exception> public static void IsWarn<TTarget>(TTarget testCase, params Rule<TTarget>[] rules) { For(rules).ExpectWarn(testCase); } /// <summary> /// Checks that the specified /// <paramref name="argumentReference" /> /// passes the check specified in /// <paramref name="expressions" /> /// </summary> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <param name="argumentReference"> /// The argument reference. /// </param> /// <param name="expressions"> /// The expressions to check against. /// </param> /// <exception cref="RuleException">If the check fails</exception> public static void That<TTarget>(Func<TTarget> argumentReference, params Expression<Predicate<TTarget>>[] expressions) { Enforce.That(argumentReference, expressions.Convert(e => Is.True(e))); } /// <summary> /// Checks that the specified /// <paramref name="item" /> /// passes the check specified in /// <paramref name="expressions" /> /// </summary> /// <typeparam name="TTarget"> /// The type of the target. /// </typeparam> /// <param name="item"> /// The argument reference. /// </param> /// <param name="expressions"> /// The expressions to check against. /// </param> /// <exception cref="RuleException">If the check fails</exception> public static void That<TTarget>(TTarget item, params Expression<Predicate<TTarget>>[] expressions) { Enforce.That(item, expressions.Convert(e => Is.True(e))); } /// <summary> /// Determines whether the specified expression is true. /// </summary> /// <param name="expression">The expression.</param> /// <exception cref="RuleException">if the check fails</exception> public static void IsTrue(Expression<Func<bool>> expression) { Enforce.With<RuleException>(expression.Compile()(), "Expression should return 'true': {0}.", expression.Body); } /// <summary> /// Determines whether the specified expression is true. /// </summary> /// <param name="expression">The expression.</param> public static void IsFalse(Expression<Func<bool>> expression) { Enforce.With<RuleException>(!expression.Compile()(), "Expression should return 'false': {0}.", expression.Body); } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/LocalizableAttribute.cs using System; namespace Lokad.Quality { /// <summary> /// Indicates that marked elements is localizable or not. /// </summary> [AttributeUsage(AttributeTargets.All, Inherited = true)] [NoCodeCoverage] public sealed class LocalizableAttribute : Attribute { private readonly bool _isLocalizable; /// <summary> /// Initializes a new instance of the <see cref="LocalizableAttribute"/> class. /// </summary> /// <param name="isLocalizable"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param> public LocalizableAttribute(bool isLocalizable) { _isLocalizable = isLocalizable; } /// <summary> /// Gets a value indicating whether a element should be localized. /// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value> /// </summary> public bool IsLocalizable { get { return _isLocalizable; } } /// <summary> /// Returns whether the value of the given object is equal to the current <see cref="LocalizableAttribute"/>. /// </summary> /// <param name="obj">The object to test the value equality of. </param> /// <returns> /// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { var attribute = obj as LocalizableAttribute; return attribute != null && attribute.IsLocalizable == IsLocalizable; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current <see cref="LocalizableAttribute"/>.</returns> public override int GetHashCode() { return base.GetHashCode(); } } }<file_sep>/Source/Lokad.Shared/Rules/RuleMessage.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using Lokad.Quality; namespace Lokad.Rules { /// <summary> Rule message </summary> [Immutable] [Serializable] public sealed class RuleMessage : IEquatable<RuleMessage> { const string Format = "{0}: [{1}] {2}"; readonly RuleLevel _level; readonly string _message; readonly string _path; /// <summary> /// Initializes a new instance of the <see cref="RuleMessage"/> class. /// </summary> /// <param name="path">The path.</param> /// <param name="level">The level.</param> /// <param name="message">The message.</param> public RuleMessage(string path, RuleLevel level, string message) { _path = path; _level = level; _message = message; } /// <summary> /// Gets the object path for the current message. /// </summary> /// <value>The path object path.</value> public string Path { get { return _path; } } /// <summary> /// Gets the <see cref="RuleLevel"/> associated with this message. /// </summary> /// <value>The level.</value> public RuleLevel Level { get { return _level; } } /// <summary> /// Gets the message. /// </summary> /// <value>The message.</value> public string Message { get { return _message; } } bool IEquatable<RuleMessage>.Equals(RuleMessage other) { return _message == other.Message && Level == other.Level && Path == other.Path; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, Format, Path, Level, Message); } } }<file_sep>/Source/Lokad.Shared/Utils/EnumUtil.TFromEnum.TToEnum.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Lokad { /// <summary> /// Ensures that enums can be converted between each other /// </summary> /// <typeparam name="TFromEnum">The type of from enum.</typeparam> /// <typeparam name="TToEnum">The type of to enum.</typeparam> static class EnumUtil<TFromEnum, TToEnum> where TFromEnum : struct, IComparable where TToEnum : struct, IComparable { static readonly IDictionary<TFromEnum, TToEnum> Enums; static readonly TFromEnum[] Unmatched; static EnumUtil() { var fromEnums = EnumUtil.GetValues<TFromEnum>(); Enums = new Dictionary<TFromEnum, TToEnum>(fromEnums.Length, EnumUtil<TFromEnum>.Comparer); var unmatched = new List<TFromEnum>(); foreach (var fromEnum in fromEnums) { var @enum = fromEnum; MaybeParse .Enum<TToEnum>(fromEnum.ToString()) .Handle(() => unmatched.Add(@enum)) .Apply(match => Enums.Add(@enum, match)); } Unmatched = unmatched.ToArray(); } public static TToEnum Convert(TFromEnum from) { ThrowIfInvalid(); return Enums[from]; } static void ThrowIfInvalid() { if (Unmatched.Length > 0) { var list = Unmatched.Select(e => e.ToString()).Join(", "); var message = string.Format(CultureInfo.InvariantCulture, "Can't convert from {0} to {1} because of unmatched entries: {2}", typeof (TFromEnum), typeof (TToEnum), list); throw new ArgumentException(message); } } } }<file_sep>/Source/Lokad.Testing/Testing/Models/ModelAssert.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Diagnostics; using Lokad.Quality; using Lokad.Rules; namespace Lokad.Testing { /// <summary> /// Helper class for testing equality of Lokad model classes and printing out the detailed errors /// </summary> public static class ModelAssert { static void ThrowIfNotModel<TModel>() { if (!DesignUtil.ClassCache<TModel>.IsModel) { var error = string.Format("Type '{0}' should have '{1}' with '{2}' tag.", typeof(TModel), typeof(ClassDesignAttribute), DesignUtil.ConvertTagToString(DesignTag.Model)); throw new ArgumentException(error); } } /// <summary> /// Asserts that the two models are equal /// </summary> /// <typeparam name="TModel"> /// The type of the model. /// </typeparam> /// <param name="expected">The expected value.</param> /// <param name="actual">The actual value.</param> /// <param name="format"> /// The format for the exception message. /// </param> /// <param name="args"> /// The arguments for the exception message. /// </param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreEqual<TModel>(TModel expected, TModel actual, string format, params object[] args) { ThrowIfNotModel<TModel>(); var messages = GetEqualityMessages(expected, actual); if (!messages.IsSuccess) { var rules = new RuleException(messages); throw new FailedAssertException(string.Format(format, args), rules); } } /// <summary> /// Asserts that the two models are equal /// </summary> /// <typeparam name="TModel"> /// The type of the model. /// </typeparam> /// <param name="expected">The expected value.</param> /// <param name="actual">The actual value.</param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreEqual<TModel>(TModel expected, TModel actual) { AreEqual(expected, actual, "Models of type '{0}' should be equal.", typeof(TModel).Name); } /// <summary> /// Asserts that the two models are not equal /// </summary> /// <typeparam name="TModel"> /// The type of the model. /// </typeparam> /// <param name="expected">The expected value.</param> /// <param name="actual">The actual value.</param> /// <param name="format"> /// The format for the exception message. /// </param> /// <param name="args"> /// The arguments for the exception message. /// </param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreNotEqual<TModel>(TModel expected, TModel actual, string format, params object[] args) { ThrowIfNotModel<TModel>(); var messages = GetEqualityMessages(expected, actual); if (messages.IsSuccess) { throw new FailedAssertException(string.Format(format, args)); } } /// <summary> /// Asserts that the two models are not equal /// </summary> /// <typeparam name="TModel"> /// The type of the model. /// </typeparam> /// <param name="expected">The expected value.</param> /// <param name="actual">The actual value.</param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreNotEqual<TModel>(TModel expected, TModel actual) { AreNotEqual(expected, actual, "Models of type '{0}' should not be equal.", typeof(TModel).Name); } static readonly ITestModelEqualityProvider _provider; static ModelAssert() { var dict = new TestModelEqualityCache(); _provider = new TestModelEqualityBuilder(dict); dict.UnknownType = type => { Debug.WriteLine("Building provider for " + type); return _provider.GetEqualityTester(type); }; } static RuleMessages GetEqualityMessages<TModel>(TModel expected, TModel actual) { var type = typeof (TModel); var name = type.Name; return Scope.GetMessages(name, scope => { var tester = _provider.GetEqualityTester(type); var result = tester(scope, type, expected, actual); if (!result) { scope.Error("Equality check has failed"); } }); } /// <summary> /// Asserts that the two model collections are equal /// </summary> /// <typeparam name="TModel"> /// The type of the model. /// </typeparam> /// <param name="expected">The expected collection.</param> /// <param name="actual">The actual collection.</param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreEqualMany<TModel>(ICollection<TModel> expected, ICollection<TModel> actual) { AreEqualMany( expected, actual, "Models of type '{0}' should be equal.", typeof(TModel).Name); } /// <summary> /// Asserts that the two model collections are equal /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="expected">The expected collection.</param> /// <param name="actual">The actual collection.</param> /// <param name="format">The format.</param> /// <param name="args">The args.</param> /// <exception cref="FailedAssertException">When check fails</exception> public static void AreEqualMany<TModel>( ICollection<TModel> expected, ICollection<TModel> actual, string format, params object[] args) { ThrowIfNotModel<TModel>(); var messages = GetEqualityMessages(expected, actual); if (!messages.IsSuccess) { var rules = new RuleException(messages); var message = string.Format(format, args); throw new FailedAssertException(message, rules); } } } }<file_sep>/Source/Lokad.ActionPolicy/Exceptions/CircuitBreakerStateLock.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Threading; using Lokad.Quality; using Lokad.Threading; #if !SILVERLIGHT2 namespace Lokad.Exceptions { [Immutable] sealed class CircuitBreakerStateLock : ICircuitBreakerState { readonly ICircuitBreakerState _inner; readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); public CircuitBreakerStateLock(ICircuitBreakerState inner) { _inner = inner; } public Exception LastException { get { using (_lock.GetReadLock()) { return _inner.LastException; } } } public bool IsBroken { get { using (_lock.GetReadLock()) { return _inner.IsBroken; } } } public void Reset() { using (_lock.GetWriteLock()) { _inner.Reset(); } } public void TryBreak(Exception ex) { using (_lock.GetWriteLock()) { _inner.TryBreak(ex); } } } } #endif<file_sep>/Source/Lokad.Shared/IProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Interface that abstracts away providers /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <remarks> /// things like IDataCache (from the Database layers) or IResolver (from the IoC layers) /// are just samples of this interface /// </remarks> [CLSCompliant(true)] public interface IProvider<TKey, TValue> { /// <summary> /// Retrieves <typeparamref name="TValue"/> given the /// </summary> /// <param name="key"></param> /// <returns></returns> /// <exception cref="ResolutionException">when the key can not be resolved</exception> TValue Get(TKey key); } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/NotNullAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the value of marked element could never be <c>null</c> /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class NotNullAttribute : Attribute { } }<file_sep>/Test/Lokad.Shared.Test/Result2Tests.cs using System; using Lokad.Diagnostics; using Lokad.Rules; using Lokad.Testing; using NUnit.Framework; using System.Linq; namespace Lokad { using MyResult = Result<string, Result2Tests.Failure>; [TestFixture] public sealed class Result2Tests { // ReSharper disable InconsistentNaming public enum Failure { None, FatalError, ItIsRaining } [Test, Expects.InvalidOperationException] public void Access_Success() { var result = MyResult.CreateSuccess("value"); Assert.IsTrue(result.IsSuccess); Assert.AreEqual("value", result.Value); Assert.IsNull(result.Error, "this should fail"); } [Test, Expects.InvalidOperationException] public void Access_Error() { var result = MyResult.CreateError(Failure.ItIsRaining); Assert.IsFalse(result.IsSuccess); Assert.AreEqual(result.Error, Failure.ItIsRaining); Assert.IsNull(result.Value, "This should fail"); } [Test, Expects.ArgumentNullException] public void Reference_Value_Is_Checked_For_Null() { // if you have R#, this should be highlighted MyResult.CreateSuccess(default(string)); } [Test] public void Value_Can_Be_Default() { Result<int,int>.CreateSuccess(default(int)); } [Test] public void Implicit_value_Conversion() { MyResult result = "value"; RuleAssert.IsTrue(() => result.IsSuccess); } [Test] public void Implicit_error_conversion() { MyResult result = Failure.FatalError; RuleAssert.IsFalse(() => result.IsSuccess); } readonly MyResult ResultSuccess = "Hi"; readonly MyResult ResultError = Failure.ItIsRaining; [Test] public void Apply_with_error() { ResultError.Apply(i => Assert.Fail()); } [Test] public void Apply_with_value() { var applied = string.Empty; ResultSuccess.Apply(i => applied = i); Assert.AreEqual(ResultSuccess.Value, applied); } [Test] public void Convert_and_equal() { Assert.AreEqual(ResultSuccess, ResultSuccess.Convert(i => i.ToString()), "#1"); Assert.AreEqual(ResultError, ResultError.Convert(i => i.ToString()), "#2"); } [Test] public void Combine() { var error1 = MyResult.CreateError(Failure.ItIsRaining); var error1s = MyResult.CreateError(Failure.ItIsRaining); Func<string, MyResult> fails = i => { throw new InvalidOperationException(); }; Assert.AreEqual(error1s, error1.Combine(fails)); Assert.AreEqual(error1s, ResultSuccess.Combine(i => error1s)); Assert.AreEqual(MyResult.CreateSuccess("Hi!"), ResultSuccess.Combine(i => MyResult.CreateSuccess(i + "!"))); } [Test] public void ToMaybe() { Assert.AreEqual(Maybe<string>.Empty, ResultError.ToMaybe()); Assert.AreEqual(Maybe.From("Hi"), ResultSuccess.ToMaybe()); Assert.AreEqual(Maybe<string>.Empty, ResultError.ToMaybe(i => i)); Assert.AreEqual(Maybe.From("Hi"), ResultSuccess.ToMaybe(i => i)); } [Test] public void Equality_members() { // Silverlight does not contain Hashset var hashset = new[] {ResultSuccess}.ToDictionary(r => r); Assert.IsTrue(hashset.ContainsKey(ResultSuccess)); Assert.IsFalse(hashset.ContainsKey(ResultError)); Assert.IsTrue(hashset.ContainsKey("Hi")); } void Throw(Failure failure) { Assert.AreEqual(ResultError.Error, failure); throw new InvalidOperationException(); } [Test] public void Success_with_apply_handle() { var val = ""; ResultSuccess .Apply(x => val = x) .Handle(Throw) .Apply(x => val += x); Assert.AreEqual(ResultSuccess.Value + ResultSuccess.Value, val); } [Test, Expects.InvalidOperationException] public void Failure_with_apply_handle() { ResultError .Apply(x => Assert.Fail()) .Handle(Throw); } [Test] public void ExposeException() { var exception = ResultSuccess.ExposeException(s => new InvalidOperationException("should not fail")); Assert.AreEqual(exception, ResultSuccess.Value); } [Test, Expects.InvalidOperationException] public void ExposeException_with_failure() { ResultError.ExposeException(s => new InvalidOperationException(s.ToString())); } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendType.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Lokad { /// <summary> /// Helper related to the <see cref="Type"/>. /// </summary> public static class ExtendType { ///<summary> /// Extension method to retrieve attributes from the type. ///</summary> ///<param name="target">Type to perform operation upon</param> ///<param name="inherit"><see cref="MemberInfo.GetCustomAttributes(Type,bool)"/></param> ///<typeparam name="T">Attribute to use</typeparam> ///<returns>Empty array of <typeparamref name="T"/> if there are no attributes</returns> public static T[] GetAttributes<T>(this ICustomAttributeProvider target, bool inherit) where T : Attribute { if (target.IsDefined(typeof (T), inherit)) { return target .GetCustomAttributes(typeof (T), inherit) .ToArray(a => (T) a); } return new T[0]; } /// <summary> /// Returns single attribute from the type. /// </summary> /// <typeparam name="T">Attribute to use</typeparam> /// <param name="target">Attribute provider</param> ///<param name="inherit"><see cref="MemberInfo.GetCustomAttributes(Type,bool)"/></param> /// <returns><em>Null</em> if the attribute is not found</returns> /// <exception cref="InvalidOperationException">If there are 2 or more attributes</exception> public static T GetAttribute<T>(this ICustomAttributeProvider target, bool inherit) where T : Attribute { if (target.IsDefined(typeof (T), inherit)) { var attributes = target.GetCustomAttributes(typeof (T), inherit); if (attributes.Length > 1) { throw new InvalidOperationException("More than one attribute is declared"); } return (T) attributes[0]; } return null; } /// <summary> /// Selects non-abstract types marked with the specified attribute. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="types"></param> /// <param name="inherit"></param> /// <returns></returns> public static IEnumerable<Type> MarkedWith<T>(this IEnumerable<Type> types, bool inherit) where T : Attribute { return types.Where(type => (!type.IsAbstract) && type.IsDefined(typeof (T), inherit)); } } }<file_sep>/Test/Lokad.Testing.Test/Properties/AssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly : AssemblyTitle("Lokad.Testing.Test")] [assembly : AssemblyDescription("")]<file_sep>/Source/Lokad.Shared/Quality/ReSharper/InvokerParameterNameAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the function argument should be string literal and match one of the parameters of the caller function. /// For example, <see cref="ArgumentNullException"/> has such parameter. /// </summary> /// <remarks>This attribute helps R# in code analysis</remarks> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class InvokerParameterNameAttribute : Attribute { } }<file_sep>/Source/Lokad.Shared/Data/SqlClient/SqlServerGuidComparer.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Quality; namespace Lokad.Data.SqlClient { /// <summary> /// This class compares two guids according to the SQL server ordering rules. /// </summary> [Serializable] [Immutable] public sealed class SqlServerGuidComparer : IComparer<Guid> { /// <summary> /// Singleton instance of the <see cref="SqlServerGuidComparer"/> /// </summary> public static readonly IComparer<Guid> Instance = new SqlServerGuidComparer(); static readonly int[] Importance = new[] {3, 2, 1, 0, 5, 4, 7, 6, 9, 8, 15, 14, 13, 12, 11, 10}; /// <summary> /// Compares two guids and returns a value indicating whether one is less than, equal to, or greater than the other. /// </summary> /// <param name="x">The first guid to compare.</param> /// <param name="y">The second guid to compare.</param> /// <returns> /// Value indicating relation between x and y /// </returns> public int Compare(Guid x, Guid y) { var a = x.ToByteArray(); var b = y.ToByteArray(); for (int i = Importance.Length - 1; i >= 0; i--) { var compare = Importance[i]; var c = a[compare].CompareTo(b[compare]); if (c != 0) { return c; } } return 0; } } }<file_sep>/Test/Lokad.Stack.Test/Logging/LoggingStackTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; using Lokad.Rules; using NUnit.Framework; namespace Lokad.Logging { [TestFixture] public sealed class LoggingStackTests { static readonly string TestLog = Path.Combine(TestPath, "test.log"); TextWriter _out; const string TestPath = "Logs"; [Test] public void Test_RollingLog() { Assert.IsFalse(File.Exists(TestLog), "File should not exist before test"); LoggingStack.UseRollingLog(TestLog, 10.Mb(), 10); LoggingStack.GetLog().Error(new Exception(), "Test"); Assert.IsTrue(File.Exists(TestLog), "Log should be created"); } [Test] public void Test_DailyLog() { Assert.IsFalse(Directory.Exists(TestPath)); LoggingStack.UseDailyLog(TestLog); LoggingStack.GetLog().Error(new Exception(), "Some exception"); Assert.IsTrue(File.Exists(TestLog), "Log should be created"); } [TestFixtureSetUp] public void Init() { _out = Console.Out; } [Test] public void Test_ConsoleLog() { using (var writer = new StringWriter()) { Console.SetOut(writer); LoggingStack.UseConsoleLog(); LoggingStack.GetLog().Error(new Exception(), "Some exception"); Enforce.That(writer.ToString(), StringIs.NotEmpty); } } [TearDown] public void Dispose() { LoggingStack.Reset(); if (Directory.Exists(TestPath)) Directory.Delete(TestPath, true); Console.SetOut(_out); } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendIDictionary.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; namespace Lokad { /// <summary> /// Extensions for <see cref="IDictionary{TKey,TValue}"/> /// </summary> public static class ExtendIDictionary { /// <summary> /// Wraps the dictionary with the read-only provider instance /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="self">The dictionary.</param> /// <returns>provider instance that wraps the dictionary</returns> public static IProvider<TKey, TValue> AsProvider<TKey, TValue>(this IDictionary<TKey, TValue> self) { if (self == null) throw new ArgumentNullException("self"); return new Provider<TKey, TValue>(key => self[key]); } /// <summary> /// Wraps the provider with the read-only provider instance /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="self">The dictionary.</param> /// <returns>provider instance that wraps the dictionary</returns> public static INamedProvider<TValue> AsProvider<TValue>(this IDictionary<string, TValue> self) { if (self == null) throw new ArgumentNullException("self"); return new NamedProvider<TValue>(key => self[key]); } /// <summary> /// Returns <paramref name="defaultValue"/> if the given <paramref name="key"/> /// is not present within the dictionary /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="self">The dictionary.</param> /// <param name="key">The key to look for.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value matching <paramref name="key"/> or <paramref name="defaultValue"/> if none is found</returns> public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> self, TKey key, TValue defaultValue) { TValue value; if (self.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Gets the value from the <paramref name="dictionary"/> in form of the <see cref="Maybe{T}"/>. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns>value from the dictionary</returns> public static Maybe<TValue> GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) { TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } return Maybe<TValue>.Empty; } } }<file_sep>/Source/Lokad.Shared/Utils/BufferUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper utilities for working with byte buffers /// </summary> public static class BufferUtil { /// <summary> /// Calculates simple hash code /// </summary> /// <param name="bytes">The bytes to hash.</param> /// <returns>hash for the buffer</returns> /// <exception cref="ArgumentNullException">if bytes are null</exception> public static int CalculateSimpleHashCode([NotNull] byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); if (bytes.Length < 4) { return ShortHash(bytes); } return LongHash(bytes); } static int LongHash(byte[] bytes) { int result = bytes.Length.GetHashCode(); unchecked { for (int i = 0; i < bytes.Length; i += 4) { var remains = bytes.Length - i; int sliceHash = remains >= 4 ? BitConverter.ToInt32(bytes, i) : BitConverter.ToInt32(bytes, bytes.Length - 4); result = (result*0x18d) ^ sliceHash; } } return result; } static int ShortHash(byte[] bytes) { var result = bytes.Length.GetHashCode(); unchecked { for (int i = 0; i < bytes.Length; i++) { result = (result*0x18d) ^ bytes[i].GetHashCode(); } } return result; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/EnforceScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class EnforceScopeTests { [Test, Expects.RuleException] public void Test() { var Test = 1; try { using (var t = ScopeFactory.ForEnforce(() => Test, Scope.WhenError)) { ScopeTestHelper.FireErrors(t); } } catch (RuleException ex) { ScopeTestHelper.ShouldBeClean(ex); ScopeTestHelper.ShouldHave(ex, "ErrA"); ScopeTestHelper.ShouldNotHave(ex, "ErrB", "ErrC"); throw; } } } }<file_sep>/Source/Lokad.Shared/Utils/VersionUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Helper class for <see cref="Version"/> /// </summary> public static class VersionUtil { /// <summary> /// Normalizes the specified version by replacing all -1 with 0 /// </summary> /// <param name="version">The version.</param> /// <returns>version that has all 0 replaced with -1</returns> public static Version Normalize(this Version version) { var c = version.Build == -1 ? 0 : version.Build; var d = version.Revision == -1 ? 0 : version.Revision; return new Version(version.Major, version.Minor, c, d); } } }<file_sep>/Source/Lokad.Shared/ExtendISupportSyntaxForSerialization.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using Lokad.Serialization; namespace Lokad { /// <summary> /// Syntax extensions for <see cref="ISupportSyntaxForSerialization"/> /// </summary> public static class ExtendISupportSyntaxForSerialization { /// <summary> /// Uses the binary formatter. /// </summary> /// <param name="module">The module to extend.</param> public static void UseBinaryFormatter(this ISupportSyntaxForSerialization module) { module.RegisterSerializer<BinaryMessageSerializer>(); } /// <summary> /// Uses the data contract serializer. /// </summary> /// <param name="module">The module to extend.</param> public static void UseDataContractSerializer(this ISupportSyntaxForSerialization module) { module.RegisterSerializer<DataContractMessageSerializer>(); } } }<file_sep>/Source/Lokad.Shared/Settings/ISettingsKeyFilter.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Settings { /// <summary> /// Implements filtering interface for the /// <see cref="ISettingsProvider" /> /// </summary> public interface ISettingsKeyFilter { /// <summary> /// Filters the path, either accepting it (and optionally altering) /// or by returning empty result /// </summary> /// <param name="keyPath">The key path.</param> /// <returns>filtered key path</returns> Maybe<string> Filter(string keyPath); } }<file_sep>/Source/Lokad.Testing/Testing/Models/TestModelEqualityDelegate.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Rules; namespace Lokad.Testing { /// <summary> /// Delegate that represents model equality tester /// </summary> delegate bool TestModelEqualityDelegate(IScope scope, Type type, object o1, object o2); }<file_sep>/Source/Lokad.ActionPolicy/HandlingProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using Lokad.Quality; namespace Lokad { /// <summary> /// Simple reliability layer for the <see cref="IProvider{TKey,TValue}"/> /// </summary> /// <typeparam name="TKey">type of the Key item</typeparam> /// <typeparam name="TValue">type of the values</typeparam> [Serializable] [Immutable] public sealed class HandlingProvider<TKey, TValue> : IProvider<TKey, TValue> { readonly IProvider<TKey, TValue> _provider; readonly ActionPolicy _policy; /// <summary> /// Creates generic reliability wrapper around the <see cref="IProvider{TKey,TValue}"/> /// </summary> /// <param name="provider"></param> /// <param name="policy"></param> public HandlingProvider(IProvider<TKey, TValue> provider, ActionPolicy policy) { _provider = provider; _policy = policy; } /// <summary> /// <see cref="IProvider{TKey,TValue}.Get"/> /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue Get(TKey key) { try { return _policy.Get(() => _provider.Get(key)); } catch (Exception ex) { Type valueType = typeof (TValue); throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0} with key '{1}'", valueType, (object) key), ex); } } } /// <summary> /// This shortcuts simplifies creation of <see cref="HandlingProvider"/> instances /// </summary> public static class HandlingProvider { /// <summary> /// Creates new instance of <see cref="HandlingProvider{TKey,TValue}"/> /// by wrapping another <see cref="IProvider{TKey,TValue}"/> instance /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="provider">The provider to wrap.</param> /// <param name="policy">The action policy.</param> /// <returns>new provider instance</returns> public static IProvider<TKey, TValue> For<TKey, TValue>(IProvider<TKey, TValue> provider, ActionPolicy policy) { return new HandlingProvider<TKey, TValue>(provider, policy); } } }<file_sep>/Test/Lokad.Shared.Test/Linq/ArrayExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Linq { [TestFixture] public sealed class ArrayExtensionsTests { [Test, Expects.ArgumentNullException] public void Slice_Detects_Null_Argument() { ExtendArray.SliceArray<int>(null, 3); } [Test, Expects.ArgumentOutOfRangeException] public void Slice_Detects_Zero_SliceLength() { new int[0].SliceArray(0); } [Test] public void Slice_Works_For_Empty_Arrays() { CollectionAssert.AreEqual(new int[0][], new int[0].SliceArray(4)); } [Test] public void Slice_Works_For_Full_Slices() { var slices = Range.Array(8).SliceArray(4); var expected = new[] { new[] {0, 1, 2, 3}, new[] {4, 5, 6, 7} }; CollectionAssert.AreEqual(expected, slices); } [Test] public void Slice_Works_For_Incomplete_Slices() { var slices = Range.Array(7).SliceArray(4); var expected = new[] { new[] {0, 1, 2, 3}, new[] {4, 5, 6} }; CollectionAssert.AreEqual(expected, slices); } [Test] public void ForEach() { var i = Rand.Next(20); Range.Array(i, n => 1).ForEach(n => i -= 1); Assert.AreEqual(i, 0); } [Test] public void Append() { var i = Rand.Next(10); var a = Range.Array(i).Append(Range.Array(i)); for (int j = 0; j < i; j++) { Assert.AreEqual(a[j], a[j + i]); } } [Test] public void Convert_With_Int() { var ints = Range.Array(Rand.Next(10)).Convert((n, i) => n - i); foreach (var i in ints) { Assert.AreEqual(0, i); } } [Test] public void Empty_jagged_array2() { var obj = new object[0,0]; object[][] objects = obj.ToJaggedArray(); Assert.AreEqual(0, objects.Length); } [Test] public void Non_empty_jagger_array2() { var obj = new[,] {{1, 2}, {3, 4}}; int[][] actual = obj.ToJaggedArray(); var expected = new[] {new[] {1, 2}, new[] {3, 4}}; CollectionAssert.AreEqual(expected, actual); } [Test] public void Shifted_jagged_array2() { var instance = Array.CreateInstance(typeof (int), new[] {2, 2}, new[] {1, 1}); var array = (int[,]) instance; array[1, 1] = 1; array[1, 2] = 2; array[2, 1] = 3; array[2, 2] = 4; var expected = new[] {new[] {1, 2}, new[] {3, 4}}; CollectionAssert.AreEqual(expected, array.ToJaggedArray()); } } }<file_sep>/Source/Lokad.Shared/Rules/Scope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Lokad.Quality; namespace Lokad.Rules { /// <summary> /// Helper class that invokes different scopes /// </summary> [UsedImplicitly] public static class Scope { /// <summary> /// Returns true if <paramref name="level"/> /// is <see cref="RuleLevel.Error"/> or higher /// </summary> /// <param name="level">The level to check.</param> /// <returns>true if the condition is met</returns> [NoCodeCoverage] public static bool WhenError(RuleLevel level) { return level >= RuleLevel.Error; } /// <summary> /// Returns true if <paramref name="level"/> /// is not <see cref="RuleLevel.None"/> /// </summary> /// <param name="level">The level.</param> /// <returns>true if the condition is met</returns> [NoCodeCoverage] public static bool WhenAny(RuleLevel level) { return level > RuleLevel.None; } /// <summary> /// Returns true if <paramref name="ruleLevel"/> /// is <see cref="RuleLevel.Warn"/> or higher /// </summary> /// <param name="ruleLevel">The rule level.</param> /// <returns>true if the condition is met</returns> [NoCodeCoverage] public static bool WhenWarn(RuleLevel ruleLevel) { return ruleLevel >= RuleLevel.Warn; } /// <summary> /// Returns true if <paramref name="ruleLevel"/> /// is <see cref="RuleLevel.None"/> or higher /// </summary> /// <param name="ruleLevel">The rule level.</param> /// <returns>true if the condition is met</returns> [NoCodeCoverage] public static bool WhenNone(RuleLevel ruleLevel) { return ruleLevel == RuleLevel.None; } /// <summary> /// Creates scope that runs full check and then fails with /// <see cref="RuleException"/>, if the resulting /// <see cref="RuleLevel"/> matches the <paramref name="predicate"/> /// </summary> /// <param name="name">The name for the scope.</param> /// <param name="predicate">The predicate.</param> /// <returns>new scope instance</returns> public static IScope ForValidation(string name, Predicate<RuleLevel> predicate) { return ScopeFactory.ForValidation(name, predicate); } /// <summary> /// Creates scope that throws <see cref="RuleException"/> as soon as /// first message matching <paramref name="predicate"/> is received. /// </summary> /// <param name="scopeName">Name of the scope.</param> /// <param name="predicate">The predicate.</param> /// <returns>new scope instance</returns> public static IScope ForEnforce(string scopeName, Predicate<RuleLevel> predicate) { return ScopeFactory.ForEnforce(scopeName, predicate); } /// <summary> /// Creates scope that throws <see cref="ArgumentException"/> as soon as /// first message matching <paramref name="predicate"/> is received. /// </summary> /// <param name="scopeName">Name of the scope.</param> /// <param name="predicate">The predicate.</param> /// <returns>new scope instance</returns> public static IScope ForEnforceArgument(string scopeName, Predicate<RuleLevel> predicate) { return ScopeFactory.ForEnforceArgument(scopeName, predicate); } /// <summary> Determines whether the specified item has problems of /// <see cref="RuleLevel.Error"/> or higher. </summary> /// <typeparam name="TItem">type of the item to run rules against</typeparam> /// <param name="item">The item to run rules against.</param> /// <param name="rules">The rules to execute.</param> /// <returns> /// <c>true</c> if the specified item is in error state; otherwise, <c>false</c>. /// </returns> public static bool IsError<TItem>(TItem item, params Rule<TItem>[] rules) { using (IScope scope = new TrackScope()) { scope.ValidateInScope(item, rules); return scope.IsError(); } } /// <summary> Determines whether the specified item does not have any problems </summary> /// <typeparam name="TItem">type of the item to run rules against</typeparam> /// <param name="item">The item to run rules against.</param> /// <param name="rules">The rules to execute.</param> /// <returns> /// <c>true</c> if the specified item is in error state; otherwise, <c>false</c>. /// </returns> public static bool IsValid<TItem>(TItem item, params Rule<TItem>[] rules) { using (IScope scope = new TrackScope()) { scope.ValidateInScope(item, rules); return scope.IsNone(); } } /// <summary> Determines whether the specified item has problems of /// <see cref="RuleLevel.Warn"/> or higher. </summary> /// <typeparam name="TItem">type of the item to run rules against</typeparam> /// <param name="item">The item to run rules against.</param> /// <param name="rules">The rules to execute.</param> /// <returns> /// <c>true</c> if the specified item is in warning state; otherwise, <c>false</c>. /// </returns> public static bool IsWarn<TItem>(TItem item, params Rule<TItem>[] rules) { using (IScope scope = new TrackScope()) { scope.ValidateInScope(item, rules); return scope.IsWarn(); } } /// <summary> Collects all rule messages associated with the /// specified <paramref name="item"/> </summary> /// <typeparam name="TItem">The type of the item to run the rules against.</typeparam> /// <param name="item">The item to run the rules against.</param> /// <param name="name">The name of the scope.</param> /// <param name="rules">The rules to execute.</param> /// <returns>read-only collection of <see cref="RuleMessage"/></returns> public static RuleMessages GetMessages<TItem>(TItem item, string name, params Rule<TItem>[] rules) { if (name == null) throw new ArgumentNullException("name"); return SimpleScope.GetMessages(name, scope => scope.ValidateInScope(item, rules)); } /// <summary> Collects all rule messages associated with the /// specified <paramref name="item"/> </summary> /// <typeparam name="TItem">The type of the item to run the rules against.</typeparam> /// <param name="item">The item to run the rules against.</param> /// <param name="rules">The rules to execute.</param> /// <returns>read-only collection of <see cref="RuleMessage"/></returns> public static RuleMessages GetMessages<TItem>(TItem item, params Rule<TItem>[] rules) { return SimpleScope.GetMessages(typeof(TItem).Name, scope => scope.ValidateInScope(item, rules)); } /// <summary> /// Gets the messages created by action being executed against the scope. /// </summary> /// <param name="name">The name for the scope.</param> /// <param name="scopeAction">The scope action.</param> /// <returns>read-only collection of <see cref="RuleMessage"/></returns> public static RuleMessages GetMessages([NotNull] string name, [NotNull] Action<IScope> scopeAction) { if (name == null) throw new ArgumentNullException("name"); if (scopeAction == null) throw new ArgumentNullException("scopeAction"); return SimpleScope.GetMessages(name, scopeAction); } /// <summary> /// Collects all rule messages associated with the /// specified <paramref name="itemReference"/> /// </summary> /// <typeparam name="TItem">The type of the item to run the rules against.</typeparam> /// <param name="itemReference">The item reference.</param> /// <param name="rules">The rules to execute.</param> /// <returns> /// read-only collection of <see cref="RuleMessage"/> /// </returns> public static RuleMessages GetMessages<TItem>(Func<TItem> itemReference, params Rule<TItem>[] rules) { if (itemReference == null) throw new ArgumentNullException("itemReference"); return ScopeFactory.GetMessages(itemReference, scope => scope.ValidateInScope(itemReference(), rules)); } /// <summary> /// Collects all rule messages associated with the /// specified <paramref name="sequenceReference"/> /// </summary> /// <typeparam name="TItem">The type of the item to run the rules against.</typeparam> /// <param name="sequenceReference">The sequence reference.</param> /// <param name="rules">The rules to execute.</param> /// <returns> read-only collection of <see cref="RuleMessage"/> </returns> public static RuleMessages GetMessagesForMany<TItem>(Func<IEnumerable<TItem>> sequenceReference, params Rule<TItem>[] rules) { if (sequenceReference == null) throw new ArgumentNullException("sequenceReference"); return ScopeFactory.GetMessages(sequenceReference, scope => scope.ValidateInScope(sequenceReference(), rules)); } /// <summary> Collects all rule messages associated with the /// specified <paramref name="items"/> </summary> /// <typeparam name="TItem">The type of the item to run the rules against.</typeparam> /// <param name="items">The item to run the rules against.</param> /// <param name="name">The name of the scope.</param> /// <param name="rules">The rules to execute.</param> /// <returns>read-only collection of <see cref="RuleMessage"/></returns> public static RuleMessages GetMessagesForMany<TItem>(IEnumerable<TItem> items, string name, params Rule<TItem>[] rules) { if (name == null) throw new ArgumentNullException("name"); return SimpleScope.GetMessages(name, scope => scope.ValidateInScope(items, rules)); } /// <summary> /// Runs full validation scan of the specified item and throws error /// if the level is not <see cref="RuleLevel.None"/> /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="item">The item to validate.</param> /// <param name="rules">The rules.</param> /// <exception cref="RuleException">if any rules have failed</exception> [DebuggerNonUserCode] public static void Validate<T>(T item, params Rule<T>[] rules) { using (var scope = ScopeFactory.ForValidation(typeof (T).Name, WhenAny)) { scope.ValidateInScope(item, rules); } } /// <summary> /// Runs full validation scan of the specified collection /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="items">The collection to validate.</param> /// <param name="rules">The validators.</param> /// <exception cref="RuleException">if any rules have failed</exception> [DebuggerNonUserCode] public static void ValidateMany<T>(IEnumerable<T> items, params Rule<T>[] rules) { using (var scope = ScopeFactory.ForValidation(typeof (T).Name, WhenAny)) { scope.ValidateInScope(items, rules); } } /// <summary> /// Rule path separator char /// </summary> [UsedImplicitly] public const char RulePathSeprator = '.'; [NoCodeCoverage] internal static string ComposePathInternal(string prefix, string suffix) { // no checks here, since the call is coming from the trusted code. return prefix + RulePathSeprator + suffix; } /// <summary> /// Composes the path for the <see cref="Rule{T}"/>. /// </summary> /// <param name="prefix">The prefix.</param> /// <param name="suffix">The suffix.</param> /// <returns>composed path</returns> /// <exception cref="ArgumentException">if path parameters are null or empty</exception> [NoCodeCoverage] public static string ComposePath(string prefix, string suffix) { if (string.IsNullOrEmpty(prefix)) throw new ArgumentException("prefix"); if (string.IsNullOrEmpty(suffix)) throw new ArgumentException("suffix"); return ComposePathInternal(prefix, suffix); } /// <summary> /// Creates new scope for logging into the provided string builder /// </summary> /// <param name="scopeName">Name of the scope.</param> /// <param name="log">The builder to write to.</param> /// <returns>composed scope</returns> public static IScope ForLogging([NotNull] string scopeName, [NotNull] StringBuilder log) { if (log == null) throw new ArgumentNullException("log"); if (string.IsNullOrEmpty(scopeName)) throw new ArgumentException("scopeName"); var format = "{0} [{1}]: {2}" + Environment.NewLine; return new SimpleScope(scopeName, (path, level, message) => log.AppendFormat(format, path, level, message)); } } }<file_sep>/Source/Lokad.Shared/Monads/Maybe.1.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class that indicates nullable value in a good-citizenship code /// </summary> /// <typeparam name="T">underlying type</typeparam> [Serializable] [UsedImplicitly] [Immutable] public sealed class Maybe<T> : IEquatable<Maybe<T>> { readonly T _value; readonly bool _hasValue; Maybe(T item, bool hasValue) { _value = item; _hasValue = hasValue; } internal Maybe(T value) : this(value, true) { // ReSharper disable CompareNonConstrainedGenericWithNull if (value == null) { throw new ArgumentNullException("value"); } // ReSharper restore CompareNonConstrainedGenericWithNull } /// <summary> /// Default empty instance. /// </summary> public static readonly Maybe<T> Empty = new Maybe<T>(default(T), false); /// <summary> /// Gets the underlying value. /// </summary> /// <value>The value.</value> public T Value { get { if (!_hasValue) { throw new InvalidOperationException("Code should not access value when it is not available."); } return _value; } } /// <summary> /// Gets a value indicating whether this instance has value. /// </summary> /// <value><c>true</c> if this instance has value; otherwise, <c>false</c>.</value> public bool HasValue { get { return _hasValue; } } /// <summary> /// Retrieves value from this instance, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public T GetValue(Func<T> defaultValue) { return _hasValue ? _value : defaultValue(); } /// <summary> /// Retrieves value from this instance, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public T GetValue(T defaultValue) { return _hasValue ? _value : defaultValue; } /// <summary> /// Retrieves value from this instance, using a <paramref name="defaultValue"/> /// factory, if it is absent /// </summary> /// <param name="defaultValue">The default value to provide.</param> /// <returns>maybe value</returns> public Maybe<T> GetValue(Func<Maybe<T>> defaultValue) { return _hasValue ? this : defaultValue(); } /// <summary> /// Retrieves value from this instance, using a <paramref name="defaultValue"/> /// if it is absent /// </summary> /// <param name="defaultValue">The default value to provide.</param> /// <returns>maybe value</returns> public Maybe<T> GetValue(Maybe<T> defaultValue) { return _hasValue ? this : defaultValue; } /// <summary> /// Applies the specified action to the value, if it is present. /// </summary> /// <param name="action">The action.</param> /// <returns>same instance for inlining</returns> public Maybe<T> Apply(Action<T> action) { if (_hasValue) { action(_value); } return this; } /// <summary> /// Executes the specified action, if the value is absent /// </summary> /// <param name="action">The action.</param> /// <returns>same instance for inlining</returns> public Maybe<T> Handle(Action action) { if (!_hasValue) { action(); } return this; } /// <summary> /// Exposes the specified exception if maybe does not have value. /// </summary> /// <param name="exception">The exception.</param> /// <returns>actual value</returns> /// <exception cref="Exception">if maybe does not have value</exception> public T ExposeException(Func<Exception> exception) { if (!_hasValue) { throw exception(); } return _value; } /// <summary> /// Throws the exception if maybe does not have value. /// </summary> /// <returns>actual value</returns> /// <exception cref="InvalidOperationException">if maybe does not have value</exception> public T ExposeException([NotNull] string message) { if (message == null) throw new ArgumentNullException(@"message"); if (!_hasValue) { throw new InvalidOperationException(message); } return _value; } /// <summary> /// Throws the exception if maybe does not have value. /// </summary> /// <returns>actual value</returns> /// <exception cref="InvalidOperationException">if maybe does not have value</exception> [StringFormatMethod("message")] public T ExposeException([NotNull] string message, params object[] args) { if (message == null) throw new ArgumentNullException(@"message"); if (!_hasValue) { var text = string.Format(message, args); throw new InvalidOperationException(text); } return _value; } /// <summary> /// Combines this optional with the pipeline function /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="combinator">The combinator (pipeline funcion).</param> /// <returns>optional result</returns> public Maybe<TTarget> Combine<TTarget>(Func<T, Maybe<TTarget>> combinator) { return _hasValue ? combinator(_value) : Maybe<TTarget>.Empty; } /// <summary> /// Converts this instance to <see cref="Maybe{T}"/>, /// while applying <paramref name="converter"/> if there is a value. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns></returns> public Maybe<TTarget> Convert<TTarget>(Func<T, TTarget> converter) { return _hasValue ? converter(_value) : Maybe<TTarget>.Empty; } /// <summary> /// Retrieves converted value, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <typeparam name="TTarget">type of the conversion target</typeparam> /// <param name="converter">The converter.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public TTarget Convert<TTarget>(Func<T, TTarget> converter, Func<TTarget> defaultValue) { return _hasValue ? converter(_value) : defaultValue(); } /// <summary> /// Retrieves converted value, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <typeparam name="TTarget">type of the conversion target</typeparam> /// <param name="converter">The converter.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public TTarget Convert<TTarget>(Func<T, TTarget> converter, TTarget defaultValue) { return _hasValue ? converter(_value) : defaultValue; } /// <summary> /// Determines whether the specified <see cref="Maybe{T}"/> is equal to the current <see cref="Maybe{T}"/>. /// </summary> /// <param name="maybe">The <see cref="Maybe"/> to compare with.</param> /// <returns>true if the objects are equal</returns> public bool Equals(Maybe<T> maybe) { if (ReferenceEquals(null, maybe)) return false; if (ReferenceEquals(this, maybe)) return true; if (_hasValue != maybe._hasValue) return false; if (!_hasValue) return true; return _value.Equals(maybe._value); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var maybe = obj as Maybe<T>; if (maybe == null) return false; return Equals(maybe); } /// <summary> /// Serves as a hash function for this instance. /// </summary> /// <returns> /// A hash code for the current <see cref="Maybe{T}"/>. /// </returns> public override int GetHashCode() { unchecked { // ReSharper disable CompareNonConstrainedGenericWithNull return ((_value != null ? _value.GetHashCode() : 0)*397) ^ _hasValue.GetHashCode(); // ReSharper restore CompareNonConstrainedGenericWithNull } } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Maybe<T> left, Maybe<T> right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Maybe<T> left, Maybe<T> right) { return !Equals(left, right); } /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Maybe{T}"/>. /// </summary> /// <param name="item">The item.</param> /// <returns>The result of the conversion.</returns> public static implicit operator Maybe<T>(T item) { // ReSharper disable CompareNonConstrainedGenericWithNull if (item == null) throw new ArgumentNullException("item"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Maybe<T>(item); } /// <summary> /// Performs an explicit conversion from <see cref="Maybe{T}"/> to <typeparamref name="T"/>. /// </summary> /// <param name="item">The item.</param> /// <returns>The result of the conversion.</returns> public static explicit operator T(Maybe<T> item) { if (item == null) throw new ArgumentNullException("item"); if (!item.HasValue) throw new ArgumentException("May be must have value"); return item.Value; } /// <summary> /// Converts maybe into result, using the specified error as the failure /// descriptor /// </summary> /// <typeparam name="TError">The type of the failure.</typeparam> /// <param name="error">The error.</param> /// <returns>result describing current maybe</returns> public Result<T, TError> Join<TError>(TError error) { if (_hasValue) return _value; return error; } /// <summary> /// Converts maybe into result, using the specified error as the failure /// descriptor /// </summary> /// <returns>result describing current maybe</returns> public Result<T> JoinMessage(string error) { if (_hasValue) return _value; return error; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (_hasValue) { return "<" + _value + ">"; } return "<Empty>"; } } }<file_sep>/Source/Lokad.Shared/Silverlight/ExtendString.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if SILVERLIGHT2 using System.Globalization; namespace System { /// <summary> /// Extends string for the silverlight compatibility /// </summary> public static class ExtendString { /// <summary> /// Converts string to uppercase, using the invariant culture. /// </summary> /// <param name="source">The source.</param> /// <returns>string in the upper case</returns> public static string ToUpperInvariant(this string source) { return source.ToUpper(CultureInfo.InvariantCulture); } } } #endif<file_sep>/Test/Lokad.Quality.Test/TypeDefinitionExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using NUnit.Framework; namespace Lokad.Quality.Test { [TestFixture] public sealed class TypeDefinitionExtensionsTests { // ReSharper disable InconsistentNaming [Test] public void With() { var definitions = GlobalSetup.Codebase .Types.With<ElementAttribute>().ToArray(); var expected = new[] {GlobalSetup.Codebase.Find(typeof (Fire)).Value}; CollectionAssert.AreEquivalent(expected, definitions); } [Test] public void Resolve() { var resolve = GlobalSetup.Codebase .Find<ElementAttribute>().Resolve(); Assert.AreEqual(typeof (ElementAttribute), resolve); } [Test] public void GetConstructors_of_empty_class() { var ctors = GlobalSetup.Codebase .Find(typeof (Fire)).Value .GetConstructors(); CollectionAssert.IsEmpty(ctors); } [Test] public void GetConstructors_of_class() { var ctors = GlobalSetup.Codebase .Find<ElementAttribute>() .GetConstructors(); CollectionAssert.IsNotEmpty(ctors); Assert.AreEqual(1, ctors.Count()); Assert.AreEqual(".ctor", ctors.First().Name); } [UsedImplicitly] sealed class ClassWithProperty { internal string Property { get; set; } } [Test] public void GetProperties() { var properties = GlobalSetup.Codebase .Find<ClassWithProperty>() .GetProperties(); CollectionAssert.IsNotEmpty(properties); Assert.AreEqual(1, properties.Count()); Assert.AreEqual("Property", properties.First().Name); } [Test] public void GetProperties_of_empty_class() { CollectionAssert.IsEmpty(GlobalSetup.Codebase .Find(typeof (Fire)).Value .GetProperties()); } } }<file_sep>/Source/Lokad.Testing/Testing/MockContainer/MockContainer.1.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Testing { /// <summary> /// Extends the <see cref="MockContainer"/> and autoregisters the specified subject. /// </summary> /// <typeparam name="TSubject">The type of the subject.</typeparam> public sealed class MockContainer<TSubject> : MockContainer { /// <summary> /// Testing subject /// </summary> public TSubject Subject { get { return Resolve<TSubject>(); } } /// <summary> /// Initializes a new instance of the <see cref="MockContainer{TSubject}"/> class. /// </summary> public MockContainer() { Register<TSubject>(); } } }<file_sep>/Source/Lokad.Shared/Utils/ResourceUtil.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; using System.Reflection; namespace Lokad { /// <summary> /// Simple helper class to replace common "DataMother" helper /// used in tests. /// </summary> /// <typeparam name="T"></typeparam> public static class ResourceUtil<T> { static readonly Assembly _assembly = typeof (T).Assembly; /// <summary> /// Gets the stream for the associated resource from the <typeparamref name="T"/> /// namespace. /// </summary> /// <seealso cref="Assembly.GetManifestResourceStream(Type,string)"/> /// <param name="name">The name of the resource.</param> /// <returns></returns> public static Stream GetStream(string name) { if (name == null) throw new ArgumentNullException("name"); return _assembly.GetManifestResourceStream(typeof (T), name); } } }<file_sep>/Source/Lokad.Shared/NamedProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using Lokad.Quality; namespace Lokad { /// <summary> /// This class provides way to create providers out of lambda shortcuts /// </summary> /// <typeparam name="T"></typeparam> [Serializable] [Immutable] public sealed class NamedProvider<T> : IProvider<string, T>, INamedProvider<T> { readonly Func<string, T> _resolver; /// <summary> /// Initializes a new instance of the <see cref="NamedProvider{T}"/> class. /// </summary> /// <param name="resolver">The resolver.</param> public NamedProvider(Func<string, T> resolver) { _resolver = resolver; } /// <summary> /// Retrieves <typeparamref name="T"/> given the <paramref name="key"/> /// </summary> /// <param name="key"></param> /// <returns></returns> /// <exception cref="ResolutionException">when the key cannot be resolved</exception> public T Get(string key) { try { return _resolver(key); } catch (Exception ex) { Type valueType = typeof (T); throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0} with key '{1}'", valueType, (object) key), ex); } } } /// <summary> /// Shortcuts for <see cref="NamedProvider{T}"/> /// </summary> [NoCodeCoverage] public static class NamedProvider { /// <summary> /// Creates new instance of the <see cref="INamedProvider{TValue}"/> out of /// the provider function (shortcut syntax) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="providerFunction">The provider function.</param> /// <returns></returns> public static INamedProvider<T> For<T>(Func<string, T> providerFunction) { if (providerFunction == null) throw new ArgumentNullException("providerFunction"); return new NamedProvider<T>(providerFunction); } } }<file_sep>/Source/Lokad.Quality/QualityAssert.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Helper class for verifying code quality assertions. /// </summary> public static class QualityAssert { static QualityException Error(string message, params object[] args) { return new QualityException(string.Format(message, args)); } /// <summary> /// Verifies that every definition in the specified sequence passes <paramref name="check"/>; /// </summary> /// <param name="definitions">The definitions.</param> /// <param name="check">The check.</param> /// <exception cref="QualityException">if any definitions fail.</exception> public static void TypesPass(IEnumerable<TypeDefinition> definitions, Predicate<TypeDefinition> check) { var failing = definitions.Where(t => !check(t)); if (!failing.Any()) return; var types = failing .Select(t => t.FullName) .Join(Environment.NewLine); throw Error("Failing types:\r\n{0}", types); } /// <summary> /// Verifies that every definition in the specified sequence passes <paramref name="check"/>; /// </summary> /// <param name="definitions">The definitions.</param> /// <param name="check">The check.</param> /// <exception cref="QualityException">if any definitions fail.</exception> public static void MethodsPass(IEnumerable<MethodDefinition> definitions, Predicate<MethodDefinition> check) { var failing = definitions.Where(t => !check(t)); if (!failing.Any()) return; var types = failing .Select(t => t.ToString()) .Join(Environment.NewLine); throw Error("Failing methods:\r\n{0}", types); } } }<file_sep>/Source/Lokad.Shared/Diagnostics/ExecutionStatistics.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad.Diagnostics { /// <summary> /// Statistics about some execution counter /// </summary> [Serializable] [Immutable] public sealed class ExecutionStatistics { readonly long _openCount; readonly long _closeCount; readonly long[] _counters; readonly long _runningTime; readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="ExecutionStatistics"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="openCount">The open count.</param> /// <param name="closeCount">The close count.</param> /// <param name="counters">The counters.</param> /// <param name="runningTime">The running time.</param> public ExecutionStatistics(string name, long openCount, long closeCount, long[] counters, long runningTime) { _openCount = openCount; _closeCount = closeCount; _counters = counters; _runningTime = runningTime; _name = name; } /// <summary> /// Gets the number of times the counter has been opened /// </summary> /// <value>The open count.</value> public long OpenCount { get { return _openCount; } } /// <summary> /// Gets the number of times the counter has been properly closed. /// </summary> /// <value>The close count.</value> public long CloseCount { get { return _closeCount; } } /// <summary> /// Gets the native counters collected by this counter. /// </summary> /// <value>The counters.</value> public long[] Counters { get { return _counters; } } /// <summary> /// Gets the total running time between open and close statements in ticks. /// </summary> /// <value>The running time expressed in 100-nanosecond units.</value> public long RunningTime { get { return _runningTime; } } /// <summary> /// Gets the name for this counter. /// </summary> /// <value>The name.</value> public string Name { get { return _name; } } } }<file_sep>/Source/Lokad.Shared/Diagnostics/ExecutionCounters.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; #if !SILVERLIGHT2 namespace Lokad.Diagnostics { /// <summary> /// In-memory thread-safe collection of <see cref="ExecutionCounter"/> /// </summary> public sealed class ExecutionCounters { /// <summary> /// Default instance of this counter /// </summary> public static readonly ExecutionCounters Default = new ExecutionCounters(); readonly object _lock = new object(); readonly IList<ExecutionCounter> _counters = new List<ExecutionCounter>(); /// <summary> /// Registers the execution counters within this collection. /// </summary> /// <param name="counters">The counters.</param> public void RegisterRange(IEnumerable<ExecutionCounter> counters) { lock (_lock) { _counters.AddRange(counters); } } /// <summary> /// Retrieves statistics for all exception counters in this collection /// </summary> /// <returns></returns> public IList<ExecutionStatistics> ToList() { lock (_lock) { return _counters.Select(c => c.ToStatistics()).ToList(); } } /// <summary> /// Resets all counters. /// </summary> public void ResetAll() { lock (_lock) { foreach (var counter in _counters) { counter.Reset(); } } } } } #endif<file_sep>/Source/Lokad.Shared/Rules/ExtendIScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using Lokad.Quality; using Lokad.Reflection; namespace Lokad.Rules { ///<summary> /// <para>Extensions that encapsulate some repetitive tasks /// of setting scopes, and calling validation rules.</para> /// <para>Basically that's the class that links together scope /// and validation logics.</para></summary> public static class ExtendIScope { /// <summary> Outputs formatted <see cref="RuleLevel.Error"/> /// message into the <paramref name="scope"/> using the /// <see cref="CultureInfo.InvariantCulture"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message (see <see cref="string.Format(string,object)"/>).</param> /// <param name="args">The arguments.</param> [StringFormatMethod("message")] public static void Error([NotNull] this IScope scope, [NotNull] string message, params object[] args) { scope.Write(RuleLevel.Error, string.Format(CultureInfo.InvariantCulture, message, args)); } /// <summary> Outputs <see cref="RuleLevel.Error"/> /// message into the <paramref name="scope"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message.</param> public static void Error([NotNull] this IScope scope, [NotNull] string message) { scope.Write(RuleLevel.Error, message); } /// <summary> Outputs formatted <see cref="RuleLevel.Warn"/> /// message into the <paramref name="scope"/> using the /// <see cref="CultureInfo.InvariantCulture"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message (see <see cref="string.Format(string,object)"/>).</param> /// <param name="args">The arguments.</param> [StringFormatMethod("message")] public static void Warn([NotNull] this IScope scope, [NotNull] string message, params object[] args) { scope.Write(RuleLevel.Warn, string.Format(CultureInfo.InvariantCulture, message, args)); } /// <summary> Outputs <see cref="RuleLevel.Warn"/> /// message into the <paramref name="scope"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message.</param> public static void Warn([NotNull] this IScope scope, [NotNull] string message) { scope.Write(RuleLevel.Warn, message); } /// <summary> Outputs formatted <see cref="RuleLevel.None"/> /// message into the <paramref name="scope"/> using the /// <see cref="CultureInfo.InvariantCulture"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message (see <see cref="string.Format(string,object)"/>).</param> /// <param name="args">The arguments.</param> [StringFormatMethod("message")] public static void Info([NotNull] this IScope scope, [NotNull] string message, params object[] args) { scope.Write(RuleLevel.None, string.Format(CultureInfo.InvariantCulture, message, args)); } /// <summary> Outputs <see cref="RuleLevel.None"/> /// message into the <paramref name="scope"/> </summary> /// <param name="scope">The scope.</param> /// <param name="message">The message.</param> public static void Info([NotNull] this IScope scope, [NotNull] string message) { scope.Write(RuleLevel.None, message); } /// <summary> Determines whether the specified <paramref name="scope"/> /// is in the <see cref="RuleLevel.Error"/> state. </summary> /// <param name="scope">The scope.</param> /// <returns> /// <c>true</c> if the specified scope is in <see cref="RuleLevel.Error"/> /// state; otherwise, <c>false</c>. /// </returns> public static bool IsError([NotNull] this IScope scope) { return scope.Level >= RuleLevel.Error; } /// <summary> Determines whether the specified <paramref name="scope"/> /// is in the <see cref="RuleLevel.None"/> state. </summary> /// <param name="scope">The scope.</param> /// <returns> /// <c>true</c> if the specified scope is in <see cref="RuleLevel.None"/> /// state; otherwise, <c>false</c>. /// </returns> public static bool IsNone([NotNull] this IScope scope) { return scope.Level == RuleLevel.None; } /// <summary> Determines whether the specified <paramref name="scope"/> /// is in the <see cref="RuleLevel.Warn"/> state. </summary> /// <param name="scope">The scope.</param> /// <returns> /// <c>true</c> if the specified scope is in <see cref="RuleLevel.Warn"/> /// state; otherwise, <c>false</c>. /// </returns> public static bool IsWarn([NotNull] this IScope scope) { return scope.Level >= RuleLevel.Warn; } /// <summary> /// Validates some member using the <paramref name="scopeProvider"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="scopeProvider">The scope provider.</param> /// <param name="item">The item to validate.</param> /// <param name="name">The name of the variable that holds item to validate.</param> /// <param name="rules">The rules to run.</param> public static void Validate<T>(this INamedProvider<IScope> scopeProvider, T item, string name, params Rule<T>[] rules) { if (scopeProvider == null) throw new ArgumentNullException("scopeProvider"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Provided string can't be null or empty", "name"); // item can be null, it will be checked by the validation using (var scope = scopeProvider.Get(name)) { scope.CheckObject(item, rules); } } /// <summary> Validates some member using the provided <paramref name="parentScope"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="item">The item to validate.</param> /// <param name="name">The name of the variable that holds item to validate.</param> /// <param name="rules">The rules to run.</param> public static void Validate<T>(this IScope parentScope, [NotNull] T item, [NotNull] string name, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Provided string can't be null or empty", "name"); // item can be null, it will be checked by the validation using (var scope = parentScope.Create(name)) { scope.CheckObject(item, rules); } } /// <summary> /// Validates some member using the provided <paramref name="parentScope"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="property">The property reference.</param> /// <param name="rules">The rules to run.</param> /// <remarks>For the medium-trust use: <see cref="Validate{TModel,TProperty}"/></remarks> public static void Validate<T>(this IScope parentScope, [NotNull] Func<T> property, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (property == null) throw new ArgumentNullException("reference"); // item can be null, it will be checked by the validation var name = Reflect.MemberName(property); using (var scope = parentScope.Create(name)) { scope.CheckObject(property(), rules); } } /// <summary> /// Validates the member (field or property) using the expressions (compiled and cached statically by runtime). This should work for the medium trust environments (i.e.: ASP.NET MVC). /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TMember">The type of the member.</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="model">The model to validate.</param> /// <param name="memberAccessor">The member accessor expression.</param> /// <param name="rules">The rules.</param> public static void Validate<TModel, TMember>(this IScope parentScope, TModel model, Expression<Func<TModel, TMember>> memberAccessor, params Rule<TMember>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (memberAccessor == null) throw new ArgumentNullException("memberAccessor"); var info = Express.MemberWithLambda(memberAccessor); using (var scope = parentScope.Create(info.Name)) { scope.CheckObject(TypeCache<TModel>.GetMemberValue(model, memberAccessor), rules); } } /// <summary> /// Validates some <see cref="IEnumerable{T}"/> member using the provided <paramref name="parentScope"/>. /// This variant uses expressions (compiled and statically cached for the performance). /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TMember">The type of the member.</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="model">The model to validate.</param> /// <param name="memberAccessor">The member accessor.</param> /// <param name="rules">The rules to run.</param> public static void ValidateMany<TModel, TMember>(this IScope parentScope, TModel model, Expression<Func<TModel,IEnumerable<TMember>>> memberAccessor, params Rule<TMember>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (memberAccessor == null) throw new ArgumentNullException("memberAccessor"); // item can be null, it will be checked by the validation var info = Express.MemberWithLambda(memberAccessor); using (var scope = parentScope.Create(info.Name)) { scope.ValidateInScope(TypeCache<TModel>.GetMemberValue(model, memberAccessor), rules); } } /// <summary> /// Validates some <see cref="IEnumerable{T}"/> member using the provided <paramref name="parentScope"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="propertyReference">Reference to collection property to validate.</param> /// <param name="rules">The rules to run.</param> /// <remarks>For the medium-trust use: <see cref="ValidateMany{TModel,TMember}"/></remarks> public static void ValidateMany<T>(this IScope parentScope, Func<IEnumerable<T>> propertyReference, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (propertyReference == null) throw new ArgumentNullException("propertyReference"); // item can be null, it will be checked by the validation var name = Reflect.MemberName(propertyReference); using (var scope = parentScope.Create(name)) { scope.ValidateInScope(propertyReference(), rules); } } /// <summary> /// Validates some <see cref="IEnumerable{T}"/> member using the provided <paramref name="parentScope"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="items">The collection to validate.</param> /// <param name="name">The name of the variable that holds item to validate.</param> /// <param name="rules">The rules to run.</param> public static void ValidateMany<T>(this IScope parentScope, IEnumerable<T> items, string name, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Provided string can't be null or empty", "name"); // item can be null, it will be checked by the validation using (var scope = parentScope.Create(name)) { scope.ValidateInScope(items, rules); } } /// <summary> /// Validates some <see cref="IEnumerable{T}"/> member using the provided <paramref name="parentScope"/>. /// </summary> /// <typeparam name="T">type of the item to validate</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="items">The collection to validate.</param> /// <param name="name">The name of the variable that holds item to validate.</param> /// <param name="limit">The limit (if collection is bigger, then validation will not continue).</param> /// <param name="rules">The rules to run.</param> public static void ValidateMany<T>(this IScope parentScope, ICollection<T> items, string name, int limit, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Provided string can't be null or empty", "name"); // item can be null, it will be checked by the validation using (var scope = parentScope.Create(name)) { scope.ValidateInScope(items, rules); } } /// <summary> /// Runs the specified rules against the provided object in the current scope /// </summary> /// <typeparam name="T">type of the object being validated</typeparam> /// <param name="scope">The scope.</param> /// <param name="item">The item to validate.</param> /// <param name="rules">The rules to execute.</param> public static void ValidateInScope<T>(this IScope scope, T item, params Rule<T>[] rules) { if (scope == null) throw new ArgumentNullException("scope"); // item can be null, it will be checked by the validation CheckObject(scope, item, rules); } static void CheckObject<T>(this IScope self, T item, params Rule<T>[] rules) { // [abdullin]: I know // ReSharper disable CompareNonConstrainedGenericWithNull if (item == null) // ReSharper restore CompareNonConstrainedGenericWithNull { self.Error("Object of type \'{0}\' should not be null.", typeof (T).Name); } else { foreach (var rule in rules) { rule(item, self); } } } /// <summary> /// Runs validation rules against some some <see cref="IEnumerable{T}"/>. /// </summary> /// <typeparam name="T">type of the items being validated</typeparam> /// <param name="parentScope">The parent scope.</param> /// <param name="items">Collection of the items to validate</param> /// <param name="rules">The rules to run.</param> public static void ValidateInScope<T>(this IScope parentScope, IEnumerable<T> items, params Rule<T>[] rules) { if (parentScope == null) throw new ArgumentNullException("parentScope"); if (items == null) { parentScope.Error("Collection of type \'{0}\' should not be null.", typeof (T).Name); } else { int i = 0; foreach (var item in items) { using (var scope = parentScope.Create("[" + i + "]")) { scope.CheckObject(item, rules); } i += 1; } } } /// <summary> /// Creates a wrapper that lowers the importance of messages /// being passed to the specified <paramref name="scope"/>. /// </summary> /// <param name="scope">The scope to wrap.</param> /// <returns>new instance of the wrapper</returns> public static IScope Lower(this IScope scope) { return new ModifierScope(scope, ModifierScope.Lower); } /// <summary> /// Creates a wrapper that boosts the <see cref="RuleLevel"/> of /// messages being passed to the specified<paramref name="scope"/>. /// </summary> /// <param name="scope">The scope to wrap.</param> /// <returns>new instance of the wrapper</returns> public static IScope Raise(this IScope scope) { return new ModifierScope(scope, ModifierScope.Raise); } } }<file_sep>/Test/Lokad.Shared.Test/RandTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; using System.Linq; // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedMember.Global namespace Lokad { [TestFixture] public sealed class RandTests { [SetUp] public void SetUp() { Rand.ResetToDefault(1); } [TestFixtureTearDown] public void Dispose() { Rand.ResetToDefault(); } public enum Option { No, Yes, Maybe } /// <summary> /// Tests this instance. /// </summary> [Test] public void Test() { Assert.AreEqual(534011718, Rand.Next()); Assert.AreEqual(1, Rand.Next(10)); Assert.AreEqual(34, Rand.Next(30, 40)); Assert.AreEqual(0.77160412202198247d, Rand.NextDouble()); Assert.AreEqual(3, Rand.NextItem(new[] {1, 2, 3, 4})); Assert.AreEqual(Option.Yes, Rand.NextEnum<Option>()); Assert.AreNotEqual(0, Rand.NextString(1, 5).Length); Assert.AreEqual(new Guid("aefd513f-48a7-b49d-b3f3-172961cc2bcb"), Rand.NextGuid()); Assert.AreEqual(new DateTime(590668128477790000), Rand.NextDate()); Assert.AreEqual(new DateTime(633936311847180000), Rand.NextDate(2009, 2010)); Assert.AreEqual(true, Rand.NextBool(1)); Assert.AreEqual(false, Rand.NextBool(0)); Assert.AreEqual(false, Rand.NextBool()); Assert.AreEqual("accusam", Rand.String.NextWord()); Assert.AreEqual("Sed stet amet in invidunt.", Rand.String.NextSentence(1, 6)); var actual = Rand.String.NextText(20,90); Assert.IsTrue(actual.Contains(Environment.NewLine)); Assert.AreEqual(537, actual.Length); Assert.AreEqual(87, actual.Count(c => c==' ')); Assert.AreEqual(new[] { new Guid("df4ddcf6-69a5-8870-5860-e15353afd241"), new Guid("276152fa-f318-d27b-3871-ca2c3c022647"), new Guid("7e1926f3-d485-71aa-6ff0-f25ceb0e691c"), }, Rand.NextGuids(3)); Assert.AreEqual(new[] { new Guid("820f5bd2-a0e3-6002-7ba6-339e434b553a"), new Guid("962d5f99-bb54-a826-f0b8-27011ee62907"), new Guid("a66a7dad-c516-850f-161d-0a2d76d22ca4"), }, Rand.NextGuids(1, 4)); } [Test] public void Next_1() { var array = Range.Array(100, i => Rand.Next(30)); CollectionAssert.Contains(array, 0); } [Test] public void NextItems_shuffles_array_when_all_items_are_selected() { var expected = Range.Array(10); CollectionAssert.AreEquivalent(expected, Rand.NextItems(expected, 10)); } [Test] public void NextItems_returns_subset() { var expected = Range.Array(10); var actual = Rand.NextItems(expected, 5); CollectionAssert.IsSubsetOf(actual, expected); Assert.AreEqual(5,actual.Length); } [Test] public void NextDate() { Assert.LessOrEqual(new DateTime(2008,1,1), Rand.NextDate(2008, 3000)); Assert.Greater(new DateTime(2008,1,1), Rand.NextDate(1900,2008)); } [Test] public void NextEnumWithoutDefault_never_returns_default() { for (int i = 0; i < 10; i++) { Assert.AreNotEqual(Option.No, Rand.NextEnumExceptDefault<Option>()); } } #if !SILVERLIGHT2 public sealed class XmlTestClass { public string Member { get; set; } } [Test] public void NextString_Is_Serializable() { XmlUtil.Serialize(new XmlTestClass { Member = Rand.NextString(10, 1000) }); } #endif //[Test] //public void Next_String() //{ // for (int i = 48; i < 122; i++) // { // Console.WriteLine("'" + ((char)i) + "'"); // } //var range = Enumerable // .Range(char.MinValue, char.MaxValue - char.MinValue) // .Select(i => (char)i); //range // .GroupBy(c => char.GetUnicodeCategory(c)) // .ForEach(g => Console.WriteLine("{0} - {1}", g.Key, g.Count())); //range.Select(c => // { // try // { // XmlUtil.Serialize(new string(c, 1)); // return new { c, Ex = "Good" }; // } // catch (Exception ex) // { // return new { c, Ex = ex.GetType().Name }; // } // }) // .Where(p => p.Ex != "Good") // .GroupBy(p => char.GetUnicodeCategory(p.c)) // .ForEach(g => Console.WriteLine("{0} - {1}", g.Key, g.Count())); //var c1 = range.Where(c => char.IsPunctuation(c)); //Console.WriteLine(new string(c1.ToArray())); //Console.WriteLine("{0},{1}", c1.Min(c => (int)c), c1.Max(c => (int)c)); //} } }<file_sep>/Source/Lokad.Shared/Rules/Scopes/TrackScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// <see cref="IScope"/> that merely keeps track of the worst level. /// </summary> [Serializable] public sealed class TrackScope : IScope { RuleLevel _level; readonly Action<RuleLevel> _report = level => { }; /// <summary> /// Initializes a new instance of the <see cref="TrackScope"/> class. /// </summary> public TrackScope() { } TrackScope(Action<RuleLevel> report) { _report = report; } void IDisposable.Dispose() { _report(_level); } IScope IScope.Create(string name) { return new TrackScope(level => { if (level > _level) _level = level; }); } void IScope.Write(RuleLevel level, string message) { if (level > _level) _level = level; } RuleLevel IScope.Level { get { return _level; } } } }<file_sep>/Test/Lokad.Shared.Test/Tuples/TripleTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class TripleTests { static readonly Tuple<DateTime, int, double> _t1 = new Tuple<DateTime, int, double>(DateTime.MinValue, 1, Math.PI); static readonly Tuple<DateTime, int, double> _t2 = Tuple.From(DateTime.MinValue, 1, Math.PI); static readonly Triple<DateTime, int, double> _t3 = Tuple.From(DateTime.MinValue, 1, Math.E); [Test] public void Test_Equality() { Assert.AreEqual(_t1, _t2); Assert.AreNotEqual(_t1, _t3); } [Test] public void Test_Operators() { Assert.IsTrue(_t1 == _t2, "#1"); Assert.IsTrue(_t1 != _t3, "#2"); } [Test] public void Test_Hash() { var h1 = _t1.GetHashCode(); var h2 = _t2.GetHashCode(); var h3 = _t3.GetHashCode(); Assert.AreNotEqual(0, h1, "#1"); Assert.AreNotEqual(0, h3, "#2"); Assert.AreEqual(h1, h2, "#3"); Assert.AreNotEqual(h2, h3, "#4"); } #if !SILVERLIGHT2 [Test, Ignore] public void Test() { // this test is used as sample only var set = new HashSet<Triple<int, bool, bool>> { Tuple.From(1, true, false), Tuple.From(1, true, true) }; Assert.IsTrue(set.Contains(Tuple.From(1, true, false))); Assert.IsFalse(set.Contains(Tuple.From(2, true, true))); } #endif } }<file_sep>/Test/Lokad.Shared.Test/Utils/VersionUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class VersionUtilTests { [Test] public void Test() { Assert.AreEqual(new Version(1, 0, 0, 0), new Version(1, 0).Normalize()); Assert.AreEqual(new Version(1, 2, 0, 0), new Version(1, 2).Normalize()); Assert.AreEqual(new Version(1, 2, 3, 0), new Version(1, 2, 3).Normalize()); Assert.AreEqual(new Version(1, 2, 3, 4), new Version(1, 2, 3, 4).Normalize()); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/IsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class IsTests { [Test] public void Within_X_Y() { RuleAssert.For(Is.Within(0, 20)) .ExpectNone(0, 12, 20) .ExpectError(-1, 21, int.MaxValue); RuleAssert.For(Is.Within(0D, 20D)) .ExpectNone(0, 12, 20) .ExpectError(-1, 21, int.MaxValue); } [Test] public void Between_X_Y() { RuleAssert.For(Is.Between(0, 20)) .ExpectNone(1, 15, 19) .ExpectError(-1, 0, 20, int.MaxValue); RuleAssert.For(Is.Between(0D, 20D)) .ExpectNone(1, 15, 19) .ExpectError(-1, 0, 20, int.MaxValue); } [Test] public void Default() { RuleAssert.For<Guid>(Is.Default) .ExpectNone(Guid.Empty) .ExpectError(Guid.NewGuid()); RuleAssert.For<int>(Is.Default) .ExpectNone(0) .ExpectError(1, 2); } [Test] public void NotDefault() { RuleAssert.For<Guid>(Is.NotDefault) .ExpectNone(Guid.NewGuid()) .ExpectError(Guid.Empty); RuleAssert.For<double>(Is.NotDefault) .ExpectNone(1, 2) .ExpectError(0, 0D); } [Test] public void NotEqual_X() { RuleAssert.For(Is.NotEqual(Guid.Empty)) .ExpectNone(Guid.NewGuid()) .ExpectError(Guid.Empty); RuleAssert.For(Is.NotEqual(3D)) .ExpectNone(1, 2, Math.PI) .ExpectError(3, 3D); } [Test] public void GreaterThen_X() { RuleAssert.For(Is.GreaterThan(5D)) .ExpectNone(6, 6D, 5.1D) .ExpectError(5, 5D, 2); } [Test] public void LessThan_X() { RuleAssert.For(Is.LessThan(5D)) .ExpectNone(4.9, 4D, 3) .ExpectError(5, 5D, 6); } [Test] public void AtMost_X() { RuleAssert.For(Is.AtMost(5D)) .ExpectNone(-1, 4D, 5D, 5) .ExpectError(5.000001, 6D); } [Test] public void AtLeast_X() { RuleAssert.For(Is.AtLeast(5D)) .ExpectNone(10, 6D, 5D, 5) .ExpectError(4.999999, 4D); } [Test] public void Equal_X() { RuleAssert.For(Is.Equal(Tuple.From(1, 2))) .ExpectNone(Tuple.From(1, 2)) .ExpectError(Tuple.From(2, 1), Tuple.From(3, 4)); } [Test] public void Value_X() { RuleAssert.For(Is.Value(RuleLevel.Error)) .ExpectNone(RuleLevel.Error) .ExpectError(RuleLevel.None, RuleLevel.Warn); } [Test] public void True_X() { RuleAssert.For(Is.True<int>(i => (i > 2) && (i%2 == 0))) .ExpectNone(4, 6) .ExpectError(0, 1, 3, 5); } } }<file_sep>/Source/Lokad.Shared/Monads/Result.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> Helper class for creating <see cref="Result{T}"/> instances </summary> [NoCodeCoverage] [Immutable] public static class Result { /// <summary> Creates success result </summary> /// <typeparam name="TValue">The type of the result.</typeparam> /// <param name="value">The item.</param> /// <returns>new result instance</returns> /// <seealso cref="Result{T}.CreateSuccess"/> [NotNull] public static Result<TValue> CreateSuccess<TValue>([NotNull] TValue value) { return Result<TValue>.CreateSuccess(value); } /// <summary> Creates success result </summary> /// <typeparam name="TValue">The type of the result.</typeparam> /// <param name="value">The item.</param> /// <returns>new result instance</returns> /// <seealso cref="Result{T}.CreateSuccess"/> [Obsolete("Use CreateSuccess instead")] public static Result<TValue> Success<TValue>([NotNull]TValue value) { return CreateSuccess(value); } } }<file_sep>/Test/Lokad.Shared.Test/Threading/WaitForTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if !SILVERLIGHT2 using System; using System.Diagnostics; using System.Linq; using System.Threading; using NUnit.Framework; namespace Lokad.Threading { [TestFixture] public sealed class WaitForTests { // ReSharper disable InconsistentNaming [Test] [ExpectedException(typeof(TimeoutException))] public void Expired_Request_Throws_Timeout_Exception() { Func<int> longRequest = () => { Thread.Sleep(1000); return 1; }; var waitFor = new WaitFor<int>(1.Milliseconds()); waitFor.Run(longRequest); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Non_Expired_Request_Throws_Inner_Exception() { Func<int> request = () => { throw new ArgumentOutOfRangeException(); }; new WaitFor<int>(1.Minutes()).Run(request); } [Test] public void Proper_Request_Returns_Value() { Func<int> request = () => { Thread.Sleep(1); return 1; }; var waitFor = new WaitFor<int>(1.Minutes()); var result = waitFor.Run(request); Assert.AreEqual(1, result); } [Test] public void Closures_Work_Properly() { int counter = 0; Func<int> request = () => counter++; var waitFor = new WaitFor<int>(1.Minutes()); Enumerable.Range(0, 5).ForEach(n => Assert.AreEqual(n, waitFor.Run(request))); Assert.AreEqual(5, counter); } [Test] [Explicit] public void Count_OverHead() { var waitFor = new WaitFor<int>(1.Minutes()); var watch = Stopwatch.StartNew(); const int count = 10000; for (int i = 0; i < count; i++) { waitFor.Run(() => 1); } var ticks = watch.ElapsedTicks; Console.WriteLine("Overhead is {0} ms", TimeSpan.FromTicks(ticks / count).TotalMilliseconds); } private static int LocalStack() { throw new InvalidOperationException("TEST"); } [Test] public void Stack_Is_Persisted() { try { WaitFor<int>.Run(10.Minutes(), LocalStack); } catch (Exception e) { StringAssert.Contains("LocalStack", e.ToString()); } } } } #endif<file_sep>/Source/Lokad.Testing/Testing/Models/TestModelEqualityBuilder.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Lokad.Quality; using Lokad.Rules; #pragma warning disable 1591 namespace Lokad.Testing { /// <summary> /// Builds equality testers for the models, using the provided design hints /// </summary> sealed class TestModelEqualityBuilder : ITestModelEqualityProvider { static readonly string FieldTag = DesignUtil.ConvertTagToString(DesignTag.ImmutableWithFields); static readonly string PropertyTag = DesignUtil.ConvertTagToString(DesignTag.ImmutableWithProperties); readonly ITestModelEqualityProvider _provider; public TestModelEqualityBuilder(ITestModelEqualityProvider provider) { _provider = provider; } public TestModelEqualityDelegate GetEqualityTester(Type type) { var tags = DesignUtil.GetClassDesignTags(type, false); var equatable = typeof(IEquatable<>).MakeGenericType(type); if (equatable.IsAssignableFrom(type)) { // horray, friendly type here var methodInfo = equatable.GetMethod("Equals"); return (scope, t, expected, actual) => { Enforce.That(t == type); bool result; if (TryReferenceCheck(scope, expected, actual, out result)) { return result; } return TestGenericEquality(scope, methodInfo, expected, actual); }; } if (tags.Contains(FieldTag)) { var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); return (scope, t, expected, actual) => { Enforce.That(t == type); bool result; if (TryReferenceCheck(scope, expected, actual, out result)) { return result; } return TestFieldEquality(scope, expected, actual, fields); }; } if (tags.Contains(PropertyTag)) { var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); return (scope, t, expected, actual) => { Enforce.That(t == type); bool result; if (TryReferenceCheck(scope, expected, actual, out result)) { return result; } return TestPropertyEquality(scope, expected, actual, props); }; } if (typeof (ICollection).IsAssignableFrom(type)) { return (scope, t, expected, actual) => { bool result; if (TryReferenceCheck(scope, expected, actual, out result)) { return result; } var first = (ICollection) expected; var second = (ICollection) actual; return TestCollectionEquality(scope, first, second, first.Count, second.Count); }; } if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof (ICollection<>))) { //var elementType = type.GetGenericArguments()[0]; var count = type.GetProperty("Count"); return (scope, t, expected, actual) => { bool result; if (TryReferenceCheck(scope, expected, actual, out result)) { return result; } var firstCount = Convert.ToInt32(count.GetValue(expected, null)); var secondCount = Convert.ToInt32(count.GetValue(actual, null)); return TestCollectionEquality(scope, (IEnumerable) expected, (IEnumerable) actual, firstCount, secondCount); }; } return (scope1, t, one1, two1) => TestSimpleEquality(scope1, one1, two1); } bool TestFieldEquality(IScope scope, object one, object another, IEnumerable<FieldInfo> fields) { bool equals = true; foreach (var fieldInfo in fields) { var type = fieldInfo.FieldType; var v1 = fieldInfo.GetValue(one); var v2 = fieldInfo.GetValue(another); using (var child = scope.Create(fieldInfo.Name)) { var equality = _provider.GetEqualityTester(type); var localEquality = equality(child, type, v1, v2); if (!localEquality) { equals = false; //child.Error("Expected field '{0}' was '{1}'", v1, v2); } } } return equals; } bool TestPropertyEquality(IScope scope, object expected, object actual, PropertyInfo[] props) { bool equals = true; foreach (var fieldInfo in props) { var type = fieldInfo.PropertyType; var v1 = fieldInfo.GetValue(expected, null); var v2 = fieldInfo.GetValue(actual, null); using (var child = scope.Create(fieldInfo.Name)) { var tester = _provider.GetEqualityTester(type); var localEquality = tester(child, type, v1, v2); if (!localEquality) { equals = false; //child.Error("Expected property '{0}' was '{1}'", v1, v2); } } } return equals; } static bool TryReferenceCheck(IScope scope, object expected, object actual, out bool result) { var expectedIsNull = ReferenceEquals(expected, null); var actualIsNull = ReferenceEquals(actual, null); if (expectedIsNull && actualIsNull) { result = true; return true; } if (expectedIsNull || actualIsNull) { var expectedString = expectedIsNull ? "<null>" : expected.GetType().Name; var actualString = actualIsNull ? "<null>" : actual.GetType().Name; result = false; scope.Error("Expected {0} was {1}", expectedString, actualString); return true; } result = false; return false; } bool TestCollectionEquality(IScope scope, IEnumerable expected, IEnumerable actual, int count1, int count2) { if (count1 != count2) { scope.Error("Expected ICollection count {0} was {1}", count1, count2); return false; } if (count1 == 0) { return true; } var e1 = expected.GetEnumerator(); var e2 = actual.GetEnumerator(); bool equals = true; for (int i = 0; i < count1; i++) { e1.MoveNext(); e2.MoveNext(); using (var child = scope.Create("[" + i + "]")) { bool result; if (TryReferenceCheck(child, e1.Current, e2.Current, out result)) { equals |= result; } else { var t1 = e1.Current.GetType(); var t2 = e2.Current.GetType(); if (t1 != t2) { scope.Error("Expected '{0}' was '{1}'", t1, t2); equals = false; } else { var tester = _provider.GetEqualityTester(t1); if (!tester(child, t1, e1.Current, e2.Current)) { equals = false; } } } } } return equals; } static bool TestGenericEquality(IScope scope, MethodInfo info, object expected, object actual) { var o = info.Invoke(expected, new[] {actual}); var result = Convert.ToBoolean(o); if (!result) { scope.Error("Expected IEquatable<T> '{0}' was '{1}'.", expected, actual); } return result; } static bool TestSimpleEquality(IScope scope, object expected, object actual) { var result = expected.Equals(actual); if (!result) { scope.Error("Object equality failed. Expected '{0}' was '{1}'.", expected, actual); } return result; } } }<file_sep>/Test/Lokad.Shared.Test/Utils/SystemUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class SystemUtilTests { // ReSharper disable InconsistentNaming [TearDown] public void TearDown() { SystemUtil.Reset(); } [Test] public void Fixed_Now() { var now = SystemUtil.Now; SystemUtil.SetDateTimeProvider(() => DateTime.MaxValue); Assert.AreNotEqual(now, SystemUtil.Now); Assert.AreEqual(SystemUtil.Now, SystemUtil.Now); } [Test] public void Utc_diff() { var time = DateTime.Now; var diff = time - time.ToUniversalTime(); SystemUtil.SetTime(DateTime.Now); Assert.AreEqual(diff, SystemUtil.Now - SystemUtil.UtcNow); } [Test] public void Utc_diff_offset() { var now1Local = DateTime.Now; var diff1 = now1Local - now1Local.ToUniversalTime(); var now2 = SystemUtil.NowOffset; var now2Local = now2.DateTime; var now2Utc = now2.UtcDateTime; Assert.AreEqual(diff1, now2Local - now2Utc); Assert.AreEqual(TimeSpan.Zero, new DateTimeOffset(now2Local) - new DateTimeOffset(now2Utc)); Assert.AreEqual(now2, new DateTimeOffset(now2Local)); Assert.AreEqual(now2, new DateTimeOffset(now2Utc)); } [Test] public void Normal_Now() { var time0 = DateTime.Now; var time1 = SystemUtil.Now; var time2 = DateTime.Now; Assert.IsTrue(time0 <= time1 && time1 <= time2); } [Test] public void Normal_UtcNow() { var time0 = DateTime.UtcNow; var time1 = SystemUtil.UtcNow; var time2 = DateTime.UtcNow; Assert.IsTrue(time0 <= time1 && time1 <= time2); } [Test] public void Test_Sleep() { SystemUtil.Sleep(TimeSpan.FromMilliseconds(0)); var flag = false; SystemUtil.SetSleep(s => { Assert.AreEqual(1.Seconds(), s); flag = true; }); SystemUtil.Sleep(1.Seconds()); Assert.IsTrue(flag); } [Test] public void GetHashCode_works_with_nulls() { SystemUtil.GetHashCode("test", null); } } }<file_sep>/Source/Lokad.Shared/Reflection/Reflect.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; using System.Reflection.Emit; namespace Lokad.Reflection { /// <summary> /// Helper class for the IL-based strongly-typed reflection /// </summary> /// <remarks>This class is not supported by Silverlight 2.0, yet</remarks> public static class Reflect { static readonly byte Ldarg_0 = (byte) OpCodes.Ldarg_0.Value; static readonly byte Ldfld = (byte) OpCodes.Ldfld.Value; static readonly byte Ldflda = (byte) OpCodes.Ldflda.Value; static readonly byte Constrained = (byte) OpCodes.Constrained.Value; static readonly byte Stloc_0 = (byte) OpCodes.Stloc_0.Value; static readonly byte CallVirt = (byte) OpCodes.Callvirt.Value; static readonly byte Ret = (byte) OpCodes.Ret.Value; static Maybe<string> MemberNameSafely<T>(Func<T> expression) { #if SILVERLIGHT2 return Maybe<string>.Empty; #else return Member(expression).Combine(x => GetNameForMember(x)); #endif } internal static string MemberName<T>(Func<T> expression) { return MemberNameSafely(expression).GetValue(ReflectCache<T>.ReferenceName); } static Maybe<string> GetNameForMember(MemberInfo member) { switch (member.MemberType) { case MemberTypes.Field: return member.Name; case MemberTypes.Method: var name = member.Name; if (!name.StartsWith("get_")) return Maybe<string>.Empty; return name.Remove(0, 4); default: return Maybe<string>.Empty; } } internal static string VariableName<T>(Func<T> expression) { return VariableNameSafely(expression).GetValue(ReflectCache<T>.ReferenceName); } static Maybe<string> VariableNameSafely<T>(Func<T> expression) { #if SILVERLIGHT2 return Maybe<string>.Empty; #else return VariableSafely(expression) .Convert(e => e.Name); #endif } #if !SILVERLIGHT2 /// <summary> /// Retrieves via IL the information of the <b>local</b> variable passed in the expression. /// <code> /// var myVar = "string"; /// var info = Reflect.Variable(() =&gt; myVar) /// </code> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression">The expression containing the local variable to reflect.</param> /// <returns>information about the variable (if able to retrieve)</returns> /// <exception cref="ReflectLambdaException">if the provided expression is not a simple variable reference</exception> public static FieldInfo Variable<T>(Func<T> expression) { return VariableSafely(expression) .ExposeException(() => new ReflectLambdaException("Expected simple variable reference")); } /// <summary> /// Retrieves via IL the information of the <b>local</b> variable passed in the expression. /// <code> /// var myVar = "string"; /// var info = Reflect.Variable(() =&gt; myVar) /// </code> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression">The expression containing the local variable to reflect.</param> /// <returns>information about the variable (if able to retrieve)</returns> public static Maybe<FieldInfo> VariableSafely<T>(Func<T> expression) { Enforce.Argument(() => expression); var method = expression.Method; var body = method.GetMethodBody(); if (null == body) return Maybe<FieldInfo>.Empty; var il = body.GetILAsByteArray(); // in DEBUG we end up with stack // in release, there is a ret at the end if ((il[0] == Ldarg_0) && (il[1] == Ldfld) && ((il[6] == Stloc_0) || (il[6] == Ret))) { var fieldHandle = BitConverter.ToInt32(il, 2); var module = method.Module; var expressionType = expression.Target.GetType(); if (!expressionType.IsGenericType) { return module.ResolveField(fieldHandle); } var genericTypeArguments = expressionType.GetGenericArguments(); // method does not have any generics //var genericMethodArguments = method.GetGenericArguments(); return module.ResolveField(fieldHandle, genericTypeArguments, Type.EmptyTypes); } return Maybe<FieldInfo>.Empty; } /// <summary> /// Retrieves via IL the <em>getter method</em> for the property being reflected. /// <code> /// var i2 = new /// { /// MyProperty = "Value" /// }; /// var info = Reflect.Property(() => i2.Property); /// // info will have name of "get_MyProperty" /// </code> /// </summary> /// <typeparam name="T">type of the property to reflect</typeparam> /// <param name="expression">The expression.</param> /// <returns>getter method for the property.</returns> /// <exception cref="ReflectLambdaException">if reference is not a simple property</exception> public static MethodInfo Property<T>(Func<T> expression) { return PropertySafely(expression) .ExposeException(() => new ReflectLambdaException("Expected simple property reference")); } /// <summary> /// Retrieves via IL the <em>getter method</em> for the property being reflected. /// <code> /// var i2 = new /// { /// MyProperty = "Value" /// }; /// var info = Reflect.Property(() => i2.Property); /// // info will have name of "get_MyProperty" /// </code> /// </summary> /// <typeparam name="T">type of the property to reflect</typeparam> /// <param name="expression">The expression.</param> /// <returns>getter method for the property.</returns> public static Maybe<MethodInfo> PropertySafely<T>(Func<T> expression) { return DelegatedPropertySafely(expression); } static Maybe<MemberInfo> Member<T>(Func<T> expression) { return DelegatedMember(expression); } // in DEBUG we end up with stack // in release, there is a ret at the end static Maybe<MethodInfo> DelegatedPropertySafely(Delegate expression) { var method = expression.Method; var body = method.GetMethodBody(); if (null == body) return Maybe<MethodInfo>.Empty; var il = body.GetILAsByteArray(); if ((il[0] == Ldarg_0) && (il[1] == Ldfld) && (il[6] == CallVirt) && ((il[11] == Stloc_0) || (il[11] == Ret))) { var getHandle = BitConverter.ToInt32(il, 7); return (MethodInfo) method.Module.ResolveMethod(getHandle); } if ((il[0] == Ldarg_0) && (il[1] == Ldflda) && (il[6] == 0xfe) && (il[7] == Constrained) && (il[12] == CallVirt) && ((il[17] == Stloc_0) || (il[17] == Ret))) { var getHandle = BitConverter.ToInt32(il, 13); return (MethodInfo) method.Module.ResolveMethod(getHandle); } return Maybe<MethodInfo>.Empty; //throw new ArgumentException("Expected simple property reference"); } static Maybe<MemberInfo> DelegatedMember(Delegate expression) { var method = expression.Method; var body = method.GetMethodBody(); if (null == body) return Maybe<MemberInfo>.Empty; var il = body.GetILAsByteArray(); if ((il[0] == Ldarg_0) && (il[1] == Ldfld) && ((il[6] == CallVirt) || (il[6] == Ldfld)) && ((il[11] == Stloc_0) || (il[11] == Ret))) { var getHandle = BitConverter.ToInt32(il, 7); return method.Module.ResolveMember(getHandle); } return Maybe<MemberInfo>.Empty; //throw new ArgumentException("Expected simple member reference"); } #endif } }<file_sep>/Source/Lokad.ActionPolicy/Exceptions/RetryStateWithSleep.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Quality; namespace Lokad.Exceptions { [Immutable] sealed class RetryStateWithSleep : IRetryState { readonly IEnumerator<TimeSpan> _enumerator; readonly Action<Exception, TimeSpan> _onRetry; public RetryStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Action<Exception, TimeSpan> onRetry) { _onRetry = onRetry; _enumerator = sleepDurations.GetEnumerator(); } public bool CanRetry(Exception ex) { if (_enumerator.MoveNext()) { var current = _enumerator.Current; _onRetry(ex, current); SystemUtil.Sleep(current); return true; } return false; } } }<file_sep>/Test/Lokad.Shared.Test/Extensions/ExtendStreamTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; namespace Lokad { #if !SILVERLIGHT2 [TestFixture] public sealed class ExtendStreamTests { // ReSharper disable InconsistentNaming [Test] public void Pump() { var list = Enumerable.Range(0, 1000).ToList(); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, list); stream.Seek(0, SeekOrigin.Begin); using (var target = new MemoryStream()) { stream.PumpTo(target, 20); target.Seek(0, SeekOrigin.Begin); var list1 = formatter.Deserialize(target) as List<int>; CollectionAssert.AreEqual(list, list1); } formatter.Serialize(stream, list); } } [Test] public void Compression_with_opened_streams() { var array = Range.Array(10); using (var stream = new MemoryStream()) { using (var compress = stream.Compress(true)) { XmlUtil.SerializeArray(array, compress); } stream.Seek(0, SeekOrigin.Begin); using (var decompress = stream.Decompress(true)) { var i = XmlUtil<int[]>.Deserialize(decompress); CollectionAssert.AreEqual(array, i); } } } [Test] public void Default_compression() { var array = Range.Array(10); byte[] buffer; using (var stream = new MemoryStream()) { using (var compress = stream.Compress()) { XmlUtil.SerializeArray(array, compress); } buffer = stream.ToArray(); } using (var stream = new MemoryStream(buffer)) using (var decompress = stream.Decompress()) { var i = XmlUtil<int[]>.Deserialize(decompress); CollectionAssert.AreEqual(array, i); } } } #endif }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/DateIsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class DateIsTests { [Test] public void Test() { RuleAssert.For<DateTime>(DateIs.SqlCompatible) .ExpectNone(new DateTime(1753, 1, 1), DateTime.MaxValue) .ExpectError(DateTime.MinValue, new DateTime(1753, 1, 1).AddSeconds(-1)); } } }<file_sep>/Source/Lokad.Shared/Rules/RuleMessages.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Collections.ObjectModel; namespace Lokad.Rules { /// <summary> /// Collection of messages with the associated highest level /// </summary> public sealed class RuleMessages : ReadOnlyCollection<RuleMessage> { readonly RuleLevel _level; internal static readonly RuleMessages Empty = new RuleMessages(new List<RuleMessage>(0), RuleLevel.None); internal RuleMessages(IList<RuleMessage> list, RuleLevel level) : base(list) { _level = level; } /// <summary> /// The highest level within the collection /// </summary> /// <value>The level.</value> public RuleLevel Level { get { return _level; } } /// <summary> /// Gets a value indicating whether this instance has a message /// of <see cref="RuleLevel.Error"/> or higher. /// </summary> /// <value><c>true</c> if this instance has message of /// <see cref="RuleLevel.Error"/> or higher ; otherwise, <c>false</c>.</value> public bool IsError { get { return _level >= RuleLevel.Error; } } /// <summary> /// Gets a value indicating whether this instance has a message /// of <see cref="RuleLevel.Warn"/> or higher. /// </summary> /// <value><c>true</c> if this instance has message of /// <see cref="RuleLevel.Warn"/> or higher ; otherwise, <c>false</c>.</value> public bool IsWarn { get { return _level >= RuleLevel.Warn; } } /// <summary> /// Gets a value indicating whether this instance does not have any messages /// of <see cref="RuleLevel.Warn"/> or higher /// </summary> /// <value> /// <c>true</c> if this instance does not have any messages /// of <see cref="RuleLevel.Warn"/> or higher; otherwise, <c>false</c>. /// </value> public bool IsSuccess { get { return _level < RuleLevel.Warn; } } } }<file_sep>/Source/Lokad.Logging/ILog.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Shared interface to abstract away from the specific /// logging library /// </summary> public interface ILog { /// <summary> Writes the message to the logger </summary> /// <param name="level">The importance level</param> /// <param name="message">The actual message</param> void Log(LogLevel level, object message); /// <summary> /// Writes the exception and associated information /// to the logger /// </summary> /// <param name="level">The importance level</param> /// <param name="ex">The actual exception</param> /// <param name="message">Information related to the exception</param> void Log(LogLevel level, Exception ex, object message); /// <summary> /// Determines whether the messages of specified level are being logged down /// </summary> /// <param name="level">The level.</param> /// <returns> /// <c>true</c> if the specified level is logged; otherwise, <c>false</c>. /// </returns> bool IsEnabled(LogLevel level); } }<file_sep>/Source/Lokad.ActionPolicy/Exceptions/RetryPolicy.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Exceptions { static class RetryPolicy { internal static void Implementation(Action action, ExceptionHandler canRetry, Func<IRetryState> stateBuilder) { var state = stateBuilder(); while (true) { try { action(); return; } catch (Exception ex) { if (!canRetry(ex)) { throw; } if (!state.CanRetry(ex)) { throw; } } } } } }<file_sep>/Host/Lokad.Linker/Program.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; using Lokad.Quality; using Mono.Cecil; namespace Lokad.Linker { class Program { static void Main(string[] args) { // dependency chain var inputName = args[0]; var oldName = args[1]; var linkedName = args[2]; var outputName = args[3]; var linked = AssemblyFactory.GetAssembly(linkedName); var target = AssemblyFactory.GetAssembly(inputName); var old = AssemblyFactory.GetAssembly(oldName); foreach (var module in target.GetModules()) { var obsolete = module .GetAssemblyReferences(old.Name.FullName) .ToArray(); foreach (var reference in obsolete) { reference.Name = linked.Name.Name; reference.Hash = linked.Name.Hash; reference.Version = linked.Name.Version; reference.PublicKeyToken = linked.Name.PublicKeyToken; } } AssemblyFactory.SaveAssembly(target, outputName); } } public static class Pending { public static IEnumerable<AssemblyNameReference> GetAssemblyReferences(this ModuleDefinition module, string fullName) { return module.GetAssemblyReferences().Where(nr => nr.FullName == fullName); } } }<file_sep>/Test/Lokad.Logging.Test/ILogExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Diagnostics; using Lokad.Rules; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ILogExtensionsTests { [Test] public void UseCases() { var log = NullLog.Instance; var ex = new Exception(); const int id = 0; log.Debug("Message"); log.Debug(ex, "Message with exception"); log.DebugFormat("Message #{0}", id); log.DebugFormat(ex, "Message #{0}", id); RuleAssert.IsFalse(() => log.IsDebugEnabled()); log.Warn("Message"); log.Warn(ex, "Message with exception"); log.WarnFormat("Message #{0}", id); log.WarnFormat(ex, "Message #{0}", id); RuleAssert.IsFalse(() => log.IsWarnEnabled()); log.Info("Message"); log.Info(ex, "Message with exception"); log.InfoFormat("Message #{0}", id); log.InfoFormat(ex, "Message #{0}", id); RuleAssert.IsFalse(() => log.IsInfoEnabled()); log.Error("Message"); log.Error(ex, "Message with exception"); log.ErrorFormat("Message #{0}", id); log.ErrorFormat(ex, "Message #{0}", id); RuleAssert.IsFalse(() => log.IsErrorEnabled()); log.Fatal("Message"); log.Fatal(ex, "Message with exception"); log.FatalFormat("Message #{0}", id); log.FatalFormat(ex, "Message #{0}", id); RuleAssert.IsFalse(() => log.IsFatalEnabled()); } } }<file_sep>/Test/Lokad.Shared.Test/Utils/ArrayUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ArrayUtilTests { [Test] public void IsNullOrEmpty_Works() { Assert.IsTrue(ArrayUtil.IsNullOrEmpty(null)); Assert.IsTrue(ArrayUtil.IsNullOrEmpty(new int[0])); Assert.IsFalse(ArrayUtil.IsNullOrEmpty(Enumerable.Repeat(1, 1).ToArray())); } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/StringFormatMethodAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. /// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form /// </summary> /// <remarks> /// This attribute helps R# in code analysis /// </remarks> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class StringFormatMethodAttribute : Attribute { readonly string _formatParameterName; /// <summary> /// Initializes new instance of StringFormatMethodAttribute /// </summary> /// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param> public StringFormatMethodAttribute(string formatParameterName) { _formatParameterName = formatParameterName; } /// <summary> /// Gets format parameter name /// </summary> public string FormatParameterName { get { return _formatParameterName; } } } }<file_sep>/Source/Lokad.Shared/Currency/CurrencyType.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad { ///<summary> /// Currency types supported by the Lokad business ///</summary> ///<remarks> /// Hardcoded for simplicity, but could be switched to string codes, if needed. ///</remarks> public enum CurrencyType { /// <summary> /// Undefined currency /// </summary> /// <remarks>this must be default!</remarks> None = 0x00, /// <summary> /// EUR /// </summary> Eur, /// <summary> /// American Dollar /// </summary> Usd, /// <summary> /// Australian dollar /// </summary> Aud, /// <summary> /// Canadian dollar /// </summary> Cad, /// <summary> /// Swiss franc /// </summary> Chf, /// <summary> /// Pound sterling /// </summary> Gbp, /// <summary> /// Japanese yen /// </summary> Jpy, /// <summary> /// Russian ruble /// </summary> Rub, /// <summary> /// Mexican Peso /// </summary> Mxn } }<file_sep>/Source/Lokad.Shared/ICommand.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad { /// <summary> /// Generic interface for the command pattern. /// </summary> public interface ICommand { /// <summary> /// Encapsulates action /// </summary> void Execute(); } }<file_sep>/Source/Lokad.Shared/Rules/IScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// Concept from the xLim2. That's simple nesting logger that is used by /// the validation rules. /// </summary> /// <remarks> /// <para>It has logical the extensibility (not implemented, because there /// does not seem to be any need) for maintaining the error level in /// attached and detached scopes. Warnings, Fatals or Info messages /// could be added here (full ILogScope if needed).</para> /// <para> Same extensibility /// could be turned on for capturing detailed validation info on complex /// long-running validation scenarios (you'd hate to debug these). </para> /// <para> Note, that in order to maintain .NET 2.0 compatibility, /// is is recommended to use interface-declared methods instead of the /// extensions (or use some extension weaver).</para> /// </remarks> public interface IScope : IDisposable { /// <summary> /// Creates the nested scope with the specified name. /// </summary> /// <param name="name">New name for the nested scope.</param> /// <returns>Nested (and linked) scope instance</returns> IScope Create(string name); /// <summary> /// Writes <paramref name="message"/> with the specified /// <paramref name="level"/> to the <see cref="IScope"/> /// </summary> /// <param name="level">The level.</param> /// <param name="message">The message.</param> void Write(RuleLevel level, string message); /// <summary> /// Gets the current <see cref="RuleLevel"/> of this scope /// </summary> /// <value>The level.</value> RuleLevel Level { get; } // used for complex multi-step integration scenarios // IScope CreateDetached(string name) } }<file_sep>/Test/Lokad.Shared.Test/Threading/ParallelExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Diagnostics; using NUnit.Framework; namespace Lokad.Threading { [TestFixture] public sealed class ParallelExtensionsTests { // ReSharper disable InconsistentNaming [Test] public void SelectInParallel_for_empty_array() { var results = (new int[0]).SelectInParallel(i => 2*i); CollectionAssert.IsEmpty(results); } [Test] public void SelectInParallel_for_array() { var results = Range .Array(10, i => i) .SelectInParallel(i => i*2); CollectionAssert.AreEquivalent(results, Range.Array(10, i => i*2)); } [Test] public void SelectInParallel_Exception() { try { Range.Array(10) .SelectInParallel(i => { if (i == 5) throw new InvalidOperationException("Part of the test."); return i*2; }); Assert.Fail(); } catch (Exception ex) { Assert.IsInstanceOfType(typeof(InvalidOperationException), ex.InnerException, "Unexpected ex: {0}", ex.ToString()); } } [Test] public void SelectInParallel_SmokeTest() { var results = Range .Array(100, i => i) .SelectInParallel(i => i*2); CollectionAssert.AreEquivalent(results, Range.Array(100, i => i*2)); } [Test] public void SelectInParallel_is_ordered() { const int count = 100000; var results = Range.Array(count).SelectInParallel(i => i * 2); for (int i = 0; i < count; i++) { Assert.AreEqual(i*2, results[i], "#A00"); } } #if !SILVERLIGHT2 [Test, Explicit] public void ContextTesting() { const int outerCount = 100000; Func<int, double> operation = i => { double val = 0; var limit = Rand.Next(5000, 10000); for (int j = 0; j < limit; j++) { val = Math.Sin(val + j); } return val; }; using (Counter("Lokad")) { Range .Array(outerCount) .SelectInParallel(operation); } var wait = new WaitFor<double>(2.Seconds()); using (Counter("Lokad+WaitFor")) { Range .Array(outerCount) .SelectInParallel(i => wait.Run(() => operation(i))); } } static IDisposable Counter(string name) { var watch = Stopwatch.StartNew(); return new DisposableAction(() => Console.WriteLine("'{0}' took {1}", name, watch.Elapsed)); } #endif [Test, Explicit] public void Test() { Console.WriteLine("CPUcount: {0}", Environment.ProcessorCount); var watch = Stopwatch.StartNew(); var work = Range.Array(10, i => i); var parallel = work.SelectInParallel(span => { SystemUtil.Sleep(span.Seconds()); return string.Format("This operation took {0} seconds", span); }); foreach (var span in parallel) { Console.WriteLine("@{0}s: {1}", watch.Elapsed.TotalSeconds.Round(2), span); } Console.WriteLine("Total running time: {0}", watch.Elapsed); } } }<file_sep>/Source/Lokad.Shared/Quality/ClassDesignAttribute.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq; namespace Lokad.Quality { /// <summary> /// Base attribute for marking classes with some design constraints /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] public class ClassDesignAttribute : Attribute { readonly string[] _classDesignTags; /// <summary> /// Gets the class design tags. /// </summary> /// <value>The class design tags.</value> [UsedImplicitly] public string[] ClassDesignTags { get { return _classDesignTags; } } /// <summary> /// Initializes a new instance of the <see cref="ClassDesignAttribute"/> class. /// </summary> /// <param name="designTags">The design tags.</param> public ClassDesignAttribute(params string[] designTags) { _classDesignTags = designTags; } /// <summary> /// Initializes a new instance of the <see cref="ClassDesignAttribute"/> class. /// </summary> /// <param name="classDesignTag">The class design tag.</param> public ClassDesignAttribute(string classDesignTag) { Enforce.ArgumentNotEmpty(() => classDesignTag); _classDesignTags = new [] { classDesignTag }; } /// <summary> /// Initializes a new instance of the <see cref="ClassDesignAttribute"/> class. /// </summary> /// <param name="designTag">The design tag.</param> public ClassDesignAttribute(DesignTag designTag) { _classDesignTags = new[] {DesignUtil.ConvertTagToString(designTag)}; } /// <summary> /// Initializes a new instance of the <see cref="ClassDesignAttribute"/> class. /// </summary> /// <param name="designTags">The design tags.</param> public ClassDesignAttribute(params DesignTag[] designTags) { _classDesignTags = designTags .ToArray(DesignUtil.ConvertTagToString); } } }<file_sep>/Source/Lokad.Shared/Quality/DesignTag.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Quality { /// <summary> /// Predefined class design tags /// </summary> public enum DesignTag { /// <summary>Undefined</summary> Undefined, /// <summary> /// The object is a data model /// </summary> Model, /// <summary> /// The object is immutable, using readonly fields /// </summary> ImmutableWithFields, /// <summary> /// The object is immutable, using properties with private setters /// </summary> ImmutableWithProperties, } }<file_sep>/Source/Lokad.Shared/Serialization/IDataContractMapper.cs using System; namespace Lokad.Serialization { /// <summary> /// Class responsible for mapping types to contracts and vise-versa /// </summary> public interface IDataContractMapper { /// <summary> /// Gets the contract name by the type /// </summary> /// <param name="messageType">Type of the message.</param> /// <returns>contract name (if found)</returns> Maybe<string> GetContractNameByType(Type messageType); /// <summary> /// Gets the type by contract name. /// </summary> /// <param name="contractName">Name of the contract.</param> /// <returns>type that could be used for contract deserialization (if found)</returns> Maybe<Type> GetTypeByContractName(string contractName); } }<file_sep>/Source/Lokad.Shared/KeyInvalidException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; using Lokad.Quality; namespace Lokad { /// <summary> /// This exception is thrown when the key is not valid (i.e.: not found) /// </summary> /// <remarks> TODO: add proper implementation.</remarks> [Serializable] [NoCodeCoverage] public class KeyInvalidException : Exception { /// <summary> /// Initializes a new instance of the <see cref="KeyInvalidException"/> class. /// </summary> public KeyInvalidException() { } /// <summary> /// Initializes a new instance of the <see cref="KeyInvalidException"/> class. /// </summary> /// <param name="message">The message.</param> public KeyInvalidException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="KeyInvalidException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public KeyInvalidException(string message, Exception inner) : base(message, inner) { } #if !SILVERLIGHT2 /// <summary> /// Initializes a new instance of the <see cref="KeyInvalidException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="info"/> parameter is null. /// </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException"> /// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). /// </exception> protected KeyInvalidException( SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }<file_sep>/Test/Lokad.Shared.Test/MaybeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class MaybeTests { // ReSharper disable InconsistentNaming [Test] [Expects.ArgumentNullException] public void Nullables_are_detected() { const object o = null; Maybe.From(o); } [Test] [Expects.InvalidOperationException] public void Empty_protects_value() { Assert.IsFalse(Maybe<int>.Empty.HasValue); Assert.Fail(Maybe<int>.Empty.Value.ToString()); } [Test] public void Implicit_conversion() { Maybe<int> maybe = 10; Assert.IsTrue(maybe.HasValue); Assert.AreEqual(10, maybe.Value); } [Test] public void Apply1() { Maybe<int>.Empty.Apply(i => Assert.Fail()); int applied = 0; Maybe10.Apply(i => applied = i); Assert.AreEqual(10, applied); } static readonly Maybe<int> Maybe10 = 10; static readonly Maybe<int> MaybeEmpty = Maybe<int>.Empty; [Test] public void GetValue() { Assert.AreEqual(4, MaybeEmpty.GetValue(4)); Assert.AreEqual(10, Maybe10.GetValue(4)); Assert.AreEqual(4, MaybeEmpty.GetValue(() => 4)); Assert.AreEqual(10, Maybe10.GetValue(() => 4)); Assert.AreEqual(4, MaybeEmpty.GetValue(MaybeEmpty).GetValue(4)); Assert.AreEqual(10, Maybe10.GetValue(Maybe10).GetValue(4)); Assert.AreEqual(4, MaybeEmpty.GetValue(() => MaybeEmpty).GetValue(() => 4)); Assert.AreEqual(10, Maybe10.GetValue(() => Maybe10).GetValue(() => 4)); } [Test] public void Convert() { Assert.AreEqual(Maybe.From("10"), Maybe10.Convert(i => i.ToString())); Assert.AreEqual(Maybe<string>.Empty, MaybeEmpty.Convert(i => i.ToString())); Assert.AreEqual("10", Maybe10.Convert(i => i.ToString(), () => "none")); Assert.AreEqual("none", MaybeEmpty.Convert(i => i.ToString(), () => "none")); Assert.AreEqual("10", Maybe10.Convert(i => i.ToString(), "none")); Assert.AreEqual("none", MaybeEmpty.Convert(i => i.ToString(), "none")); } [Test] public void Combine() { Maybe10.Combine(v => SayHi(v)).ShouldFail(); MaybeEmpty.Combine(v => SayHi(v)).ShouldFail(); Maybe.From(2).Combine(v => SayHi(v)).ShouldBe("Hi x 2"); } static Maybe<string> SayHi(int value) { if (value > 3) return Maybe<string>.Empty; return "Hi x " + value; } [Test] public void Equals() { Assert.IsTrue(Maybe10 == Maybe.From(10)); Assert.IsTrue(Maybe10 != MaybeEmpty); } [Test] public void Check_GetHashCode() { Assert.AreEqual(Maybe10.GetHashCode(), Maybe.From(10).GetHashCode()); } static void Throw() { throw new InvalidOperationException(); } [Test] public void Handle_and_apply() { var i = 0; Maybe10 .Handle(Throw) .Apply(x => i = x) .Handle(Throw); Assert.AreEqual(Maybe10.Value, i); } [Test, Expects.InvalidOperationException] public void Exposing1() { MaybeEmpty.ExposeException("Fail"); } [Test, ExpectedException(typeof(KeyInvalidException))] public void Exposing2() { MaybeEmpty.ExposeException(() => new KeyInvalidException("Key has invalid value")); } [Test] public void Exposing_Valid() { Maybe10 .ExposeException("Fail") .ShouldBeEqualTo(10); Maybe10 .ExposeException(() => new KeyInvalidException("Key has invalid value")) .ShouldBeEqualTo(10); } [Test] public void Join() { Maybe10.JoinMessage("Failed").ShouldBe(10); MaybeEmpty.JoinMessage("Failed").ShouldBe("Failed"); Maybe10.Join(SomeFailure.Fail).ShouldBe(10); MaybeEmpty.Join(SomeFailure.Fail).ShouldBe(SomeFailure.Fail); } [Test] public void Equations() { Maybe<DateTime> m1 = SystemUtil.UtcNow; Maybe<DateTime> m2 = Maybe<DateTime>.Empty; Assert.IsTrue(m1.EqualsTo(m1)); Assert.IsTrue(m2.EqualsTo(m2)); Assert.IsFalse(m1.EqualsTo(m2)); Assert.IsFalse(m2.EqualsTo(m1)); } enum SomeFailure { None,Fail } } }<file_sep>/Source/Lokad.Shared/IStartable.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Generic interface for marking startable classes. Opposite for the <see cref="IDisposable"/> /// </summary> public interface IStartable { /// <summary> /// Starts this instance up. /// </summary> void StartUp(); } }<file_sep>/Source/Lokad.Shared/Serialization/BinaryMessageSerializer.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Lokad.Quality; namespace Lokad.Serialization { /// <summary> /// Message serializer that uses <see cref="BinaryFormatter"/>. It is recommended to user ProtocolBuffers instead. /// </summary> [UsedImplicitly] public sealed class BinaryMessageSerializer : IMessageSerializer { readonly BinaryFormatter _formatter = new BinaryFormatter(); /// <summary> /// Serializes the object to the specified stream /// </summary> /// <param name="instance">The instance.</param> /// <param name="destinationStream">The destination stream.</param> public void Serialize(object instance, Stream destinationStream) { _formatter.Serialize(destinationStream, instance); } /// <summary> /// Deserializes the object from specified source stream. /// </summary> /// <param name="sourceStream">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> public object Deserialize(Stream sourceStream, Type type) { return _formatter.Deserialize(sourceStream); } /// <summary> /// Gets the contract name by the type /// </summary> /// <param name="messageType">Type of the message.</param> /// <returns>contract name (if found)</returns> public Maybe<string> GetContractNameByType(Type messageType) { return messageType.AssemblyQualifiedName; } /// <summary> /// Gets the type by contract name. /// </summary> /// <param name="contractName">Name of the contract.</param> /// <returns>type that could be used for contract deserialization (if found)</returns> public Maybe<Type> GetTypeByContractName(string contractName) { return Type.GetType(contractName); } } }<file_sep>/Source/Lokad.Shared/Serialization/IMessageSerializer.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion namespace Lokad.Serialization { /// <summary> /// Joins data serializer and contract mapper /// </summary> public interface IMessageSerializer : IDataSerializer, IDataContractMapper { } }<file_sep>/Test/Lokad.Shared.Test/Data/SqlClient/SqlServerGuidComparerTest.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Lokad.Data.SqlClient { [TestFixture] public sealed class SqlServerGuidComparerTest { [Test] public void Test_Sorting() { var order = new[] {0, 1, 2, 3, 4, 5, 6, 7, 9, 8, 15, 14, 13, 12, 11, 10}; var source = new string('0', 32); // create guids var guids = Range .Create(16, () => source.ToCharArray()) .Apply((a, i) => a[i*2 + 1] = '1') .Select((a, i) => Tuple.From(i, new Guid(new string(a)))); var sorted = guids .OrderBy(g => g.Item2, _comparer) .Select(g => g.Item1); CollectionAssert.AreEqual(order, sorted.ToArray()); } [Test] public void Test_Equals() { Assert.AreEqual(0, _comparer.Compare(Guid.Empty, Guid.Empty)); var guid = Guid.NewGuid(); Assert.AreEqual(0, _comparer.Compare(guid, guid)); } static readonly IComparer<Guid> _comparer = new SqlServerGuidComparer(); } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/TrackScopeTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class TrackScopeTests { [Test] public void Test_Nesting() { using (var t = new TrackScope()) { ScopeTestHelper.RunNesting(0, t); Assert.IsTrue(t.IsError()); } } } }<file_sep>/Source/Lokad.Shared/Utils/FormatUtil.cs using System; namespace Lokad { /// <summary> /// Pretty format utils /// </summary> public static class FormatUtil { static readonly string[] ByteOrders = new[] { "EB", "PB", "TB", "GB", "MB", "KB", "Bytes" }; static readonly long MaxScale; static FormatUtil() { MaxScale = (long)Math.Pow(1024, ByteOrders.Length - 1); } /// <summary> /// Formats the size in bytes to a pretty string. /// </summary> /// <param name="sizeInBytes">The size in bytes.</param> /// <returns></returns> public static string SizeInBytes(long sizeInBytes) { var max = MaxScale; foreach (var order in ByteOrders) { if (sizeInBytes > max) return string.Format("{0:##.##} {1}", decimal.Divide(sizeInBytes, max), order); max /= 1024; } return "0 Bytes"; } static string PositiveTimeSpan(TimeSpan timeSpan) { const int second = 1; const int minute = 60 * second; const int hour = 60 * minute; const int day = 24 * hour; const int month = 30 * day; double delta = timeSpan.TotalSeconds; if (delta < 1) return timeSpan.Milliseconds + " ms"; if (delta < 1 * minute) return timeSpan.Seconds == 1 ? "one second" : timeSpan.Seconds + " seconds"; if (delta < 2 * minute) return "a minute"; if (delta < 50 * minute) return timeSpan.Minutes + " minutes"; if (delta < 70 * minute) return "an hour"; if (delta < 2 * hour) return (int)timeSpan.TotalMinutes + " minutes"; if (delta < 24 * hour) return timeSpan.Hours + " hours"; if (delta < 48 * hour) return (int)timeSpan.TotalHours + " hours"; if (delta < 30 * day) return timeSpan.Days + " days"; if (delta < 12 * month) { var months = (int)Math.Floor(timeSpan.Days / 30.0); return months <= 1 ? "one month" : months + " months"; } var years = (int)Math.Floor(timeSpan.Days / 365.0); return years <= 1 ? "one year" : years + " years"; } /// <summary> /// Displays time passed since (or remaining before) some event expressed in UTC, displaying it as '<em>5 days ago</em>'. /// </summary> /// <param name="dateInUtc">The date in UTC.</param> /// <returns>formatted event</returns> public static string TimeOffsetUtc(DateTime dateInUtc) { var now = DateTime.UtcNow; var offset = now - dateInUtc; return TimeSpan(offset); } /// <summary> /// Displays time passed since some event expressed, displaying it as '<em>5 days ago</em>'. /// </summary> /// <param name="localTime">The local time.</param> /// <returns></returns> public static string TimeOffset(DateTime localTime) { var now = DateTime.Now; var offset = now - localTime; return TimeSpan(offset); } /// <summary> /// Formats time span nicely /// </summary> /// <param name="offset">The offset.</param> /// <returns>formatted string</returns> public static string TimeSpan(TimeSpan offset) { if (offset > System.TimeSpan.Zero) { return PositiveTimeSpan(offset) + " ago"; } return PositiveTimeSpan(-offset) + " from now"; } } }<file_sep>/Test/Lokad.Shared.Test/Settings/SettingsTests.cs using System.Collections.Generic; using NUnit.Framework; using Lokad.Testing; namespace Lokad.Settings { [TestFixture] public sealed class SettingsTests { readonly ISettingsProvider _provider = new Dictionary<string, string> { {"Path/1", "1"}, {"Path/2", "2"}, {"Root/3", "3"} }.AsSettingsProvider(); [Test] public void Test() { _provider.GetValue("Path/1").ShouldBe("1"); _provider.GetValue("Path/?").ShouldFail(); } [Test] public void Filtering() { var provider = _provider.FilteredByPrefix("Path/"); provider.GetValue("Path/1").ShouldFail(); provider.GetValue("1").ShouldBe("1"); } } }<file_sep>/Source/Lokad.ActionPolicy/ExceptionHandlerSyntax.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using Lokad.Exceptions; using Lokad.Rules; namespace Lokad { /// <summary> Fluent API for defining <see cref="ActionPolicy"/> /// that allows to handle exceptions. </summary> public static class ExceptionHandlerSyntax { /* Development notes * ================= * If a stateful policy is returned by the syntax, * it must be wrapped with the sync lock */ static void DoNothing2(Exception ex, int count) { } static void DoNothing2(Exception ex, TimeSpan sleep) { } /// <summary> /// Builds <see cref="ActionPolicy"/> that will retry exception handling /// for a couple of times before giving up. /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="retryCount">The retry count.</param> /// <returns>reusable instance of policy</returns> public static ActionPolicy Retry(this Syntax<ExceptionHandler> syntax, int retryCount) { Enforce.Argument(() => syntax); Func<IRetryState> state = () => new RetryStateWithCount(retryCount, DoNothing2); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } /// <summary> /// Builds <see cref="ActionPolicy"/> that will retry exception handling /// for a couple of times before giving up. /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetry">The action to perform on retry (i.e.: write to log). /// First parameter is the exception and second one is its number in sequence. </param> /// <returns>reusable policy instance </returns> public static ActionPolicy Retry(this Syntax<ExceptionHandler> syntax, int retryCount, Action<Exception, int> onRetry) { Enforce.Arguments(() => syntax, () => onRetry); Enforce.Argument(() => retryCount, Is.GreaterThan(0)); Func<IRetryState> state = () => new RetryStateWithCount(retryCount, onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } /// <summary> Builds <see cref="ActionPolicy"/> that will keep retrying forever </summary> /// <param name="syntax">The syntax to extend.</param> /// <param name="onRetry">The action to perform when the exception could be retried.</param> /// <returns> reusable instance of policy</returns> public static ActionPolicy RetryForever(this Syntax<ExceptionHandler> syntax, Action<Exception> onRetry) { Enforce.Arguments(() => syntax, () => onRetry); var state = new RetryState(onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, () => state)); } /// <summary> <para>Builds the policy that will keep retrying as long as /// the exception could be handled by the <paramref name="syntax"/> being /// built and <paramref name="sleepDurations"/> is providing the sleep intervals. /// </para> /// <para>See <see cref="Range"/> for methods to create long intervals on-the-fly</para> /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="sleepDurations">The sleep durations.</param> /// <param name="onRetry">The action to perform on retry (i.e.: write to log). /// First parameter is the exception and second one is the planned sleep duration. </param> /// <returns>new policy instance</returns> public static ActionPolicy WaitAndRetry(this Syntax<ExceptionHandler> syntax, IEnumerable<TimeSpan> sleepDurations, Action<Exception, TimeSpan> onRetry) { Enforce.Arguments(() => syntax, () => onRetry, () => sleepDurations); Func<IRetryState> state = () => new RetryStateWithSleep(sleepDurations, onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } /// <summary> <para>Builds the policy that will keep retrying as long as /// the exception could be handled by the <paramref name="syntax"/> being /// built and <paramref name="sleepDurations"/> is providing the sleep intervals. /// </para> /// <para>See <see cref="Range"/> for methods to create long intervals on-the-fly</para> /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="sleepDurations">The sleep durations.</param> /// <returns>new policy instance</returns> public static ActionPolicy WaitAndRetry(this Syntax<ExceptionHandler> syntax, IEnumerable<TimeSpan> sleepDurations) { Enforce.Arguments(() => syntax, () => sleepDurations); Func<IRetryState> state = () => new RetryStateWithSleep(sleepDurations, DoNothing2); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } #if !SILVERLIGHT2 /// <summary> /// <para>Builds the policy that will "break the circuit" after <paramref name="countBeforeBreaking"/> /// exceptions that could be handled by the <paramref name="syntax"/> being built. The circuit /// stays broken for the <paramref name="duration"/>. Any attempt to /// invoke method within the policy, while the circuit is broken, will immediately re-throw /// the last exception. </para> /// <para>If the action fails within the policy after the block period, then the breaker /// is blocked again for the next <paramref name="duration"/>. /// It will be reset, otherwise.</para> /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="duration">How much time the breaker will stay open before resetting</param> /// <param name="countBeforeBreaking">How many exceptions are needed to break the circuit</param> /// <returns>shared policy instance</returns> /// <remarks>(see "ReleaseIT!" for the details)</remarks> public static ActionPolicyWithState CircuitBreaker(this Syntax<ExceptionHandler> syntax, TimeSpan duration, int countBeforeBreaking) { Enforce.Argument(() => syntax); Enforce.Argument(() => countBeforeBreaking, Is.GreaterThan(0)); Enforce.Argument(() => duration, Is.NotDefault); var state = new CircuitBreakerState(duration, countBeforeBreaking); var syncLock = new CircuitBreakerStateLock(state); return new ActionPolicyWithState(action => CircuitBreakerPolicy.Implementation(action, syntax.Target, syncLock)); } #endif } }<file_sep>/Test/Lokad.Shared.Test/Rules/Case1/Visitor.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { sealed class Visitor { public string Name { get; set; } public Program[] Programs { get; set; } public static Visitor CreateValid() { return new Visitor { Name = Guid.NewGuid().ToString().Replace('-', ' '), Programs = new[] {Program.CreateValid(), Program.CreateValid(), Program.CreateValid()} }; } } }<file_sep>/Source/Lokad.Shared/Tuples/Triple.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Tuple class with 3 items /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> [Serializable] [Immutable] public sealed class Triple<T1, T2, T3> : Tuple<T1, T2, T3> { /// <summary> /// Initializes a new instance of the <see cref="Triple{T1, T2, T3}"/> class. /// </summary> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> public Triple(T1 first, T2 second, T3 third) : base(first, second, third) { } } }<file_sep>/Test/Lokad.Shared.Test/Utils/TypeUtilTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class TypeUtilTests { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] sealed class MyAttribute : Attribute{ } // ReSharper disable InconsistentNaming [MyAttribute] [MyAttribute] public sealed class ClassWith2Attributes { } [MyAttribute] public sealed class ClassWithAttribute { } [Test] public void GetAttributes_Works_For_Multiple_Instances() { var attributes = typeof(ClassWith2Attributes).GetAttributes<MyAttribute>(false); Assert.AreEqual(2, attributes.Length); } [Test] public void GetAttributes_Returns_Empty() { Assert.AreEqual(0, typeof(int).GetAttributes<MyAttribute>(false).Length); } [Test, Expects.InvalidOperationException] public void GetAttribute_Throws_Exception_On_Multiple_Attributes() { typeof(ClassWith2Attributes).GetAttribute<MyAttribute>(false); } [Test] public void GetAttribute_Works() { var result = typeof(ClassWithAttribute).GetAttribute<MyAttribute>(false); Assert.IsNotNull(result, "1"); Assert.AreEqual(typeof(MyAttribute), result.GetType(), "2"); } [Test] public void GetAttribute_Returns_Null() { Assert.IsNull(typeof(int).GetAttribute<MyAttribute>(false)); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Scopes/ScopeTestHelper.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Rules { static class ScopeTestHelper { public static void FireErrors(IScope t) { t.Error("ErrA"); using (var scope = t.Create("Nested")) { scope.Error("ErrB"); } t.Error("ErrC"); } public static void ShouldHave(Exception ex, params string[] args) { foreach (var s in args) { StringAssert.Contains(s, ex.Message); } } public static void ShouldNotHave(Exception ex, params string[] args) { foreach (var s in args) { Assert.IsFalse(ex.Message.Contains(s)); } } public static void ShouldBeClean(Exception ex) { Assert.IsFalse( ex.Message.Contains("Scope") || ex.Message.Contains("Dispose") || ex.Message.Contains("Write"), "Exception {0} should not contain debug info", ex); } public static void RunNesting(int nil, IScope scope) { scope.Write(RuleLevel.None, "None1"); using (var child = scope.Create("Group1")) { child.Write(RuleLevel.Warn, "Warn1"); using (var grand = child.Create("Group2")) { grand.Write(RuleLevel.None, "None2"); grand.Error("Error1"); } child.Write(RuleLevel.None, "None3"); } scope.Write(RuleLevel.None, "None4"); } } }<file_sep>/Source/Lokad.Shared/Diagnostics/Persist/ConversionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Diagnostics.Persist { /// <summary> /// Helper extensions for converting to/from data classes in the Diagnostics namespace /// </summary> public static class ConversionExtensions { /// <summary> /// Converts immutable statistics objects to the persistence objects /// </summary> /// <param name="statisticsArray">The immutable statistics objects.</param> /// <returns>array of persistence objects</returns> public static ExecutionData[] ToPersistence(this ExecutionStatistics[] statisticsArray) { return statisticsArray.Convert(es => new ExecutionData { CloseCount = es.CloseCount, Counters = es.Counters, Name = es.Name, OpenCount = es.OpenCount, RunningTime = es.RunningTime }); } /// <summary> /// Converts persistence objects to immutable statistics objects /// </summary> /// <param name="dataArray">The persistence data objects.</param> /// <returns>array of statistics objects</returns> public static ExecutionStatistics[] FromPersistence(this ExecutionData[] dataArray) { return dataArray.Convert( d => new ExecutionStatistics( d.Name, d.OpenCount, d.CloseCount, d.Counters, d.RunningTime)); } } }<file_sep>/Test/Lokad.Shared.Test/ResolverTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class ResolverTests { [Test, Expects.ResolutionException] public void Test_Wrap1() { var t = new Resolver(type => { throw new InvalidOperationException("Failed"); }, (type, s) => null); t.Get<ICommand>(); } [Test, Expects.ResolutionException] public void Test_Wrap2() { var t = new Resolver(type => null, (type, s) => { throw new InvalidOperationException("Failed"); }); t.Get<ICommand>("Name"); } } }<file_sep>/Source/Lokad.Shared/Rules/RuleException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Lokad.Rules { /// <summary> /// Exception that is thrown when some validation error is encountered /// </summary> /// <remarks> /// TODO: add proper implementation /// </remarks> [Serializable] public sealed class RuleException : Exception { /// <summary> /// Initializes a new instance of the <see cref="RuleException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="reference">The reference.</param> public RuleException(string message, string reference) : base(string.Format("{0}: {1}", reference, message)) { } /// <summary> /// Initializes a new instance of the <see cref="RuleException"/> class. /// </summary> /// <param name="message">The message.</param> public RuleException(string message) : base(message) { } /// <summary> Initializes a new instance of the <see cref="RuleException"/> class. </summary> /// <param name="messages">The messages.</param> public RuleException(IEnumerable<RuleMessage> messages) : base(FromMessages(messages)) { } static string FromMessages(IEnumerable<RuleMessage> messages) { var collection = messages.ToArray(); if (collection.Length == 1) return collection[0].ToString(); var builder = new StringBuilder("Rule messages:"); foreach (var message in messages) { builder .AppendLine() .Append(message); } return builder.ToString(); } #if !SILVERLIGHT2 /// <summary> /// Initializes a new instance of the <see cref="RuleException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="info"/> parameter is null. /// </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException"> /// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). /// </exception> RuleException( SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/DoubleIsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class DoubleIsTests { [Test] public void Valid() { RuleAssert.For<double>(DoubleIs.Valid) .ExpectError(double.NaN, 1/0D, double.PositiveInfinity, double.NegativeInfinity) .ExpectNone(1D, 0D, Math.PI); } } }<file_sep>/Sample/Shared/RulesUI/CustomerIs.cs using System; using System.Rules; namespace RulesUI { public static class CustomerIs { public static void Valid(Customer customer, IScope scope) { scope.Validate(() => customer.Name, StringIs.Limited(3, 64)); if (customer.Address.Country == Country.Russia) { scope.Validate(() => customer.Email, (s, scope1) => { if (!string.IsNullOrEmpty(s)) scope1.Error( @"Russian customers do not have emails. Use pigeons instead."); }); } else { scope.Validate(() => customer.Email, StringIs.ValidEmail); } } // dynamic rule public static Rule<Customer> From(params Rule<Address>[] addressRules) { return (customer, scope) => scope.Validate(() => customer.Address, addressRules); } } }<file_sep>/Source/Lokad.Shared/Tuples/Tuple.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Lokad.Quality; namespace Lokad { /// <summary> /// Helper class that simplifies tuple inline generation /// </summary> /// <example> /// Tuple.From("Mike",1,true) /// </example> [NoCodeCoverage] public static class Tuple { /// <summary> /// Creates <see cref="Pair{T1,T2}"/> out of two arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <returns>New tuple instance</returns> public static Pair<T1, T2> From<T1, T2>(T1 first, T2 second) { return new Pair<T1, T2>(first, second); } /// <summary> /// Creates <see cref="Triple{T1,T2,T3}"/> out of the three arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <returns>New tuple instance</returns> public static Triple<T1, T2, T3> From<T1, T2, T3>(T1 first, T2 second, T3 third) { return new Triple<T1, T2, T3>(first, second, third); } /// <summary> /// Creates <see cref="Tuple{T1,T2,T3,T4}"/> out of four arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <returns>New instance</returns> public static Quad<T1, T2, T3, T4> From<T1, T2, T3, T4>(T1 first, T2 second, T3 third, T4 fourth) { return new Quad<T1, T2, T3, T4>(first, second, third, fourth); } /// <summary> /// Creates <see cref="Tuple{T1,T2,T3,T4}"/> out of four arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <param name="fifth">The fifth item.</param> /// <returns>New instance</returns> public static Tuple<T1, T2, T3, T4, T5> From<T1, T2, T3, T4, T5>(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { return new Tuple<T1, T2, T3, T4, T5>(first, second, third, fourth, fifth); } /// <summary> /// Creates <see cref="Tuple{T1,T2,T3,T4}"/> out of four arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <typeparam name="T6">The type of the sixth item.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <param name="fifth">The fifth item.</param> /// <param name="sixth">The sixth item.</param> /// <returns>New instance</returns> public static Tuple<T1, T2, T3, T4, T5, T6> From<T1, T2, T3, T4, T5, T6>(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth) { return new Tuple<T1, T2, T3, T4, T5, T6>(first, second, third, fourth, fifth, sixth); } /// <summary> /// Creates <see cref="Tuple{T1,T2,T3,T4}"/> out of four arguments /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <typeparam name="T6">The type of the sixth item.</typeparam> /// <typeparam name="T7">The type of the seventh item.</typeparam> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <param name="fifth">The fifth item.</param> /// <param name="sixth">The sixth item.</param> /// <param name="seventh">The seventh item.</param> /// <returns>New instance</returns> public static Tuple<T1, T2, T3, T4, T5, T6, T7> From<T1, T2, T3, T4, T5, T6, T7>(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(first, second, third, fourth, fifth, sixth, seventh); } } }<file_sep>/Source/Lokad.ActionPolicy/ActionPolicyWithState.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Quality; namespace Lokad { /// <summary> /// Same as <see cref="ActionPolicy"/>, but indicates that this policy /// holds some state and thus must have syncronized access. /// </summary> [Immutable] [Serializable] public sealed class ActionPolicyWithState : ActionPolicy { /// <summary> /// Initializes a new instance of the <see cref="ActionPolicyWithState"/> class. /// </summary> /// <param name="policy">The policy.</param> public ActionPolicyWithState(Action<Action> policy) : base(policy) { } } }<file_sep>/Test/Lokad.Shared.Test/MaybeParseTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Globalization; using Lokad.Testing; using NUnit.Framework; namespace Lokad { [TestFixture] public sealed class MaybeParseTests { public static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; // ReSharper disable InconsistentNaming enum Tri { Good, Bad, Ugly } [Test] public void Enum() { MaybeParse.Enum<Tri>("Good").ShouldBe(Tri.Good); MaybeParse.Enum<Tri>("BAD").ShouldBe(Tri.Bad); MaybeParse.Enum<Tri>("ugly", false).ShouldFail(); MaybeParse.Enum<Tri>("").ShouldFail(); MaybeParse.Enum<Tri>(null).ShouldFail(); } [Test] public void Decimal() { MaybeParse.Decimal(12.1m.ToString()).ShouldBe(12.1m); MaybeParse.Decimal("???").ShouldFail(); MaybeParse.Decimal(null).ShouldFail(); const NumberStyles styles = NumberStyles.Number; MaybeParse.Decimal(null, styles, Invariant).ShouldFail(); MaybeParse.Decimal("??", styles, Invariant).ShouldFail(); MaybeParse.Decimal("12.1", styles, Invariant).ShouldBe(12.1m); MaybeParse.DecimalInvariant(null).ShouldFail(); MaybeParse.DecimalInvariant("??").ShouldFail(); MaybeParse.DecimalInvariant("12.1").ShouldBe(12.1m); } [Test] public void Int32() { MaybeParse.Int32("12").ShouldBe(12); MaybeParse.Int32("12.1").ShouldFail(); MaybeParse.Int32(null).ShouldFail(); MaybeParse.Int32("???").ShouldFail(); MaybeParse.Int32Invariant("12").ShouldBe(12); MaybeParse.Int32Invariant("12.1").ShouldFail(); MaybeParse.Int32Invariant(null).ShouldFail(); MaybeParse.Int32Invariant("???").ShouldFail(); } [Test] public void Int64() { MaybeParse.Int64("12").ShouldBe(12); MaybeParse.Int64("12.1").ShouldFail(); MaybeParse.Int64(null).ShouldFail(); MaybeParse.Int64("???").ShouldFail(); MaybeParse.Int64Invariant("12").ShouldBe(12); MaybeParse.Int64Invariant("12.1").ShouldFail(); MaybeParse.Int64Invariant(null).ShouldFail(); MaybeParse.Int64Invariant("???").ShouldFail(); } [Test] public void Single() { MaybeParse.Single(12.1f.ToString()).ShouldBe(12.1f); MaybeParse.Single("???").ShouldFail(); MaybeParse.Single(null).ShouldFail(); MaybeParse.SingleInvariant("12.1").ShouldBe(12.1f); MaybeParse.SingleInvariant("???").ShouldFail(); MaybeParse.SingleInvariant(null).ShouldFail(); } [Test] public void Double() { MaybeParse.Double(12.1d.ToString()).ShouldBe(12.1d); MaybeParse.Double("???").ShouldFail(); MaybeParse.Double(null).ShouldFail(); MaybeParse.DoubleInvariant("12.1").ShouldBe(12.1d); MaybeParse.DoubleInvariant("???").ShouldFail(); MaybeParse.DoubleInvariant(null).ShouldFail(); } } }<file_sep>/Sample/Shared/RulesUI/IEditorView.cs using System; using System.Rules; namespace RulesUI { public interface IEditorView<T> where T : class { Result<T> GetData(params Rule<T>[] rules); void BindData(T customer); void SetTitle(string text); } }<file_sep>/Test/Lokad.Shared.Test/Testing/IEquatableExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Testing { [TestFixture] public sealed class IEquatableExtensionsTests { sealed class Equatable : IEquatable<Equatable> { readonly int _key; public Equatable(int key) { _key = key; } public bool Equals(Equatable other) { return _key == other._key; } } [Test] public void X_EqualsTo_Y() { // generic Assert.IsTrue(1.EqualsTo(1)); Assert.IsFalse(2.EqualsTo(1)); //specialized var e1 = new Equatable(1); var e2 = new Equatable(2); Assert.IsFalse(e1.EqualsTo(e2)); Assert.IsTrue(e1.EqualsTo(e1)); } [Test] public void Xs_EqualsTo_Ys() { var array1 = new[] {1, 2, 3}; var array2 = new[] {1, 2, 4}; Assert.IsTrue(array1.EqualsTo(array1)); Assert.IsFalse(array1.EqualsTo(array2)); // specialized var e1 = new Equatable(1); var e2 = new Equatable(2); var a1 = new[] {e1, e2}; var a2 = new[] {e1, e1}; Assert.IsTrue(a1.EqualsTo(a1)); Assert.IsFalse(a1.EqualsTo(a2)); } } }<file_sep>/Source/Lokad.Shared/Serialization/DataContractUtil.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace Lokad.Serialization { /// <summary> /// Helper class to work with <see cref="DataContract"/> /// </summary> public static class DataContractUtil { /// <summary> /// Throws detailed exception the on messages without data contracts. /// </summary> /// <param name="knownTypes">The known types.</param> public static void ThrowOnMessagesWithoutDataContracts(IEnumerable<Type> knownTypes) { var failures = knownTypes .Where(m => false == m.IsDefined(typeof(DataContractAttribute), false)); if (failures.Any()) { var list = failures.Select(f => f.FullName).Join(Environment.NewLine); throw new InvalidOperationException( "All messages must be marked with the DataContract attribute in order to be used with DCS: " + list); } } /// <summary> /// Gets the contract reference, combining contract properties. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static string GetContractReference(Type type) { var contract = (DataContractAttribute)type.GetCustomAttributes(typeof(DataContractAttribute), false).First(); var name = string.IsNullOrEmpty(contract.Name) ? type.Name : contract.Name; if (string.IsNullOrEmpty(contract.Namespace)) return name; return contract.Namespace + "/" + name; } } }<file_sep>/Source/Lokad.Shared/Rules/Common/BufferIs.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Rules { /// <summary> /// Validation rules for byte arrays /// </summary> public static class BufferIs { /// <summary> /// Composes validator ensuring that size of the buffer /// is equal or less to the speicifed limit /// </summary> /// <param name="length">The length.</param> /// <returns>new rule validator instance</returns> public static Rule<byte[]> Limited(int length) { return (bytes, scope) => { if (bytes.Length > length) { scope.Error("Byte array should not be longer than {0} bytes.", length); } }; } /// <summary> /// Composes validator ensuring that buffer has valid hash /// </summary> /// <param name="hash">The hash.</param> /// <returns>new instance of the rule validato</returns> /// <seealso cref="BufferUtil.CalculateSimpleHashCode"/> public static Rule<byte[]> WithValidHash(int hash) { return (bytes, scope) => { var result = BufferUtil.CalculateSimpleHashCode(bytes); if (result != hash) { scope.Error("Byte array should have valid hash."); } }; } } }<file_sep>/Source/Lokad.Logging/ILogProvider.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad { /// <summary> /// Creates logs using the name /// </summary> public interface ILogProvider : INamedProvider<ILog> { } }<file_sep>/Test/Lokad.Testing.Test/MockContainerTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; using Rhino.Mocks.Exceptions; namespace Lokad.Testing.Test { [TestFixture] public sealed class MockContainerTests { // ReSharper disable ClassNeverInstantiated.Local // ReSharper disable UnusedParameter.Local sealed class DependsOnClass { public DependsOnClass(Component a) { } } sealed class DependsOnService { public readonly IService Service; public DependsOnService(IService service) { Service = service; } public void CallService() { Service.Call(); } } public sealed class Component : IService { public void Call() { throw new NotImplementedException(); } } public interface IService { void Call(); } // ReSharper disable InconsistentNaming [Test] [ExpectedException(typeof (ResolutionException))] public void Component_is_not_registered() { using (var c = new MockContainer<DependsOnClass>()) { Assert.IsNotNull(c.Subject); } } [Test] public void Component_is_registered_as_type() { using (var c = new MockContainer<DependsOnClass>()) { c.Register<Component>(); Assert.IsNotNull(c.Subject); } } [Test] public void Component_is_registered_as_instance() { using (var c = new MockContainer<DependsOnClass>()) { c.Register(new Component()); Assert.IsNotNull(c.Subject); } } [Test] public void Mocks_are_used_where_possible() { using (var c = MockContainer.For<DependsOnService>()) { Assert.IsNotNull(c.Subject); } } [Test] public void Mocks_are_registered_as_singletons() { using (var c = MockContainer.For<DependsOnService>()) { Assert.AreSame(c.Subject.Service, c.Resolve<IService>()); } } [Test] public void Calls_are_wired_automatically() { using (var c = MockContainer.For<DependsOnService>()) { c.Subject.CallService(); } } [Test] public void AssertWasCalled_is_verified() { using (var c = MockContainer.For<DependsOnService>()) { c.Subject.CallService(); c.AssertWasCalled<IService>(s => s.Call()); } } [Test] [ExpectedException(typeof (ExpectationViolationException))] public void AssertWasCalled_is_not_verified() { using (var c = MockContainer.For<DependsOnService>()) { c.AssertWasCalled<IService>(s => s.Call()); } } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/CannotApplyEqualityOperatorAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators. /// There is only exception to compare with <c>null</c>, it is permitted /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } }<file_sep>/Source/Lokad.Shared/Rules/Scopes/DelayedScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// This scope is just like <see cref="SimpleScope"/> /// but it delays name resolution /// </summary> [Serializable] sealed class DelayedScope : IScope { public delegate void Messenger(Func<string> pathProvider, RuleLevel level, string message); readonly Func<string> _name; readonly Messenger _messenger; readonly Action<RuleLevel> _dispose = level => { }; string _cachedName; RuleLevel _level; string GetName() { if (null == _cachedName) { _cachedName = _name(); } return _cachedName; } public DelayedScope(Func<string> name, Messenger action) { _name = name; _messenger = action; } internal DelayedScope(Func<string> name, Messenger action, Action<RuleLevel> dispose) { _name = name; _messenger = action; _dispose = dispose; } void IDisposable.Dispose() { _dispose(_level); } IScope IScope.Create(string name) { return new DelayedScope(() => Scope.ComposePathInternal(GetName(), name), _messenger, level => { if (level > _level) _level = level; }); } void IScope.Write(RuleLevel level, string message) { if (level > _level) _level = level; _messenger(GetName, level, message); } RuleLevel IScope.Level { get { return _level; } } } }<file_sep>/Source/Lokad.Shared/Rules/Scopes/SimpleScope.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Rules { /// <summary> /// <see cref="IScope"/> that maintains scope path, executes /// <see cref="Messenger"/> delegate per every message. /// </summary> [Serializable] public sealed class SimpleScope : IScope { /// <summary> /// Delegate for relaying scope messages /// </summary> public delegate void Messenger(string path, RuleLevel level, string message); readonly string _name; readonly Messenger _messenger; RuleLevel _level; readonly Action<RuleLevel> _dispose = level => { }; void IDisposable.Dispose() { _dispose(_level); } internal SimpleScope(string name, Messenger messenger, Action<RuleLevel> dispose) { _name = name; _messenger = messenger; _dispose = dispose; } /// <summary> /// Initializes a new instance of the <see cref="SimpleScope"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="messenger">The messenger.</param> public SimpleScope(string name, Messenger messenger) { _name = name; _messenger = messenger; _dispose = level => { }; } IScope IScope.Create(string name) { return new SimpleScope(Scope.ComposePathInternal(_name, name), _messenger, level => { if (level > _level) _level = level; }); } void IScope.Write(RuleLevel level, string message) { if (level > _level) _level = level; _messenger(_name, level, message); } RuleLevel IScope.Level { get { return _level; } } /// <summary> /// Gets the messages reported by the specified action to the scope. /// </summary> /// <param name="name">The name.</param> /// <param name="action">The action.</param> /// <returns>array of rule messages reported</returns> public static RuleMessages GetMessages(string name, Action<IScope> action) { if (name == null) throw new ArgumentNullException("name"); var messages = RuleMessages.Empty; using (var scope = ScopeFactory.ForMessages(name, m => messages = m)) { action(scope); } return messages; } } }<file_sep>/Test/Lokad.Quality.Test/ModuleDefinitionExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using Mono.Cecil; using NUnit.Framework; namespace Lokad.Quality.Test { [TestFixture] public sealed class ModuleDefinitionExtensionsTests { readonly ModuleDefinition[] _moduleDefinitions; // ReSharper disable InconsistentNaming public ModuleDefinitionExtensionsTests() { _moduleDefinitions = GlobalSetup.Codebase.Assemblies.SelectMany(a => a.GetModules()).ToArray(); } [Test] public void GetAssemblyReferences() { var referenced = _moduleDefinitions.SelectMany(m => m.GetAssemblyReferences()).ToArray(r => r.Name); var expected = "mscorlib,Lokad.Quality,Mono.Cecil,System.Core,nunit.framework,Lokad.Shared,Lokad.Shared.Test".Split(','); CollectionAssert.AreEquivalent(expected, referenced); } } }<file_sep>/Source/Lokad.Quality/Extensions/TypeDefinitionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Helper extensions for the <see cref="TypeDefinition"/> /// </summary> public static class TypeDefinitionExtensions { /// <summary> /// Gets the interfaces. /// </summary> /// <param name="definition">The definition.</param> /// <returns>enumerator over the interfaces</returns> public static IEnumerable<TypeReference> GetInterfaces(this TypeDefinition definition) { return definition.Interfaces.Cast<TypeReference>(); } /// <summary> /// Retrieves fields for the <see cref="TypeDefinition"/> /// </summary> /// <param name="self">The type definition.</param> /// <returns>lazy collection of the fields</returns> public static IEnumerable<FieldDefinition> GetFields(this TypeDefinition self) { return self.Fields.Cast<FieldDefinition>(); } /// <summary> /// Gets the methods found on this <see cref="TypeDefinition"/>. /// Inheritance is not considered. /// </summary> /// <param name="definition">The definition.</param> /// <returns>lazy collection of methods</returns> public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition definition) { return definition.Methods.Cast<MethodDefinition>(); } /// <summary> /// Gets the constructors found on this <see cref="TypeDefinition"/>. /// Inheritance is not considered. /// </summary> /// <param name="definition">The definition.</param> /// <returns>lazy collection of methods</returns> public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition definition) { return definition.Constructors.Cast<MethodDefinition>(); } /// <summary> /// Gets the properties found on the type definition. /// Inheritance is not considered. /// </summary> /// <param name="definition">The definition.</param> /// <returns>lazy collection of the properties</returns> public static IEnumerable<PropertyDefinition> GetProperties(this TypeDefinition definition) { return definition.Properties.Cast<PropertyDefinition>(); } /// <summary> /// Resolves the specified definition to <see cref="Type"/>. /// </summary> /// <param name="definition">The definition.</param> /// <returns>.NET Type</returns> public static Type Resolve(this TypeDefinition definition) { var name = string.Format("{0}, {1}", definition.FullName, definition.Module.Assembly.Name); return Type.GetType(name, true); } /// <summary> /// Verifies that the specified <paramref name="check"/> is satisfied /// </summary> /// <param name="definitions">The definitions.</param> /// <param name="check">The check.</param> /// <returns>the same enumerable</returns> /// <exception cref="QualityException">if any definitions do not pass the check</exception> public static IEnumerable<TypeDefinition> Should(this IEnumerable<TypeDefinition> definitions, Predicate<TypeDefinition> check) { QualityAssert.TypesPass(definitions, check); return definitions; } /// <summary> /// Selects only types with the specified attribute /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="definitions">The definitions.</param> /// <returns>filtered sequence</returns> public static IEnumerable<TypeDefinition> With<TAttribute>(this IEnumerable<TypeDefinition> definitions) where TAttribute : Attribute { return definitions.Where(d => d.Has<TAttribute>()); } } }<file_sep>/Source/Lokad.Logging/LogLevel.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Degines the importance level associated with the log /// entry in <see cref="ILog"/> /// </summary> [CLSCompliant(true)] public enum LogLevel { /// <summary> Message is intended for debugging </summary> Debug, /// <summary> Informatory message </summary> Info, /// <summary> The message is about potential problem in the system </summary> Warn, /// <summary> Some error has occured </summary> Error, /// <summary> Message is associated with the critical problem </summary> Fatal, /// <summary> /// Highest possible level /// </summary> Max = int.MaxValue, /// <summary> Smallest logging level</summary> Min = int.MinValue } }<file_sep>/Source/Lokad.Stack/Logging/LogSyntax.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using log4net.Appender; using log4net.Filter; namespace Lokad.Logging { /// <summary> /// Syntax for configuring logging within the logging stack /// </summary> public class LogSyntax : Syntax { readonly AppenderSkeleton _skeleton; internal LogSyntax(AppenderSkeleton skeleton) { _skeleton = skeleton; } /// <summary> /// Appends inclusive filter to the log /// </summary> /// <param name="minRange">The min range.</param> /// <param name="maxRange">The max range.</param> /// <returns>same syntax</returns> public LogSyntax Filter(LogLevel minRange, LogLevel maxRange) { var filter = new LevelRangeFilter { LevelMin = minRange.ToLog4Net(), LevelMax = maxRange.ToLog4Net(), AcceptOnMatch = true }; filter.ActivateOptions(); _skeleton.AddFilter(filter); //_skeleton.ActivateOptions(); return this; } } }<file_sep>/Test/Lokad.Shared.Test/Threading/ReaderWriterLockSlimExtensionsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Threading; using NUnit.Framework; #if !SILVERLIGHT2 namespace Lokad.Threading { [TestFixture] public sealed class ReaderWriterLockSlimExtensionsTests { readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); // ReSharper disable InconsistentNaming [Test] public void Test_GetReadLock() { using (_lock.GetReadLock()) { Assert.IsTrue(_lock.IsReadLockHeld); } Assert.IsFalse(_lock.IsReadLockHeld); } [Test] public void Test_GetWriteLock() { using (_lock.GetWriteLock()) { Assert.IsTrue(_lock.IsWriteLockHeld); } Assert.IsFalse(_lock.IsWriteLockHeld); } [Test] public void Test_GetUpgradeableReadLock() { using (_lock.GetUpgradeableReadLock()) { Assert.IsTrue(_lock.IsUpgradeableReadLockHeld); } Assert.IsFalse(_lock.IsUpgradeableReadLockHeld); } [Test] public void Test_All() { using (_lock.GetUpgradeableReadLock()) using (_lock.GetWriteLock()) { Assert.IsTrue(_lock.IsWriteLockHeld); Assert.IsTrue(_lock.IsUpgradeableReadLockHeld); } Assert.IsFalse(_lock.IsUpgradeableReadLockHeld); } } } #endif<file_sep>/Test/Lokad.Shared.Test/Reflection/ExpressTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Reflection; using Lokad.Rules; using NUnit.Framework; namespace Lokad.Reflection { [TestFixture] public sealed class ExpressTests { [Test] public void Constructor() { var constructor = Express.Constructor(() => new ExpressTests()); Enforce.That(constructor, Represents<ExpressTests>(".ctor")); } [Test] public void Static_Method() { var method = Express.Method(() => ReferenceEquals(null, null)); Enforce.That(method, Represents<object>("ReferenceEquals")); } [Test] public void Method() { var method = Express<ExpressTests>.Method(i => i.Method()); MemberInfo m2 = Express.Method(() => Method()); Enforce.That(method, Represents<ExpressTests>("Method"), Is.SameAs(m2)); } static Rule<MemberInfo> Represents<T>(IEquatable<string> name) { return (info, scope) => { scope.Validate(info.DeclaringType, "DeclaringType", Is.SameAs(typeof (T))); scope.Validate(info.Name, "Name", Is.Equal(name)); }; } int IntProperty { get { return _intField; } } [Test] public void Property() { var property = Express.Property(() => IntProperty); MemberInfo p2 = Express<ExpressTests>.Property(i => i.IntProperty); Enforce.That(property, Is.SameAs(p2), Represents<ExpressTests>("IntProperty")); } // ReSharper disable ConvertToConstant readonly int _intField = 1; static readonly int _staticField = 4; // ReSharper restore ConvertToConstant static int StaticProperty { get { return _staticField; } } [Test] public void Static_Property() { var property = Express.Property(() => StaticProperty); Enforce.That(property, Represents<ExpressTests>("StaticProperty")); } [Test] public void Field() { var field = Express.Field(() => _intField); MemberInfo f2 = Express<ExpressTests>.Field(et => et._intField); Enforce.That(field, Is.SameAs(f2), Represents<ExpressTests>("_intField")); } [Test] public void Static_Field() { var field = Express.Field(() => _staticField); Enforce.That(field, Represents<ExpressTests>("_staticField")); } } }<file_sep>/Source/Lokad.Shared/Extensions/ExtendAction.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad { /// <summary> /// Extensions for the <see cref="Action"/> /// </summary> public static class ExtendAction { /// <summary> /// Converts the action into <see cref="DisposableAction"/> /// </summary> /// <param name="action">The action.</param> /// <returns></returns> public static IDisposable AsDisposable(this Action action) { return new DisposableAction(action); } } }<file_sep>/Test/Lokad.Testing.Test/ModelAssertRegressions.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using NUnit.Framework; namespace Lokad.Testing.Test { [TestFixture] public sealed class ModelAssertRegressions { // ReSharper disable InconsistentNaming [DesignOfClass.ImmutableFieldsModel] sealed class WithMaybe { public readonly Maybe<DateTime> Date; public WithMaybe(Maybe<DateTime> date) { Date = date; } } [Test] public void WithMaybe_non_empty_equal_valid() { var dateTime = SystemUtil.UtcNow; ModelAssert.AreEqual(new WithMaybe(dateTime), new WithMaybe(dateTime)); } [Test] public void WithMaybe_empty_equal_valid() { ModelAssert.AreEqual(new WithMaybe(Maybe<DateTime>.Empty), new WithMaybe(Maybe<DateTime>.Empty)); } [Test] public void WithMaybe_non_equal_invalid() { var m1 = new WithMaybe(Maybe<DateTime>.Empty); var m2 = new WithMaybe(SystemUtil.UtcNow); ModelAssert.AreNotEqual(m1, m2); } [DesignOfClass.ImmutableFieldsModel] sealed class WithStaticField { public static WithStaticField SingletonField = new WithStaticField(); public readonly int Value = 10; } [DesignOfClass.ImmutablePropertiesModel] sealed class WithStaticProperty { public static WithStaticProperty SingletonProperty { get; set;} public int Value { get; set;} static WithStaticProperty() { SingletonProperty = new WithStaticProperty(); } } [Test] public void Static_fields_are_ignored() { ModelAssert.AreEqual(new WithStaticField(), new WithStaticField()); } [Test] public void Static_properties_are_ignored() { ModelAssert.AreEqual(new WithStaticField(), new WithStaticField()); } } }<file_sep>/Test/Lokad.Shared.Test/Linq/ExtendIEnumerableTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Linq { [TestFixture] public sealed class ExtendIEnumerableTests { // ReSharper disable InconsistentNaming [Test] public void ForEach_Works() { int sum = 0; new[] {1, 2, 3, 4}.ForEach(i => sum += i); Assert.AreEqual(10, sum); } [Test] public void ForEach2_Works() { int sum = 0; new[] {1, 2, 3, 4}.ForEach((i, k) => sum += (i + k)); Assert.AreEqual(16, sum); } [Test] public void Exists_Works() { Assert.IsTrue(new[] {1, 2, 3, 4}.Exists(i => i == 3)); Assert.IsFalse(new[] {1, 2, 3, 4}.Exists(i => i == 5)); } [Test] public void Append_Works() { CollectionAssert.AreEqual(new[] {1, 2, 3, 4, 5}, Range.Create(1, 3).Append(4, 5).ToArray()); } [Test] public void Prepend_Works() { CollectionAssert.AreEqual(new[] {4, 5, 1, 2, 3}, Range.Create(1, 3).Prepend(4, 5).ToArray()); } [Test] public void Append_Works_For_Ranges() { CollectionAssert.AreEqual(new[] {1, 2, 3, 4}, Range.Create(1, 2).Append(new[] {3, 4}).ToArray()); } #if !SILVERLIGHT2 [Test] public void ToSet_Works() { CollectionAssert.AreEquivalent(new[] {1, 2, 3}, new[] {1, 2, 3, 2}.ToSet().ToArray()); CollectionAssert.AreEquivalent(new[] {1D, 2D, 3D}, new[] {1, 2, 3, 2}.ToSet(i => (double) i).ToArray()); } #endif [Test] public void Apply_Does_Not_Enumerate() { Enumerable.Repeat(1, 10).Apply(i => { throw new InvalidOperationException(); }); Enumerable.Repeat(1, 10).Apply((i, int1) => { throw new InvalidOperationException(); }); } [Test] public void Apply_Works() { var sum = 0; var ints = new[] {1, 2, 3, 4}; CollectionAssert.AreEqual(ints, ints.Apply(i => sum += i).ToArray()); Assert.AreEqual(10, sum); } [Test] public void Apply2_Works() { var sum = 0; var ints = new[] {1, 2, 3, 4}; CollectionAssert.AreEqual(ints, ints.Apply((i, k) => sum += (i + k)).ToArray()); Assert.AreEqual(16, sum); } [Test] public void MaxMin_Work_For_Structs() { var ints = new[] {0, 5, 3, 0}; Assert.AreEqual(5, ints.Max(Comparer<int>.Default), "Max"); Assert.AreEqual(0, ints.Min(Comparer<int>.Default), "Min"); } [Test] public void MaxMin_Work_For_Classes() { var ints = new[] {0, 2, 5, 3}.Select(i => i == 0 ? null : (object) i); Assert.AreEqual(5, ints.Max(Comparer<object>.Default), "Max"); Assert.AreEqual(2, ints.Min(Comparer<object>.Default), "Min"); } [Test, Expects.ArgumentException] public void Max_Throws_On_Empty_Struct_Sequence() { new int[0].Max(Comparer<int>.Default); } [Test, Expects.ArgumentException] public void Min_Throws_On_Empty_Struct_Sequence() { new int[0].Min(Comparer<int>.Default); } [Test] public void MaxMin_Return_Null_On_Empty_Ref_Sequence() { Assert.IsNull(new object[0].Max(Comparer<object>.Default), "Max"); Assert.IsNull(new object[0].Min(Comparer<object>.Default), "Min"); } [Test] public void Slice_Works_For_Full_Arrays() { var sliced = Range .Create(8) .Slice(4) .ToArray(); var expected = new[] { new[] {0, 1, 2, 3}, new[] {4, 5, 6, 7} }; CollectionAssert.AreEqual(expected, sliced); } [Test] public void Slice_Works_For_Partial_Collections() { var sliced = Range .Create(7) .Slice(4) .ToArray(); var expected = new[] { new[] {0, 1, 2, 3}, new[] {4, 5, 6} }; CollectionAssert.AreEqual(expected, sliced); } [Test] public void Slice_Works_For_Empty_Collections() { CollectionAssert.AreEqual(new int[0][], new int[0].Slice(5).ToArray()); } [Test, Expects.ArgumentOutOfRangeException] public void Slice_Detects_Invalid_SliceSize() { new[] {1}.Slice(-1).ToArray(); } //overload [Test] public void Weighted_Slice_Works() { var sliced = Range .Create(8) .Slice(4, i => i, 15) .ToArray(); var expected = new[] { new[] {0, 1, 2, 3}, new[] {4, 5, 6}, new[] {7} }; CollectionAssert.AreEqual(expected, sliced); } [Test] public void Weighted_Slice_Works_For_Empty_Collections() { CollectionAssert.AreEqual(new int[0][], new int[0].Slice(5, i => i, 5).ToArray()); } [Test] public void Distinct() { var sequence = Range.Array(10).Distinct(i => i%3).ToArray(); CollectionAssert.AreEqual(new[] {0, 1, 2}, sequence); } [Test] public void ToArray() { var actual = Range.Create(10).ToArray((i, index) => i + index); var expected = Range.Array(10, i => i*2); CollectionAssert.AreEqual(expected, actual); } [Test] public void ToJaggedArray() { var list = new List<IEnumerable<int>> { new List<int> { 1, 2, 3, }, new List<int> { 6, 5, 4 }, new List<int>() }; var actual = list.ToJaggedArray(); var expected = new[] {new[] {1, 2, 3}, new[] {6, 5, 4}, new int[0]}; CollectionAssert.AreEqual(expected, actual); } [Test] public void FirstOrEmpty() { var obj1 = new object(); var obj2 = new object(); var obj3 = new object(); var seq1 = new[] {obj1, obj2, obj3}; var seq2 = new object[0]; seq1.FirstOrEmpty(o => o == obj3) .ShouldBe(obj3); seq1.FirstOrEmpty(o => o == null) .ShouldFail(); seq1.FirstOrEmpty() .ShouldBe(obj1); seq2.FirstOrEmpty() .ShouldFail(); } [Test] public void ToIndexed() { var enumerable = Range.Create(10).ToIndexed(); Assert.IsTrue(enumerable.First().IsFirst); foreach (var indexer in enumerable) { Assert.AreEqual(indexer.Index, indexer.Value); Assert.AreEqual(indexer.IsFirst, indexer.Index == 0); } } [Test] public void ToIndexDictionary() { var dict = Range.Create(10).ToIndexDictionary(); for (int i = 0; i < 10; i++) { Assert.AreEqual(i, dict[i]); } } [Test] public void ToIndexDictionary_works_with_duplicate_entries() { var dict = new[] { 1, 2, 3, 4, 1 } .ToIndexDictionary(); Assert.AreEqual(0, dict[1]); } [Test] public void SelectValues() { var array = Range.Array(10, n => Rand.NextMaybe(n)); Assert.AreEqual(array.Sum(s => s.GetValue(0)), array.SelectValues().Sum()); } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/MeansImplicitUseAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections) /// </summary> /// <remarks>This attribute helps R# in code analysis</remarks> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class MeansImplicitUseAttribute : Attribute { /// <summary> /// Gets the flags. /// </summary> /// <value>The flags.</value> [UsedImplicitly] public ImplicitUseFlags Flags { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="MeansImplicitUseAttribute"/> class with <see cref="ImplicitUseFlags.STANDARD"/>. /// </summary> [UsedImplicitly] public MeansImplicitUseAttribute() : this(ImplicitUseFlags.STANDARD) { } /// <summary> /// Initializes a new instance of the <see cref="MeansImplicitUseAttribute"/> class. /// </summary> /// <param name="flags">The flags.</param> [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseFlags flags) { Flags = flags; } } }<file_sep>/Source/Lokad.Shared/Tuples/Tuple.7.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Diagnostics; using Lokad.Quality; namespace Lokad { /// <summary> /// Tuple class with 7 items /// </summary> /// <typeparam name="T1">The type of the first item.</typeparam> /// <typeparam name="T2">The type of the second item.</typeparam> /// <typeparam name="T3">The type of the third item.</typeparam> /// <typeparam name="T4">The type of the fourth item.</typeparam> /// <typeparam name="T5">The type of the fifth item.</typeparam> /// <typeparam name="T6">The type of the sixth item.</typeparam> /// <typeparam name="T7">The type of the seventh item.</typeparam> [Serializable] [DebuggerDisplay("({Item1},{Item2},{Item3},{Item4},{Item5},{Item6},{Item7})")] [Immutable] public sealed class Tuple<T1, T2, T3, T4, T5, T6, T7> : IEquatable<Tuple<T1, T2, T3, T4, T5, T6, T7>> { readonly T1 _item1; readonly T2 _item2; readonly T3 _item3; readonly T4 _item4; readonly T5 _item5; readonly T6 _item6; readonly T7 _item7; /// <summary> /// Gets the item1. /// </summary> /// <value>The item1.</value> public T1 Item1 { get { return _item1; } } /// <summary> /// Gets the item2. /// </summary> /// <value>The item2.</value> public T2 Item2 { get { return _item2; } } /// <summary> /// Gets the item3. /// </summary> /// <value>The item3.</value> public T3 Item3 { get { return _item3; } } /// <summary> /// Gets the item4. /// </summary> /// <value>The item4.</value> public T4 Item4 { get { return _item4; } } /// <summary> /// Gets the item5. /// </summary> /// <value>The item5.</value> public T5 Item5 { get { return _item5; } } /// <summary> /// Gets the item6. /// </summary> /// <value>The item6.</value> public T6 Item6 { get { return _item6; } } /// <summary> /// Gets the item7. /// </summary> /// <value>The item7.</value> public T7 Item7 { get { return _item7; } } /// <summary> /// Initializes a new instance of the <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/> class. /// </summary> /// <param name="first">The first item.</param> /// <param name="second">The second item.</param> /// <param name="third">The third item.</param> /// <param name="fourth">The fourth item.</param> /// <param name="fifth">The fifth item.</param> /// <param name="sixth">The sixth item.</param> /// <param name="seventh">The seventh item.</param> public Tuple(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth, T7 seventh) { _item1 = first; _item2 = second; _item3 = third; _item4 = fourth; _item5 = fifth; _item6 = sixth; _item7 = seventh; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/>. /// </returns> public override string ToString() { return string.Format("({0},{1},{2},{3},{4},{5},{6})", Item1, Item2, Item3, Item4, Item5, Item6, Item7); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) throw new NullReferenceException("obj is null"); if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Tuple<T1, T2, T3, T4, T5, T6, T7>)) return false; return Equals((Tuple<T1, T2, T3, T4, T5, T6, T7>) obj); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="obj" /> parameter; otherwise, false. /// </returns> /// <param name="obj"> /// An object to compare with this object. /// </param> public bool Equals(Tuple<T1, T2, T3, T4, T5, T6, T7> obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return Equals(obj.Item1, Item1) && Equals(obj.Item2, Item2) && Equals(obj.Item3, Item3) && Equals(obj.Item4, Item4) && Equals(obj.Item5, Item5) && Equals(obj.Item6, Item6) && Equals(obj.Item7, Item7); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="Tuple{T1,T2,T3,T4,T5,T6,T7}" />. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() { return SystemUtil.GetHashCode(Item1, Item2, Item3, Item4, Item5, Item6, Item7); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Tuple<T1, T2, T3, T4, T5, T6, T7> left, Tuple<T1, T2, T3, T4, T5, T6, T7> right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Tuple<T1, T2, T3, T4, T5, T6, T7> left, Tuple<T1, T2, T3, T4, T5, T6, T7> right) { return !Equals(left, right); } } }<file_sep>/Source/Lokad.ActionPolicy/Exceptions/CircuitBreakerState.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Exceptions { sealed class CircuitBreakerState : ICircuitBreakerState { public CircuitBreakerState(TimeSpan duration, int exceptionsToBreak) { _duration = duration; _exceptionsToBreak = exceptionsToBreak; Reset(); } readonly TimeSpan _duration; readonly int _exceptionsToBreak; int _count; DateTime _blockedTill; Exception _lastException; public Exception LastException { get { return _lastException; } } public bool IsBroken { get { return SystemUtil.Now < _blockedTill; } } public void Reset() { _count = 0; _blockedTill = DateTime.MinValue; _lastException = new InvalidOperationException("This exception should never be thrown"); } public void TryBreak(Exception ex) { _lastException = ex; _count += 1; if (_count >= _exceptionsToBreak) { BreakTheCircuit(); } } void BreakTheCircuit() { _blockedTill = SystemUtil.Now.Add(_duration); } } }<file_sep>/Source/Lokad.Serialization/Serialization/ProtoBufMessageSerializer.cs #region (c)2009-2010 Lokad - New BSD license // Copyright (c) Lokad 2009-2010 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Lokad.Quality; using System.Linq; namespace Lokad.Serialization { [UsedImplicitly] public class ProtoBufMessageSerializer : IMessageSerializer { readonly IDictionary<string, Type> _contract2Type = new Dictionary<string, Type>(); readonly IDictionary<Type, string> _type2Contract = new Dictionary<Type, string>(); readonly IDictionary<Type, IFormatter> _type2Formatter = new Dictionary<Type, IFormatter>(); [UsedImplicitly] public ProtoBufMessageSerializer(ICollection<Type> knownTypes) { if (knownTypes.Count == 0) throw new InvalidOperationException("ProtoBuf requires some known types to serialize. Have you forgot to supply them?"); foreach (var type in knownTypes) { var reference = ProtoBufUtil.GetContractReference(type); var formatter = ProtoBufUtil.CreateFormatter(type); _contract2Type.Add(reference, type); _type2Contract.Add(type, reference); _type2Formatter.Add(type, formatter); } } /// <summary> /// Initializes a new instance of the <see cref="ProtoBufMessageSerializer"/> class. /// </summary> /// <param name="types">The types.</param> [UsedImplicitly] public ProtoBufMessageSerializer(IKnowSerializationTypes types) : this (types.GetKnownTypes().ToSet()) { } public void Serialize(object instance, Stream destination) { _type2Formatter .GetValue(instance.GetType()) .ExposeException("Can't find serializer for unknown object type '{0}'. Have you passed all known types to the constructor?", instance.GetType()) .Serialize(destination, instance); } public object Deserialize(Stream source, Type type) { return _type2Formatter .GetValue(type) .ExposeException("Can't find serializer for unknown object type '{0}'. Have you passed all known types to the constructor?", type) .Deserialize(source); } public Maybe<string> GetContractNameByType(Type messageType) { return _type2Contract.GetValue(messageType); } public Maybe<Type> GetTypeByContractName(string contractName) { return _contract2Type.GetValue(contractName); } } }<file_sep>/Test/Lokad.Quality.Test/CecilExtensionsTest.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Diagnostics; using System.Linq; using Lokad.Testing; using Mono.Cecil; using NUnit.Framework; namespace Lokad.Quality.Test { [TestFixture] public class CecilExtensionsTest { // ReSharper disable RedundantExtendsListEntry [ImmutableAttribute] abstract class B : IA, IB // ReSharper restore RedundantExtendsListEntry { public abstract void Do(); public abstract void Do(IA a); } interface IA : IB { void Do(); void Do(IA a); } interface IB { } readonly Codebase _base = GlobalSetup.Codebase; [Test] public void Interface_Inheritance_Is_Detected() { var inheritance = _b.GetInheritance(_base).ToArray(); // test that there are only unique names var dictionary = inheritance.ToDictionary(t => t.Name).Keys.ToSet(); CollectionAssert.Contains(dictionary, typeof (IB).Name); CollectionAssert.Contains(dictionary, typeof (IA).Name); CollectionAssert.Contains(dictionary, typeof (B).Name); } [Test, Expects.InvalidOperationException] public void Has_Does_Not_Work_On_Serializable() { _b.Has<SerializableAttribute>(); } readonly TypeDefinition _b = GlobalSetup.Codebase.Find<B>(); [Test] public void Has() { Assert.IsTrue(_b.Has<ImmutableAttribute>()); Assert.IsFalse(_b.Has<DebuggableAttribute>()); } } }<file_sep>/Source/Lokad.Shared/Rand.String.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Globalization; using System.Text; using System.Linq; namespace Lokad { partial class Rand { /// <summary> /// Helper random methods related to strings /// </summary> public static class String { static readonly string[] Words; static readonly string[] WordBase = new[] { "2 accumsan", "7 accusam", "2 ad", "2 adipiscing", "2 aliquam", "2 aliquip", "7 aliquyam", "13 amet", "1 assum", "9 at", "2 augue", "3 autem", "2 blandit", "7 clita", "2 commodo", "1 congue", "2 consectetuer", "5 consequat", "7 consetetur", "1 cum", "2 delenit", "15 diam", "2 dignissim", "16 dolor", "14 dolore", "7 dolores", "1 doming", "5 duis", "7 duo", "9 ea", "7 eirmod", "1 eleifend", "2 elit", "7 elitr", "2 enim", "7 eos", "9 erat", "2 eros", "3 esse", "7 est", "32 et", "3 eu", "2 euismod", "3 eum", "2 ex", "2 exerci", "1 facer", "2 facilisi", "3 facilisis", "2 feugait", "3 feugiat", "7 gubergren", "3 hendrerit", "1 id", "3 illum", "1 imperdiet", "6 in", "7 invidunt", "14 ipsum", "3 iriure", "2 iusto", "7 justo", "7 kasd", "7 labore", "2 laoreet", "1 liber", "2 lobortis", "14 lorem", "2 luptatum", "9 magna", "1 mazim", "2 minim", "3 molestie", "1 nam", "2 nibh", "1 nihil" , "2 nisl", "7 no", "1 nobis", "2 nonummy", "7 nonumy", "2 nostrud", "5 nulla", "2 odio", "1 option", "1 placerat", "1 possim", "2 praesent", "2 qui", "2 quis", "1 quod", "7 rebum", "7 sadipscing", "7 sanctus", "7 sea", "15 sed", "13 sit", "1 soluta", "7 stet", "2 suscipit", "7 takimata", "2 tation", "2 te", "8 tempor", "2 tincidunt", "2 ullamcorper", "13 ut", "6 vel", "3 velit", "2 veniam", "9 vero", "6 voluptua", "2 volutpat", "3 vulputate", "2 wisi", "2 zzril", }; static readonly char[] PunctuationBase = ".............!?".ToArray(); static String() { Words = WordBase.SelectMany(w => { var split = w.Split(' '); return Range.Repeat(split[1], int.Parse(split[0])); }).ToArray(); } /// <summary> /// Gets the Lorem Ipsum sentence with random word count. /// </summary> /// <param name="lowerBound">The lower bound for the word count (inclusive).</param> /// <param name="upperBound">The upper bound for the word count (exclusive).</param> /// <returns>random sentence of Lorem ipsum</returns> public static string NextSentence(int lowerBound, int upperBound) { var builder = new StringBuilder(); var count = Next(lowerBound, upperBound); AppendSentence(builder, count); return builder.ToString(); } /// <summary> /// Gets random word from the Lorem Ipsum dictionary. /// </summary> /// <returns>random word from the Lorem Ipsum dictionary</returns> public static string NextWord() { return NextItem(Words); } static void AppendSentence(StringBuilder builder, int count) { for (int i = 0; i < count; i++) { var value = NextWord(); if (i == 0) { value = char.ToUpper(value[0], CultureInfo.InvariantCulture) + value.Remove(0, 1); } else { value = ' ' + value; } builder.Append(value); } if (count > 0) { builder.Append(NextItem(PunctuationBase)); } } /// <summary> /// Gets the Lorem ipsum text with the random word count. /// </summary> /// <param name="lowerBound">The lower bound for the word count (inclusive).</param> /// <param name="upperBound">The upper bound for the word count (exclusive).</param> /// <returns>random text of Lorem Ipsum</returns> public static string NextText(int lowerBound, int upperBound) { int count = Next(lowerBound, upperBound); const int wordsInSentenceUpper = 10; var builder = new StringBuilder(); while (count > 0) { var wordCount = Next(1, Math.Min(wordsInSentenceUpper, count)); AppendSentence(builder, wordCount); count -= wordCount; if (count > 0) { if (NextBool(0.08D)) { builder.AppendLine(); } else builder.Append(' '); } } return builder.ToString(); } } } }<file_sep>/Source/Lokad.Shared/Diagnostics/Persist/ExecutionData.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Lokad.Diagnostics.Persist { /// <summary> /// Diagnostics: Persistence class for aggregated method calls and timing. /// </summary> [Serializable] [DataContract] [DebuggerDisplay("{Name}: {OpenCount}, {RunningTime}")] public sealed class ExecutionData { /// <summary> /// Name of the executing method /// </summary> [XmlAttribute] [DataMember(Order = 1)] public string Name { get; set; } /// <summary> /// Number of times the counter has been opened /// </summary> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 2)] public long OpenCount { get; set; } /// <summary> /// Gets or sets the counter has been closed /// </summary> /// <value>The close count.</value> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 3)] public long CloseCount { get; set; } /// <summary> /// Total execution count of the method in ticks /// </summary> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 4)] public long RunningTime { get; set; } /// <summary> /// Method-specific counters /// </summary> [DataMember(Order = 5)] public long[] Counters { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ExecutionData"/> class. /// </summary> public ExecutionData() { Counters = new long[0]; } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Common/StringIsTests.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Lokad.Testing; using NUnit.Framework; namespace Lokad.Rules { [TestFixture] public sealed class StringIsTests { // ReSharper disable InconsistentNaming const string ValidEmails = @"<EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> IPInsteadOfDomain@127.0.0.1 <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL> <EMAIL>"; const string InvalidEmails = @"<EMAIL> missingDomain@.com @missingLocal.org missingatSign.net missing<EMAIL> colonButNoPort@127.0.0.1: someone-else@127.0.0.1.26 .<EMAIL> <EMAIL> <EMAIL> domainStartsWithDash@-<EMAIL>.com domainEndsWithDash@domain-.com numbersInTLD@domain.c0m missingTLD@domain. ! ""#$%(),/;<>[]`|@<EMAIL> invalidCharsInDomain@! ""#$%(),/;<>_[]`|.org local@SecondLevelDomainNamesAreInvalidIfTheyAreLongerThan64Charactersss.org"; const string ValidHostNames = @"localhost 127.0.0.1 localhost:80 proxy.com:8080 google.com myserver.com uncommonTLD.museum x.org"; const string InvalidHostNames = @"127.0.0.1: _domain.com domain_.com domain.com: domain. ! ""#$%(),/;<>_[]`|.org SecondLevelDomainNamesAreInvalidIfTheyAreLongerThan64Charactersss.org"; static string[] Split(string source) { return source.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } //TL<EMAIL>oc [Test] public void ValidEmail_Positives() { RuleAssert.For<string>(StringIs.ValidEmail) .ExpectNone(Split(ValidEmails)); } [Test] public void ValidEmail_Negatives() { RuleAssert.For<string>(StringIs.ValidEmail) .ExpectError(Split(InvalidEmails)); } [Test] public void ValidHost_Positives() { RuleAssert.For<string>(StringIs.ValidServerConnection) .ExpectNone(Split(ValidHostNames)); } [Test] public void ValidHost_Negatives() { RuleAssert.For<string>(StringIs.ValidServerConnection) .ExpectError(Split(InvalidHostNames)); } [Test] public void Limited_X_Y() { RuleAssert.For(StringIs.Limited(1, 3)) .ExpectNone("A", "AA", "AAA") .ExpectError(null, "", "AAAA"); } [Test] public void Limited_X() { RuleAssert.For(StringIs.Limited(3)) .ExpectNone("", "A", "AA", "AAA") .ExpectError(null, "AAAA"); } [Test] public void Without_X() { RuleAssert.For(StringIs.Without('!')) .ExpectNone("", "ABCD", "?@#") .ExpectError(null, "!", "ABCD!"); } [Test] public void WithoutLeadingWhiteSpace() { RuleAssert.For(StringIs.WithoutLeadingWhiteSpace) .ExpectNone("", "non", "trailing ", "mid dle") .ExpectError(null, "\r new line", "\n new line", "\t tab", " space"); } [Test] public void WithoutTrailingWhiteSpace() { RuleAssert.For(StringIs.WithoutTrailingWhiteSpace) .ExpectNone("", "non", " leading", "mid dle") .ExpectError(null, "new line\r", "new line\n", "tab\t", "space "); } [Test] public void WithoutUppercase() { RuleAssert.For(StringIs.WithoutUppercase) .ExpectNone("", "valid", "another\tvalid") .ExpectError("Fail", "\tthis should Fail"); } } }<file_sep>/Source/Lokad.Stack/Logging/LoggingStack.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; using System.Reflection; using log4net; using log4net.Appender; using log4net.Config; using log4net.Repository; using Lokad.Quality; namespace Lokad.Logging { ///<summary> /// This class provides hookup routines to the logging library ///</summary> public static class LoggingStack { /// <summary> /// Configures the logging system to write to console /// </summary> /// <param name="configure">The configuration option.</param> /// <returns>log syntax</returns> public static LogSyntax UseConsoleLog([NotNull] Action<LogOptions> configure) { Enforce.Argument(() => configure); var options = ConfiguratorHelper.GetDefaultOptions(); configure(options); var appender = ConfiguratorHelper.BuildConsoleLog(options); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Configures the logging system to write to trace /// </summary> /// <param name="configure">The configuration option.</param> /// <returns>log syntax</returns> public static LogSyntax UseTraceLog([NotNull] Action<ListeningLogOptions> configure) { Enforce.Argument(() => configure); var options = ConfiguratorHelper.GetDefaultListeningOptions(); configure(options); var appender = ConfiguratorHelper.BuildTraceLog(options); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Configures the logging system to write to the debug listeners /// </summary> /// <param name="configure">The configuration option.</param> /// <returns>log syntax</returns> public static LogSyntax UseDebugLog([NotNull] Action<ListeningLogOptions> configure) { Enforce.Argument(() => configure); var options = ConfiguratorHelper.GetDefaultListeningOptions(); configure(options); var appender = ConfiguratorHelper.BuildDebugLog(options); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Configures the logging system to write to console /// </summary> /// <returns>log syntax</returns> public static LogSyntax UseTraceLog() { return UseTraceLog(c => { }); } /// <summary> /// Configures the logging system to write to console /// </summary> /// <returns>log syntax</returns> public static LogSyntax UseDebugLog() { return UseTraceLog(c => { }); } /// <summary> /// Configures the logging system to write to console /// </summary> /// <returns>log syntax</returns> public static LogSyntax UseConsoleLog() { return UseConsoleLog(c => { }); } /// <summary> /// Configures the logging system to write to console with colors /// </summary> /// <param name="configure">The configuration options.</param> /// <returns>log syntax</returns> public static LogSyntax UseColoredConsoleLog([NotNull] Action<LogOptions> configure) { Enforce.Argument(() => configure); var options = ConfiguratorHelper.GetDefaultOptions(); configure(options); var appender = ConfiguratorHelper.BuildColoredConsoleLog(options); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Configures the logging system to write to console with colors /// </summary> /// <returns>log syntax</returns> public static LogSyntax UseColoredConsoleLog() { return UseColoredConsoleLog(l => { }); } /// <summary> /// Logging system is configured from App.config /// </summary> public static void UseConfig() { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly())); } /// <summary> /// Resets logging configuration to the default state. /// </summary> public static void Reset() { LogManager.GetRepository(Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly()).ResetConfiguration(); } /// <summary> /// File is used to configure the logging system /// </summary> /// <param name="fileName"></param> public static void ConfigureFromFile(string fileName) { XmlConfigurator.Configure(new FileInfo(fileName)); } /// <summary> Defines logging to Windows Event Log and returns syntax /// to tweak the settings </summary> /// <param name="logName">Name of the event log.</param> /// <param name="applicationName">Name of the application.</param> /// <returns>configuration syntax</returns> public static LogSyntax UseEventLog(string logName, string applicationName) { Enforce.ArgumentNotEmpty(() => logName); Enforce.ArgumentNotEmpty(() => applicationName); var appender = ConfiguratorHelper.GetEventLogAppender(logName, applicationName); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Defines logging to rolling text logs with one log per day /// </summary> /// <param name="path">The path.</param> /// <returns>configuration syntax</returns> public static LogSyntax UseDailyLog(string path) { Enforce.ArgumentNotEmpty(() => path); EnsurePath(path); var appender = ConfiguratorHelper.GetDailyLog(path); Configure(appender); return new LogSyntax(appender); } /// <summary> /// Defines logging to rolling text logs with <paramref name="maxSize"/> /// and <paramref name="numberOfBackups"/> to keep. /// </summary> /// <param name="path">The path to store logs in.</param> /// <param name="maxSize">Max size of the log.</param> /// <param name="numberOfBackups">The number of backups.</param> /// <returns>configuration syntax</returns> public static LogSyntax UseRollingLog(string path, long maxSize, int numberOfBackups) { Enforce.ArgumentNotEmpty(() => path); EnsurePath(path); var appender = ConfiguratorHelper.GetRollingLog(path, numberOfBackups, maxSize); Configure(appender); return new LogSyntax(appender); } static void EnsurePath(string path) { var directory = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(directory)) { Directory.CreateDirectory(directory); } } /// <summary> /// Get log provider /// </summary> /// <returns>provider instance</returns> public static ILogProvider GetLogProvider() { return LogProviderWrapper.Instance; } /// <summary> /// Gets the log with the "Default" name. /// </summary> /// <returns>new log instance</returns> public static ILog GetLog() { return LogWrapper.GetByName("Default"); } static void Configure(IAppender appender) { var repository = LogManager.GetRepository(Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly()); var config = (IBasicRepositoryConfigurator) repository; config.Configure(appender); } } }<file_sep>/Sample/Shared/RulesUI/Program.cs using System; using System.Windows.Forms; namespace RulesUI { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // normally we get this through the IoC IEditorView<Customer> view = new CustomerView(); // ask user for a new customer that complies with some rules view.SetTitle("New customer"); var result = view.GetData( CustomerIs.Valid, CustomerIs.From(AddressIs.Valid)); if (!result.IsSuccess) { MessageBox.Show("Exiting. Reason: " + result.ErrorMessage); return; } MessageBox.Show("Let's edit customer now with more strict rule"); var customer = result.Value; // display customer in the view and ask user to make it // comply with the rule set that is more strict view.SetTitle("Editing " + customer.Name); view.BindData(customer); result = view.GetData( CustomerIs.Valid, CustomerIs.From(AddressIs.Valid, AddressIs.In(Country.Russia))); if (result.IsSuccess) { MessageBox.Show("Congratulations for getting through rule-driven sample"); } } } }<file_sep>/Source/Lokad.Shared/Reflection/TypeCache.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Linq; namespace Lokad.Reflection { static class TypeCache<TModel> { static TypeCache() { foreach (var propertyInfo in typeof(TModel).GetProperties()) { CompilePropertyGetter(propertyInfo); } foreach (var fieldInfo in typeof(TModel).GetFields()) { CompileFieldGetter(fieldInfo); } } public static TValue GetMemberValue<TValue>(TModel instance, Expression<Func<TModel,TValue>> expression) { var info = Express.MemberWithLambda(expression); return (TValue)Getters[info](instance); } static readonly IDictionary<MemberInfo, Func<TModel, object>> Getters = new Dictionary<MemberInfo, Func<TModel, object>>(); static void CompilePropertyGetter(PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) return; if (propertyInfo.GetGetMethod(true).IsStatic) return; // this var self = Expression.Parameter(typeof(TModel), "this"); // this.Property var property = Expression.Property(self, propertyInfo); // (object)((this).Property) var propertyCast = Expression.Convert(property, typeof(object)); var lambda = Expression.Lambda<Func<TModel, object>>(propertyCast, self); Getters.Add(propertyInfo, lambda.Compile()); } static void CompileFieldGetter(FieldInfo fieldInfo) { if (fieldInfo.IsStatic) return; // this var self = Expression.Parameter(typeof(TModel), "this"); // this.Property var accessor = Expression.Field(self, fieldInfo); // (object)((this).Property) var cast = Expression.Convert(accessor, typeof(object)); var lambda = Expression.Lambda<Func<TModel, object>>(cast, self); Getters.Add(fieldInfo, lambda.Compile()); } } }<file_sep>/Source/Lokad.Shared/Linq/ArrayExtensionsForLinq.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace System.Linq { /// <summary> /// Array extensions that belong to the LINQ namespace /// </summary> public static class ArrayExtensionsForLinq { /// <summary> /// Joins arrays together /// </summary> /// <typeparam name="T">type of the arrays</typeparam> /// <param name="self">The first array to join.</param> /// <param name="second">The second array to join.</param> /// <returns>Joined array</returns> public static T[] Append<T>(this T[] self, params T[] second) { if (self == null) throw new ArgumentNullException("self"); if (second == null) throw new ArgumentNullException("second"); var newArray = new T[self.Length + second.Length]; Array.Copy(self, newArray, self.Length); Array.Copy(second, 0, newArray, self.Length, second.Length); return newArray; } ///// <summary> ///// Joins arrays together ///// </summary> ///// <typeparam name="T">type of the arrays</typeparam> ///// <param name="self">The first array to join.</param> ///// <param name="beginning">The second array to join.</param> ///// <returns>Joined array</returns> //public static T[] Prepend<T>(this T[] self, params T[] beginning) //{ // if (self == null) throw new ArgumentNullException("self"); // if (beginning == null) throw new ArgumentNullException("second"); // var newArray = new T[self.Length + beginning.Length]; // Array.Copy(beginning, newArray, beginning.Length); // Array.Copy(self, 0, newArray, beginning.Length, self.Length); // return newArray; //} } }<file_sep>/Source/Lokad.Quality/Extensions/ParameterDefinitionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Helper extensions for the <see cref="ParameterDefinition"/> /// </summary> public static class ParameterDefinitionExtensions { /// <summary> /// Checks by full name if the provided <paramref name="parameter"/> /// matches the provided <typeparamref name="TType"/> /// </summary> /// <typeparam name="TType">type to check against</typeparam> /// <param name="parameter">parameter to check</param> /// <returns> /// <c>true</c> if the specified parameter matches the type; otherwise, <c>false</c>. /// </returns> public static bool Is<TType>(this ParameterDefinition parameter) { return parameter.ParameterType.Is<TType>(); } } }<file_sep>/Source/Lokad.Quality/Extensions/InstructionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Mono.Cecil; using Mono.Cecil.Cil; namespace Lokad.Quality { /// <summary> /// Extension methods for <see cref="Instruction"/> /// </summary> public static class InstructionExtensions { /// <summary> /// Checks if the instruction creates the specified type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instruction">The instr.</param> /// <returns></returns> public static bool Creates<T>(this Instruction instruction) { if (instruction.OpCode != OpCodes.Newobj) return false; var reference = (MemberReference) instruction.Operand; return reference.DeclaringType.FullName == CecilUtil<T>.MonoName; } } }<file_sep>/Source/Lokad.Testing/ExtendResult2.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq.Expressions; namespace Lokad.Testing { /// <summary> /// Extends <see cref="Result{TValue,TError}"/> for the purposes of testing /// </summary> public static class ExtendResult2 { /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <param name="error">The error.</param> /// <returns>same result instance for further inlining</returns> public static Result<TValue, TError> ShouldFailWith<TValue, TError>(this Result<TValue, TError> result, TError error) { Assert.IsFalse(result.IsSuccess, "Result should be a failure"); Assert.IsTrue(result.Error.Equals(error), "Result should have expected failure{0}Expected: {1}.{0}Was: {2}.", Environment.NewLine, error, result.Error); return result; } /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <param name="error">The error.</param> /// <returns>same result instance for further inlining</returns> public static Result<TValue, TError> ShouldBe<TValue, TError>(this Result<TValue, TError> result, TError error) { return ShouldFailWith(result, error); } /// <summary> /// Asserts that the result is valid and equal to some value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <param name="value">The value.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue, TError> ShouldBe<TValue, TError>(this Result<TValue, TError> result, TValue value) { return ShouldPassWith(result, value); } /// <summary> /// Asserts that the result is equal to some error /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <returns>same result instance for further inlining</returns> public static Result<TValue, TError> ShouldFail<TValue, TError>(this Result<TValue, TError> result) { Assert.IsFalse(result.IsSuccess, "Result should be a failure"); return result; } /// <summary> /// Asserts that the result is valid and equal to some value /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <param name="value">The value.</param> /// <returns> /// same result instance for further inlining /// </returns> public static Result<TValue, TError> ShouldPassWith<TValue, TError>(this Result<TValue, TError> result, TValue value) { Assert.IsTrue(result.IsSuccess, "Result should be a success"); var equatable = value as IEquatable<TValue>; if (equatable != null) { Assert.IsTrue(equatable.EqualsTo(result.Value), "Result should be equal to: '{0}'", value); } else { Assert.IsTrue(result.Value.Equals(value), "Result should have value: {0}", value); } return result; } /// <summary> /// Checks that the result has a value matching to the provided expression in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <param name="expression">The expression.</param> /// <returns>same result instance for inlining</returns> public static Result<TValue, TError> ShouldPassCheck<TValue, TError>(this Result<TValue, TError> result, Expression<Func<TValue, bool>> expression) { Assert.IsTrue(result.IsSuccess, "result should be valid"); var check = expression.Compile(); Assert.IsTrue(check(result.Value), "Expression should be true: '{0}'.", expression.Body.ToString()); return result; } /// <summary> /// Ensures that the result is a success in tests. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="result">The result.</param> /// <returns>same result instance for inlining</returns> public static Result<TValue, TError> ShouldPass<TValue, TError>(this Result<TValue, TError> result) { Assert.IsTrue(result.IsSuccess, "Result should be valid"); return result; } } }<file_sep>/Source/Lokad.Shared/Reflection/ReflectLambdaException.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Runtime.Serialization; namespace Lokad.Reflection { /// <summary> /// Exception thrown, when <see cref="Reflect"/> fails to parse some lambda /// </summary> [Serializable] public sealed class ReflectLambdaException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ReflectLambdaException"/> class. /// </summary> /// <param name="message">The message.</param> public ReflectLambdaException(string message) : base(message) { } #if !SILVERLIGHT2 ReflectLambdaException( SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }<file_sep>/Source/GlobalAssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly : AssemblyCompany("Lokad")] [assembly : AssemblyProduct("Lokad Shared Libraries")] [assembly : AssemblyCulture("")] [assembly : ComVisible(false)] [assembly : AllowPartiallyTrustedCallers] ///<summary> /// Assembly information class that is shared between all projects ///</summary> static class GlobalAssemblyInfo { internal const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001009df7" + "e75ec7a084a12820d571ea9184386b479eb6e8dbf365106519bda8fc437cbf8e" + "fb3ce06212ac89e61cd0caa534537575c638a189caa4ac7b831474ceca5a" + "cf5018f2d4b41499044ce90e4f67bb0e8da4121882399b13aabaa6ff" + "46b4c24d5ec6141104028e1b5199e2ba1e35ad95bd50c1cf6ec5" + "<KEY>"; internal const string Copyright = "Copyright (c) Lokad 2008-2009"; internal const string Trademark = "This code is released under the terms of the new BSD licence"; }<file_sep>/Source/VersionAssemblyInfo.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Reflection; [assembly : AssemblyVersion("0.0.0.0")] [assembly : AssemblyFileVersion("0.0.0.0")] [assembly : AssemblyConfiguration("Development version")]<file_sep>/Source/Lokad.Shared/Reflection/Express.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Linq.Expressions; using System.Reflection; using Lokad.Rules; namespace Lokad.Reflection { /// <summary> /// Helper class for the Expression-based strongly-typed reflection /// </summary> public static class Express { static Rule<LambdaExpression> LambdaIs(ExpressionType type) { return (expression, scope) => { if (expression.Body.NodeType != type) scope.Error("Lambda expression must be of type {0}", type); }; } /// <summary> /// Gets the <see cref="MethodInfo"/> /// from the provided <paramref name="method"/>. /// </summary> /// <param name="method">The method expression.</param> /// <returns>method information</returns> public static MethodInfo MethodWithLambda(LambdaExpression method) { Enforce.Argument(() => method, LambdaIs(ExpressionType.Call)); return ((MethodCallExpression) method.Body).Method; } /// <summary> Gets the <see cref="ConstructorInfo"/> from the /// provided <paramref name="constructor"/> lambda. </summary> /// <param name="constructor">The constructor expression.</param> /// <returns>constructor information</returns> public static ConstructorInfo ConstructorWithLamda(LambdaExpression constructor) { Enforce.Argument(() => constructor, LambdaIs(ExpressionType.New)); return ((NewExpression) constructor.Body).Constructor; } /// <summary> Gets the <see cref="MemberInfo"/> (field or property) /// from the provided <paramref name="member"/> </summary> /// <param name="member">The property expression.</param> /// <returns>member information</returns> public static MemberInfo MemberWithLambda(LambdaExpression member) { Enforce.Argument(() => member, LambdaIs(ExpressionType.MemberAccess)); return ((MemberExpression) member.Body).Member; } /// <summary> Gets the <see cref="PropertyInfo"/> from the provided /// <paramref name="property"/> expression. </summary> /// <param name="property">The property expression.</param> /// <returns>property information</returns> public static PropertyInfo PropertyWithLambda(LambdaExpression property) { var value = MemberWithLambda(property); if (value.MemberType != MemberTypes.Property) throw new InvalidOperationException("Member must be a property reference"); return (PropertyInfo) value; } /// <summary> Gets the <see cref="FieldInfo"/> from the provided /// <paramref name="field"/> expression. </summary> /// <param name="field">The field expression.</param> /// <returns>field information</returns> public static FieldInfo FieldWithLambda(LambdaExpression field) { var value = MemberWithLambda(field); if (value.MemberType != MemberTypes.Field) throw new InvalidOperationException("Member must be a field reference"); return (FieldInfo) value; } /// <summary> Gets the <see cref="MethodInfo"/> /// from the provided <paramref name="method"/>. /// </summary> /// <param name="method">The method expression.</param> /// <returns>method information</returns> public static MethodInfo Method(Expression<Action> method) { return MethodWithLambda(method); } /// <summary> /// Gets the <see cref="ConstructorInfo"/> /// from the provided <paramref name="constructorExpression"/>. /// </summary> /// <param name="constructorExpression">The constructor expression.</param> /// <returns>constructor information</returns> public static ConstructorInfo Constructor<T>(Expression<Func<T>> constructorExpression) { return ConstructorWithLamda(constructorExpression); } /// <summary> Gets the <see cref="PropertyInfo"/> from the provided /// <paramref name="property"/> expression. </summary> /// <param name="property">The property expression.</param> /// <returns>property information</returns> public static PropertyInfo Property<T>(Expression<Func<T>> property) { return PropertyWithLambda(property); } /// <summary> Gets the <see cref="FieldInfo"/> from the provided /// <paramref name="field"/> expression. </summary> /// <param name="field">The field expression.</param> /// <returns>field information</returns> public static FieldInfo Field<T>(Expression<Func<T>> field) { return FieldWithLambda(field); } } /// <summary> /// Helper class for the Expression-based strongly-typed reflection /// </summary> public static class Express<TTarget> { /// <summary> Gets the <see cref="MethodInfo"/> from /// the provided <paramref name="method"/> expression. </summary> /// <param name="method">The expression.</param> /// <returns>method information</returns> /// <seealso cref="Express.MethodWithLambda"/> public static MethodInfo Method(Expression<Action<TTarget>> method) { return Express.MethodWithLambda(method); } /// <summary> Gets the <see cref="PropertyInfo"/> from the provided /// <paramref name="property"/> expression. </summary> /// <param name="property">The property expression.</param> /// <returns>property information</returns> /// <seealso cref="Express.MemberWithLambda"/> /// <seealso cref="Express.PropertyWithLambda"/> public static PropertyInfo Property<T>(Expression<Func<TTarget, T>> property) { return Express.PropertyWithLambda(property); } /// <summary> Gets the <see cref="FieldInfo"/> from the provided /// <paramref name="field"/> expression. </summary> /// <param name="field">The field expression.</param> /// <returns>field information</returns> /// <seealso cref="Express.MemberWithLambda"/> /// <seealso cref="Express.FieldWithLambda"/> public static FieldInfo Field<T>(Expression<Func<TTarget, T>> field) { return Express.FieldWithLambda(field); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/Case1/BusinessRules.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Rules { static class BusinessRules { // actual rules. // we assume that good citizenship is enforced (no need to check for nulls) public static void NameRules(string value, IScope scope) { // rules are plain .NET code if (value.Length == 0) scope.Error("String can not be empty"); if (value.Length > 2500) scope.Error("Length must be less than 2500"); } public static void SanitationRules(string value, IScope scope) { if (value.Contains("-")) scope.Error("Can not contain '-'"); } public static void VisitorRules(Visitor visitor, IScope scope) { // rules can validate members in the same manner scope.Validate(visitor.Name, "Name", NameRules); scope.Validate(visitor.Programs, "Programs", ProgramsRules); } public static void ProgramsRules(Program[] programs, IScope scope) { // Validating items of a collection if (programs.Length > 2500) { scope.Error("Only 2500 programs are allowed"); } else { // every item will be validated (or only till the first exception hits, // that's for the scope to decide scope.ValidateInScope(programs, ProgramRules); } } public static void ProgramRules(Program program, IScope scope) { // custom logic if (!program.Active) scope.Error("Program must be active"); // passing member validation down to the next ruleset // (note, that we have multiple rulesets here) scope.Validate(program.Name, "Name", NameRules, SanitationRules); } } }<file_sep>/Source/Lokad.Shared/Silverlight/SerializableAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion #if SILVERLIGHT2 using System; namespace Lokad { /// <summary> /// Attribute marker to make code compatible with Silverlight /// </summary> [AttributeUsage(AttributeTargets.Class,AllowMultiple = false)] sealed class SerializableAttribute : Attribute { } } #endif<file_sep>/Source/Lokad.Quality/Extensions/AssemblyDefinitionExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Helper extensions for the <see cref="AssemblyDefinition"/> /// </summary> public static class AssemblyDefinitionExtensions { /// <summary> /// Gets the modules. /// </summary> /// <param name="self">The self.</param> /// <returns>list of modules for the provided assembly definition</returns> public static IEnumerable<ModuleDefinition> GetModules(this AssemblyDefinition self) { return self.Modules.Cast<ModuleDefinition>(); } /// <summary> /// Gets all assembly references for the modules in the provided <see cref="AssemblyDefinition"/>. /// </summary> /// <param name="self">The assembly definition to check.</param> /// <returns>enumerable of the assembly references</returns> /// <remarks>This is a lazy routine</remarks> public static IEnumerable<AssemblyNameReference> GetAssemblyReferences(this AssemblyDefinition self) { return self.GetModules().SelectMany(m => m.AssemblyReferences.Cast<AssemblyNameReference>()); } /// <summary> /// Gets all <see cref="TypeDefinition"/> entries for the modules in the provided /// <see cref="AssemblyDefinition"/>. /// </summary> /// <param name="self">The assembly definition to scan.</param> /// <returns>This is a lazy routine</returns> public static IEnumerable<TypeDefinition> GetAllTypes(this AssemblyDefinition self) { return self.Modules.Cast<ModuleDefinition>().SelectMany(m => m.Types.Cast<TypeDefinition>()); } /// <summary> /// Gets all the <see cref="TypeDefinition"/> important types for the modules in the /// provided <see cref="AssemblyDefinition"/> /// </summary> /// <param name="self">The <see cref="AssemblyDefinition"/> to check.</param> /// <returns>lazy enumerator over the results</returns> public static IEnumerable<TypeDefinition> GetTypes(this AssemblyDefinition self) { return self.Modules .Cast<ModuleDefinition>() .SelectMany(m => m.Types.Cast<TypeDefinition>()) .Where(t => !t.Has<CompilerGeneratedAttribute>() && !t.Name.StartsWith("<") && !t.Name.StartsWith("__")); } /// <summary> /// Gets the type references for the modules in the provided <paramref name="assemblyDefinition"/>. /// </summary> /// <param name="assemblyDefinition">The assembly definition.</param> /// <returns>lazy enumerator over the results</returns> public static IEnumerable<TypeReference> GetTypeReferences(this AssemblyDefinition assemblyDefinition) { return assemblyDefinition.Modules .Cast<ModuleDefinition>() .SelectMany(m => m.TypeReferences.Cast<TypeReference>()); } } }<file_sep>/Test/Lokad.Shared.Test/Rules/ExtendIScopeForMediumTrustTests.cs using System; using System.Diagnostics; using NUnit.Framework; using System.Linq; namespace Lokad.Rules { [TestFixture] public sealed class ExtendIScopeForMediumTrustTests { // ReSharper disable InconsistentNaming sealed class Model { public string Name { get; set; } public string Login; public string[] Names { get; set; } public string[] Logins; public Model() { Names = new string[0]; Logins = new string[0]; } } static void ValidateModelExpression(Model model, IScope scope) { scope.Validate(model, m => m.Login, StringIs.ValidEmail); scope.Validate(model, m => m.Name, StringIs.NotEmpty); scope.ValidateMany(model, m => m.Logins, StringIs.ValidEmail); scope.ValidateMany(model, m => m.Names, StringIs.NotEmpty); } static void ValidateModel(Model model, IScope scope) { scope.Validate(() => model.Login, StringIs.ValidEmail); scope.Validate(() => model.Name, StringIs.NotEmpty); } [Test, Explicit, Ignore] public void Test() { var model = new Model() { Login = "<EMAIL>", Name = "<NAME>" }; MeasureExecution(() => Scope.IsValid(model, ValidateModelExpression)); MeasureExecution(() => Scope.IsValid(model, ValidateModel)); } [Test] public void Invalid_field() { var model = new Model() { Login = "<EMAIL>", Name = "" }; RuleAssert.IsError(model, ValidateModelExpression); } [Test] public void Invalid_property() { var model = new Model() { Login = "<EMAIL>", Name = "valid" }; RuleAssert.IsError(model, ValidateModelExpression); } [Test] public void Invalid_property_collection() { RuleAssert.IsError(new Model() { Login = "<EMAIL>", Name = "valid", Names = new []{""} }, ValidateModelExpression); } [Test] public void Invalid_field_collection() { RuleAssert.IsError(new Model() { Login = "<EMAIL>", Name = "valid", Logins = new[] { "non-email" } }, ValidateModelExpression); } [Test] public void Valid_model() { RuleAssert.IsNone(new Model() { Login = "<EMAIL>", Name = "valid", Logins = new[] { "<EMAIL>" }, Names = new [] { "Another name"} }, ValidateModelExpression); } static void MeasureExecution(Action action) { action(); // JIT var startNew = Stopwatch.StartNew(); for (int i = 0; i < 100000; i++) { action(); } startNew.Stop(); Console.WriteLine("Execution time: {0} ", startNew.Elapsed); } } }<file_sep>/Source/Lokad.Quality/Extensions/CustomAttributeExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Extension helpers for <see cref="CustomAttribute"/> /// </summary> public static class CustomAttributeExtensions { /// <summary> /// Checks by full name if the provided <paramref name="attribute"/> /// matches the provided <typeparamref name="TAttribute"/> /// </summary> /// <typeparam name="TAttribute">type to check against</typeparam> /// <param name="attribute">attribute to check</param> /// <returns> /// <c>true</c> if the specified attribute matches the type; otherwise, <c>false</c>. /// </returns> public static bool Is<TAttribute>(this CustomAttribute attribute) { return attribute.Constructor.DeclaringType.Is<TAttribute>(); } } }<file_sep>/Sample/Shared/RulesUI/Customer.cs namespace RulesUI { public sealed class Customer { readonly Address _address; readonly string _name; readonly string _email; public Customer(string name, Address address, string email) { _address = address; _email = email; _name = name; } public string Email { get { return _email; } } public string Name { get { return _name; } } public Address Address { get { return _address; } } } }<file_sep>/Source/Lokad.Shared/Quality/ReSharper/CanBeNullAttribute.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Quality { /// <summary> /// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] [NoCodeCoverage] public sealed class CanBeNullAttribute : Attribute { } }<file_sep>/Source/Lokad.Shared/Serialization/ISupportSyntaxForSerialization.cs #region Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // Copyright (c) 2009-2010 LOKAD SAS. All rights reserved. // You must not remove this notice, or any other, from this software. // This document is the property of LOKAD SAS and must not be disclosed. #endregion namespace Lokad.Serialization { /// <summary> /// Syntax support for .Serialization configurations. /// </summary> public interface ISupportSyntaxForSerialization { /// <summary> /// Registers the specified data serializer as singleton implementing <see cref="IMessageSerializer"/>, <see cref="IDataSerializer"/> and <see cref="IDataContractMapper"/>. It can import <see cref="IKnowSerializationTypes"/> /// </summary> /// <typeparam name="TSerializer">The type of the serializer.</typeparam> void RegisterSerializer<TSerializer>() where TSerializer : IMessageSerializer; } }<file_sep>/Source/Lokad.Quality/Extensions/TypeReferenceExtensions.cs #region (c)2009 Lokad - New BSD license // Copyright (c) Lokad 2009 // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using Mono.Cecil; namespace Lokad.Quality { /// <summary> /// Helper extensions for the <see cref="TypeReference"/> /// </summary> public static class TypeReferenceExtensions { /// <summary> /// Determines whether the provided name has name mathcing to the <typeparamref name="TType"/> /// </summary> /// <typeparam name="TType">type to compare with</typeparam> /// <param name="definition">The definition.</param> /// <returns> /// <c>true</c> if the specified definition matches the provided type, overwise <c>false</c>. /// </returns> public static bool Is<TType>(this TypeReference definition) { return definition.FullName == CecilUtil<TType>.MonoName; } /// <summary> /// Determines whether the provided <see cref="TypedReference"/> /// has specified attribute (matching is done by full name) /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="self">The <see cref="TypeDefinition"/> to check.</param> /// <returns> /// <c>true</c> if the type has the specified attribute otherwise, <c>false</c>. /// </returns> public static bool Has<TAttribute>(this TypeReference self) where TAttribute : Attribute { if (typeof (TAttribute) == typeof (SerializableAttribute)) { throw new InvalidOperationException("SerializableAttribute should be checked by inspecting type flags"); } foreach (CustomAttribute attribute in self.CustomAttributes) { if (attribute.Is<TAttribute>()) return true; } return false; } } }
24b79681d331d9f93a469b7cd6945654922d2f2c
[ "C#", "Text" ]
296
C#
AndreasSummer/lokad-shared-libraries
a8b7467a4bac49db5f26f7dd4694c1e8f485140c
b5b76b706d62a7cacdf2b72dd78e55f09f6bec36
refs/heads/master
<repo_name>luyoutao/scater<file_sep>/R/areSizeFactorsCentred.R #' Check if the size factors are centred at unity #' #' Checks if each set of size factors is centred at unity, such that abundances can be reasonably compared between features normalized with different sets of size factors. #' #' @param object A SingleCellExperiment object containing any number of (or zero) sets of size factors. #' @param centre a numeric scalar, the value around which all sets of size factors should be centred. #' @param tol a numeric scalar, the tolerance for testing equality of the mean of each size factor set to \code{centre}. #' #' @return A logical scalar indicating whether all sets of size factors are centered. #' If no size factors are available, \code{TRUE} is returned. #' #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), #' colData = sc_example_cell_info #' ) #' keep_gene <- rowSums(counts(example_sce)) > 0 #' example_sce <- example_sce[keep_gene,] #' #' sizeFactors(example_sce) <- runif(ncol(example_sce)) #' areSizeFactorsCentred(example_sce) #' example_sce <- normalize(example_sce, centre = TRUE) #' areSizeFactorsCentred(example_sce) #' areSizeFactorsCentred <- function(object, centre=1, tol=1e-6) { all.sf.sets <- c(list(NULL), as.list(sizeFactorNames(object))) for (sfname in all.sf.sets) { sf <- sizeFactors(object, type=sfname) if (!is.null(sf) && abs(mean(sf) - centre) > tol) { return(FALSE) } } return(TRUE) } <file_sep>/R/10ximport-wrapper.R #' Load in data from 10x experiment #' #' Creates a full or sparse matrix from a sparse data matrix provided by 10X #' genomics. #' #' @param data_dir Directory containing the matrix.mtx, genes.tsv, and #' barcodes.tsv files provided by 10x. A vector or named vector can be given in #' order to load several data directories. If a named vector is given, the cell #' barcode names will be prefixed with the name. #' @param min_total_cell_counts integer(1) threshold such that cells (barcodes) #' with total counts below the threshold are filtered out #' @param min_mean_gene_counts numeric(1) threshold such that genes with mean #' counts below the threshold are filtered out. #' @param ... passed arguments #' #' @details This function calls \code{\link[DropletUtils]{read10xCounts}} #' from the \pkg{DropletUtils} package. It is deprecated and will be removed #' in the next release. #' #' @return Returns an SingleCellExperiment object with counts data stored as a #' sparse matrix. Rows are named with the gene name and columns are named with #' the cell barcode (if \code{data_dir} contains one element; otherwise the #' columns are unnamed to avoid problems with non-unique barcodes). #' #' @import Matrix #' @rdname read10xResults #' @aliases read10xResults read10XResults #' @export #' @examples #' sce10x <- read10xResults(system.file("extdata", package="scater")) #' read10xResults <- function(data_dir, min_total_cell_counts = NULL, min_mean_gene_counts = NULL) { .Deprecated("DropletUtils::read10xCounts") out <- DropletUtils::read10xCounts(data_dir) if (!is.null(min_total_cell_counts)) { keep_cell <- .colSums(counts(out)) >= min_total_cell_counts out <- out[,keep_cell] } if (!is.null(min_mean_gene_counts)) { keep_gene <- .rowMeans(counts(out)) >= min_mean_gene_counts out <- out[keep_gene,] } return(out) } #' @rdname read10xResults #' @export read10XResults <- function(...) { read10xResults(...) } #' Downsample a count matrix #' #' Downsample a count matrix to a desired proportion. #' #' @param x matrix of counts #' @param prop numeric scalar or vector of length \code{ncol(x)} in [0, 1] #' indicating the downsampling proportion #' #' @details This function calls \code{\link[DropletUtils]{downsampleMatrix}}. #' from the \pkg{DropletUtils} package. It is deprecated and will be removed #' in the next release. #' #' @return an integer matrix of downsampled counts #' #' @export #' @examples #' sce10x <- read10xResults(system.file("extdata", package="scater")) #' downsampled <- downsampleCounts(counts(sce10x), prop = 0.5) #' downsampleCounts <- function(x, prop) { .Deprecated("DropletUtils::downsampleMatrix") DropletUtils::downsampleMatrix(x, prop) } <file_sep>/R/calculate-expression.R ## A set of functions for calculating and summarising expression values #' Calculate which features are expressed in which cells using a threshold on #' observed counts, transcripts-per-million, counts-per-million, FPKM, or #' defined expression levels. #' #' @param object a \code{\link{SingleCellExperiment}} object with expression #' and/or count data. #' @param detection_limit numeric scalar giving the minimum expression level #' for an expression observation in a cell for it to qualify as expressed. #' @param exprs_values character scalar indicating whether the count data #' (\code{"counts"}), the log-transformed count data (\code{"logcounts"}), #' transcript-per-million (\code{"tpm"}), counts-per-million (\code{"cpm"}) or #' FPKM (\code{"fpkm"}) should be used to define if an observation is expressed #' or not. Defaults to the first available value of those options in the #' order shown. #' @return a logical matrix indicating whether or not a feature in a particular #' cell is expressed. #' #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' assay(example_sce, "is_exprs") <- calcIsExprs(example_sce, #' detection_limit = 1, exprs_values = "counts") calcIsExprs <- function(object, detection_limit = 0, exprs_values = "counts") { assay(object, i = exprs_values) > detection_limit } #' Count the number of expressed genes per cell #' #' #' @param object a \code{\link{SingleCellExperiment}} object or a numeric #' matrix of expression values. #' @param detection_limit numeric scalar providing the value above which #' observations are deemed to be expressed. Defaults to #' \code{object@detection_limit}. #' @param exprs_values character scalar indicating whether the count data #' (\code{"counts"}), the log-transformed count data (\code{"logcounts"}), #' transcript-per-million (\code{"tpm"}), counts-per-million (\code{"cpm"}) or #' FPKM (\code{"fpkm"}) should be used to define if an observation is expressed #' or not. Defaults to the first available value of those options in the #' order shown. However, if \code{is_exprs(object)} is present, it will be #' used directly; \code{exprs_values} and \code{detection_limit} are ignored. #' @param byrow logical scalar indicating if \code{TRUE} to count expressing #' cells per feature (i.e. gene) and if \code{FALSE} to count expressing #' features (i.e. genes) per cell. #' @param subset_row logical, integeror character vector indicating which rows #' (i.e. features/genes) to use. #' @param subset_col logical, integer or character vector indicating which columns #' (i.e., cells) to use. #' #' @details Setting \code{subset_row} or \code{subset_col} is equivalent to #' subsetting \code{object} before calling \code{nexprs}, but more efficient #' as a new copy of the matrix is not constructed. #' #' @description An efficient internal function that avoids the need to construct #' 'is_exprs_mat' by counting the number of expressed genes per cell on the fly. #' #' @return If \code{byrow=TRUE}, an integer vector containing the number of cells #' expressing each feature, of the same length as the number of features in #' \code{subset_row} (all features in \code{exprs_mat} if \code{subset_row=NULL}). #' #' If \code{byrow=FALSE}, an integer vector containing the number of genes #' expressed in each cell, of the same length as the number of cells specified in #' \code{subset_col} (all cells in \code{exprs_mat} if \code{subset_col=NULL}). #' #' @import SingleCellExperiment #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' nexprs(example_sce)[1:10] #' nexprs(example_sce, byrow = TRUE)[1:10] #' nexprs <- function(object, detection_limit = 0, exprs_values = "counts", byrow = FALSE, subset_row = NULL, subset_col = NULL) { if (methods::is(object, "SingleCellExperiment")) { exprs_mat <- assay(object, i = exprs_values) } else { exprs_mat <- object } subset_row <- .subset2index(subset_row, target = exprs_mat, byrow = TRUE) subset_col <- .subset2index(subset_col, target = exprs_mat, byrow = FALSE) if (!byrow) { return(.colAbove(exprs_mat, rows=subset_row, cols=subset_col, value=detection_limit)) } else { return(.rowAbove(exprs_mat, rows=subset_row, cols=subset_col, value=detection_limit)) } } #' Calculate transcripts-per-million (TPM) #' #' Calculate transcripts-per-million (TPM) values for expression from counts for #' a set of features. #' #' @param object a \code{SingleCellExperiment} object #' @param effective_length vector of class \code{"numeric"} providing the #' effective length for each feature in the \code{SingleCellExperiment} object #' @param calc_from character string indicating whether to compute TPM from #' \code{"counts"}, \code{"normcounts"} or \code{"fpkm"}. #' Default is to use \code{"counts"}, in which case the \code{effective_length} #' argument must be supplied. #' #' @return Matrix of TPM values. #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' tpm(example_sce) <- calculateTPM(example_sce, effective_length = 5e04, #' calc_from = "counts") #' #' ## calculate from FPKM #' fpkm(example_sce) <- calculateFPKM(example_sce, effective_length = 5e04, #' use_size_factors = FALSE) #' tpm(example_sce) <- calculateTPM(example_sce, effective_length = 5e04, #' calc_from = "fpkm") calculateTPM <- function(object, effective_length = NULL, calc_from = "counts") { if ( !methods::is(object, "SingleCellExperiment") ) stop("object must be an SingleCellExperiment") ## Check that arguments are correct calc_from <- match.arg(calc_from, c("counts", "normcounts", "fpkm"), several.ok = FALSE) if ( calc_from == "counts" || calc_from == "normcounts" ) { if ( is.null(effective_length) ) stop("effective_length argument is required if computing TPM from counts") } ## Compute values to return tpm_to_add <- switch(calc_from, counts = .countToTpm(counts(object), effective_length), normcounts = .countToTpm(normcounts(object), effective_length), fpkm = .fpkmToTpm(fpkm(object))) ## Return TPM values rownames(tpm_to_add) <- rownames(object) colnames(tpm_to_add) <- colnames(object) tpm_to_add } .countToTpm <- function(counts, eff_len) { ## Expecting a count matrix of nfeatures x ncells ## can't have any zero counts, so expect to apply offset counts0 <- counts counts0[counts == 0] <- NA rate <- log(counts0) - log(eff_len) denom <- log(.colSums(counts)) out <- exp( t(t(as.matrix(rate)) - denom) + log(1e6) ) out[is.na(out)] <- 0 out } .countToFpkm <- function(counts, eff_len) { ## Expecting a count matrix of nfeatures x ncells ## Need to be careful with zero counts counts0 <- counts counts0[counts == 0] <- NA logfpkm <- log(counts0) + log(1e9) - log(eff_len) logfpkm <- t(t(logfpkm) - log(.colSums(counts))) out <- exp( logfpkm ) out[is.na(out)] <- 0 out } .fpkmToTpm <- function(fpkm) { ## Expecting an FPKM matrix of nfeatures x ncells exp( t(t(log(as.matrix(fpkm))) - log(.colSums(fpkm))) + log(1e6) ) } .countToEffCounts <- function(counts, len, eff_len) { counts * (len / eff_len) } #' Calculate counts per million (CPM) #' #' Calculate count-per-million (CPM) values from the count data. #' #' @param object A SingleCellExperiment object or count matrix. #' @param exprs_values A string specifying the assay of \code{object} #' containing the count matrix, if \code{object} is a SingleCellExperiment. #' @param use_size_factors a logical scalar specifying whether #' the size factors in \code{object} should be used to construct #' effective library sizes. #' @param size_factors A numeric vector containing size factors to #' use for all non-spike-in features. #' #' @details #' If requested, size factors are used to define the effective library sizes. #' This is done by scaling all size factors such that the mean scaled size factor is equal to the mean sum of counts across all features. #' The effective library sizes are then used to compute the CPM matrix. #' #' If \code{use_size_factors=TRUE} and \code{object} is a SingleCellExperiment, size factors are automatically extracted from the object. #' If \code{use_size_factors=FALSE} or \code{object} is a matrix, the sum of counts for each cell is directly used as the library size. #' #' Note that effective library sizes may be computed differently for features marked as spike-in controls. #' This is due to the presence of control-specific size factors in \code{object}. #' See \code{\link{normalizeSCE}} for more details. #' #' If \code{size_factors} is supplied, it will override the any size factors for non-spike-in features in \code{object} (if it is a SingleCellExperiment). #' The spike-in size factors will still be used. #' If \code{object} is a matrix, \code{size_factors} will be used instead of the library size. #' #' @return Matrix of CPM values. #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' cpm(example_sce) <- calculateCPM(example_sce, use_size_factors = FALSE) #' calculateCPM <- function(object, exprs_values="counts", use_size_factors = TRUE, size_factors = NULL) { sf_list <- list(size.factors=list(NULL), index = rep(1L, nrow(object))) if (is(object, 'SingleCellExperiment')) { if (use_size_factors) { sf_list <- .get_all_sf_sets(object) } object <- assay(object, i=exprs_values) } # Overwriting size factors if provided, otherwise defaulting to lib sizes. if (!is.null(size_factors)) { sf_list$size.factors[[1]] <- size_factors } else if (is.null(sf_list$size.factors[[1]])) { sf_list$size.factors[[1]] <- librarySizeFactors(object) } # Computing a CPM matrix. Size factors are centered at 1, so # all we have to do is to divide further by the library size (in millions). cpm_mat <- .compute_exprs(object, sf_list$size.factors, sf_to_use = sf_list$index, log = FALSE, sum = FALSE, logExprsOffset = 0, subset_row = NULL) lib_sizes <- .colSums(object) cpm_mat <- cpm_mat / (mean(lib_sizes)/1e6) # Restoring attributes. rownames(cpm_mat) <- rownames(object) colnames(cpm_mat) <- colnames(object) return(cpm_mat) } #' Calculate fragments per kilobase of exon per million reads mapped (FPKM) #' #' Calculate fragments per kilobase of exon per million reads mapped (FPKM) #' values for expression from counts for a set of features. #' #' @param object an \code{SingleCellExperiment} object #' @param effective_length vector of class \code{"numeric"} providing the #' effective length for each feature in the \code{SCESet} object #' @param ... Further arguments to pass to \code{\link{calculateCPM}}. #' #' @return Matrix of FPKM values. #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' effective_length <- rep(1000, 2000) #' fpkm(example_sce) <- calculateFPKM(example_sce, effective_length, #' use_size_factors = FALSE) #' calculateFPKM <- function(object, effective_length, ...) { if ( !methods::is(object, "SingleCellExperiment") ) stop("object must be an SingleCellExperiment") cpms <- calculateCPM(object, ...) effective_length <- effective_length / 1e3 cpms / effective_length } <file_sep>/R/normalizeSCE.R #' Normalise a SingleCellExperiment object using pre-computed size factors #' #' Compute normalised expression values from count data in a SingleCellExperiment object, using the size factors stored in the object. #' #' @param object A SingleCellExperiment object. #' @param exprs_values String indicating which assay contains the count data that should be used to compute log-transformed expression values. #' @param return_log Logical scalar, should normalized values be returned on the log2 scale? # If \code{TRUE}, output is stored as \code{"logcounts"} in the returned object; if \code{FALSE} output is stored as \code{"normcounts"}. #' @param log_exprs_offset Numeric scalar specifying the offset to add when log-transforming expression values. #' If \code{NULL}, value is taken from \code{metadata(object)$log.exprs.offset} if defined, otherwise 1. #' @param centre_size_factors Logical scalar, should size factors centred at unity be stored in the returned object if \code{exprs_values="counts"}? #' @param ... Arguments passed to \code{normalize} when calling \code{normalise}. #' #' @details #' Features marked as spike-in controls will be normalized with control-specific size factors, if these are available. #' This reflects the fact that spike-in controls are subject to different biases than those that are removed by gene-specific size factors (namely, total RNA content). #' If size factors for a particular spike-in set are not available, a warning will be raised. #' #' Size factors will automatically be centred prior to calculation of normalized expression values, regardless of the value of \code{centre_size_factors}. #' The \code{centre_size_factors} argument is only used to determine whether the #' #' \code{normalize} is exactly the same as \code{normalise}, the option #' provided for those who have a preference for North American or #' British/Australian spelling. #' #' @section Warning about centred size factors: #' Centring the size factors ensures that the computed \code{exprs} can be interpreted as being on the same scale as log-counts. #' This is also standardizes the effect of the \code{log_exprs_offset} addition, #' and ensures that abundances are roughly comparable between features normalized with different sets of size factors. #' #' Generally speaking, centering does not affect relative comparisons between cells in the same \code{object}, as all size factors are scaled by the same amount. #' However, if two different \code{SingleCellExperiment} objects are run separately through \code{normalize}, the size factors in each object will be rescaled differently. #' This means that the size factors and log-expression values will \emph{not} be comparable between objects. #' #' This lack of comparability is not always obvious. #' For example, if we subsetted an existing SingleCellExperiment object, and ran \code{normalize} separately on each subset, #' the resulting expression values in each subsetted object would \emph{not} be comparable to each other. #' This is despite the fact that all cells were originally derived from a single SingleCellExperiment object. #' #' In general, it is advisable to only compare size factors and expression values between cells in one SingleCellExperiment object. #' If objects are to be combined, new size factors should be computed using all cells in the combined object, followed by running \code{normalize}. #' #' @return an SingleCellExperiment object #' #' @name normalize #' @rdname normalize #' @aliases normalize normalise normalize,SingleCellExperiment-method normalise,SingleCellExperiment-method #' @author <NAME> and <NAME> #' @importFrom BiocGenerics normalize #' @importFrom S4Vectors metadata 'metadata<-' #' @importFrom SummarizedExperiment assay #' #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), #' colData = sc_example_cell_info #' ) #' keep_gene <- rowSums(counts(example_sce)) > 0 #' example_sce <- example_sce[keep_gene,] #' #' ## Apply TMM normalisation taking into account all genes #' example_sce <- normaliseExprs(example_sce, method = "TMM") #' ## Scale counts relative to a set of control features (here the first 100 features) #' example_sce <- normaliseExprs(example_sce, method = "none", #' feature_set = 1:100) #' #' ## normalize the object using the saved size factors #' example_sce <- normalize(example_sce) #' normalizeSCE <- function(object, exprs_values = "counts", return_log = TRUE, log_exprs_offset = NULL, centre_size_factors = TRUE) { exprs_mat <- assay(object, i = exprs_values) sf.list <- .get_all_sf_sets(object) if (is.null(sf.list$size.factors[[1]])) { warning("using library sizes as size factors") sf.list$size.factors[[1]] <- .colSums(exprs_mat) } ## using logExprsOffset=1 if argument is NULL if ( is.null(log_exprs_offset)) { if (!is.null(metadata(object)$log.exprs.offset)) { log_exprs_offset <- metadata(object)$log.exprs.offset } else { log_exprs_offset <- 1 } } ## Compute normalized expression values. norm_exprs <- .compute_exprs( exprs_mat, sf.list$size.factors, sf_to_use = sf.list$index, log = return_log, sum = FALSE, logExprsOffset = log_exprs_offset, subset_row = NULL) ## add normalised values to object if (return_log) { assay(object, "logcounts") <- norm_exprs metadata(object)$log.exprs.offset <- log_exprs_offset } else { assay(object, "normcounts") <- norm_exprs } ## centering all existing size factors if requested if (centre_size_factors) { sf <- sizeFactors(object) if (!is.null(sf)) { sf <- sf / mean(sf) sizeFactors(object) <- sf } # ... and for all named size factor sets. for (type in sizeFactorNames(object)) { sf <- sizeFactors(object, type = type) sf <- sf / mean(sf) sizeFactors(object, type = type) <- sf } } ## return object return(object) } #' @rdname normalize #' @aliases normalize #' @export setMethod("normalize", "SingleCellExperiment", normalizeSCE) #' @rdname normalize #' @aliases normalise #' @export normalise <- function(...) { normalize(...) } <file_sep>/R/calcAverage.R #' Calculate average counts, adjusting for size factors or library size #' #' Calculate average counts per feature, adjusting them as appropriate to take #' into account for size factors for normalization or library sizes (total #' counts). #' #' @param object A SingleCellExperiment object or count matrix. #' @param exprs_values A string specifying the assay of \code{object} containing the count matrix, if \code{object} is a SingleCellExperiment. #' @param use_size_factors a logical scalar specifying whetherthe size factors in \code{object} should be used to construct effective library sizes. #' @param size_factors A numeric vector containing size factors to use for all non-spike-in features. #' @param subset_row A vector specifying whether the rows of \code{object} should be (effectively) subsetted before calcaulting feature averages. #' #' @details #' The size-adjusted average count is defined by dividing each count by the size factor and taking the average across cells. #' All sizes factors are scaled so that the mean is 1 across all cells, to ensure that the averages are interpretable on the scale of the raw counts. #' #' If \code{use_size_factors=TRUE} and \code{object} is a SingleCellExperiment, size factors are automatically extracted from the object. #' For spike-in controls, control-specific size factors will be used if available (see \code{\link{normalizeSCE}}). #' If \code{use_size_factors=FALSE} or \code{object} is a matrix, the library size for each cell is used as the size factor via \code{\link{librarySizeFactors}}. #' #' If \code{size_factors} is supplied, it will override the any size factors for non-spike-in features in \code{object} (if it is a SingleCellExperiment). #' The spike-in size factors will still be used. #' If \code{object} is a matrix, \code{size_factors} will be used instead of the library size. #' #' @return Vector of average count values with same length as number of features, or the number of features in \code{subset_row} if supplied. #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' #' ## calculate average counts #' ave_counts <- calcAverage(example_sce) #' calcAverage <- function(object, exprs_values="counts", use_size_factors=TRUE, size_factors=NULL, subset_row = NULL) { sf_list <- list(size.factors=list(NULL), index = rep(1L, nrow(object))) if (is(object, 'SingleCellExperiment')) { if (use_size_factors) { sf_list <- .get_all_sf_sets(object) } object <- assay(object, i=exprs_values) } # Overwriting size factors if provided, otherwise defaulting to lib sizes. if (!is.null(size_factors)) { sf_list$size.factors[[1]] <- rep(size_factors, length.out=ncol(object)) } else if (is.null(sf_list$size.factors[[1]])) { sf_list$size.factors[[1]] <- librarySizeFactors(object) } # Computes the average count, adjusting for size factors or library size. all.ave <- .compute_exprs(object, sf_list$size.factors, sf_to_use = sf_list$index, log = FALSE, sum = TRUE, logExprsOffset = 0, subset_row = subset_row) # Adding names while being row-aware. if (!is.null(subset_row)) { tmp_subset <- .subset2index(subset_row, object) names(all.ave) <- rownames(object)[tmp_subset] } else { names(all.ave) <- rownames(object) } return(all.ave / ncol(object)) } <file_sep>/R/normalizeExprs.R #' Normalise expression levels for a SingleCellExperiment object #' #' Compute normalised expression values from a SingleCellExperiment object and #' return the object with the normalised expression values added. #' #' @param object A SingleCellExperiment object. #' @param method character string specified the method of calculating #' normalisation factors. Passed to \code{\link[edgeR]{calcNormFactors}}. #' @param design design matrix defining the linear model to be fitted to the #' normalised expression values. If not \code{NULL}, then the residuals of this #' linear model fit are used as the normalised expression values. #' @param feature_set character, numeric or logical vector indicating a set of #' features to use for calculating normalisation factors. If character, entries #' must all be in \code{featureNames(object)}. If numeric, values are taken to #' be indices for features. If logical, vector is used to index features and should #' have length equal to \code{nrow(object)}. #' @param exprs_values character string indicating which slot of the #' assayData from the \code{SingleCellExperiment} object should be used for the calculations. #' Valid options are \code{'counts'}, \code{'tpm'}, \code{'cpm'}, \code{'fpkm'} #' and \code{'exprs'}. Defaults to the first available value of these options in #' in order shown. #' @param return_norm_as_exprs logical, should the normalised expression values #' be returned to the \code{exprs} slot of the object? Default is TRUE. If #' FALSE, values in the \code{exprs} slot will be left untouched. Regardless, #' normalised expression values will be returned to the \code{norm_exprs} slot #' of the object. #' @param return_log logical(1), should normalized values be returned on the log #' scale? Default is \code{TRUE}. If \code{TRUE} and \code{return_norm_as_exprs} #' is \code{TRUE} then normalised output is stored as \code{"logcounts"} in the #' returned object; if \code{TRUE} and \code{return_norm_as_exprs} #' is \code{FALSE} then normalised output is stored as \code{"norm_exprs"}; #' if \code{FALSE} output is stored as \code{"normcounts"} #' @param ... arguments passed to \code{normaliseExprs} (in the case of #' \code{normalizeExprs}) or to \code{\link[edgeR]{calcNormFactors}}. #' #' @details This function allows the user to compute normalised expression #' values from an SingleCellExperiment object. The 'raw' values used can be the values in the #' \code{'counts'} (default), or another specified assay slot #' of the SingleCellExperiment. Normalised expression values are computed through #' \code{\link{normalizeSCE}} and are on the log2-scale by default (if #' \code{return_log} is TRUE), with an offset defined by the #' \code{metadata(object)$log.exprs.offset} value in the SingleCellExperiment #' object. These are added to the \code{'norm_exprs'} slot of the returned object. If #' \code{'exprs_values'} argument is \code{'counts'} and \code{return_log} is #' \code{FALSE} a \code{'normcounts'} slot is added, containing normalised #' counts-per-million values. #' #' If the raw values are counts, this function will compute size factors using #' methods in \code{\link[edgeR]{calcNormFactors}}. Library sizes are multiplied #' by size factors to obtain an "effective library size" before calculation of #' the aforementioned normalized expression values. If \code{feature_set} is #' specified, only the specified features will be used to calculate the #' size factors. #' #' If the user wishes to remove the effects of certain explanatory variables, #' then the \code{'design'} argument can be defined. The \code{design} argument #' must be a valid design matrix, for example as produced by #' \code{\link[stats]{model.matrix}}, with the relevant variables. A linear #' model is then fitted using \code{\link[limma]{lmFit}} on expression values #' after any size-factor and library size normalisation as descrived above. The #' returned values in \code{'norm_exprs'} are the residuals from the linear #' model fit. #' #' After normalisation, normalised expression values can be accessed with the #' \code{\link{norm_exprs}} function (with corresponding accessor functions for #' counts, tpm, fpkm, cpm). These functions can also be used to assign normalised #' expression values produced with external tools to a SingleCellExperiment object. #' #' \code{normalizeExprs} is exactly the same as \code{normaliseExprs}, provided #' for those who prefer North American spelling. #' #' @return an SingleCellExperiment object #' #' @name normalizeExprs #' @rdname normalizeExprs #' @aliases normalizeExprs #' #' @author <NAME> #' @importFrom edgeR calcNormFactors.default #' @importFrom limma lmFit #' @importFrom limma residuals.MArrayLM #' @export #' @examples #' data("sc_example_counts") #' data("sc_example_cell_info") #' example_sce <- SingleCellExperiment( #' assays = list(counts = sc_example_counts), colData = sc_example_cell_info) #' keep_gene <- rowSums(counts(example_sce)) > 0 #' example_sce <- example_sce[keep_gene,] #' #' ## Apply TMM normalisation taking into account all genes #' example_sce <- normaliseExprs(example_sce, method = "TMM") #' ## Scale counts relative to a set of control features (here the first 100 features) #' example_sce <- normaliseExprs(example_sce, method = "none", #' feature_set = 1:100) #' normalizeExprs <- function(object, method = "none", design = NULL, feature_set = NULL, exprs_values = "counts", return_norm_as_exprs = TRUE, return_log = TRUE, ...) { .Deprecated(msg="'normalizeExprs' is deprecated. Use edgeR::calcNormFactors(), normalize(), limma::removeBatchEffect() directly instead.") if (!methods::is(object, "SingleCellExperiment")) stop("object argument must be a SingleCellExperiment") ## If counts, we can compute size factors. if (exprs_values == "counts") { exprs_mat <- assay(object, i = exprs_values) ## Check feature_set if (is.character(feature_set)) { if ( !(all(feature_set %in% rownames(object))) ) stop("not all 'feature_set' in 'rownames(object)'") } if ( !is.null(feature_set) ) exprs_mat_for_norm <- exprs_mat[feature_set,] else exprs_mat_for_norm <- exprs_mat ## Compute normalisation factors with calcNormFactors from edgeR norm_factors <- edgeR::calcNormFactors.default(exprs_mat_for_norm, method = method, ...) lib_size <- .colSums(exprs_mat_for_norm) if ( any(is.na(norm_factors)) ) { norm_factors[is.na(norm_factors)] <- 1 warning("normalization factors with NA values replaced with unity") } size_factors <- norm_factors * lib_size size_factors <- size_factors / mean(size_factors) sizeFactors(object) <- size_factors ## Computing (normalized) CPMs is also possible. assay(object, "normcounts") <- calculateCPM(object, use_size_factors = TRUE) } ## Computing normalized expression values, if we're not working with 'exprs'. if (exprs_values != "logcounts") { object <- normalizeSCE( object, exprs_values = exprs_values, return_log = return_log) } ## If a design matrix is provided, then normalised expression values are ## residuals of a linear model fit to norm_exprs values with that design if ( !is.null(design) ) { if (exprs_values != "logcounts") { if (return_log) { if (return_norm_as_exprs) norm_exprs_mat <- exprs(object) else norm_exprs_mat <- norm_exprs(object) } else { if (return_norm_as_exprs) norm_exprs_mat <- normcounts(object) } } else norm_exprs_mat <- exprs(object) limma_fit <- limma::lmFit(norm_exprs_mat, design) if (return_log) norm_exprs(object) <- limma::residuals.MArrayLM( limma_fit, norm_exprs_mat) else normcounts(object) <- limma::residuals.MArrayLM( limma_fit, norm_exprs_mat) } ## Return normalised expression values in exprs(object)? if ( return_norm_as_exprs && return_log && exprs_values == "logcounts" ) assay(object, "logcounts") <- norm_exprs(object) ## Return SingleCellExperiment object object } #' @rdname normalizeExprs #' @aliases normliseExprs #' @export normaliseExprs <- function(...) { normalizeExprs(...) }
53ecf7506ebd86f7063b8f337d905d9df66cd0f6
[ "R" ]
6
R
luyoutao/scater
64c648926ae3a43267a9d4ea64da6585b095116f
6b93ee6c25e799c0ba3c815629764561db2c3c2e
refs/heads/master
<repo_name>clintko/BarcodeMatcher_tmp<file_sep>/src/cdist_str.cpp #include "BarcodeMatcher.h" #include <Rcpp.h> using namespace Rcpp; int hamming(const std::string& str1, const std::string& str2) { // init //int dist = 1; //* int dist = 0; int len1 = str1.length(); int len2 = str2.length(); // check input if(len1 != len2) { throw std::invalid_argument("Two strings are not of the same length!"); } // end if // calculate hamming disance for (int idx = 0; idx < len1; idx += 1){ if (str1[idx] != str2[idx]) { dist += 1; } // end if } // end for //*/ return dist; } // end func //' @export // [[Rcpp::export]] NumericVector cdist_str( const StringVector& vec_str1, const StringVector& vec_str2 ) { // init int len1 = vec_str1.length(); int len2 = vec_str2.length(); NumericMatrix mat_dist(len1, len2); //for (int idx1 = 0; idx1 < len1; idx1 += 1){ // std::cout << vec_str1[idx1] << std::endl; //} //* // pairwise distance for (int idx1 = 0; idx1 < len1; idx1 += 1){ //std::cout << std::string(vec_str1[idx1]) << std::endl; for (int idx2 = 0; idx2 < len2; idx2 += 1){ //mat_dist(idx1, idx2) = hamming( // std::string(vec_str1[idx1]), // std::string(vec_str2[idx2])); mat_dist(idx1, idx2) = dist_metric_hamming( std::string(vec_str1[idx1]), std::string(vec_str2[idx2])); } // end inner loop } // end outer loop //*/ return mat_dist; } // You can include R code blocks in C++ files processed with sourceCpp // (useful for testing and development). The R code will be automatically // run after the compilation. // /*** R cdist_str(c("ab", "ac"), c("bb", "bc", "bd")) */ <file_sep>/src/dist_metric_hamming.cpp #include "BarcodeMatcher.h" #include <Rcpp.h> using namespace Rcpp; // This is a simple example of exporting a C++ function to R. You can // source this function into an R session using the Rcpp::sourceCpp // function (or via the Source button on the editor toolbar). Learn // more about Rcpp at: // // http://www.rcpp.org/ // http://adv-r.had.co.nz/Rcpp.html // http://gallery.rcpp.org/ // //' @export // [[Rcpp::export]] int dist_metric_hamming( const std::string& str1, const std::string& str2 ) { // init int dist = 0; int len1 = str1.size(); int len2 = str2.size(); // check input if(len1 != len2) { throw std::invalid_argument("Two strings are not of the same length!"); } // end if // calculate hamming disance for (int idx = 0; idx < len1; idx += 1){ if (str1[idx] != str2[idx]) { dist += 1; } // end if } // end for return dist; } // end func // You can include R code blocks in C++ files processed with sourceCpp // (useful for testing and development). The R code will be automatically // run after the compilation. // /*** R dist_metric_hamming("abc", "aBc") */ <file_sep>/tests/testthat/test-hello.R context("test-hello") # note: for more info of using test, check below # https://www.youtube.com/watch?v=MoszELQFrvQ test_that("multiplication works", { expect_equal(2 * 2, 4) }) <file_sep>/R/RcppExports.R # Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: <PASSWORD> #' @export cdist_str <- function(vec_str1, vec_str2) { .Call('_BarcodeMatcher_cdist_str', PACKAGE = 'BarcodeMatcher', vec_str1, vec_str2) } #' @export dist_metric_hamming <- function(str1, str2) { .Call('_BarcodeMatcher_dist_metric_hamming', PACKAGE = 'BarcodeMatcher', str1, str2) } #' @export timesTwo <- function(x) { .Call('_BarcodeMatcher_timesTwo', PACKAGE = 'BarcodeMatcher', x) } <file_sep>/tests/testthat.R library(testthat) library(BarcodeMatcher) test_check("BarcodeMatcher") <file_sep>/src/BarcodeMatcher.h #include <Rcpp.h> int dist_metric_hamming( const std::string& str1, const std::string& str2 );<file_sep>/README.md # BarcodeMatcher a small Rcpp package for matching short reads to sequence library of barcodes # Problem solving usable to export Rcpp and the problem with Roxygen2 **ref** - https://www.r-bloggers.com/rcpp-and-roxygen2/ - https://github.com/klutometis/roxygen/issues/130 - https://support.rstudio.com/hc/en-us/community/posts/200653376-Rcpp-and-Roxygen # Problem solving deal with string http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1internal_1_1string__proxy.html http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2012-November/004643.html # Problem solving r package calling other c++ function https://stackoverflow.com/questions/31406910/using-a-c-function-in-an-other-c-function-inside-a-r-package-with-rcpp<file_sep>/R/testfun.R #' your_package #' #' Description of your package #' #' @docType package #' @author clintko #' @import Rcpp #' @importFrom Rcpp evalCpp #' @useDynLib BarcodeMatcher #' @name BarcodeMatcher NULL #' create an R function with the document. The document is copied from klutometis/roxygen #' #' @param x input numeric vector #' @param y input numeric vector #' @seealso \code{\link{fun_add}} which this function wraps #' @export #' @examples #' str_length(letters) #' str_length(c("i", "like", "programming", NA)) myfun <- function(x, y) { result = myfun_add(x, y) print(result) } #' create second R function with the document. #' #' @param x input numeric vector #' @param y input numeric vector #' @return sum up the numeric vectors #' @seealso \code{\link{fun}} which this function wraps #' @export #' @examples #' str_length(letters) #' str_length(c("i", "like", "programming", NA)) myfun_add <- function(x, y) { return(x + y) }
836b198f4ac368f379755f730be3fb6c7ffd0a4d
[ "Markdown", "R", "C++" ]
8
C++
clintko/BarcodeMatcher_tmp
74d39aa0b4082aaf2d066143f5eede9d9a66f28a
f16430d6554dd11fa98261b400d7e419e9b8a29a
refs/heads/master
<file_sep>#Step 0. Prepararing library needed and getting the files #Calling dplyr library library("dplyr") #Download the data url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(url,"./web_computing_data_set.zip") #Unziping unzip("./web_computing_data_set.zip") #Reading features and activity labels data features <- read.table("./UCI HAR Dataset/features.txt") activity_labels <- read.table("./UCI HAR Dataset/activity_labels.txt") #Reading train data training_set <- read.table("./UCI HAR Dataset/train/X_train.txt",col.names = features$V2) training_labels <- read.table("./UCI HAR Dataset/train/y_train.txt",col.names="code") training_subject <- read.table("./UCI HAR Dataset/train/subject_train.txt",col.names="subject") #Reading test data test_set <- read.table("./UCI HAR Dataset/test/X_test.txt",col.names = features$V2) test_labels <- read.table("./UCI HAR Dataset/test/y_test.txt", col.names = "code") test_subject <- read.table("./UCI HAR Dataset/test/subject_test.txt",col.names="subject") # Step 1. Merges the training and the test sets to create one data set #Combining by sections data_sets <- rbind(training_set,test_set) data_labels <- rbind(training_labels,test_labels) data_subjects <- rbind(training_subject,test_subject) #Combining all data data <- cbind(data_subjects,data_labels,data_sets) # Step 2. Extracts only the measurements on the mean and standard deviation for each measurement data_filtered <- select(data,subject, code, contains("mean"), contains("std")) # Step 3. Uses descriptive activity names to name the activities in the data set data_filtered$code <- activity_labels[data_filtered$code, 2] # Step 4. Appropriately labels the data set with descriptive variable names names(data_filtered)[2] = "activity" names(data_filtered) <- gsub("^t", "Time", names(data_filtered)) names(data_filtered) <- gsub("^f", "Frequency", names(data_filtered)) names(data_filtered) <- gsub("Acc", "Accelerometer", names(data_filtered)) names(data_filtered) <- gsub("Gyro", "Gyroscope", names(data_filtered)) names(data_filtered) <- gsub("BodyBody", "Body", names(data_filtered)) names(data_filtered) <- gsub("Mag", "Magnitude", names(data_filtered)) names(data_filtered) <- gsub("angle", "Angle", names(data_filtered)) names(data_filtered) <- gsub("gravity", "Gravity", names(data_filtered)) names(data_filtered) <- gsub("..","",names(data_filtered),fixed = TRUE) # Step 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject #Generating variables' average by group tidy_data <- data_filtered %>% group_by(subject,activity) %>% summarise_all(funs(mean)) #Creating the independent tidy data set file write.table(tidy_data,"tidy_data.txt",row.names = FALSE) <file_sep># Getting and Cleaning Data - Course Project This repository was created for the project course of Getting and Cleaning Data which is the third course of the Data Science: Foundations Using R specialization ## Project summary As the instruccions says, the purpose of this project is to "demonstrate your ability to collect, work with, and clean a data set". In order to achieving that, the participants have to prepare a tidy data set using for later analysis. The data is in the context of wearable computers, specifically accelerometers from the Samsung Galaxy S smartphone. You can access the data [here](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones). **Review criteria** * The submitted data set is tidy. * The Github repo contains the required scripts. * GitHub contains a code book that modifies and updates the available codebooks with the data to indicate all the variables and summaries calculated, along with units, and any other relevant information. * The README that explains the analysis files is clear and understandable. * The work submitted for this project is the work of the student who submitted it. ## Repository content `CodeBook.md` explains the data used, describes the variables and the transformations needed to clean it up. `run_analysis.R` is the script with the process to obtain the tidy data set. It's explained step by step `tidy_data-txt` the final result `README.md` the file that you're already reading at ## How does the script works The `run_analysis.R` has the code and descriptive comments to obtain a tidy data set. Basically, it containts five steps, but I added a step cero to explain how to get the data. 0. **Prepararing library needed and getting the files**. First, it loads the dplyr library that uses in a future step. Second, downloads the data and unziping it. Then, reads each file, identifying the ones that came from test or train and also if it is a set, label o subject file. Also reads the complementary files, features and activity labels. 1. **Merges the training and the test sets to create one data set**. This is an important step because is where all the data beggings to take form. The first part combines by sections, that means it unify the set file from train and test, then the label file from train and test, as the same way it does with subject. The second part it's when everything gets unified because links the subjects, labels and set in a same file. 2. **Extracts only the measurements on the mean and standard deviation for each measurement**. Using `select()` from the `dplyr` library it filters the data according to the requirements 3. **Uses descriptive activity names to name the activities in the data set**. A quick one, takes the activity labels file and assing its values to the code variable in the unifed data we have created 4. **Appropriately labels the data set with descriptive variable names**. This is the largest step. The first part to get through it is check on he data column names and analyze what isn't easy to understand. The point is that a variable name could be clear, so that the reader hasn't need to check the code book for to undestand it. Then when it's clear what it's necesary to improve, the function gsub gets very useful to subtitute in string objects. 5. **From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject**. The final one. Using the chain technique, it groups the data by subject and activity to then get the means of every variable in the data set and assing the result to a new frame called `tidy_data`, which is also available in the repository. The last lines is the one that creates the txt file. <file_sep># Code Book This code book first presents a quick explanation to the initial data used and then presents a deeper explanaition on the `tidy_data.txt` file ## Initial data The data was obtained from the [Human Activity Recognition Using Smartphones Dataset] (https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip). This is a zip files that contains three princiapl sections: identifiers, train and test. According to the autors, the summary of the data is: > The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. This datasets includes the following files: - `README.txt` - `features_info.txt`: Shows information about the variables used on the feature vector. - `features.txt`: List of all features. - `activity_labels.txt`: Links the class labels with their activity name. - `train/X_train.txt`: Training set. - `train/y_train.txt`: Training labels. - `test/X_test.txt`: Test set. - `test/y_test.txt`: Test labels. ## Tidy data file In order to the requirements of the project, a process of cleaning up the data has been done, which is specified in the `run_analysis.R` script. So, not all the varaible from the initial data where used. Here are explained the ones that form part from the `tidy_data.txt`. The data 180 observationts and 88 variables. The first two are the idetifiers which were used to group the data. The rest are measurements ### Identifiers `subject` - ID of participant * interger * 1 - 30 values `activity` - The type of activity that they were performing when the measurements were taken * character * 6 values * Walking * Walking Upstairs * Walking Downstairs * Sitting * Standing * Laying ### Measurements Correspond to the mean o standard deviation of different features * numeric * 86 variables "subject" "activity" "TimeBodyAccelerometer.mean.X" "TimeBodyAccelerometer.mean.Y" "TimeBodyAccelerometer.mean.Z" "TimeGravityAccelerometer.mean.X" "TimeGravityAccelerometer.mean.Y" "TimeGravityAccelerometer.mean.Z" "TimeBodyAccelerometerJerk.mean.X" "TimeBodyAccelerometerJerk.mean.Y" "TimeBodyAccelerometerJerk.mean.Z" "TimeBodyGyroscope.mean.X" "TimeBodyGyroscope.mean.Y" "TimeBodyGyroscope.mean.Z" "TimeBodyGyroscopeJerk.mean.X" "TimeBodyGyroscopeJerk.mean.Y" "TimeBodyGyroscopeJerk.mean.Z" "TimeBodyAccelerometerMagnitude.mean" "TimeGravityAccelerometerMagnitude.mean" "TimeBodyAccelerometerJerkMagnitude.mean" "TimeBodyGyroscopeMagnitude.mean" "TimeBodyGyroscopeJerkMagnitude.mean" "FrequencyBodyAccelerometer.mean.X" "FrequencyBodyAccelerometer.mean.Y" "FrequencyBodyAccelerometer.mean.Z" "FrequencyBodyAccelerometer.meanFreq.X" "FrequencyBodyAccelerometer.meanFreq.Y" "FrequencyBodyAccelerometer.meanFreq.Z" "FrequencyBodyAccelerometerJerk.mean.X" "FrequencyBodyAccelerometerJerk.mean.Y" "FrequencyBodyAccelerometerJerk.mean.Z" "FrequencyBodyAccelerometerJerk.meanFreq.X" "FrequencyBodyAccelerometerJerk.meanFreq.Y" "FrequencyBodyAccelerometerJerk.meanFreq.Z" "FrequencyBodyGyroscope.mean.X" "FrequencyBodyGyroscope.mean.Y" "FrequencyBodyGyroscope.mean.Z" "FrequencyBodyGyroscope.meanFreq.X" "FrequencyBodyGyroscope.meanFreq.Y" "FrequencyBodyGyroscope.meanFreq.Z" "FrequencyBodyAccelerometerMagnitude.mean" "FrequencyBodyAccelerometerMagnitude.meanFreq" "FrequencyBodyAccelerometerJerkMagnitude.mean" "FrequencyBodyAccelerometerJerkMagnitude.meanFreq" "FrequencyBodyGyroscopeMagnitude.mean" "FrequencyBodyGyroscopeMagnitude.meanFreq" "FrequencyBodyGyroscopeJerkMagnitude.mean" "FrequencyBodyGyroscopeJerkMagnitude.meanFreq" "Angle.tBodyAccelerometerMean.Gravity." "Angle.tBodyAccelerometerJerkMeanGravityMean." "Angle.tBodyGyroscopeMean.GravityMean." "Angle.tBodyGyroscopeJerkMean.GravityMean." "Angle.X.GravityMean." "Angle.Y.GravityMean." "Angle.Z.GravityMean." "TimeBodyAccelerometer.std.X" "TimeBodyAccelerometer.std.Y" "TimeBodyAccelerometer.std.Z" "TimeGravityAccelerometer.std.X" "TimeGravityAccelerometer.std.Y" "TimeGravityAccelerometer.std.Z" "TimeBodyAccelerometerJerk.std.X" "TimeBodyAccelerometerJerk.std.Y" "TimeBodyAccelerometerJerk.std.Z" "TimeBodyGyroscope.std.X" "TimeBodyGyroscope.std.Y" "TimeBodyGyroscope.std.Z" "TimeBodyGyroscopeJerk.std.X" "TimeBodyGyroscopeJerk.std.Y" "TimeBodyGyroscopeJerk.std.Z" "TimeBodyAccelerometerMagnitude.std" "TimeGravityAccelerometerMagnitude.std" "TimeBodyAccelerometerJerkMagnitude.std" "TimeBodyGyroscopeMagnitude.std" "TimeBodyGyroscopeJerkMagnitude.std" "FrequencyBodyAccelerometer.std.X" "FrequencyBodyAccelerometer.std.Y" "FrequencyBodyAccelerometer.std.Z" "FrequencyBodyAccelerometerJerk.std.X" "FrequencyBodyAccelerometerJerk.std.Y" "FrequencyBodyAccelerometerJerk.std.Z" "FrequencyBodyGyroscope.std.X" "FrequencyBodyGyroscope.std.Y" "FrequencyBodyGyroscope.std.Z" "FrequencyBodyAccelerometerMagnitude.std" "FrequencyBodyAccelerometerJerkMagnitude.std" "FrequencyBodyGyroscopeMagnitude.std" "FrequencyBodyGyroscopeJerkMagnitude.std"
fee61167c48d78f6bbcc4f29438cdf0ff1bc8d11
[ "Markdown", "R" ]
3
R
editholiva/getting-and-cleaning-data-project
5f273f0e2b949419e37b7d9a8a2d19e59cbebb8b
0d1fcc5e37f1c3d7d3990140643e529aabea5506
refs/heads/master
<file_sep>MM.Format.FreeMind = Object.create(MM.Format, { id: {value: "freemind"}, label: {value: "FreeMind"}, extension: {value: "mm"}, mime: {value: "application/x-freemind"} }); MM.Format.FreeMind.to = function(data) { var doc = document.implementation.createDocument(null, null); var map = doc.createElement("map"); map.setAttribute("version", "0.9.0"); map.appendChild(this._serializeItem(doc, data.root)); doc.appendChild(map); var serializer = new XMLSerializer(); return serializer.serializeToString(doc); } MM.Format.FreeMind.from = function(data) { var parser = new DOMParser(); var doc = parser.parseFromString(data, "application/xml"); if (doc.documentElement.nodeName.toLowerCase() == "parsererror") { throw new Error(doc.documentElement.textContent); } var root = doc.documentElement.getElementsByTagName("node")[0]; if (!root) { throw new Error("No root node found"); } var json = { root: this._parseNode(root, {shape:"underline"}) }; json.root.layout = "map"; json.root.shape = "ellipse"; return json; } MM.Format.FreeMind._serializeItem = function(doc, json) { var elm = this._serializeAttributes(doc, json); (json.children || []).forEach(function(child) { elm.appendChild(this._serializeItem(doc, child)); }, this); return elm; } MM.Format.FreeMind._serializeAttributes = function(doc, json) { var elm = doc.createElement("node"); elm.setAttribute("TEXT", MM.Format.br2nl(json.text)); elm.setAttribute("ID", json.id); if (json.side) { elm.setAttribute("POSITION", json.side); } if (json.shape == "box") { elm.setAttribute("STYLE", "bubble"); } if (json.collapsed) { elm.setAttribute("FOLDED", "true"); } return elm; } MM.Format.FreeMind._parseNode = function(node, parent) { var json = this._parseAttributes(node, parent); for (var i=0;i<node.childNodes.length;i++) { var child = node.childNodes[i]; if (child.nodeName.toLowerCase() == "node") { json.children.push(this._parseNode(child, json)); } } return json; } MM.Format.FreeMind._parseAttributes = function(node, parent) { var json = { children: [], text: MM.Format.nl2br(node.getAttribute("TEXT") || ""), id: node.getAttribute("ID") }; var position = node.getAttribute("POSITION"); if (position) { json.side = position; } var style = node.getAttribute("STYLE"); if (style == "bubble") { json.shape = "box"; } else { json.shape = parent.shape; } if (node.getAttribute("FOLDED") == "true") { json.collapsed = 1; } var children = node.children; for (var i=0;i<children.length;i++) { var child = children[i]; switch (child.nodeName.toLowerCase()) { case "richcontent": var body = child.querySelector("body > *"); if (body) { var serializer = new XMLSerializer(); json.text = serializer.serializeToString(body).trim(); } break; case "font": if (child.getAttribute("ITALIC") == "true") { json.text = "<i>" + json.text + "</i>"; } if (child.getAttribute("BOLD") == "true") { json.text = "<b>" + json.text + "</b>"; } break; } } return json; } <file_sep>SOURCES = src/mm.js \ src/promise.js \ src/promise-addons.js \ src/repo.js \ src/item.js \ src/map.js \ src/keyboard.js \ src/tip.js \ src/action.js \ src/clipboard.js \ src/menu.js \ src/command.js \ src/command.edit.js \ src/command.select.js \ src/layout.js \ src/layout.graph.js \ src/layout.tree.js \ src/layout.map.js \ src/shape.js \ src/shape.underline.js \ src/shape.box.js \ src/shape.ellipse.js \ src/format.js \ src/format.json.js \ src/format.freemind.js \ src/format.mma.js \ src/format.mup.js \ src/format.plaintext.js \ src/backend.js \ src/backend.local.js \ src/backend.webdav.js \ src/backend.image.js \ src/backend.file.js \ src/backend.firebase.js \ src/backend.gdrive.js \ src/ui.js \ src/ui.layout.js \ src/ui.shape.js \ src/ui.value.js \ src/ui.status.js \ src/ui.color.js \ src/ui.help.js \ src/ui.io.js \ src/ui.backend.js \ src/ui.backend.file.js \ src/ui.backend.webdav.js \ src/ui.backend.image.js \ src/ui.backend.local.js \ src/ui.backend.firebase.js \ src/ui.backend.gdrive.js \ src/mouse.js \ src/app.js .PHONY: all push clean all: my-mind.js my-mind.js: $(SOURCES) @echo "/* My Mind web app: all source files combined. */" > $@ @cat $^ >> $@ push: @hg bookmark -f master @hg push ; true @hg push github ; true clean: @rm my-mind.js
1039e5d6535a3d5e8a63498e328b19dc63f7fc24
[ "JavaScript", "Makefile" ]
2
JavaScript
HassanChiang/HassanChiang.github.io
83f5e90182c679ec0a86c9049572d11f142588aa
8685a58587670cd138af8acec8b85cd6e8a6c9c4
refs/heads/master
<file_sep>.account 公開用アカウント [openzeppelin のインストール](https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package) npm install @openzeppelin/contracts-ethereum-package [apiのtest](https://ch7s5hybm7.execute-api.ap-northeast-1.amazonaws.com/dev) tx-get:scanで全件取得してフロント側でFromAddressでフィルター or scan後にFromAddress以外を削除 or EtherscanのAPIから取得?? fin: txs-get tx-create EVT配布量:1人450EVT, ETH:1人 0.05ETH 評価 利用者に追加配布(12/6)をして、流動性があがるかどうか見る トークンを送り合った結果利用者間のコミュニケーションが増えたか、組織の活動が活性化したか<file_sep> google.charts.load('current', {packages: ['corechart', 'line'], "language":"ja"}); google.charts.setOnLoadCallback(drawBasic); var vm = new Vue function drawBasic() { fetch(url + "/user" + "?address=" + localStorage.getItem("address"), { method: "GET", }) .then(function (response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function (json) { throw new Error(json.message); }); }) .then(function (json) { // レスポンスが200番で返ってきたときの処理はここに記述する localStorage.setItem("g_weight", json.Item.g_weight); user_g_weight = json.Item.g_weight; }) .catch(function (err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); var data = new google.visualization.DataTable(); fetch(url + "/weight" + "?userId=" + localStorage.getItem("address"),{ method: "GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する //if(json.Items){ delete json.Items.userId; //} weights = json.Items; i = 0; day = 1; data.addColumn('string', 'days'); data.addColumn('number', '体重'); data.addColumn('number', '目標体重'); data.addRows(weights.length); g_border = localStorage.getItem("g_weight"); min_weight = 0; max_weight = 0; weights.forEach( function (weight) { //data.addRows([weight.timeStamp, weight.weight]); s = "8/" + day; data.setValue(i, 0, s); data.setValue(i, 1, weight.weight); data.setValue(i, 2, localStorage.getItem("g_weight"));//localStorage.getItem("g_weight")で目標取得 if(max_weight < weight.weight){ max_weight = weight.weight; } if(min_weight > weight.weight){ min_weight = weight.weight; } //data.addRows([i, j]); i = i + 1; day++; }); var chart = new google.visualization.LineChart(document.getElementById('chart_div')); /*var options = { hAxis: { title: '年月' }, vAxis: { title: '体重(kg)' }, "width":700, "height":400 };*/ options = { width: 700, height: 400, legend: 'bottom', vAxis:{minValue:(g_border - 5),maxValue:(max_weight + 5),gridlined:{count:5 }}, title: '体重の推移' }; chart.draw(data, options); }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); /* data.addRows([ [0, 0], [1, 10], [2, 23], [3, 17], [4, 18], [5, 9], [6, 11], [7, Number(weight.weight)], [8, 33], [9, 40], [10, 32], [11, 35], [12, 30], [13, 40], [14, 42], [15, 47], [16, 44], [17, 48], [18, 52], [19, 54], [20, 42], [21, 55], [22, 56], [23, 57], [24, 60], [25, 50], [26, 52], [27, 51], [28, 49], [29, 53], [30, 55], [31, 60], [32, 61], [33, 59], [34, 62], [35, 65], [36, 62], [37, 58], [38, 55], [39, 61], [40, 64], [41, 65], [42, 63], [43, 66], [44, 67], [45, 69], [46, 69], [47, 70], [48, 72], [49, 68], [50, 66], [51, 65], [52, 67], [53, 70], [54, 71], [55, 72], [56, 73], [57, 75], [58, 70], [59, 68], [60, 64], [61, 60], [62, 65], [63, 67], [64, 68], [65, 69], [66, 70], [67, 72], [68, 75], [69, 80] ]);*/ }<file_sep><?PHP function h($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); } function h2($s){ return htmlentities($s); } function getlog(){ $user_ip = getenv("REMOTE_ADDR"); $user_agent = $_SERVER['HTTP_USER_AGENT']; $access_time = date("Y-m-d,H:i:s");//この配列に日付けや時間が入ってる $csv_filename = "accesslog.csv"; $ary = array($user_agent, $user_ip, $access_time); //chmod("/home/developers/sakurai/public_html/task/work1", ); $f = fopen($csv_filename, "a"); fputcsv($f, $ary); fclose($f); } getlog(); if(isset($_POST['Text']) == 'TRUE'){ $comment = $_POST['Text']; XSS_escapeForHTML($comment); $Counter = mb_strlen($comment); echo "入力内容"; echo "<br>"; echo $comment; echo "<br />"; echo "文字数:"; echo $Counter; $text_filename = 'count.txt'; file_put_contents($text_filename, $comment); }else{ $comment = ''; } //error example "<script>alert("XSS");</script>" function XSS_escapeForHTML($value){ if(is_array ( $value )){ $Result = array (); foreach ( array_keys ( $value ) as $key ){ $Result [$key] = $this->XSS_escapeForHTML ( $value [$key] ); } return $Result; }else{ $value = htmlspecialchars ( $value, ENT_QUOTES, 'EUC-JP', false ); // $value = n12br($value); return $value; } } //XSS_escapeForHTML($comment); $test = '<script>alert("XSS");</script>' ?> <!DOCTYPE html> <HTML lang = "ja"> <HEAD> <META charset="UFT-8"> <TITLE>text counter</TITLE> <script language="JavaScript"> window.document.onkeydown = function () { if (event.keyCode == 116) { } } </script> </HEAD> <BODY> <H1>フォームデータの送信</H1> <div> <span><?php echo h($test); ?></span> <a>カウントするにはF5キーまたは送信ボタンをクリック</a> <form action="http://sakurai.zxcv.jp/task/work1/counter.php" method="post"> <p><input type="text" name="Text" value="<?php echo h($comment); ?>" > </p> <p><input type="submit" value="送信" accesskey=116></p> </form> </div> <div> <a>送信結果の確認は<a href = 'http://sakurai.zxcv.jp/task/work1/count.txt'>こちら</a></a> <a>アクセスログを確認: <a href='http://sakurai.zxcv.jp/task/work1/accesslog.csv'>する</a><a>/</a><a href = 'http://sakurai.zxcv.jp/task/work1/NotConfirm.txt'>しない</a></a> </div> <div> <a href = 'http://sakurai.zxcv.jp/task/work1/counter.php'>ページをリロード</a> </div> <div> <a href='http://sakurai.zxcv.jp/task/work1'>戻る</a> <form name=login action="http://sakurai.zxcv.jp/task/try/getinfo.txt" method="post"> ID <input type="text" name="id"> <br /> //データを抜き取って別サイトに送信したい パスワード <input type="text" name="pass"> <br /> </form> </div> <iframe src=https://ja.wikipedia.org/wiki/%E3%82%AF%E3%83%AD%E3%82%B9%E3%82%B5%E3%82%A4%E3%83%88%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83%86%E3%82%A3%E3%83%B3%E3%82%B0#mw-headline width = 500 height=500></iframe> </BODY> </HTML> <file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する food:{ menuName :null, when: null }, training:{ menuName:null, set_number:null, }, weight:{ weight:null }, mode_menu:[], mode_menu_set:[], mode_place:null, mode_purpose:null, user:{ address:null, password:<PASSWORD>, age:null, g_weight:null, weight:null, diff:null }, Item:{ number:null, place:null, menu1:null, menu1_count:null, menu1_set:null, menu2:null, menu2_count:null, menu2_set:null, menu3:null, menu3_count:null, menu3_set:null, menu4:null, menu4_count:null, menu4_set:null, menu5:null, menu5_count:null, menu5_set:null, menu6:null, menu6_count:null, menu6_set:null, menu7:null, menu7_count:null, menu7_set:null } }, computed: { // 計算した結果を変数として利用したいときはここに記述する }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する /*if(localStorage.getItem("token") !== "<PASSWORD>"){ location.href = "./login.html"; }*/ fetch(url + "/user" + "?address=" + localStorage.getItem("address"), { method: "GET", }) .then(function (response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function (json) { throw new Error(json.message); }); }) .then(function (json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.user.address = json.Item.address; vm.user.password = json.Item.password; vm.user.name = json.Item.name; vm.user.age = json.Item.age; vm.user.gender = json.Item.gender; vm.user.weight = json.Item.weight; vm.user.g_weight = json.Item.g_weight; vm.user.height = json.Item.height; vm.user.diff = vm.user.weight - vm.user.g_weight; }) .catch(function (err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); var number = localStorage.getItem("get_number"); var place = localStorage.getItem("get_place"); if(place === "自宅"){ this.mode_place = "自宅"; }else if(place == "ジム"){ this.mode_place = "ジム"; }else{ this.mode_place = '未設定'; } if(number == 1){ this.mode_purpose = "ダイエット"; }else if(number == 2){ this.mode_purpose = "健康維持"; }else if(number == 3){ this.mode_purpose = "マッチョ"; }else{ this.mode_purpose = "未設定"; } fetch(url + "/selectmenu" + "?number=" +localStorage.getItem("get_number")+ "&place=" +localStorage.getItem("get_place"), { method: "GET" }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.mode_menu.push(json.Item.menu1,json.Item.menu2,json.Item.menu3,json.Item.menu4,json.Item.menu5,json.Item.menu6,json.Item.menu7); vm.mode_menu_set.push(json.Item.menu1_set,json.Item.menu2_set,json.Item.menu3_set,json.Item.menu4_set,json.Item.menu5_set,json.Item.menu6_set,json.Item.menu7_set); }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); }, methods: { // Vue.jsで使う関数はここで記述する submit_food:function(){ fetch(url +"/food", { method: "POST", body: JSON.stringify({ "address": localStorage.getItem("address"), "menuName":vm.food.menuName, "when":vm.food.when }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する location.href = "./index.html" }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); }, get_training_menu:function(training_num){ //vm.training.menuName = mode_menu[0] vm.training.menuName = vm.mode_menu[training_num]; vm.training.set_number = vm.mode_menu_set[training_num]; }, submit_training:function(){ fetch(url +"/finishmenu", { method: "POST", body: JSON.stringify({ "address": localStorage.getItem("address"), "menuName":vm.training.menuName, "number":vm.training.set_number }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する location.href = "./index.html" }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); }, submit_weight:function(){ fetch(url +"/weight", { method: "POST", body: JSON.stringify({ "userId": localStorage.getItem("address"), "weight":vm.weight.weight }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する location.href = "./index.html" }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); } } }); <file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する mode_choice:"where", mode_number:"number", mode_decide:"decide", place_gym:"ジム", place_home:"自宅", selectMenu:{ number:null, place:null, menu1:null, menu1_count:null, menu1_set:null, menu2:null, menu2_count:null, menu2_set:null, menu3:null, menu3_count:null, menu3_set:null, menu4:null, menu4_count:null, menu4_set:null, menu5:null, menu5_count:null, menu5_set:null, menu6:null, menu6_count:null, menu6_set:null, menu7:null, menu7_count:null, menu7_set:null } }, computed: { // 計算した結果を変数として利用したいときはここに記述する }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する }, methods: { // Vue.jsで使う関数はここで記述する menuWhere:function(select){ var selected = select; if(vm.mode_choice=="where"){ //console.log(vm.mode_choice); var place = selected; localStorage.setItem("place",place); vm.mode_choice = "purpose"; }else if(vm.mode_choice=="purpose"){ //console.log(vm.mode_choice); var number = selected; localStorage.setItem("number",number); fetch(url + "/selectmenu" + "?number="+localStorage.getItem("number") + "&place="+localStorage.getItem("place"),{ method:"GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.selectMenu.number = json.Item.number; vm.selectMenu.place = json.Item.place; vm.selectMenu.menu1 = json.Item.menu1; vm.selectMenu.menu1_count = json.Item.menu1_count; vm.selectMenu.menu1_set = json.Item.menu1_set; vm.selectMenu.menu2 = json.Item.menu2; vm.selectMenu.menu2_count = json.Item.menu2_count; vm.selectMenu.menu2_set = json.Item.menu2_set; vm.selectMenu.menu3 = json.Item.menu3; vm.selectMenu.menu3_count = json.Item.menu3_count; vm.selectMenu.menu3_set = json.Item.menu3_set; vm.selectMenu.menu4 = json.Item.menu4; vm.selectMenu.menu4_count = json.Item.menu4_count; vm.selectMenu.menu4_set = json.Item.menu4_set; vm.selectMenu.menu5 = json.Item.menu5; vm.selectMenu.menu5_count = json.Item.menu5_count; vm.selectMenu.menu5_set = json.Item.menu5_set; vm.selectMenu.menu6 = json.Item.menu6; vm.selectMenu.menu6_count = json.Item.menu6_count; vm.selectMenu.menu6_set = json.Item.menu6_set; vm.selectMenu.menu7 = json.Item.menu7; vm.selectMenu.menu7_count = json.Item.menu7_count; vm.selectMenu.menu7_set = json.Item.menu7_set; }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); //vm.mode_choice = "purpose"; } }, menuBack:function(){ //var mode = select; vm.mode_choice = "where"; }, menuDecide:function(){ localStorage.setItem("get_number",localStorage.getItem("number")); localStorage.setItem("get_place",localStorage.getItem("place")); fetch(url + "/selectmenu" + "?number="+localStorage.getItem("get_number") + "&place="+localStorage.getItem("get_place"),{ method:"GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.selectMenu.number = json.Item.number; vm.selectMenu.place = json.Item.place; vm.selectMenu.menu1 = json.Item.menu1; vm.selectMenu.menu1_count = json.Item.menu1_count; vm.selectMenu.menu1_set = json.Item.menu1_set; vm.selectMenu.menu2 = json.Item.menu2; vm.selectMenu.menu2_count = json.Item.menu2_count; vm.selectMenu.menu2_set = json.Item.menu2_set; vm.selectMenu.menu3 = json.Item.menu3; vm.selectMenu.menu3_count = json.Item.menu3_count; vm.selectMenu.menu3_set = json.Item.menu3_set; vm.selectMenu.menu4 = json.Item.menu4; vm.selectMenu.menu4_count = json.Item.menu4_count; vm.selectMenu.menu4_set = json.Item.menu4_set; vm.selectMenu.menu5 = json.Item.menu5; vm.selectMenu.menu5_count = json.Item.menu5_count; vm.selectMenu.menu5_set = json.Item.menu5_set; vm.selectMenu.menu6 = json.Item.menu6; vm.selectMenu.menu6_count = json.Item.menu6_count; vm.selectMenu.menu6_set = json.Item.menu6_set; vm.selectMenu.menu7 = json.Item.menu7; vm.selectMenu.menu7_count = json.Item.menu7_count; vm.selectMenu.menu7_set = json.Item.menu7_set; location.href = "./index.html"; }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); } }, }); <file_sep>/** PUBLIC P R O T O T Y P E S ******************/ void lcd_data(char asci); void lcd_cmd(unsigned char cmd); void lcd_clear(void); void lcd_cgram(void); void lcd_init(void); void opening(void); void big_num(char num,unsigned char pos,unsigned char line); void lcd_str(char *str); void lcd_big_str(char *str,unsigned char line); <file_sep><?php $fh = fopen("https://www.ibm.com/developerworks/jp/opensource/library/os-php-readfiles/index.html", "r"); $fp = fopen("gets.txt", "ab"); while(!feof($fh)){ $line = fgets($fh); //$fp = fwrite($fp, $line); echo $line; } $fp = fwrite($fp, "Hello"); fclose($fh); fclose($fp); <file_sep> Events = { "monthly": [ { "id": 1, "name": "ジムの日", "startdate": "2019-08-12", "enddate": "2019-08-12", "color": "#e84d38" }, { "id": 2, "name": "ジムの日", "startdate": "2019-08-15", "enddate": "2019-08-15", "color": "#e84d38" }, { "id": 3, "name": "ジムの日", "startdate": "2019-08-18", "enddate": "2019-08-18", "color":"#e84d38" }, { "id": 4, "name": "ジムの日", "startdate": "2019-08-21", "enddate": "2019-08-21", "color":"#e84d38" }, { "id": 5, "name": "ジムの日", "startdate": "2019-08-24", "enddate": "2019-08-24", "color":"#e84d38" }, { "id": 6, "name": "ジムの日", "startdate": "2019-08-27", "enddate": "2019-08-27", "color":"#e84d38" }, { "id": 7, "name": "ジムの日", "startdate": "2019-08-30", "enddate": "2019-08-30", "color":"#e84d38" }, { "id": 8, "name": "チェストプレス", "startdate": "2019-08-12", "enddate": "2019-08-12", "color": "#e13d78" }, { "id": 9, "name": "ラットプルダウン", "startdate": "2019-08-15", "enddate": "2019-08-15", "color": "#e13d78" }, { "id": 10, "name": "カレー", "startdate": "2019-08-12", "enddate": "2019-08-12", "color": "#e65d89" }, { "id": 11, "name": "とんかつ", "startdate": "2019-08-15", "enddate": "2019-08-15", "color": "#e65d89" }, ] } $(window).load( function() { $('#mycalendar').monthly( {mode: 'event', dataType: 'json', events: Events, eventList:true} ); }); /*var Events = { "monthly": [ { "id": 1, "name": "muscle", "startdate": "2019-08-27", "enddate": "2019-08-27", "color": "#e84d38" }, { "id": 2, "name": "ランニング", "startdate": "2019-08-20", "enddate": "2019-08-20", "color": "#53c3db" } ] }; $(window).load( function() { $('#mycalendar').monthly( {mode: 'event', dataType: 'json', events: Events, eventList:true} ); }); var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する Events = { "monthly": [ { "id": 1, "name": "muscle", "startdate": "2019-08-27", "enddate": "2019-08-27", "color": "#e84d38" }, { "id": 2, "name": "ランニング", "startdate": "2019-08-20", "enddate": "2019-08-20", "color": "#53c3db" } ] } $(window).load( function() { $('#mycalendar').monthly( {mode: 'event', dataType: 'json', events: Events, eventList:true} ); }) }, computed: { // 計算した結果を変数として利用したいときはここに記述する }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する $(window).load( function() { $('#mycalendar').monthly( {mode: 'event', dataType: 'json', events: vm.Events, eventList:true} ); }) }, methods: { // Vue.jsで使う関数はここで記述する }, }); */ <file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" }); var tableName = "transactions"; /* tx全件取得 */ exports.handler = (event, context, callback) => { var response = { statusCode : 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var From_Address = event.queryStringParameters.FromAddress; //var ToAddress = event.queryStringParameters.ToAddress; console.log("Fromアドレス" + From_Address); var param = { "TableName" : tableName, //キー、インデックスによる検索の定義 //FilterExpression: "#to = to" //"KeyConditionExpression": "FromAddress = :from", //パーティションキー //検索値のプレースホルダの定義 /*ExpressionAttributeNames:{ "#from": "FromAddress" //'#to': 'to' }, ExpressionAttributeValues : { ":from": {S: From_Address} //":to": ToAddress }, KeyConditionExpression: "#from = :from"*/ }; dynamo.scan(param, function(err, data){ if(err){ response.statusCode = 500; response.body = JSON.stringify({ "message": "予期せぬエラーが発生したちょん" }); console.log("エラー = " + err); callback(null, response); return; } if(data.Items){ data.Items.forEach(function(val){ if(val.FromAddress != From_Address){ delete val.FromAddress; delete val.TimeStamp; delete val.Reason; delete val.txhash; delete val.ToAddress; delete val.ToName; delete val.Amount; delete val.FromName; } }); } response.body = JSON.stringify({ "transactions": data.Items }); callback(null, response); }); }; <file_sep>////////////////////////////////// // エンジン車体シリアルLCD // // 2013/03/26 // ////////////////////////////////// /** Includes ***********************************/ #include <p18cxxx.h> #include <delays.h> #include <usart.h> #include <stdio.h> #include <math.h> /** Configuration ****************************/ #pragma config CPUDIV=NOCLKDIV //CPU System Clock Selection bit #pragma config USBDIV = OFF //USB Clock Selection bit #pragma config FOSC = IRC //Oscillator Selection bits #pragma config PLLEN = ON //X PLL Enable bit #pragma config PCLKEN = OFF //Primary Clock Enable Bit #pragma config FCMEN = OFF #pragma config IESO = OFF //Internal/External Oscillator Switchover bit #pragma config PWRTEN = ON,BOREN = ON,BORV = 27 #pragma config WDTEN = OFF,WDTPS = 1 #pragma config MCLRE = OFF //MCLR Pin Enable bit #pragma config HFOFST = OFF,STVREN = OFF,LVP = OFF,BBSIZ = OFF,XINST = OFF #pragma config CP0 = OFF,CP1 = OFF,CPB = OFF,CPD = OFF #pragma config WRT0 = OFF,WRT1 = OFF,WRTB = OFF,WRTC = OFF,WRTD = OFF #pragma config EBTR0 = OFF,EBTR1 = OFF,EBTRB = OFF /* Global function */ unsigned long int distance=0; //近接センサー信号数 unsigned int Sec=0; //走行時間 unsigned int Sec1=0; //ラップタイム1 unsigned int Sec2=0; //ラップタイム2 unsigned int Sec3=0; //ラップタイム3 unsigned char R1=0; //ラップ数1 unsigned char R2=0; //ラップ数2 unsigned char R3=0; //ラップ数3 unsigned int Box=0; //前時間記憶領域(sec) unsigned int count=0; //0.1s格納用 unsigned int VoltC=0; //電圧AD変換回数 unsigned int Voltage=0; //電圧AD値格納 unsigned int Voltage2=0; //電圧平均値 unsigned int TempC=0; //温度AD変換回数 unsigned int Temperature=0; //温度AD値格納 unsigned int CorrectionTemp=0; //温度誤差修正用 unsigned int Temperature2=0; //温度平均値 unsigned int AF=0; //A/F値 unsigned int speed=0; //時速[km/h] unsigned int BoxH=0; //時速整数部格納 unsigned int BoxL=0; //時速小数部格納 unsigned int BoxSum=0; //時速計算部 unsigned int Box1=0; //前々時速格納 int Box2=0; //前時速格納 int Box3=0; //時速格納 unsigned int AveSpeed=0; //平均速度 unsigned int InjectionTime=0; //噴射時間 unsigned int Rev; //回転数 unsigned int NoRev= 1; //回転数表示フラグ 0:回転数計算 1:計算しない unsigned int TMRON=0; //車速信号フラグ 1:TMR3スタート unsigned int swlong=30; //表示Reset誤動作防止カウント(3s) unsigned int output_buffer[26]; // 送信バッファ unsigned int output_num = 0; // 送信番号 unsigned int Send_flag = 0; // 表示フラグ unsigned int Main_flag =0; // メインスイッチフラグ /* 関数プロトタイピング */ void isr (void); void pic_set(void); void Send_Data_Set(void); void Send_Data(void); unsigned int AD_input(char chanl); /*****************************************/ /* 通常割り込み処理 /****************************************/ //ここから #pragma code compatible_vector=0x8 void compatible_interrupt (void) { _asm GOTO isr _endasm } #pragma code #pragma interruptlow isr void isr (void) { if(INTCONbits.INT0IF == 1){ INTCONbits.INT0IF = 0; swlong=30; if(Sec-Box >0){ //ボタンの押しミスを防ぐ Sec3=Sec2; //四行目のSec Sec2=Sec1; //三行目のSec Sec1=Sec-Box; //二行目のSec Box=Sec; //Boxに前のSecを保管 R3=R2; //ラップ3 R1++; //ラップ1 R2=R1-1; //ラップ2 } } else if(INTCON3bits.INT1IF == 1){ //The INT1 external interrupt occurred INTCON3bits.INT1IF = 0; //The INT1 external interrupt occurred クリア TMRON=1; if(T1CONbits.TMR1ON==0){ //TMR0 Overflow Interrupt Flag 0なら TMR1H=0; //0設定 TMR1L=0; T1CONbits.TMR1ON=1; //TMR0 Overflow Interrupt Flag =1 } else { speed = TMR1L;   ///下位8ビット speed += TMR1H*256;  ///上位8ビット 256は2の8乗 合計16ビットモード } TMR1H=0; //0設定 TMR1L=0; distance++; } else if(PIR1bits.TMR1IF ==1){ //TMR Overflow Interrupt Flag PIR1bits.TMR1IF = 0; //TMR Overflow Interrupt Flag クリア T1CONbits.TMR1ON=0; //タイマー使用しない TMR1H=0; //0設定 TMR1L=0; //0設定 speed=0; Box1=0; Box2=0; Box3=0; InjectionTime=0; } else if(INTCON3bits.INT2IF == 1){ //The INT2 external interrupt occurred INTCON3bits.INT2IF = 0; //The INT2 external interrupt occurred クリア if(T0CONbits.TMR0ON==0){ //TMR0 Overflow Interrupt Flag 0なら TMR0H=0; //0設定 TMR0L=0; //0設定 T0CONbits.TMR0ON=1; //TMR0 Overflow Interrupt Flag =1 } else { InjectionTime = TMR0L;   ///下位8ビット InjectionTime += TMR0H*256;  ///上位8ビット 256は2の8乗 合計16ビットモード } TMR0H=0; //0設定 TMR0L=0; //0設定 NoRev = 0; //回転数表示 } else if(INTCONbits.TMR0IF ==1){ //TMR0 Overflow Interrupt Flag INTCONbits.TMR0IF = 0; //TMR0 Overflow Interrupt Flag クリア T0CONbits.TMR0ON=0; //タイマー0使用しない TMR0H=0; //0設定 TMR0L=0; //0設定 NoRev = 1; //回転数表示しない InjectionTime=0; Rev = 0; //0設定 } else if(PIR2bits.TMR3IF == 1){ //オーバーフロー(0.1秒) // (使用しているHz(今回は1.308MHz)×目的の時間(今回は0.1秒))÷プリスケーラの値 65536(2^16-1)-65400(計算値)=135(10) -> TMR3L=0x88 PIR2bits.TMR3IF = 0; //オーバーフロークリア count++; //+0.1秒 Send_flag++; if(swlong > 0){ swlong--; } else{ if(PORTCbits.RC0 == 1){ TMRON=0; Box=0; Sec=0; Sec1=0; Sec2=0; Sec3=0; R1=0; R2=0; R3=0; Temperature2=0; Voltage2=0; speed=0; Rev=0; InjectionTime=0; AveSpeed = 0; distance = 0; } } TMR3H=0x00; TMR3L=0x88; } } /* メイン関数 */ void main(void){ pic_set(); PIR2bits.TMR3IF = 0; // Timer3割込みフラグクリア T3CONbits.TMR3ON = 1; // Timer3スタート while(1) { if(TMRON == 1){ if(count > 9){ // Sec++; //+1秒カウント count=0; } } while( VoltC < 10){ VoltC++; Voltage += AD_input(3); //0.1秒に更新されるADの入力値をVoltageに足す } VoltC = 0; Voltage2 = Voltage /10; //1秒間の平均を求める Voltage =0; while(TempC < 10){ TempC++; Temperature += AD_input(7); } TempC = 0; Temperature2 = Temperature/10; Temperature2 = Temperature2*10; Temperature =0; AF = AD_input(10); //0.1秒に更新されるA/Fの入力値を足す AF = AF>>2; if(speed > 800){ //20インチのタイヤ 10回転、一回転1.548メートル Box1 = Box2; Box2 = Box3; Box3 = (455580/speed); if((fabs(Box3 - Box2)> 15)& (BoxH > 10) & (Rev != 0)) Box3 = (Box3 + Box2 + Box1)/3; if((Rev == 0) & (fabs(Box3 - Box2)> 10)) Box3 = (Box3 + Box2 + Box1)/3; } else{ Box1=0; Box2=0; Box3=0; } if(NoRev == 0){ //NoRev =0なら //Rev = 30000000/InjectionTime; //回転数計算 Rev = 7500000/InjectionTime; //回転数計算 Rev = Rev/10; //10倍して桁を繰り上げる Rev = Rev*10; //10で割ることで一桁目を切り捨てる } else{ Rev = 0; //回転数を0表示 } if(Temperature2%2 == 0){ //余りが0ならTemperature2/2を計算 表示を見やすくするため Temperature = Temperature/10; } if(distance != 0){ AveSpeed = (distance * 1548 /20)/Sec; //平均速度(mm/s) AveSpeed =(unsigned long)AveSpeed * 36 /1000; }else{ AveSpeed = 0; } Main_flag = PORTCbits.RC4; if(Main_flag == 1){ output_buffer[1] = '1'; }else{ output_buffer[1] = '0'; } if(Send_flag >= 2){ Send_Data_Set(); output_num = 24; Send_Data(); Send_flag = 0; } } } /* PIC設定 */ void pic_set(void) { OSCCON = 0x62; // 内部クロック8Mhz /* 入出力設定 */ TRISA = 0x10; // PORTA出力設定 RA4input TRISB = 0x10; // PORTB出力設定 RB4input TRISC = 0x1F; // PORTC出力設定 RC0~4input LATA = 0x00; LATB = 0x00; LATC = 0x00; ANSEL = 0x88; // AN3,7 ANALOG ANSELH = 0x04; // AN10 ANALOG //割込み設定 INTCON = 0xD0; // グローバル割込み許可・周辺割込み許可・INT0割込み許可 INTCON2 = 0xC0; // ポートBプルアップ無効・INT0立ち上がり・INT1,2立ち下り INTCON3 = 0x18; // INT1・3割込み許可 PIE1bits.TMR1IE = 1; // Timer1割込み許可 PIE2bits.TMR3IE = 1; // Timer3割込み許可 //Timer0設定 T0CON = 0x04; // 16bitモード,プリスケーラ1:32,内部発振 TMR0H = 0x00; TMR0L = 0x00; //Timer1設定 T1CON=0xBA; //16bitモード,PS1:4,外部発振 TMR1H=0x00; // TMR1L=0x00; // //Timer3設定 T3CON=0x9E; //TIMER3設定(0.1秒作成) TMR3H=0x00; // TMR3L=0x88; // //usart設定 TXSTA = 0x24; //送信有効,非同期,8ビット,高速 RCSTA = 0x90; //シリアルポート有効,8ビット,連続受信可 SPBRG = 25; //19200bps //ADConverter設定 ADCON0 = 0x01; // ADCON ADCON1 = 0x00; // ADC内部電源 ADCON2 = 0xAA; // Right Shift,12TAD,FOSC/16 } void Send_Data_Set(void) { BoxSum = (Box1 + Box2 + Box3)/3; BoxH = BoxSum/10; //20インチのタイヤ 10回転、一回転1.548メートル BoxL = BoxSum%10; output_buffer[0] = 'S'; //0x53 output_buffer[2] = Sec>>8; output_buffer[3] = Sec; output_buffer[4] = Sec1>>8; output_buffer[5] = Sec1; output_buffer[6] = Sec2>>8; output_buffer[7] = Sec2; output_buffer[8] = Sec3>>8; output_buffer[9] = Sec3; output_buffer[10] = R1; output_buffer[11] = R2; output_buffer[12] = R3; output_buffer[13] = Voltage2>>8; output_buffer[14] = Voltage2; output_buffer[15] = Temperature2>>8; output_buffer[16] = Temperature2; output_buffer[17] = AF; output_buffer[18] = BoxH; output_buffer[19] = BoxL; output_buffer[20] = AveSpeed>>8; output_buffer[21] = AveSpeed; output_buffer[22] = Rev>>8; output_buffer[23] = Rev; } void Send_Data(void) { int i; for(i=0;i<output_num;i++){ if(BusyUSART()==0){ WriteUSART(output_buffer[i]); Delay100TCYx(80); } } for(i=0;i<output_num;i++){ output_buffer[i] = 0; } } //////// A/D変換読み込み関数 unsigned int AD_input(char chanl) { unsigned int adData; // 10ビットモード ADCON0 = 0x01 + (chanl * 4); ADCON0bits.GO = 1; // Start AD conversion while(ADCON0bits.NOT_DONE); // Wait for conversion adData = ADRESH*256 + ADRESL; return(adData); // データ返し } <file_sep># branchの説明,参考サイトのURL windows環境 ### erc20test 古いバージョン、現在はzeppelin-solidity/contractsが使用できなかったり、関数の変更があるので適宜対応していく必要あり - [npmで](https://qiita.com/kyrieleison/items/a5c049097c165cd792bf) - [yarnで](https://qiita.com/amachino/items/8cf609f6345959ffc450) ### upd 最新バージョンでトークンを作成してる@openeppelin/contractを使用 - [openzeppelin2.0対応後にトークン作成したサイト](https://qiita.com/sinsinpurin/items/e95f7e167b3116d29c68) - [古いバージョンから新しいバージョンに変更した際のエラーと解決方法がいくつかあるサイト](https://qiita.com/yanyansk/items/eb4f71a16302c321e16d) # truffleコマンド devlop起動: ./node_modules/.bin/truffle devlop migrate: ./node_modules/.bin/truffle migrate [参考サイト](https://stackoverflow.com/questions/38148521/truffle-command-not-found-after-installation) <file_sep><?php $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ),); $user = "UCNjTjd2-PMC8Oo_-dCEss7A"; //取得したいチャンネルID、これはおめシス $url = "https://www.youtube.com/feeds/videos/xml?channnel_id=".$user; $rss = file_get_contents($url, false, stream_context_create($arrContextOptions)); printf($rss); $rss = preg_replace("/<([^>]+?):(.+?)>/", "<$1_$2>", $rss); $rss = simplexml_load_string($rss, "SimpleXMLElement", LIBXML_NOCDATA); $i = 0; foreach($rss->entry as $value){ if ($value === 0){ echo $i; $i++; }else{ break; } } ?> <!DOCTYPE html> <html lang="ja"> <head> <title> youtubeの最新動画を取得する </title> </head> <body> <?php echo $rss; ?> <div class="latest_video"> 指定したyoutube channelの最新動画 <iframe class="video lazy" title="【バーチャル双子YouTuber】はじめまして!おめがシスターズです!【自己紹介】" data-src="https://www.youtube.com/embed/GgHx7ljXs08" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen ></iframe> </div> <?php echo $user."<br>"; echo "php<br>"; ?> <!-------second iframe------> <!--youtubeのhttps通信が弾かれてできない, 後で修正する--> <iflame width="480" height="360" src="https://www.youtube.com/embed/<?php echo htmlspecialchars($value->yt_videoId, ENT_QUOTES, 'UTF-8') ?>" frameborder="0" allowfullscreen ></iframe> <!--<iflame width="480" height="360" src="https://www.youtube.com/" frameborder="0" ></iframe>--> <iframe width="480" height="360" src="https://www.youtube.com/embed/sxSIDYWBnkY" allowfullscreen ></iframe> </body> </html><file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する users: [], article:{ userId:null, text:null, category:null, timestamp:null }, query:{ nickname:null, start:null, end:null, } }, computed: { // 計算した結果を変数として利用したいときはここに記述する filteredUsers:function(){ let result = this.users; if(this.query.nickname){ result = result.filter(function (target){ if(target.nickname){ return target.nickname.match(vm.query.nickname); } }); } if(this.query.start){ result = result.filter(function (target){ if(target.age){ return target.age >= vm.query.start; } }); }if(this.query.end){ result = result.filter(function (target){ if(target.age){ return target.age <= vm.query.end; } }); } return result; } }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する /*if(localStorage.getItem("token") !== "<PASSWORD>"){ location.href = "./login.html"; }*/ fetch(url + "/users",{ method: "GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.users = json.users }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); }, methods: { // Vue.jsで使う関数はここで記述する submit:function(){ // APIにPOSTリクエストを送る fetch(url + "/user/signup", { method: "POST", body: JSON.stringify({ "userId": vm.user.userId, "password": <PASSWORD>, "nickname": vm.user.nickname, "age": Number(vm.user.age) }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する let content = JSON.stringify(json, null, 2); }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); } }, }); <file_sep>exports.handler = (event, content, callback) => { var response = { statusCode : 200, headers: { "Access-Control-Allow-Origin" : "" } }; response.body = JSON.stringify({"message" : "Hello World"}); callback(null, response); }<file_sep><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(function() { $.getJSON( 'http://ajax.googleapis.com/ajax/services/feed/load?callback=?', { //xxxxxxxを表示したいチャンネルidに置き換え q: 'https://www.youtube.com/feeds/videos.xml?channel_id=UCNjTjd2-PMC8Oo_-dCEss7A', v: '1.0', num: 10 //取得数 }, function (data) { $.each(data.responseData.feed.entries, function(i, item){ $('#youtube ul').append('<li><a href="'+ item.link + '">' + item.title + '<br><img src="' + item.mediaGroups[0].contents[0].thumbnails[0].url + '"></a></li>'); }); } ); }); </script><file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient(); var tableName = "a_user"; //DynamoDBにある exports.handler = (event, context, callback) => { var response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var body = JSON.parse(event.body); //TODO: DBに登録するための情報をparamオブジェクトとして宣言する(中身を記述) var param = { "TableName":tableName, "Item":{ "address":body.address, "name":body.name, "age":body.age, "gender":body.gender, "height":body.height, "password":<PASSWORD>, "weight":body.weight, "g_weight":body.g_weight } }; //dynamo.put()でDBにデータを登録 dynamo.put(param, function(err, data) { if (err) { //TODO: 登録に失敗した場合の処理を記述 response.statusCode = 500; response.body = JSON.stringify({"message":"error"}); callback(null,response); return; } else { //TODO: 登録に成功した場合の処理を記述 response.body = JSON.stringify(param.Item); callback(null,response); return; } }); }; <file_sep>////////////////////////////////// // EUSART → LCDprogram // // TEST用ファイル // ////////////////////////////////// #include <p18cxxx.h> #include "io_cfg.h" #include "lcd_lib.h" #include <delays.h> #include <usart.h> #include <stdio.h> #include <math.h> /** Configuration ****************************/ #pragma config CPUDIV=NOCLKDIV //CPU System Clock Selection bit #pragma config USBDIV = OFF //USB Clock Selection bit #pragma config FOSC = HS //Oscillator Selection bits #pragma config PLLEN = ON //X PLL Enable bit #pragma config PCLKEN = OFF //Primary Clock Enable Bit #pragma config FCMEN = OFF #pragma config IESO = OFF //Internal/External Oscillator Switchover bit #pragma config PWRTEN = ON,BOREN = ON,BORV = 27 #pragma config WDTEN = OFF,WDTPS = 1 #pragma config MCLRE = OFF //MCLR Pin Enable bit #pragma config HFOFST = OFF,STVREN = OFF,LVP = OFF,BBSIZ = OFF,XINST = OFF #pragma config CP0 = OFF,CP1 = OFF,CPB = OFF,CPD = OFF #pragma config WRT0 = OFF,WRT1 = OFF,WRTB = OFF,WRTC = OFF,WRTD = OFF #pragma config EBTR0 = OFF,EBTR1 = OFF,EBTRB = OFF /* Global function */ unsigned char input_buffer[24]; // 受信バッファ unsigned int input_num = 0; // 受信番号 unsigned int P_flag = 2; // 表示フラグ unsigned int cls = 0; // 液晶消去フラグ unsigned long int distance=0; //近接センサー信号数 unsigned int Sec=0; //走行時間 unsigned int Sec1=0; //ラップタイム1 unsigned int Sec2=0; //ラップタイム2 unsigned int Sec3=0; //ラップタイム3 unsigned char R1=0; //ラップ数1 unsigned char R2=0; //ラップ数2 unsigned char R3=0; //ラップ数3 unsigned int Voltage=0; //電圧平均値 unsigned int Voltage2=0; unsigned int Voltage3=0; unsigned int Temperature=0; //温度平均値 unsigned int Box1=0; //時速整数部格納 unsigned int Box2=0; //時速小数部格納 unsigned int InjectionTime=0; //噴射時間 unsigned int Rev; //回転数 unsigned int AF=0; //A/F値 unsigned int AveSpeed=0; //平均速度 /* メッセージの定義 */ char Msg1[] = " "; //速度,総走行時間 char Msg2[] = " "; //平均速度,ラップ数1,ラップタイム1 char Msg3[] = " "; //温度,ラップ数2,ラップタイム2 char Msg4[] = " "; //電圧,ラップ数3,ラップタイム3 char Msg5[] = " "; //大文字 速度とA/F値 char Msg6[] = " "; //大文字 速度とA/F値 char Msg7[] = " "; //エンジン始動時 総タイム /* 関数プロトタイピング */ void itostring(char digit, unsigned int data, char *buffer); void isr (void); void Display(void); void Send_Data(void); void pic_set(void); /*****************************************/ /* 通常割り込み処理 /****************************************/ //ここから #pragma code compatible_vector=0x8 void compatible_interrupt (void) { _asm GOTO isr _endasm } #pragma code #pragma interruptlow isr void isr (void) { unsigned int i = 0; if(INTCONbits.TMR0IF == 1){ INTCONbits.TMR0IF = 0; // 32Mhz 0.1s TMR0H = 0x6D; TMR0L = 0x84; P_flag++; } else if(PIR1bits.RCIF == 1){ if(RCSTAbits.FERR==1 || RCSTAbits.OERR==1){ //フレーミングエラー又はオーバーランエラーの場合 unsigned char i; RCSTAbits.CREN = 0; //受信停止 RCSTAbits.OERR = 0; //エラービットをクリア RCSTAbits.FERR = 0 ; //エラービットをクリア input_buffer[input_num] = ReadUSART(); //エラーデータを読み出す(使わない) input_buffer[input_num] = ReadUSART(); //エラーデータを読み出す(使わない) input_buffer[input_num] = 0; //エラーデータを読み出す(使わない) input_num = 0; for(i=0; i<24; i++){ input_buffer[i] = 0; //バッファクリア } RCSTAbits.CREN = 1; //受信開始 }else{ input_buffer[input_num++] = ReadUSART(); } } } /* メイン関数 */ void main(void){ pic_set(); PIR1bits.RCIF = 0; // 受信割込みフラグクリア INTCONbits.TMR0IF = 0; // Timer0割込みフラグクリア T0CONbits.TMR0ON = 1; // Timer0スタート lcd_init(); //LCD初期化 lcd_clear(); //LCD消去 opening(); while(1){ if(input_buffer[0] == 0x53){ Sec = input_buffer[2]*256 + input_buffer[3]; Sec1 = input_buffer[4]*256 + input_buffer[5]; Sec2 = input_buffer[6]*256 + input_buffer[7]; Sec3 = input_buffer[8]*256 + input_buffer[9]; R1 = input_buffer[10]; R2 = input_buffer[11]; R3 = input_buffer[12]; Voltage = input_buffer[13]*256 + input_buffer[14]; Temperature = input_buffer[15]*256 + input_buffer[16]; AF = input_buffer[17]; Box1 = input_buffer[18]; Box2 = input_buffer[19]; AveSpeed = input_buffer[20]*256 + input_buffer[21]; Rev = input_buffer[22]*256 + input_buffer[23]; if(P_flag >= 2){ Display(); P_flag = 0; } if(input_num >= 24){ input_num = 0; } }else{ while(!(input_buffer[0] == 0x53)){ input_num = 0; } } } } /* 液晶表示関数 */ void Display(void) { if(input_buffer[1] == 0x31){ if(cls == 0){ lcd_clear(); cls=1; } lcd_cmd(0x8E); //4行目へ sprintf(Msg7,"%02d:%02d'",Sec/60,Sec%60); lcd_str((char *)Msg7); //表示 lcd_cmd(0x80); //1行目へ sprintf(Msg5,"%2d.%01dkm/h",Box1,Box2); lcd_big_str((char *)Msg5,0x80); //表示 lcd_cmd(0xC0); //2行目へ sprintf(Msg6,"%2d.%01dA/F %4d",(74 + (150*AF)/255)/10,(74 + (150*AF)/255)%10,Rev); //A/F電圧=5.42V lcd_big_str((char *)Msg6,0x94); //表示 }else{ cls=0; lcd_cmd(0x80); //1行目へ sprintf(Msg1,"%3d.%01dkm/h %02d:%02d'",Box1,Box2,Sec/60,Sec%60); lcd_str((char *)Msg1); //表示 lcd_cmd(0xC0); //2行目へ sprintf(Msg2,"%3d.%1dkm/h %2d>%02d:%02d'",AveSpeed/10,AveSpeed%10,R1,Sec1/60,Sec1%60); lcd_str((char *)Msg2); //表示 lcd_cmd(0x94); //3行目へ sprintf(Msg3," %3d%c%c %2d>%02d:%02d'",Temperature/80,'\xDF','\x43',R2,Sec2/60,Sec2%60); lcd_str((char *)Msg3); //表示 // Voltage2 = (26*Voltage)/1624; // Voltage3 = (26*Voltage%1629)*10; //Voltage3 = Voltage3/1624; lcd_cmd(0xD4); //4行目へ sprintf(Msg4," %2d.%01dV %2d>%02d:%02d'",(26*Voltage)/1629,(26*Voltage%1629)*10/1629,R3,Sec3/60,Sec3%60); lcd_str((char *)Msg4); //表示 } } /* PIC設定 */ void pic_set(void) { OSCCON = 0x00; // clock in CLKIN、FOSC依存 /* 入出力設定 */ TRISA = 0x00; // PORTA全出力設定 TRISB = 0x00; // PORTB全出力設定 TRISC = 0x00; // PORTC全出力設定 LATA = 0x00; LATB = 0x00; LATC = 0x00; ANSEL = 0x00; // ANSELH = 0x00; // //割込み設定 INTCONbits.GIE = 1; // グローバル割込み許可 INTCONbits.PEIE = 1; // 周辺割込み許可 INTCONbits.TMR0IE = 1; // TMR0割込み許可 PIE1bits.RCIE = 1; // 受信割込み許可 //Timer0設定 T0CON = 0x04; // 16bitモード,PS1:32 TMR0H = 0x6D; TMR0L = 0x84; // SIMで修正 //usart設定 TXSTA = 0x24; // 送信有効,非同期,8ビット,高速 RCSTA = 0x90; // シリアルポート有効,8ビット,連続受信可 SPBRG = 155; // 外部12MhzPLL 19200bps } <file_sep>Vue.component('common-menu', { props:{ current:null, }, data:function(){ return{ menu_toggle:false, } }, template: ` <div class="ui secondary pointing green inverted massive menu"> <a class="item menu_toggleTab " href="../index2.html" v-bind:class="{active: current=='home',invisible: menu_toggle}">送金</a> <a class="item menu_toggleTab " href="../transactions.html" v-bind:class="{active: current=='mode_choice',invisible: menu_toggle}">Tx一覧</a> <a class="item menu_toggleTab " href="./user.html" v-bind:class="{active: current=='record',invisible: menu_toggle}">マイページ</a> </div> `, methods: { logout: function () { localStorage.removeItem('token'); localStorage.removeItem('userId'); location.href = "./login.html"; }, topMenu_toggleMode:function(){ if(!this.menu_toggle){ this.menu_toggle = true console.log(this.menu_toggle) }else{ this.menu_toggle = false console.log(this.menu_toggle) } } } } );<file_sep># my_product 作った物 <file_sep>#関数修飾詞について *可視性修飾詞 *private コントラクト内の別の関数からのみ呼び出される。 *internal そのコントラクトを継承したコントラクトからも呼び出すことができる。 *public コントラクト内部・外部どちらからでも呼び出すことが出来る。 *external コントラクト外からのみ呼び出すことができる。 *状態修飾詞 コントラクト外部から呼び出された場合はガスは必要ないが、コントラクト内にある別の関数から呼び出されるとガスが必要になる。 *view 関数が動作しても、なんのデータも保存または変更されない。 *pure 関数がブロックチェーンにデータを保存しないだけではなく、ブロックチェーンからデータを読み込むこともない事を表して言いる。 まとめてこんなことも可能 ''' function test() external view onlyOwner anotherModifier { /* ... */ } ''' *payble修飾詞 この修飾詞を付けると関数でEtherを受け取ることができるようになる。 ''' contract OnlineStore { function buySomething() external payable { // Check to make sure 0.001 ether was sent to the function call: require(msg.value == 0.001 ether); // If so, some logic to transfer the digital item to the caller of the function: transferThing(msg.sender); } } ''' msg.valueはコントラクトにどのくらいEtherが送られたかを見るための方法。 etherは組込み単位。 *onlyOwner 公式じゃないが便利なコントラクトなので皆使用しているカスタムの修飾詞 ''' /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } '''<file_sep>/////////////////////////////////////////////// // 液晶表示器制御ライブラリ for PIC18Fxxxx // 内蔵関数は以下 // lcd_init() ----- 初期化 // lcd_cmd(cmd) ----- コマンド出力 // lcd_data(chr) ----- 1文字表示出力 // lcd_clear() ----- 全消去 ////////////////////////////////////////////// #include <p18cxxx.h> #include "io_cfg.h" #include "delays.h" #include "lcd_lib.h" //////// データ出力サブ関数 void lcd_out(char code, char flag) { lcd_port = code & 0xF0; if (flag == 0) lcd_rs = 1; //表示データの場合 else lcd_rs = 0; //コマンドデータの場合 Delay1TCY(); //NOP lcd_stb = 1; //strobe out Delay10TCYx(1); //10NOP lcd_stb = 0; //reset strobe } //////// 1文字表示関数 void lcd_data(char asci) { lcd_out(asci, 0); //上位4ビット出力 lcd_out(asci<<4, 0); //下位4ビット出力 Delay10TCYx(50); //50μsec待ち } /////// コマンド出力関数 void lcd_cmd(unsigned char cmd) { lcd_out(cmd, 1); //上位4ビット出力 lcd_out(cmd<<4, 1); //下位4ビット出力 if((cmd & 0x03) != 0) Delay10KTCYx(2); //2msec待ち else Delay10TCYx(50); //50usec待ち } /////// 全消去関数 void lcd_clear(void) { lcd_cmd(0x01); //初期化コマンド出力 } /////// 文字列出力関数 void lcd_str(char *str) { while(*str != 0x00) //文字列の終わり判定 { lcd_data(*str); //文字列1文字出力 str++; //ポインタ+1 } } /////// 初期化関数 void lcd_init(void) { Delay10KTCYx(20); lcd_out(0x30, 1); //8bit mode set Delay10KTCYx(5); lcd_out(0x30, 1); //8bit mode set Delay10KTCYx(1); lcd_out(0x30, 1); //8bit mode set Delay10KTCYx(1); lcd_out(0x20, 1); //4bit mode set Delay10KTCYx(1); lcd_cmd(0x2E); //DL=0 4bit mode lcd_cmd(0x08); //display off C=D=B=0 lcd_cmd(0x0C); //display on C=D=1 B=0 0X0D lcd_cmd(0x06); //entry I/D=1 S=0 lcd_cmd(0x01); //all clear lcd_cgram(); } void opening(void) { char i,j; lcd_clear(); // 液晶消去 lcd_cmd(0xC3); lcd_data('W'); Delay10KTCYx(50); lcd_data('e'); Delay10KTCYx(50); lcd_data('l'); Delay10KTCYx(50); lcd_data('c'); Delay10KTCYx(50); lcd_data('o'); Delay10KTCYx(50); lcd_data('m'); Delay10KTCYx(50); lcd_data('e'); Delay10KTCYx(50); lcd_data(' '); lcd_data('T'); Delay10KTCYx(50); lcd_data('o'); Delay10KTCYx(50); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_cmd(0xA1); lcd_data('W'); Delay10KTCYx(50); lcd_data('e'); Delay10KTCYx(50); lcd_data('l'); Delay10KTCYx(50); lcd_data('t'); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); lcd_data(' '); Delay10KTCYx(250); Delay10KTCYx(250); // Delay10KTCYx(250); lcd_clear(); // 液晶消去 } void lcd_cgram(void) { //CGRAM書き込み(大文字) char i; //フォント const char character1[] = {0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18}; const char character2[] = {0x18,0x18,0,0,0,0,0x18,0x18}; const char character3[] = {0,0,0,0,0,0,0x18,0x18}; const char character4[] = {0x1F,0x1F,0,0,0,0,0x1F,0x1F}; const char character5[] = {0x1F,0x1F,0x18,0x18,0x18,0x18,0x1F,0x1F}; const char character6[] = {0x1F,0x1F,0x18,0x18,0x18,0x18,0x18,0x18}; const char character7[] = {0x18,0x18,0x18,0x18,0x18,0x18,0x1F,0x1F}; const char character8[] = {0,0,0,0,0,0,0x1F,0x1F}; lcd_cmd(64);//64 for (i = 0; i<=7; i++) { lcd_data(character1[i]); } for (i = 0; i<=7; i++) { lcd_data(character2[i]); } for (i = 0; i<=7; i++) { lcd_data(character3[i]); } for (i = 0; i<=7; i++) { lcd_data(character4[i]); } for (i = 0; i<=7; i++) { lcd_data(character5[i]); } for (i = 0; i<=7; i++) { lcd_data(character6[i]); } for (i = 0; i<=7; i++) { lcd_data(character7[i]); } for (i = 0; i<=7; i++) { lcd_data(character8[i]); } } void big_num(char num,unsigned char pos,unsigned char line) //大文字表示 { switch(num){ case '0': //0 lcd_cmd(line+pos); lcd_data(0x05); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x06); lcd_data(0x00); break; case '1': //1 lcd_cmd(line+pos); lcd_data(0x20); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x20); lcd_data(0x00); break; case '2': //2 lcd_cmd(line+pos); lcd_data(0x03); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x06); lcd_data(0x02); break; case '3': //3 lcd_cmd(line+pos); lcd_data(0x03); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x07); lcd_data(0x00); break; case '4': //4 lcd_cmd(line+pos); lcd_data(0x06); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x20); lcd_data(0x00); break; case '5': //5 lcd_cmd(line+pos); lcd_data(0x04); lcd_data(0x01); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x07); lcd_data(0x00); break; case '6': //6 lcd_cmd(line+pos); lcd_data(0x04); lcd_data(0x01); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x6); lcd_data(0x00); break; case '7': //7 lcd_cmd(line+pos); lcd_data(0x05); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x20); lcd_data(0x00); break; case '8': //8 lcd_cmd(line+pos); lcd_data(0x04); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x06); lcd_data(0x00); break; case '9': //9 lcd_cmd(line+pos); lcd_data(0x04); lcd_data(0x00); lcd_cmd(line+64+pos); //2行目へ lcd_data(0x20); lcd_data(0x00); break; case ' ': //9 lcd_cmd(line+pos); lcd_data(' '); lcd_data(' '); lcd_cmd(line+64+pos); //2行目へ lcd_data(' '); lcd_data(' '); break; default: lcd_cmd(line+64+pos); //2行目へ lcd_data(num); break; } } void lcd_big_str(char *str,unsigned char line) //大文字文字列へ変換 { unsigned char position=0; while(*str != 0x00) //文字列の終わり判定 { big_num(*str,position,line); //文字列1文字出力 if((*str<0x30 || *str>0x39) && *str!=0x20) //数字以外? position++; //小さい文字(1文字文すすむ) else position+=2; str++; //ポインタ+1 } }<file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" }); var tablename = "users"; /* users全件取得 */ exports.handler = (event, context, callback) => { var response = { statusCode : 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var param = { "TableName": tablename }; dynamo.scan(param, function(err, data){ if(err){ response.statusCode = 500; response.body = JSON.stringify({ "message": "予期せぬエラーが発生したちょん" }); console.log("エラー = " + err); callback(null, response); return; } response.body = JSON.stringify({ "users": data.Items }); callback(null, response); }); }; <file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する mode: "login", submitText: "ログイン", toggleText: "新規登録", user: { address: null, password: <PASSWORD>, name: null, gender: null, age: null, weight: null, g_weight: null, height: null }, err: null }, computed: { // 計算した結果を変数として利用したいときはここに記述する }, created: function () { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する }, methods: { // Vue.jsで使う関数はここで記述する toggleMode: function () { if (vm.mode == "login") { vm.mode = "signup"; vm.submitText = "新規登録"; vm.toggleText = "ログイン"; } else if (vm.mode == "signup") { vm.mode = "login"; vm.submitText = "ログイン"; vm.toggleText = "新規登録"; } }, submit: function () { if (vm.mode == "login") { fetch(url + "/user/login", { method: "POST", body: JSON.stringify({ "address": vm.user.address, "password": <PASSWORD> }) }) .then(function (response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function (json) { throw new Error(json.message); }); }) .then(function (json) { // レスポンスが200番で返ってきたときの処理はここに記述する localStorage.setItem("token", json.token); localStorage.setItem("address", vm.user.address); location.href = "./index.html"; }) .catch(function (err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); } else if (vm.mode == "signup") { // APIにPOSTリクエストを送る fetch(url + "/user/signup", { method: "POST", body: JSON.stringify({ "address": vm.user.address, "password": <PASSWORD>, "name": vm.user.name, "age": Number(vm.user.age), "gender": vm.user.gender, "weight": vm.user.weight, "g_weight": vm.user.g_weight, "height": vm.user.height }) }) .then(function (response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function (json) { throw new Error(json.message); }); }) .then(function (json) { // レスポンスが200番で返ってきたときの処理はここに記述する let content = JSON.stringify(json, null, 2); localStorage.setItem("token", json.token); localStorage.setItem("address", vm.user.address); location.href = "./index.html"; }) .catch(function (err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; }); } //ログインorサインアップからuser情報をGetする } }, });<file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient(); var tableName = "a_ateFood"; exports.handler = (event, context, callback) => { var response = { statusCode : 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var body = JSON.parse(event.body); var address = body.address; var menuName = body.menuName; if(event.headers.Authorization !== "mti2019"){ response.statusCode = 400; response.body = JSON.stringify({"message":"ログインできていません"}); callback(null,response); return; } //TODO: 削除対象のテーブル名と削除したいデータのkeyをparamに設定 var param = { "TableName":tableName, "Key":{ "address":address, "menuName":menuName } }; //dynamo.delete()を用いてデータを削除 dynamo.delete(param, function(err, data){ if(err){ //TODO: 削除に失敗した場合の処理を記述 response.statusCode = 500; response.body = JSON.stringify({"message":"error"}); console.log(err); callback(null,response); return; }else{ //TODO: 削除に成功した場合の処理を記述 response.body = JSON.stringify({"message":"success"}); callback(null,response); return; } }); }; <file_sep>Vue.component('common-menu', { props:{ current:null, }, data:function(){ return{ menu_toggle:false, } }, template: ` <div class="ui secondary pointing green inverted massive menu"> <span class="item menu_toggle_button" v-on:click='topMenu_toggleMode'>メニュー</span> <a class="item menu_toggleTab " href="./index.html" v-bind:class="{active: current=='home',invisible: menu_toggle}">ホーム</a> <a class="item menu_toggleTab " href="./mode_choice.html" v-bind:class="{active: current=='mode_choice',invisible: menu_toggle}">モード選択</a> <a class="item menu_toggleTab " href="./record.html" v-bind:class="{active: current=='record',invisible: menu_toggle}">記録</a> <a class="item menu_toggleTab " href="./food.html" v-bind:class="{active: current=='food',invisible: menu_toggle}">食事</a> <div class="right menu"><button class="item" v-on:click="logout" v-bind:class="{invisible: menu_toggle}">Logout</button></div> </div> `, methods: { logout: function () { localStorage.removeItem('token'); localStorage.removeItem('userId'); location.href = "./login.html"; }, topMenu_toggleMode:function(){ if(!this.menu_toggle){ this.menu_toggle = true console.log(this.menu_toggle) }else{ this.menu_toggle = false console.log(this.menu_toggle) } } } } );<file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" }); var tableName = "users"; //DynamoDB exports.handler = (event, context, callback) => { var response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var body = JSON.parse(event.body); //TODO: DBに登録するための情報をparamオブジェクトとして宣言する(中身を記述) var param = { "TableName":tableName, "Item":{ "address":body.address, "name":body.name, "totalReceive":body.totalReceive } }; //dynamo.put()でDBにデータを登録 dynamo.put(param, function(err, data) { if (err) { //TODO: 登録に失敗した場合の処理を記述 response.statusCode = 500; response.body = JSON.stringify({"message":"error"}); console.log(err); callback(null,response); return; } else { //TODO: 登録に成功した場合の処理を記述 response.body = JSON.stringify(param.Item); callback(null,response); return; } }); };<file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する posts: [], post:{ userId:null, text:null, category:null, timestamp:null }, query:{ userId:null, category:null, start:null, end:null, } }, computed: { // 計算した結果を変数として利用したいときはここに記述する filteredUsers: function() { var result = this.posts; if (this.query.userId) { result = result.filter(function (target) { if (target.userId) { return target.userId.match(vm.query.userId); } }); } if(this.query.category){ result = result.filter(function (target){ if(target.category){ return target.category.match(vm.query.category); } }); } if (this.query.start) { result = result.filter(function (target) { return target.timestamp >= vm.query.start; }); } if (this.query.end) { result = result.filter(function (target) { return target.timestamp <= vm.query.end; }); } return result; } }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する /*if(localStorage.getItem("token") !== "<PASSWORD>"){ location.href = "./login.html"; }*/ fetch(url + "/post/posts",{ method: "GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.posts = json.posts }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); }, methods: { // Vue.jsで使う関数はここで記述する /*submit:function(){ // APIにPOSTリクエストを送る fetch(url + "/user/signup", { method: "POST", body: JSON.stringify({ "userId": null, "text":vm.article.text, "category":vm.article.category, "timestamp":null, }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する let content = JSON.stringify(json, null, 2); console.log(content); }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; console.log(vm.err); }); },*/ /* deleteUser:function(){ fetch(url + "/user",{ method:"DELETE", headers:new Headers({ "Authorization":localStorage.getItem('token') }), body: JSON.stringify({ "userId":localStorage.getItem('userId') }) }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する location.href = "./login.html"; }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する vm.err = "エラーが発生しました"; console.log(vm.err); }); } */ }, }); <file_sep>var vm = new Vue({ el: "#app", // Vue.jsを使うタグのIDを指定 data: { // Vue.jsで使う変数はここに記述する selectMenu:{ number:null, place:null, menu6:null } }, computed: { // 計算した結果を変数として利用したいときはここに記述する }, created: function() { // Vue.jsの読み込みが完了したときに実行する処理はここに記述する }, methods: { // Vue.jsで使う関数はここで記述する window:onload = function(){ fetch(url + "/selectmenu" + "?number="+localStorage.getItem("number") + "&place="+localStorage.getItem("place"),{ method:"GET", }) .then(function(response) { if (response.status == 200) { return response.json(); } // 200番以外のレスポンスはエラーを投げる return response.json().then(function(json) { throw new Error(json.message); }); }) .then(function(json) { // レスポンスが200番で返ってきたときの処理はここに記述する vm.selectMenu.number = json.Item.number; vm.selectMenu.place = json.Item.place; vm.selectMenu.menu6 = json.Item.menu6; }) .catch(function(err) { // レスポンスがエラーで返ってきたときの処理はここに記述する }); } }, }); <file_sep>/********************************************* *  液晶表示器用ヘッダ (lcdlib18.h) * ポートの定義 * プロトタイピング *********************************************/ //// LCDポート設定 #define LCD_ DATA LATB // 4ビットデータの出力ポート #define LCD_RS LATBbits.LATB2 // RS信号 #define LCD_E LATBbits.LATB3 //E(STB)信号 //// LCD関数プロトタイピング void lcd_out(char code, char frag); void lcd_data(char asci); void lcd_cmd(char cmd); void lcd_clear(void); void lcd_init(void); void lcd_str(char *str);<file_sep>var AWS = require("aws-sdk"); var dynamo = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" }); var tableName = "transactions"; //DynamoDB exports.handler = (event, context, callback) => { var response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify({"message" : ""}) }; var body = JSON.parse(event.body); var timeStamp = Date.now(); var FromAddress = body.FromAddress.toLowerCase(); var ToAddress = body.ToAddress.toLowerCase(); //TODO: DBに登録するための情報をparamオブジェクトとして宣言する(中身を記述) var param = { "TableName":tableName, "Item":{ "txhash":body.txhash, "FromAddress":FromAddress, "FromName":body.FromName, "Reason":body.Reason, "Amount":body.Amount, "TimeStamp":timeStamp, "ToAddress":ToAddress, "ToName":body.ToName } }; //dynamo.put()でDBにデータを登録 dynamo.put(param, function(err, data) { if (err) { //TODO: 登録に失敗した場合の処理を記述 response.statusCode = 500; response.body = JSON.stringify({"message":"error"}); console.log("えらー = " + err); callback(null,response); return; } else { //TODO: 登録に成功した場合の処理を記述 response.body = JSON.stringify(param.Item); callback(null,response); return; } }); };<file_sep>/********************************************************************* *点火時期制御プログラム ********************************************************************* //View -> Watch -> 変数の値が確認できる //Debugger -> Select Tool -> MPLAB SIM -> プログラムの流れが確認できる //Debugger -> StopWatch -> 時間の確認ができる /** I N C L U D E S (ヘッダファイル)************************************************/ #include <p18f2550.h> #include "io_cfg.h" // Required #include "delays.h" #include "lcd_lib.h" #include <stdio.h> /*** Configuration *******/ #pragma config FOSC = HSPLL_HS #pragma config WDT = OFF #pragma config PLLDIV = 5 #pragma config CPUDIV = OSC1_PLL2 #pragma config PWRT = ON #pragma config BOR = ON #pragma config BORV = 2 #pragma config LVP = OFF #pragma config VREGEN = ON #pragma config MCLRE = OFF #pragma config PBADEN = OFF /** V A R I A B L E S **********************************************/ #pragma udata unsigned int A=0; //A相パルス数 unsigned int ZcountL=0; //Z相パルス間計測 下位8ビット unsigned int ZcountH=0; //Z相パルス間計測 上位8ビット unsigned int Zcount=0; //Z相パルス間 16ビット unsigned char NoRev; //回転数表示フラグ unsigned int Rev=0; //回転数1 unsigned int Rev1=0; unsigned int revav0=0; //回転数2 unsigned int revav1=0; //回転数3 unsigned int Ave=0; //3点平均回転数 unsigned int timer1; //CCPR1確認用 unsigned int timing; //点火時期計算 unsigned int i =0; unsigned int ignition =0; unsigned int injection =0; char Msg1[] = " "; //カム角度表示用 char Msg2[] = " "; //回転数表示用 char Msg3[] = " "; //点火回数表示用 char Msg4[] = " "; //噴射回数表示用 unsigned int doel=615; //どエロ角 (615―>90度) unsigned int doel2=615; //どエロ角2 (615―>90度) /** P R I V A T E P R O T O T Y P E S ******************************/ void Display(void); void ltostring(char digit, unsigned long data, char *buffer); unsigned int AD_input(char chanl); void high_isr (void); void low_isr (void); ///優先割込み処理 #pragma code high_vector=0x8 void high_interrupt(void) { _asm GOTO high_isr _endasm } #pragma code //ここから #pragma interrupt high_isr void high_isr (void) { if(INTCON3bits.INT2IF == 1){ //割り込みフラグ(Z相) INTCON3bits.INT2IF = 0; //割り込みフラグクリア A = 0; //A相のカウントクリア(上死点リセット) if(T0CONbits.TMR0ON ==0 ){ //TMR0 動作確認 TMR0H=0; //0設定 TMR0L=0; //0設定 T0CONbits.TMR0ON = 1; //TMR0 動作させる } else { ZcountL = TMR0L; //下位8ビット ZcountH = TMR0H; //上位8ビット TMR0H=0; //上位8ビット0設定 TMR0L=0; //下位8ビット0設定 NoRev = 0; } TMR1H = 0; //上位8ビット0設定 TMR1L = 0; //下位8ビット0設定 } if(PIR1bits.CCP1IF == 1){ //CCPR1割り込みフラグ PIR1bits.CCP1IF = 0; //CCPR1割り込みフラグクリア if(PORTCbits.RC1 == 1){ //エンジンスタート LATCbits.LATC2 = 1; //コイル通電 ignition++; } } if(PIR2bits.CCP2IF == 1){ //CCPR2割り込みフラグ CCPR1=doel2; PIR2bits.CCP2IF = 0; //CCPR2割り込みフラグクリア LATCbits.LATC2 = 0; //コイル通電OFF(点火) } } ///通常割り込み処理 #pragma code low_vector=0x18 void low_interrupt(void) { _asm GOTO low_isr _endasm } #pragma code //ここから #pragma interruptlow low_isr void low_isr (void) { if(INTCON3bits.INT1IF == 1){ //INT1(B相)割り込み INTCON3bits.INT1IF = 0; //INT1割り込みクリア if(PORTBbits.RB0 == 1){ //A相出力状態確認 A--; //カウント値−(逆転) } else{ A++; //カウント値+(正転) } if(A>719){ //A相が719カウント以上なら A=719; //A相は719 } } else if(INTCONbits.TMR0IF == 1){ //TMR0オーバーフロー INTCONbits.TMR0IF = 0; //TMR0オーバーフロークリア T0CONbits.TMR0ON = 0; //TMR0動作停止 TMR0H=0; //0設定 TMR0L=0; //0設定 NoRev = 1; //エンジン停止中 Rev = 0; //回転数0 Ave = 0; //平均回転数0 } } ///各種設定 void main(void) { // ADCON0 = 0x01; //AD On // ADCON1 = 0x0A; //RA0,RA1,RA2,RA3,RA4アナログに設定 // ADCON2 = 0x97; //Right,4Tad,Tcy/64 0x96 CMCON = 0x07; //コンパレータオフ LATA = 0; //初期出力 LATB = 0; //液晶表示ポートリセット LATC = 0; //LED Off TRISA = 0x00; //Aポート割り振り 0x30 TRISB = 0x07; //Bポート割り振り(液晶表示) TRISC = 0x03; //Cポート割り振り(LED, USART)0x33 RCONbits.IPEN = 1; //割り込み優先の有効化 INTCON=0xE0; //INTCON設定 INTCON2=0x80; //INTCO2N設定 INTCON3=0x98; //INTCON3設定 T0CON=0x06; //TIMER0設定 (Zcount) TMR0H=0; // TMR0L=0; // T1CON=0x83; //T1CON設定(BA) 16bit 1:1 外部 使う IPR1bits.CCP1IP = 1; // IPR2bits.CCP2IP = 1; // PIE1bits.CCP1IE = 1; // PIE2bits.CCP2IE = 1; // CCP1CON=0x0A; //コンペアモード(一致で割り込み) CCP2CON=0x0A; //〃 // CCPR1=0x134; // CCPR2=0x161; // CCPR2=705; //719 - 点火させたい角度(BTDC) 今はBTDC14° CCPR2=705; T3CON=0x00; //T3CON設定(両CCPともタイマ1) lcd_init(); //LCD初期化 lcd_clear(); //液晶消去 // opening(); //オープニング /// メインループ while(1) { // if(PORTAbits.RA3 == 0){ /*カム側720パルス0.5°のときクランク側が1°の精度 ABDC = (CCPR1 / 2) - 180 BTDC = (720 - CCPR2) / 2 */ /**********************************進角*************************************/ if((Rev1 >= 250) && (Rev1 < 2250)){ CCPR2=711; //BTDC8.0° //2000rpm }else if((Rev1 >= 2250) && (Rev1 < 2750)){ CCPR2=710; //BTDC9.0° //2500rpm }else if((Rev1 >= 2750) && (Rev1 < 3250)){ CCPR2=709; //BTDC10.0° //3000rpm }else if((Rev1 >= 3250) && (Rev1 < 4000)){ CCPR2=706; //BTDC14.0° //3500rpm }else if((Rev1 >= 4000) && (Rev1 < 5750)){ CCPR2=705; //BTDC14.0° //4000rpm }else{ ////Rev < 250 または5750 < Rev のとき LATCbits.LATC2 = 0; //コイル信号OFF } // CCPR1=0x134; // CCPR2=0x161; LATAbits.LATA0 = !PORTBbits.RB2; //上死点調整用 ////Z相 // if(timer1 > 0x15B || timer1 < 0x5A ){ //カムでの角度が347.4°(信号立下り) if(timer1 > 670 || timer1 <180 ){ LATBbits.LATB3 = 1; //BTDC20° 燃料噴射 } else{ LATBbits.LATB3 = 0; injection++; } Zcount = ZcountL; //下位8ビット Zcount += (unsigned int)ZcountH<<8; //8ビットシフトさせて if(NoRev == 0){ //NoRev =0なら(エンジン動作中) Rev = 11250000/Zcount; //回転数計算 Rev = Rev/10; //10で割ることで一桁目を切り捨てる Rev = Rev*10; //10倍して桁を繰り上げる Rev1 = Rev; //1回前の回転数 doel=(unsigned int)704-(337500/Zcount); doel2=doel; // revav1 = revav0; //2回目回転数値保存 // revav0 = Rev; //1回目回転数値保存 // Ave = (Rev + revav0 + revav1) / 3; //3点平均を計算 } if(NoRev ==1){ //NoRev =0なら(エンジン停止中) LATCbits.LATC2 = 0; //コイル通電OFF Rev = 0; doel=704; doel2=doel; } timer1 = TMR1L; // timer1 += TMR1H*256; // i++; if(i == 800){ Display(); i = 0; } //更新 } } ///A/D変換読み込み関数 unsigned int AD_input(char chanl) { unsigned int adData; // 10ビットモード ADCON0 = 0x01 + (chanl * 4); //2ビット左にシフト ADCON0bits.GO = 1; // Start AD conversion while(ADCON0bits.NOT_DONE); // Wait for conversion adData = ADRESH * 256 + ADRESL; return(adData); // データ返し } /// 数値から文字列に変換 void ltostring(char digit, unsigned long data, char *buffer) { char i; buffer += digit; // 文字列の最後 for(i=digit; i>0; i--) { // 最下位桁から上位へ buffer--; // ポインター1 *buffer = (data % 10) + '0';// その桁数値を文字にして格納 data = data / 10; // 桁-1 } } /// データ表示関数 void Display(void) { lcd_cmd(0x80); //1行目へ sprintf(Msg1, "%3d.%2d",(5*A)/10,(5*A)%10); ////文字列書式入出力関数 lcd_str((char *)Msg1); //1行目表示 lcd_cmd(0x88); //1行目へ sprintf(Msg3,"%d",ignition); ////文字列書式入出力関数 lcd_str((char *)Msg3); //1行目表示 lcd_cmd(0xC0); //2行目へ 359.5 sprintf(Msg2,"%4drpm",Rev); lcd_str((char *)Msg2); //2行目表示 /*lcd_cmd(0xC8); //2行目へ 359.5 sprintf(Msg4,"%d",injection); lcd_str((char *)Msg4);*/ } <file_sep># my_product 成果物
37a93a24de63af779aea4c2f47a204a47a609b6f
[ "Markdown", "C", "JavaScript", "PHP" ]
32
Markdown
YotaSakurai/my_product
ab36c903ad8560841d1dd358e98a8602a75bb693
becadad2eb3e81c95215be1083b8aada4840f287
refs/heads/master
<repo_name>eseawind/GyAutoSelenium<file_sep>/src/com/guyi/Base/CarDetailPage.java package com.guyi.Base; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class CarDetailPage extends BasePage { //³µÅÆÊ÷ WebElement carTreeMenus ; public CarDetailPage(WebDriver d) { super(d); // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } } <file_sep>/src/com/guyi/BaseConfig/WarnType.java package com.guyi.BaseConfig; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.openqa.selenium.WebElement; public class WarnType { static Set<String> warnitems; public WarnType() { warnitems = new HashSet<String>(); String s = "所有-紧急报瞥触动报警开关后触发-超速报警-疲劳驾驶-危险预警-GNSS模块发生故障-GNSS天线未接或被剪断-GNSS天线短路-终端主电源欠压-终端主电源掉电-终端LCD或显示器故障-TTS模块故障-摄像头故障-道路运输证IC卡模块故障-超速预警-疲劳驾驶预警-当天累计驾驶超时-超时停车-进出区域-进出路线-路段行驶时间不足/过长-路线偏离报警-车辆VSS故障-车辆油量异常-车辆被盗(通过车辆防盗器)-车辆非法点火-车辆非法位移-碰撞预警-侧翻预警-油量告警-温度告警"; String items[] = s.split("-"); // System.err.println(items.length); for (int i = 0; i < items.length; i++) { warnitems.add(items[i]); } } // 判断集合是否相等 public static boolean checkWarntype(List<WebElement> listWarntypes) { System.err.println("checking:"); if (listWarntypes == null) { return false; } Set<String> SetWarnMinusResult = new HashSet(); Set<String> SetCurentWebWarntypes = new HashSet(); for (WebElement warntype :listWarntypes) { SetCurentWebWarntypes.add( warntype.getText()); } SetCurentWebWarntypes.remove(""); if (SetCurentWebWarntypes.size() != warnitems.size()) { return false; } //1.先复制所有报警类型 SetWarnMinusResult.addAll(warnitems); //取交集 SetWarnMinusResult.retainAll(SetCurentWebWarntypes); if (SetWarnMinusResult.size() == 0 ) { return true; } return false; } /** * @param args */ public static void main(String[] args) { // for (Iterator iterator = w.warnitems.iterator(); iterator.hasNext();) // { // System.err.println(iterator.next()); // } Set<String> s1 = new HashSet<String>(); Set<String> warnitems2 = new HashSet<String>(); String str = "所有-紧急报瞥触动报警开关后触发-超速报警-疲劳驾驶-危险预警-GNSS模块发生故障-GNSS天线未接或被剪断-GNSS天线短路-终端主电源欠压-终端主电源掉电-终端LCD或显示器故障-TTS模块故障-摄像头故障-道路运输证IC卡模块故障-超速预警-疲劳驾驶预警-当天累计驾驶超时-超时停车-进出区域-进出路线-路段行驶时间不足/过长-路线偏离报警-车辆VSS故障-车辆油量异常-车辆被盗(通过车辆防盗器)-车辆非法点火-车辆非法位移-碰撞预警-侧翻预警-油量告警-温度告警"; warnitems2.add("所有"); String items[] = str.split("-"); for (int i = 0; i < items.length; i++) { warnitems2.add(items[i]); } System.err.println("test:"+warnitems2); // System.err.println(new WarnType().checkWarntype(items)); HashSet<Integer> setA = new HashSet<Integer>(); setA.add(1); setA.add(3); setA.add(5); HashSet<Integer> setB = new HashSet<Integer>(); setB.add(1); setB.add(6); HashSet<Integer> setC = new HashSet<Integer>(); setC.clear(); setC.addAll(setA); setC.retainAll(setB); System.out.println("setC=" + setC); } } <file_sep>/src/com/guyi/BaseConfig/CheckDataBase.java package com.guyi.BaseConfig; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.google.common.collect.Iterables; /** * 数据库校验 * */ public class CheckDataBase { //设定数据库驱动,数据库连接地址、端口、名称,用户名,密码 static String driverName="oracle.jdbc.driver.OracleDriver"; static String url="jdbc:oracle:thin:@192.168.1.185:1523:lenglian"; //test为数据库名称,1521为连接数据库的默认端口 static String user="sa"; //sa为用户名 static String password="sa"; //sa为密码 static PreparedStatement pstmt = null; static ResultSet rs = null; //数据库连接对象 static Connection conn = null; //关闭数据 public static void close() { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(System.err); } } //连接数据库 public static void connDataBase(String sql){ try { Class.forName(driverName); //获取数据库连接 conn = DriverManager.getConnection(url, user, password); // System.err.println(conn); //创建该连接下的PreparedStatement对象 pstmt = conn.prepareStatement(sql); // System.err.println(pstmt); //执行查询语句,将数据保存到ResultSet对象中 rs = pstmt.executeQuery(); // System.err.println(rs); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { System.err.println("CheckDataBase数据库连接异常"); e.printStackTrace(); } } public static int checkNum(String sql){ int result =0; //反射Oracle数据库驱动程序类 try { connDataBase( sql); //将指针移到下一行,判断rs中是否有数据 if(rs.next()){ //输出查询结果 从1开始 // System.err.println("总记录数:"+rs.getString(1)); result = Integer.valueOf(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public static void checkoneRecord(String sql,HashMap<String,String> map){ connDataBase(sql); try { if (rs.next()) { Iterator<Entry<String, String>> itr = map.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String,String> entry=(Map.Entry<String,String>) itr.next(); // System.err.println("test---"+entry.getKey()); try { // System.err.println(entry.getKey()); String tmp =rs.getString(entry.getKey()); entry.setValue(tmp); } catch (SQLException e) { e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } close(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String sql= "select * from tb_base_fee where fee_id =1241 "; // int i =CheckDataBase.checkNum(sql); // System.err.println("总记录:"+i); HashMap map = new HashMap<String, String>(); map.put("fee_id", null); map.put("start_site", null); map.put("end_site", null); map.put("road_toll", null); map.put("kilo_number", null); CheckDataBase.checkoneRecord(sql, map); System.err.println(map); } } <file_sep>/README.md GyAutoSelenium ============== 古易冷链自动化项目 <file_sep>/src/com/guyi/Base/HomePage.java package com.guyi.Base; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; /** * 首页登录 * * */ public class HomePage extends BasePage { WebDriver driver; // @FindBy(name="userName-inputEl") // WebElement username; // @FindBy(id="userPwd-inputEl") // WebElement password; public HomePage(WebDriver driver) { super(driver); this.driver = driver; // driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } public Boolean login(String usr, String pwd, String url) { try { driver.get(url); // System.err.println("login"+driver); // LoginPage page = PageFactory.initElements(driver, LoginPage.class); // 1.登录系统 userName-inputEl // System.err.println("test"+driver.findElements(By.id("userName-inputEl"))); new WebDriverWait(driver, 30).until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { // System.err.println("打开登录界面中:"); log.debug( "打开登录界面中:"); return driver.findElement(By.id("userName-inputEl")).isDisplayed(); } }); WebElement username = this.getElement("username"); username.clear(); username.sendKeys(usr); WebElement passwd = this.getElement("passwd"); passwd.clear(); passwd.sendKeys(pwd); WebElement loginBTN = this.getElement("loginBTN"); //点击登录按钮 ((JavascriptExecutor) driver).executeScript("arguments[0].click();",loginBTN); // System.err.println("已登录"); log.info("已登录"); } catch (Exception e) { // System.err.println(e); log.error(e); return false; } return true; } public Boolean loginfail(String usr, String pwd, String url){ //点击登录按钮 ((JavascriptExecutor) driver).executeScript("arguments[0].click();", driver.findElement(By.xpath("//span[@class='x-btn-inner x-btn-inner-center']"))); //判断是否弹出登录失败提示框 WebElement loginfail=null; try { loginfail = new WebDriverWait(driver, 3) .until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver arg0) { List<WebElement> spans= arg0.findElements(By .xpath("//div[@class='x-window x-message-box x-layer x-window-default x-closable x-window-closable x-window-default-closable']//span")); // System.err.println(spans.size()); for(WebElement e :spans){ if( e.getText().equals("登陆失败!") ){ return e; } } return null; } }); } catch (Exception e) { System.err.println("没找到,登录成功"); return false; } return true; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); System.err.println(driver.getClass().getName()); HomePage l = new HomePage(driver); System.err.println(l); // Boolean ispass = l.login("test", "test", "http://192.168.1.180:8080/login.htm"); Boolean ispass = l.login("test", "test", "http://192.168.3.11:8011/index.htm"); // Boolean ispass = l.login("test", "test", "http://guyi2013.vicp.cc:8088/index.htm"); System.err.println(ispass); driver.quit(); } } <file_sep>/src/log4j.properties #\u8BBE\u7F6E\u7EA7\u522B\uFF1A log4j.rootLogger=info,appender1 #\u8F93\u51FA\u5230\u6587\u4EF6(\u8FD9\u91CC\u9ED8\u8BA4\u4E3A\u8FFD\u52A0\u65B9\u5F0F) log4j.appender.appender1=org.apache.log4j.ConsoleAppender #\u8BBE\u7F6E\u6587\u4EF6\u8F93\u51FA\u8DEF\u5F84 #\u30101\u3011\u6587\u672C\u6587\u4EF6 #log4j.appender.appender1.File=c:/Log4JDemo02.log #\u30102\u3011HTML\u6587\u4EF6 #\u8BBE\u7F6E\u6587\u4EF6\u8F93\u51FA\u6837\u5F0F log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout #log4j.appender.appender1.layout=org.apache.log4j.PatternLayout<file_sep>/src/com/guyi/TestNG/TestNGBase.java package com.guyi.TestNG; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; import com.guyi.Base.BasePage; public class TestNGBase { static WebDriver driver ; static BasePage basepage ; @Test public void createDriver() { if(TestNGBase.driver == null ){ driver = new FirefoxDriver(); System.err.println("test TestNGBase---------"+driver); } driver.manage().window().maximize(); } @BeforeTest public void beforeTest() { } @AfterTest public void afterTest() { } @BeforeSuite public void beforeSuite() { System.err.println("11111"); } @AfterSuite public void afterSuite() { System.err.println("¹Ø±Õdriver"); driver.quit(); } } <file_sep>/src/test/testList.java package test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class testList { public testList() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<String> s = new ArrayList<String>(); s.add("a1"); s.add("a2"); s.add("a3"); s.add("a4"); // s.remove(1); // for (int i = 0; i < s.size(); i++) { // System.err.println(String.valueOf(i)+s.get(i)); // if (i==1) { // s.remove(1); // } // System.err.println(String.valueOf(i)+s.get(i)); // } List<String> stmp = new ArrayList<String>(); for (String aa : s) { if (aa.equals("a2")) { stmp.add(aa); } if (aa.equals("a5")) { stmp.add(aa); } System.err.println(aa); } s.removeAll(stmp); System.err.println(s); } } <file_sep>/src/com/guyi/CarMonitor/CarMonitor.java package com.guyi.CarMonitor; import java.util.Iterator; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import com.guyi.Base.BasePage; import com.guyi.Base.HomePage; public class CarMonitor extends BasePage { public CarMonitor(WebDriver d) { super(d); // TODO Auto-generated constructor stub } //选择车辆 /** * @param menuname 分页名称: 存在多个分页时做判断 * @param comparyname 车队名称 * @param plate 车牌 * @return 是否正确选择 * */ public boolean SelectCar(String menuname,String comparyname,String plate){ boolean result = true; List<WebElement> tabbar=getDisplayedElements("tabbarpath"); for(WebElement e:tabbar){ //选择分页 if (e.getText().equals(menuname)) { new Actions(driver).click(e).perform(); } } //找到右边窗体, 固定一个 WebElement fatherDiv ; fatherDiv= driver.findElement(By.xpath("/html/body/div[contains(@id,'panel')]")); //找到右边框体中的车辆树 xpath String strXpath= ".//div/table/tbody/tr/td/div/span[@class='x-tree-node-text']"; List<WebElement> cartrees =fatherDiv.findElements(By.xpath(strXpath)); for(WebElement e :cartrees){ this.log.debug(e.getText()); //首先打开车队目录树 车队名称 if (e.getText().equals(comparyname)) { new Actions(driver).doubleClick(e).perform(); } } sleep(1000); //点击车队后,页面会刷新,需重新获取一次 cartrees =fatherDiv.findElements(By.xpath(".//tr/td/div/span")); for(WebElement e :cartrees){ log.debug(e.getText()); if (e.getText().equals(plate)) { sleep(4000); new Actions(driver).click(e).perform(); // } } } cartrees =getAllElements("CarTrees"); System.err.println(cartrees); System.err.println(cartrees.get(1)); new Actions(driver).contextClick(cartrees.get(4)).perform(); sleep(1000); List<WebElement> menutrees = getAllElements("menuTemplateAndOil"); System.err.println(menutrees ); for (WebElement e : menutrees) { System.err.println(e.getText()); if (e.getText().equals("温度油量")) { e.click(); } } // TempOil 为yaml配置标签 判断温度油量界面是否存在 不存在则用例失败 if (getElementNoWait("TempOil") == null) { log.error("未弹出温度油量界面"); result = false; }else { log.info("温度油量正常显示"); } sleep(2000); WebElement btnclose =getElement("btnClose"); // System.err.println(btnclose.isDisplayed()); driver.manage().window().maximize(); if (!btnclose.isDisplayed()) { //如果温度油量界面中关闭按钮没有显示 则返回失败 return false; } btnclose.click(); if( getElementNoWait("TempOil") != null ){ log.info("油量界面关闭失败"); result = false; return result; } return result; } public boolean contextMenu(){ return true; } public boolean QueryGroupMileage(String startDate,String Starttime,String endDate,String endTime){ boolean result = true; List<WebElement> tabs= getAllElements("GroupMileageTabName"); for(WebElement e : tabs){ // System.err.println(e.getText()); if (e.getText().equals("分段里程")) { e.click(); } } WebElement elementSdate = getElement("startdate"); elementSdate.clear(); elementSdate.sendKeys(startDate); //设置开始日期 WebElement elementStime = getElement("starttime"); elementStime.clear(); elementStime.sendKeys(Starttime); //设置开始时间 WebElement elementEdate = getElement("enddate"); elementEdate.clear(); elementEdate.sendKeys(endDate); //设置end日期 WebElement elementEtime = getElement("endtime"); elementEtime.clear(); elementEtime.sendKeys(endTime); //设置结束时间 List<WebElement> btnquery = getAllElements("btnGroupMileage"); for(WebElement e : btnquery){ System.err.println(e.getText()); if (e.getText().equals("查询")) { e.click(); } } System.err.println(btnquery ); return result; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // System.err.println("11"); WebDriver d = new FirefoxDriver(); d.manage().window().maximize(); HomePage hp = new HomePage(d); // d.get("http://192.168.1.180:8080/index.htm"); // WebElement e =hp.getElement("username"); // new Actions(d).contextClick(e).perform(); // hp.login("bsuser", "123456","http://192.168.1.180:8080/index.htm"); hp.login("bsuser", "123456","http://guyi2013.vicp.cc:8011/index.htm"); CarMonitor cm = new CarMonitor(d); cm.openMenus("车辆监控-车辆监控2"); cm.SelectCar("车辆监控2", "合利物流", "闽A-00011"); cm.QueryGroupMileage("2014-06-25", "", "2014-07-01","12:00:11"); } }
f951631d0e42964ef844c9570088af0a71df2d4a
[ "Markdown", "Java", "INI" ]
9
Java
eseawind/GyAutoSelenium
b9198e3f00514f02ea23053cd60d7b45cbaf369a
c6ad8e65500de366b7ed127d561b04c9dcf8431f
refs/heads/master
<repo_name>BradyMcd/hid-acer-one<file_sep>/Makefile # Comment/uncomment the following line to disable/enable debugging # DEBUG = y MODULE_NAME = hid-acer-one KVER = $(shell uname -r) MODDESTDIR = /lib/modules/$(KVER)/kernel/drivers/hid/ # Add debugging flag (or not) to CFLAGS ifeq ($(DEBUG),y) DEBFLAGS = -O -g -DSHORT_DEBUG # "-O" is needed to expand inlines else DEBFLAGS = -O2 endif ccflags-y += $(DEBFLAGS) ifneq ($(KERNELRELEASE),) # call from kernel build system obj-m := hid-acer-one.o else KERNELDIR ?= /lib/modules/$(KVER)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules endif clean: rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions install: install -p -m 644 $(MODULE_NAME).ko $(MODDESTDIR) /sbin/depmod -a ${KVER} uninstall: rm -f $(MODDESTDIR)/$(MODULE_NAME).ko /sbin/depmod -a ${KVER} <file_sep>/README.md # Overview of the error Some Acer keyboards report excessively large max usage values. This causes an error at boot which leaves the keyboard inoperable; since the max use values in the report descriptor exceed HID_MAX_USAGES the descriptor isn't parsed. This module simply changes the report descriptor to have more sensible max usage values during boot before passing the edited version up to the generic hid module for parsing. ##### Known keyboards with this issue * `06CB:73F4` (This is the only one targeted by this fix at present) * `06CB:2968` * `06CB:2991` This module specifically targets keyboards identifying themsleves as ` 06CB:73F4 `. If your device identifies itself as `06CB:2968` or `06CB:2991` they should work OOTB on Linux Kernels version 4.3 and above, for older kernels the fix (which this module was adapted from) can be found [here](https://github.com/SWW13/hid-acer). #### Symptoms of the error Symptoms that this might be a problem you are experiencing is a message along the lines of `hid (null): usage index exceeded` followed by hid-generic complaining that `parsing failed` in your dmesg logs. ## Build / Install First install linux-headers for your version of Linux, some details can be found [here](http://www.cyberciti.biz/tips/build-linux-kernel-module-against-installed-kernel-source-tree.html). ``` git clone https://github.com/BradyMcD/hid-acer-one.git cd hid-acer-one make sudo make install ``` #### Uninstall ``` sudo make uninstall ``` <file_sep>/acer-hids.h #ifndef ACER_HIDS #define ACER_HIDS #define USB_VENDOR_ID_ACER_SYNAPTICS 0x06cb #define USB_VENDOR_ID_ACER_SYNAPTICS_TP_73F4 0x73F4 #endif//ACER_HIDS <file_sep>/hid-acer-one.c /* * HID driver for acer devices * * Copyright (c) 2016 <NAME> * Modified from Simon Wörner's hid-acer <https://github.com/SWW13/hid-acer> */ /* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "acer-hids.h" /* Some Acer keyboards have an issue where they report an excessive max usages value * The kyboard targeted in this fix identifies itself as 06CB:73F4 * * At boot this module inspects the report descriptor for a specific error and changes the values so that they will parse properly */ #define ACER_KBD_RDESC_SIZE 188 #define ACER_KBD_RDESC_CHECK_POS (173 * sizeof(__u8)) #define ACER_KBD_RDESC_CHECK_DATA 0x2AFFFF150026FFFF #define ACER_KBD_RDESC_FIX_POS1 ACER_KBD_RDESC_CHECK_POS + 2 #define ACER_KBD_RDESC_FIX_POS2 ACER_KBD_RDESC_CHECK_POS + 7 static __u8 *acer_kbd_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize){ /* Check that the descriptor size matches what we expect */ if (*rsize == ACER_KBD_RDESC_SIZE) { __u64 check = be64_to_cpu(*(__be64 *)(rdesc + ACER_KBD_RDESC_CHECK_POS)); /* check for invalid max usages */ if (check == ACER_KBD_RDESC_CHECK_DATA) { hid_info(hdev, "fixing up acer keyboard report descriptor\n"); /* change max values to 0xFF00 */ rdesc[ACER_KBD_RDESC_FIX_POS1] = 0x00; rdesc[ACER_KBD_RDESC_FIX_POS2] = 0x00; } } return rdesc; } static const struct hid_device_id acer_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ACER_SYNAPTICS, USB_VENDOR_ID_ACER_SYNAPTICS_TP_73F4) }, { } }; MODULE_DEVICE_TABLE(hid, acer_devices); static struct hid_driver acer_driver = { .name = "acer", .id_table = acer_devices, .report_fixup = acer_kbd_report_fixup, }; module_hid_driver(acer_driver); MODULE_AUTHOR("<NAME>"); MODULE_LICENSE("GPL");
438e4fec2529f20649c52e5a732a4b77731ae52d
[ "Markdown", "C", "Makefile" ]
4
Makefile
BradyMcd/hid-acer-one
b15f93d08f4ffc512a439c6a823bc390490c0c17
328e24f39e5efeb7186aab8cdb195998d510d0db
refs/heads/master
<file_sep>Given a string, compute recursively a new string where all appearances of "pi" have been replaced by "3.14". Sample Input 1 : xpix Sample Output : x3.14x Sample Input 2 : pipi Sample Output : 3.143.14 Sample Input 3 : pip Sample Output : 3.14p +++++++++++++++++++++++++++++++++++++++++++++++++++ public class solution { // Return the changed string public static String replace(String input){ // Write your code here if(input.length()<=1) { return input; } if(input.charAt(0)=='p' && input.charAt(1)=='i' && input.length()>=2) { return 3.14+replace(input.substring(2,input.length() )); } return input.charAt(0)+ replace(input.substring(1,input.length())); } } <file_sep>Complex Number Class A ComplexNumber class contains two data members : one is real part (R) and other is imaginary (I) (both integer). Implement the Complex numbers class that contains following functions - 1. constructor You need to create the appropriate constructor. 2. plus - This function adds two given complex numbers and updates the first complex number. e.g. if C1 = 4 + i5 and C2 = 3 +i1 C1.plus(C2) results in: C1 = 7 + i6 and C2 = 3 + i1 3. multiply - This function multiplies two given complex numbers and updates the first complex number. e.g. C1 = 4 + i5 and C2 = 1 + i2 C1.multiply(C2) results in: C1 = -6 + i13 and C2 = 1 + i2 4. print - This function prints the given complex number in the following format : a + ib Note : There is space before and after '+' (plus sign) and no space between 'i' (iota symbol) and b. Input Format : Line 1 : Two integers - real and imaginary part of 1st complex number Line 2 : Two integers - real and imaginary part of 2nd complex number Line 3 : An integer representing choice (1 or 2) (1 represents plus function will be called and 2 represents multiply function will be called) Sample Input 1 : 4 5 6 7 1 Sample Output 1 : 10 + i12 Sample Input 2 : 4 5 6 7 2 Sample Output 2 : -11 + i58 +++++++++++++++++++++++++++++++++++++++++++++++++++ public static void main(String[] args) { Scanner s = new Scanner(System.in); int real1 = s.nextInt(); int imaginary1 = s.nextInt(); int real2 = s.nextInt(); int imaginary2 = s.nextInt(); ComplexNumbers c1 = new ComplexNumbers(real1, imaginary1); ComplexNumbers c2 = new ComplexNumbers(real2, imaginary2); int choice = s.nextInt(); if(choice == 1) { // Add c1.plus(c2); c1.print(); } else if(choice == 2) { // Multiply c1.multiply(c2); c1.print(); } else { return; } } ******************/ public class ComplexNumbers { // Complete this class private int real; private int imaginary; private int newReal; private int newimaginary; public ComplexNumbers(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public int getNewReal() { return newReal; } public void setNewReal(int newReal) { this.newReal = newReal; } public int getNewimaginary() { return newimaginary; } public void setNewimaginary(int newimaginary) { this.newimaginary = newimaginary; } public int getReal() { return real; } public void setReal(int real) { this.real = real; } public int getImaginary() { return imaginary; } public void setImaginary(int imaginary) { this.imaginary = imaginary; } public void plus(ComplexNumbers c2) { newReal = this.real + c2.real; newimaginary = this.imaginary + c2.imaginary; } public void print() { System.out.println(getNewReal() + " " + "+" + " " + "i" + getNewimaginary()); } public void multiply(ComplexNumbers c2) { int newReal = (this.real * c2.real) - (this.imaginary * c2.imaginary); setNewReal(newReal); int newimaginary = ((this.real * c2.imaginary)) + ((this.imaginary * c2.real)); setNewimaginary(newimaginary); } } +++++++++++++++++++++++++++++++++++++++++++++++++++ import java.util.Scanner; public class Runner { public static void main(String[] args) { Scanner s = new Scanner(System.in); int real1 = s.nextInt(); int imaginary1 = s.nextInt(); int real2 = s.nextInt(); int imaginary2 = s.nextInt(); ComplexNumbers c1 = new ComplexNumbers(real1, imaginary1); ComplexNumbers c2 = new ComplexNumbers(real2, imaginary2); int choice = s.nextInt(); if(choice == 1) { // Add c1.plus(c2); c1.print(); } else if(choice == 2) { // Multiply c1.multiply(c2); c1.print(); } else { return; } } } <file_sep>Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer. Input format : Numeric string (string, Eg. "1234") Output format : Corresponding integer (int, Eg. 1234) Sample Input 1 : 1231 Sample Output 1: 1231 Sample Input 2 : 12567 Sample Output 2 : 12567 public class solution { public static int convertStringToInt(String input){ // Write your code here if (input.length() == 1) { return (input.charAt(0)-'0' ); } double y = convertStringToInt(input.substring(1)); double x = input.charAt(0) - '0'; x = x * Math.pow(10, input.length() - 1) + y; return (int)(x); } } <file_sep>Given a string, compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*". Sample Input 1 : hello Sample Output 1: hel*lo Sample Input 2 : xxyy Sample Output 2: x*xy*y Sample Input 3 : aaaa Sample Output 3: a*a*a*a +++++++++++++++++++++++++++++++++++++++++++++++++++ public class solution { // Return the updated string public static String addStars(String s) { if(s.length()==1){ return s; } char arr1[]=s.toCharArray(); char arr2[]=new char[arr1.length-1]; for(int index=0;index<arr1.length-1;index++){ arr2[index]=arr1[index]; } String temp2=new String(arr2); String actual=addStars(temp2); String s3=Character.toString(arr1[arr1.length-1]); if(actual.charAt(actual.length()-1)==arr1[arr1.length-1]){ return actual+"*"+s3; } return actual+s3; } } <file_sep>Given an array of length N, you need to find and return the sum of all elements of the array. Do this recursively. Input Format : Line 1 : An Integer N i.e. size of array Line 2 : N integers which are elements of the array, separated by spaces Output Format : Sum Constraints : 1 <= N <= 10^3 Sample Input : 3 9 8 9 Sample Output : 26 +++++++++++++++++++++++++++++++++++++++++++++++++++ public class Solution { public static int sum(int input[]) { if(input.length==1){ return input[0]; } int smallerInput[]=new int[input.length-1]; for(int i=1;i<input.length;i++){ smallerInput[i-1]=input[i]; } int total=sum(smallerInput); total+=input[0]; return total; } } import java.util.Scanner; public class Runner { static Scanner s = new Scanner(System.in); public static void main(String[] args) { int n = s.nextInt(); int input[] = new int[n]; for(int i = 0; i < n; i++) { input[i] = s.nextInt(); } System.out.println(Solution.sum(input)); } } <file_sep>Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. Do this recursively. Input Format : Line 1 : An Integer N i.e. size of array Line 2 : N integers which are elements of the array, separated by spaces Line 3 : Integer x Output Format : true or false Constraints : 1 <= N <= 10^3 Sample Input : 3 9 8 10 8 Sample Output : true +++++++++++++++++++++++++++++++++++++++++++++++++++ public class Solution { public static boolean checkNumber(int input[], int x) { return check(input, 0, x); } public static boolean check(int[] input, int startIndex, int x) { if (startIndex == input.length) { return false; } if (input[startIndex] == x) { return true; } return check(input, startIndex + 1, x); } } import java.util.Scanner; public class Runner { static Scanner s = new Scanner(System.in); public static void main(String[] args) { int n = s.nextInt(); int input[] = new int[n]; for(int i = 0; i < n; i++) { input[i] = s.nextInt(); } int x = s.nextInt(); System.out.println(Solution.checkNumber(input, x)); } } <file_sep>Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). Do this recursively. Indexing in the array starts from 0. Input Format : Line 1 : An Integer N i.e. size of array Line 2 : N integers which are elements of the array, separated by spaces Line 3 : Integer x Output Format : indexes where x is present in the array (separated by space) Constraints : 1 <= N <= 10^3 Sample Input : 5 9 8 10 8 8 8 Sample Output : 1 3 4 +++++++++++++++++++++++++++++++++++++++++++++++++++ public class Solution { public static int[] allIndexes(int input[], int x) { /* Your class should be named Solution * Don't write main(). * Don't read input, it is passed as function argument. * Return output and don't print it. * Taking input and printing output is handled automatically. */ return allIndexes(input,x,0); } public static int[] allIndexes(int input[], int x,int startIndex){ if(startIndex == input.length){ int[] rv = new int[0]; return rv; } int[] roaIndex = allIndexes(input,x,startIndex + 1); if(input[startIndex] == x){ int[] totalIndex = new int[(roaIndex.length) + 1]; totalIndex[0] = startIndex; for(int i = 0;i < roaIndex.length;i++){ totalIndex[i+1] = roaIndex[i]; } return totalIndex; } else{ return roaIndex; } } } import java.util.Scanner; public class Runner { static Scanner s = new Scanner(System.in); public static int[] takeInput(){ int size = s.nextInt(); int[] input = new int[size]; for(int i = 0; i < size; i++){ input[i] = s.nextInt(); } return input; } public static void main(String[] args) { int[] input = takeInput(); int x = s.nextInt(); int output[] = Solution.allIndexes(input, x); for(int i = 0; i < output.length; i++) { System.out.print(output[i] + " "); } } } <file_sep>Given an array/list of length N, you need to find and return the sum of all elements of the array/list. Input Format : Line 1 : An Integer N i.e. size of array/list Line 2 : N integers which are elements of the array/list, separated by spaces Output Format : Sum Constraints : 1 <= N <= 10^6 Sample Input : 3 9 8 9 Sample Output : 26 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public class Solution { public static int sum(int[] input){ int sum=0; for(int i=0;i<input.length;i++) { sum=sum+input[i]; } return sum; } } public class Runner { static Scanner s = new Scanner(System.in); public static int[] takeInput(){ int size = s.nextInt(); int[] input = new int[size]; for(int i = 0; i < size; i++){ input[i] = s.nextInt(); } return input; } public static void main(String[] args) { int[] input = takeInput(); System.out.println(Solution.sum(input)); } } <file_sep>Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. You should start traversing your array from 0, not from (N - 1). Do this recursively. Indexing in the array starts from 0. Input Format : Line 1 : An Integer N i.e. size of array Line 2 : N integers which are elements of the array, separated by spaces Line 3 : Integer x Output Format : last index or -1 Constraints : 1 <= N <= 10^3 Sample Input : 4 9 8 10 8 8 Sample Output : 3 +++++++++++++++++++++++++++++++++++++++++++++++++++ public class Solution { public static int lastIndex(int input[], int x) { /* Your class should be named Solution * Don't write main(). * Don't read input, it is passed as function argument. * Return output and don't print it. * Taking input and printing output is handled automatically. */ if(input.length<=1){ if(input[0]==x){ return 0; }else{ return -1; } } int []smallArray=new int[input.length-1]; for(int index=1;index<input.length;index++){ smallArray[index-1]=input[index]; } int val=lastIndex(smallArray,x); if(val==-1){ if(input[0]==x){ return 0; } } if(val>=0){ return ++val; } return -1; } } import java.util.Scanner; public class Runner { static Scanner s = new Scanner(System.in); public static int[] takeInput(){ int size = s.nextInt(); int[] input = new int[size]; for(int i = 0; i < size; i++){ input[i] = s.nextInt(); } return input; } public static void main(String[] args) { int[] input = takeInput(); int x = s.nextInt(); System.out.println(Solution.lastIndex(input, x)); } }
6cc590ab382d14325f46ab03fc224d81dc28ee54
[ "Java" ]
9
Java
kunal8411/Coding-NInja
f6a0c75869fe3a98e5cadefd7b4b064bf463370d
40558ca762722fb65864dcb4fca8a9b7d1d702db
refs/heads/main
<file_sep> //@desc get all bootcamps //@access public // @route GET api/v1/bootcamps const ErrorResponse = require('../utlis/errorresponse'); const asyncHandler = require('../middleware/async'); const Bootcamp = require('../models/Bootcamp'); const geocoder = require('../utlis/geocoder'); exports.getBootcamps = asyncHandler(async (req,res , next) => { let query; // console.log(req.query); //Copy req.query const reqQuery = {...req.query}; //Create querystring let queryStr = JSON.stringify(reqQuery); //Fields to exclude const removeFields= ['select','sort']; //Loop over remove fields and delete from reqQuery removeFields.forEach(param => delete reqQuery[param]); // console.log(reqQuery); // console.log(queryStr); //Create operators queryStr = queryStr.replace(/\b(gt|lt|gte|lte|in)\b/g,match=>`$${match}`); // console.log(queryStr); //Finding resource query = Bootcamp.find(JSON.parse(queryStr)); //Select fields if(req.query.select){ const fields = req.query.select.split(',').join(' '); query = query.select(fields); } if(req.query.sort){ const sortBy = req.query.sort.split(',').join(' '); // console.log(sortBy); query = query.sort(sortBy) // console.log(query); }else{ query = query.sort('-createdAt'); } //Executing query const bootcamps = await query; res.status(200).json({ success:true, data:bootcamps, count:bootcamps.length }) }); //@desc get single bootcamp //@access public // @route GET api/v1/bootcamps/:id exports.getBootcamp = asyncHandler(async (req,res , next) => { const bootcamp = await Bootcamp.findById(req.params.id) if(!bootcamp){ return next(new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`,404)); } res.status(200).json({ success:true, data:bootcamp }) }) //@desc create new bootcamp //@access private // @route POST api/v1/bootcamps exports.createBootcamp = asyncHandler(async (req,res , next) => { const bootcamp = await Bootcamp.create(req.body); res.status(201).json({ success:true, data:bootcamp }) }) //@desc update single bootcamp //@access private // @route PUT api/v1/bootcamps/:id exports.updateBootcamp = asyncHandler( async (req,res , next) => { const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body,{ new:true, runValidators:true }) if(!bootcamp){ return res.status(400).json({success:false}) } res.status(200).json({success:true,data:bootcamp}) }) //@desc delete bootcamp //@access private // @route DELETE api/v1/bootcamps/:id exports.deleteBootcamp = asyncHandler( async (req,res , next) => { const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id) if(!bootcamp){ return next(err); } res.status(200).json({success:true,data:{}}) }) //@desc Get bootcamps within a place //@access private // @route DELETE api/v1/bootcamps/radius/:zipcode/:distance exports.getBootcampsInRadius = asyncHandler( async (req,res , next) => { const {zipcode,distance} = req.params; //Get lat&&lang from geocoder const loc = await geocoder.geocode(zipcode); const lat = loc[0].latitude; const lng = loc[0].longitude; //Calc radius using radians //Divide dist by radius of Earth const radius = distance / 3963; const bootcamps = await Bootcamp.find({ location :{$geoWithin:{$centerSphere:[[lng,lat],radius]}} }); if(!bootcamps){ return next(new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`,404)); } res.status(200).json({ success:true, count:bootcamps.length, data:bootcamps }); }) <file_sep>const ErrorResponse = require("../utlis/errorresponse"); const erroeHandler = (err,req,res,next) =>{ //Log let error = {...err}; error.message = err.message; console.log(err.message); //Mongoose Bad object Id if(err.name === 'CastError'){ const message = `Resource not found ${err.value}`; error = new ErrorResponse(message,404); } // Mongoose duplicate key if(err.code === 11000){ const message = `Suplicate field value entered `; error = new ErrorResponse(message,400); } //Mongoose Validation error if(err.name === 'ValidationError'){ const message = Object.values(err.errors).map(val => val.message) error = new ErrorResponse(message,404); } res.status( error.statusCode || 500).json({ sucess:false, error:error.message || "Server Error" }) } module.exports = erroeHandler;
2013a6542f47665e143336435d2a30570f047c8e
[ "JavaScript" ]
2
JavaScript
Souvik-Banerjee2000/devcamper
183ea0c2a6e4927e247c9fb73ba555fca4aa8c7c
1e51eb208fd3f8dc6520d37e80885a52f82fe968
refs/heads/master
<repo_name>xiaobao5214/javatest<file_sep>/src/V.java /** * Created by jingbao on 2017/7/14. */ public class V { } <file_sep>/src/BigNumber.java /** * Created by jingbao on 2017/7/14. */ public class BigNumber { public static void main(String[] args) { System.out.println(getBigNumber("135268079")); } public static String getBigNumber(String number){ char[] arr = {'零','一','二','三','四','五','六','七','八','九'}; char[] numArr = number.toCharArray(); for (int i = 0; i < numArr.length; i++) { numArr[i] = arr[numArr[i]-'0']; } return new String(numArr); } } <file_sep>/src/aa.java /** * Created by jingbao on 2017/7/14. */ public class aa { private String name; private int age; public static void main(String[] args) { System.out.println("再试一次cherry-pick"); System.out.println("我来试试cherry-pick命令"); } public void setName(String name) { this.name = name; } public String getName(){ return name; } }
b151e248342d14b785e470855bed12ad4c2a6a04
[ "Java" ]
3
Java
xiaobao5214/javatest
af89f623a60806d1fb06cca9c118cc2641635827
7b602ca38379989b27e0690d9177c8c0b2b3142e
refs/heads/master
<file_sep>import Tiempo from "./tiempo.js" import Fecha from "./fecha.js" import ElementoPedido from "./elementoPedido.js" import Cliente from "./cliente.js" import Direccion from "./direccion.js" import Precio from "./precio.js" import Producto from "./producto.js" import Pedido from "./pedido.js" export default class Restaurante { /** * * @param {string} nombre * @param {number} telefono * @param {Direccion} direccion * @param {Array} productos * @param {Array} pedidos */ constructor({nombre, telefono, direccion}){ this._nombre = nombre; this._telefono = telefono; this._direccion = direccion; this._productos = new Array(); this._pedidos = new Array(); } registrarProductos(producto){ this._productos.push(producto); } listrarProductos(){ this._productos.forEach(producto=>{ console.log(producto.getDescripcion()); }); } registrarPedidos(pedido){ this._pedidos.push(pedido); } listarPedidos(){ this._pedidos.forEach((pedido) =>{ console.log(pedido.getResumen()); }); } registrarPedido(pedido){ if (this.buscar() == undefined){ this._pedidos.push(pedido); return true; } return false; } buscarPedido(pedido){ let resultado = this._pedidos.find(e => e.esIgualA(pedido)); return resultado; } eliminar(pedido){ let indice = this.buscarPedido(pedido); if(indice < 0){ return false; } this._pedidos.splice(indice, 1); return true; } actualizarPedido(pedido, nuevoPedido){ let indice = this.buscarPedido(pedido); if(indice < 0){ return false; } this._pedidos.splice(indice, 1, nuevoPedido); return true; } }<file_sep>export default class Direccion{ /** * * @param {string} calle * @param {number} numeroExterior * @param {number} numeroInterior * @param {string} colonia * @param {number} codigoPostal * @param {string} ciudad * @param {string} municipio */ constructor(calle, numeroExterior, numeroInterior, colonia, codigoPostal, ciudad, municipio){ this._calle = calle; this._numeroExterior = numeroExterior; this._numeroInterior = numeroInterior; this._colonia = colonia; this._codigoPostal = codigoPostal; this._ciudad = ciudad; this._municipio = municipio; } getFormatoCorto(){ return (`Calle ${this._calle} #${this._numeroExterior}`) } getFormatoExtendido(){ return (`Calle ${this._calle} Num.Ext.${this._numeroExterior} Num.Int.${this._numeroInterior}, colonia${this._colonia}. Cod.Post.${this._codigoPostal} ${this._ciudad} ${this._municipio}`) } }<file_sep>export default class Tiempo{ /** * * @param {number} hora * @param {number} minutos */ constructor(hora, minutos){ this._hora = hora; this._minutos = minutos; this._periodo = ["am","pm"]; } getFormato12(){ if (this._hora>=12 && this._hora<=23){ if(this._hora==12){ return (`${this._hora}:${this._minutos} ${this._periodo[1]}`); } else{ var hora = this._hora-12; } return (`${hora}:${this._minutos} ${this._periodo[1]}`); } else if (this._hora==24){ return (`00:${this._minutos} ${this._periodo[0]}`); } else{ return (`${this._hora}:${this._minutos} ${this._periodo[0]}`); } } getFormato24(){ if(this._periodo === "pm"||this._periodo === "PM"||this._periodo === "Pm"){this._hora = this._hora + 12} return(`${this._hora}:${this._minutos}`); } }<file_sep>import Producto from "./producto.js" import Precio from "./precio.js" export default class ElementoPedido{ /** * * @param {Producto} producto * @param {number} cantidad */ constructor(producto, cantidad){ this._producto = producto; this._cantidad = cantidad; } getDescripcion(){ var costo = this._producto.precio.valor; var total = costo*this._cantidad; var descripcion = `${this._cantidad} x ${this._producto.nombre} $${total}`; return descripcion; } }
5b3f989a8fcfd8348d94f98acb6e4014c07d3f17
[ "JavaScript" ]
4
JavaScript
POO-2020/tarea-02-encapsulacion-y-herencia-el-restaurante-PaAdRaAg
7cdc5250541ddf1ff88e98b4a41344939a557fab
96231ed7033c1df527f99e8b2af607e9086217b2
refs/heads/master
<file_sep>'use strict'; const getPlugin = require('./get-plugin'); module.exports = getPlugin; <file_sep>'use strict'; function formatApiData(response) { const body = response.getBody(); return body.data || []; } module.exports = formatApiData;<file_sep>'use strict'; const getPlugin = require('./get-plugin'); function getPluginClientId(namespace) { return getPlugin(namespace) .then(function(plugin) { if (!plugin) { return; } return plugin.client && plugin.client.apiKey; }); } module.exports = getPluginClientId; <file_sep># zn-backend-get-plugin Module to get a plugin and plugin api client id by namespace. Useful when making certain API requests, such as file uploads, that require an OAuth 2 client id. Plugin and backend service must be marked as `offline` to have a client id. ## Installation ```bash npm i @zenginehq/backend-get-plugin --save ``` ## Usage ```js const $getPlugin = require('@zenginehq/backend-get-plugin'); exports.run = function(eventData) { $getPlugin(eventData.request.params.pluginNamespace) .then(function(plugin) { // ... }); }; ``` ```js const $getPluginClientId = require('@zenginehq/backend-get-plugin/get-client-id'); exports.run = function(eventData) { $getPluginClientId(eventData.request.params.pluginNamespace) .then(function(clientId) { // ... }); }; ```
43b120b90e91be7ae00d6639a62f7f47a9a2fdb6
[ "JavaScript", "Markdown" ]
4
JavaScript
ZengineHQ/zn-backend-get-plugin
aa7e73290bea81a74a1bdf81b1a15d65852d10d7
6174734356791322d21c7fe1e883049c8be503ef
refs/heads/master
<repo_name>tsiiiboho/hambasafe<file_sep>/Server/Hambasafe.Server/Services/TableStorage/ITableStorageService.cs using Microsoft.WindowsAzure.Storage.Table; namespace Hambasafe.Server.Services.TableStorage { public interface ITableStorageService { void Save(string connectionString, string tableName, params TableEntity[] toSave); T Get<T>(string connectionString, string tableName, string partitionKey, string rowKey) where T : TableEntity; T[] GetAll<T>(string connectionString, string tableName, string partitionKey) where T : TableEntity, new(); void Delete<T>(string connectionString, string tableName, string partitionKey, string rowKey) where T : TableEntity; } }<file_sep>/Server/Hambasafe.Server/Services/Configuration/ConfigurationService.cs using System.Configuration; namespace Hambasafe.Server.Services.Configuration { public class ConfigurationService : IConfigurationService { public string GetStorageConnectionString() { return ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString; } } }<file_sep>/Server/Hambasafe.Server/Models/v1/UserModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { public class UserModel { public UserModel(Entities.User user) { UserId = user.UserId; Token = user.Token; FirstNames = user.FirstNames; LastName = user.LastName; Gender = user.Gender; DateOfBirth = user.DateOfBirth; Status = user.Status; MobileNumber = user.MobileNumber; EmailAddress = user.EmailAddress; } public UserModel() { } public int UserId { get; set; } public string Token { get; set; } public string ProfilePicture { get; set; } public string FirstNames { get; set; } public string LastName { get; set; } public string Gender { get; set; } public DateTime DateOfBirth { get; set; } public string Status { get; set; } public string MobileNumber { get; set; } public string EmailAddress { get; set; } } }<file_sep>/Server/Hambasafe.Server/Services/Configuration/ConfigurationServiceModule.cs using Ninject.Modules; namespace Hambasafe.Server.Services.Configuration { public class ConfigurationServiceModule : NinjectModule { public override void Load() { Bind<IConfigurationService>().To<ConfigurationService>(); } } }<file_sep>/Server/Hambasafe.Server/Models/v1/RegisterModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { public class RegisterModel { public RegisterModel() { } public string FirstNames { get; set; } public string LastName { get; set; } public string Gender { get; set; } public DateTime DateOfBirth { get; set; } public string MobileNumber { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public ProfilePictureModel ProfilePicture { get; set; } } }<file_sep>/Server/Hambasafe.UnitTests/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Hambasafe.UnitTests { [TestFixture] public class SmokeTest { [Test] public void WhenActionThenExpect() { Assert.True(true); } } } <file_sep>/Server/Hambasafe.Server/Models/v1/EventLocation.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Hambasafe.DataAccess; namespace Hambasafe.Server.Models.v1 { public class EventLocation { public EventLocation() { } public EventLocation(DataAccess.Entities.EventLocation location) { Id = location.EventLocationId; SuburbId = location.SuburbId; Address = location.Address; Latitude = location.Latitude; Longitude = location.Longitude; } public int? Id { get; set; } public int SuburbId { get; set; } public string Address { get; set; } public Nullable<double> Latitude { get; set; } public Nullable<double> Longitude { get; set; } } }<file_sep>/Server/Hambasafe.Server/Enums/EventIntensity.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Hambasafe.Server.Enums { public enum EventIntensity { NotApplicable = 0, Beginner, Medium, Advanced } }<file_sep>/Server/Hambasafe.Server/Models/v1/CountryModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Device.Location; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class CountryModel { public CountryModel(Entities.Country country) { CountryId = country.CountryId; Name = country.Name; Code = country.Code; } public CountryModel() { } public int CountryId { get; set; } public string Name { get; set; } public string Code { get; set; } } }<file_sep>/Server/Hambasafe.Server/Services/TableStorage/TableStorageServiceModule.cs using Ninject.Modules; namespace Hambasafe.Server.Services.TableStorage { public class TableStorageServiceModule : NinjectModule { public override void Load() { Bind<ITableStorageService>().To<TableStorageService>(); } } }<file_sep>/Server/Hambasafe.Server/Services/TableStorage/TableStorageService.cs using System; using System.Linq; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace Hambasafe.Server.Services.TableStorage { public class TableStorageService : ITableStorageService { public void Save(string connectionString, string tableName,params TableEntity[] toSave) { CloudTable table = GetTable(connectionString, tableName); if (toSave.Length > 1) { TableBatchOperation batchOperation = new TableBatchOperation(); foreach (TableEntity entity in toSave) { batchOperation.InsertOrReplace(entity); } Execute(table, () => table.ExecuteBatch(batchOperation)); } else if (toSave.Length == 1) { TableOperation insertOperation= TableOperation.InsertOrReplace(toSave.First()); Execute(table, () => table.Execute(insertOperation)); } } private void Execute(CloudTable table, Action toExecute ) { try { toExecute(); } catch (StorageException error) { if (error.RequestInformation.HttpStatusCode == 404) { table.CreateIfNotExistsAsync(); toExecute(); } else { throw; } } } private static CloudTable GetTable(string connectionString, string tableName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(tableName); return table; } public T Get<T>(string connectionString, string tableName, string partitionKey, string rowKey) where T : TableEntity { CloudTable table = GetTable(connectionString, tableName); TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey); table.CreateIfNotExists(); TableResult retrievedResult = table.Execute(retrieveOperation); return (T) retrievedResult.Result; } public T[] GetAll<T>(string connectionString, string tableName, string partitionKey) where T : TableEntity, new() { CloudTable table = GetTable(connectionString, tableName); TableQuery<T> query = new TableQuery<T>(); if (!string.IsNullOrWhiteSpace(partitionKey)) { query.Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey)); } table.CreateIfNotExists(); T[] result = table.ExecuteQuery(query).ToArray(); return result; } public void Delete<T>(string connectionString, string tableName, string partitionKey, string rowKey) where T : TableEntity { CloudTable table = GetTable(connectionString, tableName); TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey); table.CreateIfNotExists(); TableResult retrievedResult = table.Execute(retrieveOperation); if (retrievedResult.Result != null) { TableOperation deleteOperation = TableOperation.Delete((ITableEntity) retrievedResult.Result); table.Execute(deleteOperation); } } } }<file_sep>/Server/Hambasafe.Server/Attributes/GeneralExceptionFilterAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Http.Filters; namespace Hambasafe.Server.Attributes { public class GeneralExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent($"{context.Exception.Message} ({context.Exception.GetType()})"), ReasonPhrase = context.Exception.Message }; throw new HttpResponseException(responseMessage); } } }<file_sep>/Server/Hambasafe.Server/Controllers/v1/UsersController.cs using System; using System.ComponentModel; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Hambasafe.Server.Models.v1; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Controllers.v1 { [RoutePrefix("v1")] public class UsersController : ApiControllerBase { public UsersController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } [AllowAnonymous] [Route("create-user"), HttpPost] public async Task<HttpResponseMessage> CreateUser(UserModel newUser) { try { //TODO add this return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("users"), HttpGet] public async Task<HttpResponseMessage> GetAllUsers() { try { Entities.HambasafeDataContext context = new Entities.HambasafeDataContext(); var users = context.Users.ToList().Select(e => new UserModel(e)); return Request.CreateResponse(HttpStatusCode.OK, users); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("users"), HttpGet] public async Task<HttpResponseMessage> GetUsers(string username) { try { Entities.HambasafeDataContext context = new Entities.HambasafeDataContext(); var users = context.Users.ToList().Where(a=> a.FirstNames.ToUpper().Contains(username.ToUpper()) || a.LastName.ToUpper().Contains(username.ToUpper())).Select(e => new UserModel(e)); return Request.CreateResponse(HttpStatusCode.OK, users); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("user"), HttpGet] public async Task<HttpResponseMessage> GetUser(int id) { try { Entities.HambasafeDataContext context = new Entities.HambasafeDataContext(); UserModel user = new UserModel(context.Users.ToList().Where(e => e.UserId == id) as Entities.User); return Request.CreateResponse(HttpStatusCode.OK, user); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("profile"), HttpGet] public async Task<HttpResponseMessage> GetProfile(int id) { try { Entities.HambasafeDataContext context = new Entities.HambasafeDataContext(); UserModel user = new UserModel(context.Users.ToList().Where(e => e.UserId == id) as Entities.User); return Request.CreateResponse(HttpStatusCode.OK, user); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/Server/Hambasafe.Server/Controllers/v1/EventTypeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Web.Http; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using Hambasafe.DataAccess.Entities; using Hambasafe.Server.Models.v1; namespace Hambasafe.Server.Controllers.v1 { [RoutePrefix("v1")] public class EventTypeController : ApiControllerBase { public EventTypeController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("event-types"), HttpGet] public async Task<HttpResponseMessage> GetEventTypes() { HambasafeDataContext context = new HambasafeDataContext(); try { var eventTypes = context.EventTypes.ToList().Select(et => new EventTypeModel(et)); return Request.CreateResponse(HttpStatusCode.OK, eventTypes); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/Server/Hambasafe.Server/Controllers/v1/LocationController.cs using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using Hambasafe.DataAccess.Entities; using models = Hambasafe.Server.Models.v1; namespace Hambasafe.Server.Controllers.v1 { [RoutePrefix("v1")] public class LocationController : ApiControllerBase { public LocationController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("locations"), HttpGet] public async Task<HttpResponseMessage> GetAllLocations() { try { var dataContext = new HambasafeDataContext(); return Request.CreateResponse(HttpStatusCode.OK, dataContext.EventLocations.ToList().Select(l=>new models.EventLocation(l))); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("locations-by-suburb"), HttpGet] public async Task<HttpResponseMessage> GetLocationsBySuburb(int suburbId) { try { var dataContext = new HambasafeDataContext(); return Request.CreateResponse(HttpStatusCode.OK, dataContext.EventLocations.ToList() .Where(l=>l.SuburbId==suburbId)); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("location"), HttpGet] public async Task<HttpResponseMessage> GetLocation(int id) { try { var dataContext = new HambasafeDataContext(); return Request.CreateResponse(HttpStatusCode.OK, dataContext.EventLocations.ToList() .Where(l => l.EventLocationId == id)); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/README.md Hambasafe Application ===================== The Hambasafe Application repository consists of two main solutions located in the Client and Server folders. Server ------ Server code for the Hambasafe application. Application architecture consists of a 3-tier model consisting of: - Hamba.Server Azure hosted WebAPI at [HambasafeDev.azurewebsites.net](http://hambasafedev.azurewebsites.net/api/): `http://hambasafedev.azurewebsites.net/api/` - Hamba.Logic Business Logic layer responsible for translating DataAccess models to models in the WebApi Layer - Hamba.DataAccess Data Access layer responsible for performing CRUD operations on the SQL Azure hosted database. Entity Framework (EF6) is used as the translating ORM. <file_sep>/Server/Hambasafe.Server/2 - REST API Documentation.md #REST API Documentation ##Major Entities ###Users - `/v1/users/` - `/v1/users?id=1` - `/v1/users?username="peter"` ###Events - `/v1/events/` - `/v1/events?id=1` - `/v1/events?created-by-user="peter"` - `/v1/events?attended-by-user="peter"` - `/v1/events?suburb="rondebosch"` ##Attributes/Types ###EventType - `/v1/eventtypes` ###Address Attributes - `/v1/provinces` - `/v1/cities` - `/v1/cities?province="Western Cape"` - `/v1/suburbs` - `/v1/suburbs?city="Cape Town"` <file_sep>/Server/Hambasafe.Server/Models/v1/ProfilePictureModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Device.Location; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class ProfilePictureModel { public ProfilePictureModel(Entities.Country country) { CountryId = country.CountryId; Name = country.Name; Code = country.Code; } public ProfilePictureModel() { } public int CountryId { get; set; } public string Name { get; set; } public string Code { get; set; } } }<file_sep>/Server/Hambasafe.Server/Controllers/VersionController.cs using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; //using Hambasafe.Server.Services.Configuration; //using Hambasafe.Server.Services.TableStorage; namespace Hambasafe.Server.Controllers { public class VersionController : ApiControllerBase { public VersionController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } /// <summary> /// Use this api point to determine the latest version url for endpoints /// </summary> /// <returns></returns> [AllowAnonymous] [Route("versionurl"), HttpGet] public async Task<HttpResponseMessage> GetVersionUrl() { try { var version = $"v{GetType().Assembly.GetName().Version.Major}"; return Request.CreateResponse(HttpStatusCode.OK, version); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/Server/Hambasafe.Server/Controllers/v1/EventsController.cs using System; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Threading.Tasks; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using Hambasafe.Server.Models.v1; using Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Controllers.v1 { [RoutePrefix("v1")] public class EventsController : ApiControllerBase { public EventsController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } [AllowAnonymous] [Route("create-event"), HttpPost] public async Task<HttpResponseMessage> CreateEvent(EventModel eventModel) { try { var dataContext = new HambasafeDataContext(); var eventEntity = new Event() { Name = eventModel.Name, }; return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("event"), HttpGet] public async Task<HttpResponseMessage> GetEvent(int id) { try { var dataContext = new HambasafeDataContext(); var evnt = dataContext.Events.ToList().Where(e => e.EventId == id) .Select(e => new EventModel(e)) .First(); return Request.CreateResponse(HttpStatusCode.OK, evnt); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("events"), HttpGet] public async Task<HttpResponseMessage> GetEvents() { try { var dataContext = new HambasafeDataContext(); var events = dataContext.Events.ToList().Select(e => new EventModel(e)); return Request.CreateResponse(HttpStatusCode.OK, events); } catch (Exception error) { return HandleError(error); } } /// <summary> /// Implemented /// </summary> [AllowAnonymous] [Route("events-by-user"), HttpGet] public async Task<HttpResponseMessage> GetEventsByUser(int userid) { try { var dataContext = new HambasafeDataContext(); var events = dataContext.Events.ToList().Where(e => e.OwnerUserId == userid).Select(e => new EventModel(e)); return Request.CreateResponse(HttpStatusCode.OK, events); } catch (Exception error) { return HandleError(error); } } [AllowAnonymous] [Route("events-by-attendee"), HttpGet] public async Task<HttpResponseMessage> GetEventsByAttendee(int attendeeid) { try { //TODO implement return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } [AllowAnonymous] [Route("events-by-attendee"), HttpGet] public async Task<HttpResponseMessage> GetEventsByAttendeeName(string attendeename) { try { //TODO implement return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } [AllowAnonymous] [Route("events-by-suburb"), HttpGet] public async Task<HttpResponseMessage> GetEventsBySuburb(string suburbname) { try { //TODO implement return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } [AllowAnonymous] [Route("events-by-suburb"), HttpGet] public async Task<HttpResponseMessage> GetEventsBySuburb(int suburbid) { try { //TODO implement return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } [AllowAnonymous] [Route("events-by-coordinates"), HttpGet] public async Task<HttpResponseMessage> GetEventsByCoordinates(double latitude, double longitude, int radius) { try { HambasafeDataContext context = new HambasafeDataContext(); //TODO implement //var matchingLocations = context.Location return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/Server/Hambasafe.Server/1 - API - Data layer interactions.md #API - Data layer interactions Results of discussion about responsibility split between API and data layer. ## API Layer - will provide "view models" to the UI via a RESTful interface. - view models will present/accept the data as needed by the UI; in other words the API matches the business case, and will not be 1:1 with the data model. - the business logic will reside in this layer in order to keep the business logic completely separate from dependence on the Entity Framework. ##Data Layer - will provide a data model for the API layer to interact with which requires no references in the API later code or project to the Entity Framework. - will provide CRUD methods for the data model entities and a mechanism to wrap multiple entity updates/creates in an atomic transaction. <file_sep>/Server/Hambasafe.Server/Attributes/AuthenticateUserAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Http.Controllers; namespace Hambasafe.Server.Attributes { public class AuthenticateUserAttribute : AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext actionContext) { if (HttpContext.Current.User.Identity.IsAuthenticated) { //retrieve controller action's authorization attributes var authorizeAttributes = actionContext.ActionDescriptor.GetCustomAttributes<AuthorizeVerifiedUsersAttribute>(); //check controller and action BypassValidation value if (BypassValidation || actionAttributes.Count > 0 && actionAttributes.Any(x => x.BypassValidation)) { return true; } else { //return false if user is unverified } return base.IsAuthorized(actionContext); } } }<file_sep>/Server/Hambasafe.Server/Controllers/v1/AuthenticationController.cs using System; using System.ComponentModel; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Hambasafe.Server.Models.v1; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using Hambasafe.DataAccess.Entities; using System.Text; using System.Security.Cryptography; namespace Hambasafe.Server.Controllers.v1 { [RoutePrefix("v1")] public class AuthenticationController : ApiControllerBase { public AuthenticationController(IConfigurationService configuration, ITableStorageService tableStorage) : base(configuration, tableStorage) { } [AllowAnonymous] [Route("register"), HttpGet] public async Task<HttpResponseMessage> Register(RegisterModel registerModel) { try { var dataContext = new HambasafeDataContext(); // Create new user var User = new User() { FirstNames = registerModel.FirstNames, LastName = registerModel.LastName, Gender = registerModel.Gender, DateOfBirth = registerModel.DateOfBirth, Status = "created", MobileNumber = registerModel.MobileNumber, EmailAddress = registerModel.EmailAddress, DateCreated = new DateTime(), DateLastLogin = new DateTime() }; // Create the token var key = Encoding.UTF8.GetBytes(registerModel.Password.ToUpper()); string hashString; //using (var hmac = new HMACSHA256(key)) //{ // var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes()); // hashString = Convert.ToBase64String(hash); //} //return hashString; return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception error) { return HandleError(error); } } } } <file_sep>/Server/Hambasafe.Server/Models/v1/SuburbModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Device.Location; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class SuburbModel { public SuburbModel(Entities.Suburb suburb) { SuburbId = suburb.SuburbId; Name = suburb.Name; Latitude = suburb.Latitude; Longitude = suburb.Longitude; PostalCode = suburb.PostalCode; Province = new ProvinceModel(suburb.Province); } public SuburbModel() { } public int SuburbId { get; set; } public string Name { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public string PostalCode { get; set; } public ProvinceModel Province { get; set; } } }<file_sep>/Server/Hambasafe.Server/Models/v1/EventTypeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class EventTypeModel { public EventTypeModel(Entities.EventType dbEventType) { EventTypeId = dbEventType.EventTypeId; Name = dbEventType.Name; Description = dbEventType.Description; } public EventTypeModel() { } public int EventTypeId { get; set; } public string Name { get; set; } public string Description { get; set; } } }<file_sep>/Server/Hambasafe.Server/Controllers/ApiControllerBase.cs using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; using Hambasafe.Server.Attributes; using Hambasafe.Server.Models; using Hambasafe.Server.Services.Configuration; using Hambasafe.Server.Services.TableStorage; using log4net; namespace Hambasafe.Server.Controllers { [GeneralExceptionFilter] public class ApiControllerBase : ApiController { private readonly IConfigurationService _configuration; private readonly ITableStorageService _tableStorage; public ApiControllerBase(IConfigurationService configuration, ITableStorageService tableStorage) { _configuration = configuration; _tableStorage = tableStorage; } protected HttpResponseMessage HandleError(Exception error) { // Until we can figure out how to push to the azure storage, errors are not going to be logged // WriteErrorReport(error); Log.Error(error.Message, error); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error.Message); } private string ConnectionString() { string connectionString = _configuration.GetStorageConnectionString(); return connectionString; } private void WriteErrorReport(Exception error) { ErrorReport errorReport = new ErrorReport(error); string connectionString = ConnectionString(); if (HttpContext.Current != null) { HttpRequest currentRequest = HttpContext.Current.Request; errorReport.UserHostAddress = currentRequest.UserHostAddress; errorReport.Url = currentRequest.Url.ToString(); errorReport.UserAgentString = currentRequest.UserAgent; } errorReport.PartitionKey = error.GetType().Name; errorReport.RowKey = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); _tableStorage.Save(connectionString, "ApiError", errorReport); } private ILog Log { get { return LogManager.GetLogger(GetType()); } } } }<file_sep>/Server/Hambasafe.Server/Models/v1/ProvinceModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Device.Location; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class ProvinceModel { public ProvinceModel(Entities.Province province) { ProvinceId = province.ProvinceId; Name = province.Name; Country = new CountryModel(province.Country); } public ProvinceModel() { } public int ProvinceId { get; set; } public string Name { get; set; } public CountryModel Country { get; set; } } }<file_sep>/Server/Hambasafe.Server/Models/v1/EventModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using Entities = Hambasafe.DataAccess.Entities; namespace Hambasafe.Server.Models.v1 { [RoutePrefix("v1")] public class EventModel { public EventModel(Entities.Event dbEvent) { EventId = dbEvent.EventId; Name = dbEvent.Name; Description = dbEvent.Description; EventType = new EventTypeModel(dbEvent.EventType); EventDateTimeStart = dbEvent.DateTimeStart; EventDateTimeEnd = dbEvent.DateTimeEnd; Attributes = dbEvent.Attributes; WaitMins = dbEvent.MaxWaitingMinutes; PublicEvent = dbEvent.IsPublic; } public EventModel() { } public int EventId { get; set; } public string Name { get; set; } public string Description { get; set; } public EventTypeModel EventType { get; set; } public DateTime EventDateTimeStart { get; set; } public DateTime? EventDateTimeEnd { get; set; } public object Attributes { get; set; } public int WaitMins { get; set; } public bool? PublicEvent { get; set; } } }
b6fa70144b67fd31f749e02ed86aa2d78ab48ac6
[ "Markdown", "C#" ]
28
C#
tsiiiboho/hambasafe
ff2744bdcbd879f6f3182e972b47d2203cdce638
e7baa12a94731aa5e1868ad72bc04a333c63b5a7
refs/heads/master
<file_sep>#!/bin/sh case $1 in config) cat <<'EOM' graph_title Mastodon local statuses graph_vlabel statuses graph_category mastodon graph_args -l 0 local_statuses.label local statuses local_statuses.min 0 EOM exit 0;; esac printf "local_statuses.value " echo "SELECT COUNT(*) FROM statuses AS s, accounts AS a WHERE a.id=s.account_id AND a.domain IS NULL;" | psql mastodon -tq | head -n 1 <file_sep>#!/bin/sh case $1 in config) cat <<'EOM' graph_title Mastodon accounts graph_vlabel accounts graph_category mastodon graph_args -l 0 accounts.label remote accounts accounts.min 0 EOM exit 0;; esac printf "accounts.value " echo "SELECT COUNT(*) FROM accounts;" | psql mastodon -tq | head -n 1 <file_sep># mastodon-munin A few munin plugins for Mastodon: * Local and total accounts * Local and total toots Installation: (dont do that in /root) ```bash git clone https://github.com/0xa/mastodon-munin.git cd mastodon-munin/ ln -s $PWD/plugins/mastodon_{accounts,local_accounts,statuses,local_statuses} /etc/munin/plugins/ ln -s $PWD/plugins-conf.d/mastodon /etc/munin/plugin-conf.d/ service munin-node restart ``` There's also a plugin that count ⚧ in bios, but I'm not sure everyone wants it or I want everyone to use it, so just add it if you want, or with another search. There are may fun things to do. <file_sep>#!/bin/sh case $1 in config) cat <<'EOM' graph_title Mastodon total statuses graph_vlabel statuses graph_category mastodon graph_args -l 0 statuses.label statuses statuses.min 0 EOM exit 0;; esac printf "statuses.value " echo "SELECT COUNT(*) FROM statuses;" | psql mastodon -tq | head -n 1 <file_sep>#!/bin/sh case $1 in config) cat <<'EOM' graph_title Mastodon local accounts graph_vlabel accounts graph_category mastodon graph_args -l 0 accounts.label local accounts accounts.min 0 EOM exit 0;; esac printf "accounts.value " echo "SELECT COUNT(*) FROM accounts WHERE domain IS NULL;" | psql mastodon -tq | head -n 1
8c56d2f5b2fbfa84f7896aa3e11fdf5fea7b999f
[ "Markdown", "Shell" ]
5
Shell
0xa/mastodon-munin
bd427a333dd3819b1093bcfc0fdf3372b90403aa
458916fc7ad229523e452d096f59e5dc2b926bef
refs/heads/master
<repo_name>TyronSamaroo/Tyron-Samaroo-DP<file_sep>/GlassFalling.java /** * Glass Falling * Author: <NAME> */ public class GlassFalling { // Do not change the parameters! public int glassFallingRecur(int floors, int sheets) { // Fill in here and change the return // Base Case. If no floors no trials can be done. If 1 floor only 1 trial can be done. if(floors == 0 || floors == 1) { return floors; } //Base Case Part 2: If only 1 sheet remaining must do trials for max number of floors. if(sheets == 1) { return floors; } //Need this to store number of trials for each iteration int numTrials = Integer.MAX_VALUE; for (int i = 1; i <=floors; i++) { // Case 1 n 2 int tempTrials = Math.max(glassFallingRecur(i-1,sheets-1),glassFallingRecur(floors-i,sheets)); numTrials = min(tempTrials,numTrials); } return numTrials + 1; } static int max(int a, int b) { return(a>b)? a:b; } static int min(int a, int b) { return(a<b)? a:b; } // Optional: // Pick whatever parameters you want to, just make sure to return an int. // public int glassFallingMemoized(int floors,int sheets) { // // Fill in here and change the return // if(floors == 0 || floors == 1) // { // return floors; // } // if(sheets == 1) // { // return floors; // } // // int [][] glassMemTable = new int[sheets+1][floors+1]; // //Need to initialize all to a value I wont use. // for (int i = 0; i <=floors ; i++) { // for (int j = 0; j <= sheets; j++) // glassMemTable[i][j] = -1; // // // } // // return 0; // } // Do not change the parameters! public int glassFallingBottomUp(int floors, int sheets) { // Fill in here and change the return] // Setting up table to store needed values int arrayTrials[][] = new int[sheets+1][floors+1]; // Base Case If we have no floor no trials needed. If we have only 1 floor then only 1 trial required for (int i = 1; i <=sheets ; i++) { arrayTrials[i][0] = 0; arrayTrials[i][1] = 1; } // Base Case 2: If there is only 1 sheet then we will need to do same amount of trials as there are floors. for (int i = 1; i <=floors ; i++) { arrayTrials[1][i] = i; } // Checking each sheet with each floor for (int i = 2; i <=sheets; i++) { for (int j = 2; j <=floors ; j++) { int tempTrials; arrayTrials[i][j]= Integer.MAX_VALUE; for (int k = 1; k<= j; k++) { tempTrials = 1 + Math.max(arrayTrials[i-1][k-1],arrayTrials[i][j-k]); arrayTrials[i][j] = Math.min(tempTrials,arrayTrials[i][j]); } } } return arrayTrials[sheets][floors]; } public static void main(String args[]){ GlassFalling gf = new GlassFalling(); // Recursion with 100,3 takes long // Do not touch the below lines of code, and make sure // in your final turned-in copy, these are the only things printed int minTrials1Recur = gf.glassFallingRecur(27,2); int minTrials1Bottom = gf.glassFallingBottomUp(27,2); // int minTrials2Recur = gf.glassFallingRecur(100,3); int minTrials2Bottom = gf.glassFallingBottomUp(100, 3); System.out.println(minTrials1Recur + " " + minTrials1Bottom);// // System.out.println(minTrials2Bottom + " " + minTrials2Bottom); System.out.println("N/A" + " " + minTrials2Bottom); } }
7c49d41ab7aebf654231b366f44460152054d20a
[ "Java" ]
1
Java
TyronSamaroo/Tyron-Samaroo-DP
66a6d93ba30be75a5d5d89714332e45217c75e3d
368fa503a3195c19a16339962fdeff59f7cbd846
refs/heads/master
<file_sep><!doctype html> <html> <head> <title>Articles</title> <?php include($_SERVER['DOCUMENT_ROOT'].'/res/php/head.php'); ?> </head> <body> <?php include($_SERVER['DOCUMENT_ROOT'].'/res/php/sidebar.php'); ?> <div id="content-wrapper"> <div id="top-bar"> <img id="menu" src="/res/images/menu.svg" /> </div> <main id="content"> <h1>Welcome</h1> <p>This is my personal website that I created to share my content with other people.</p> <h2>About Me</h2> <p>My name is <NAME>, and I love everything to do with computers.</p> <h3>(As of July 2016)</h3> <p>I am 20 years old and have lived in Maine all of my life between two locations, the city of Auburn, and for the past decade sunny Wells, Maine.</p> <p>I am a developer who primarily deals with Java, as it is my first and favorite language. I have over 5 years experience programming with Java, and have only recently decided to look into programming with other languages.</p> <p>I am currently working as an intern at IDEXX Laboratories in Westbrook, Maine as a developer. Although I cannot give out any specific details, I <i>think</i> it's okay for me to say that I am working on automating software testing.</p> <h3>Some Things I Enjoy</h3> <ul> <li>Skiing</li> <li>Snowboarding</li> <li>Skateboarding</li> <li>Tennis</li> <li><i><b><u>Computer</u></b></i> games</li> <li>Programming (<i>duh</i>)</li> <li>Organization</li> </ul> <h3>Some Things I Dislike</h3> <ul> <li>Waste</li> <li>Sloppiness</li> <li>Inconsistencies</li> <li>Ambiguities</li> <li>Rhetorical paradoxes</li> <li>Latency</li> <li>Flash</li> <li>Internet Explorer</li> <li>Dairy</li> </ul> </main> </div> </body> <?php include($_SERVER['DOCUMENT_ROOT'].'/res/php/scripts.php'); ?> </html><file_sep>GibsDev.com =========== This repository contains the source files for (my website) [gibsdev.com](http://gibsdev.com) Feel free to use any code that you see, but don't be a copy-paste coder. No one likes a copy paste coder.
e6287cbdc75f05eb2d0fb90cc8c2dea724703691
[ "Markdown", "PHP" ]
2
PHP
GibsDev/website
6b94163de4fb3f593b66083ed24681c1de503e60
9b3801e35a75d190f4a4506b2b5b6dd4336e5644
refs/heads/master
<file_sep>$(window).load(function(){ "use strict"; /* ========================================================== */ /* Popup-Gallery */ /* ========================================================== */ $('.popup-gallery').find('a.popup1').magnificPopup({ type: 'image', gallery: { enabled:true } }); $('.popup-gallery').find('a.popup2').magnificPopup({ type: 'image', gallery: { enabled:true } }); $('.popup-gallery').find('a.popup3').magnificPopup({ type: 'image', gallery: { enabled:true } }); $('.popup-gallery').find('a.popup4').magnificPopup({ type: 'iframe', gallery: { enabled:false } }); /* ========================================================== */ /* Navigation Background Color */ /* ========================================================== */ $(window).scroll(function() { if($(this).scrollTop() > 100) { $('.navbar-fixed-top').addClass('opaque'); } else { $('.navbar-fixed-top').removeClass('opaque'); } }); /* ========================================================== */ /* SmoothScroll */ /* ========================================================== */ $(".nav li a, a.scrool").click(function(e){ var full_url = this.href; var parts = full_url.split("#"); var trgt = parts[1]; var target_offset = $("#"+trgt).offset(); var target_top = target_offset.top; $('html,body').animate({scrollTop:target_top -69}, 1000); return false; }); /* ========================================================== */ /* Contact */ /* ========================================================== */ $('#contact-form').each( function(){ var form = $(this); //form.validate(); form.submit(function(e) { if (!e.isDefaultPrevented()) { jQuery.post(this.action,{ 'names':$('input[name="contact_names"]').val(), 'email':$('input[name="contact_email"]').val(), 'phone':$('input[name="contact_phone"]').val(), 'message':$('textarea[name="contact_message"]').val(), },function(data){ form.fadeOut('fast', function() { $(this).siblings('p').show(); }); }); e.preventDefault(); } }); }) /* ========================================================== */ /* Register */ /* ========================================================== */ $('#register-form').each( function(){ var form = $(this); //form.validate(); form.submit(function(e) { if (!e.isDefaultPrevented()) { jQuery.post(this.action,{ 'names':$('input[name="register_names"]').val(), 'phone':$('input[name="register_phone"]').val(), 'date':$('input[name="register_date"]').val(), 'email':$('input[name="register_email"]').val(), 'ticket':$('select[name="register_ticket"]').val(), 'time':$('select[name="register_time"]').val(), },function(data){ form.fadeOut('fast', function() { $(this).siblings('p.register_success_box').show(); }); }); e.preventDefault(); } }); }) /* ========================================================== */ /* Revolution Slider - Home Page */ /* ========================================================== */ var tpj = jQuery; var revapi280; tpj(document).ready(function() { if (tpj("#rev_slider_280_1").revolution == undefined) { revslider_showDoubleJqueryError("#rev_slider_280_1"); } else { revapi280 = tpj("#rev_slider_280_1").show().revolution({ sliderType: "hero", jsFileLocation: "../../revolution/js/", sliderLayout: "fullscreen", dottedOverlay: "none", delay: 9000, navigation: {}, responsiveLevels: [1240, 1024, 778, 480], visibilityLevels: [1240, 1024, 778, 480], gridwidth: [1240, 1024, 778, 480], gridheight: [868, 768, 960, 720], lazyType: "none", shadow: 0, spinner: "spinner2", autoHeight: "off", fullScreenAutoWidth: "off", fullScreenAlignForce: "off", fullScreenOffsetContainer: "", fullScreenOffset: "60", disableProgressBar: "on", hideThumbsOnMobile: "off", hideSliderAtLimit: 0, hideCaptionAtLimit: 0, hideAllCaptionAtLilmit: 0, debugMode: false, fallbacks: { simplifyAll: "off", disableFocusListener: false, } }); } }); /*ready*/ /* ========================================================== */ /* Revolution Slider - About Page */ /* ========================================================== */ var tpj=jQuery; var revapi30; tpj(document).ready(function() { if(tpj("#rev_slider_30_1").revolution == undefined){ revslider_showDoubleJqueryError("#rev_slider_30_1"); }else{ revapi30 = tpj("#rev_slider_30_1").show().revolution({ sliderType:"carousel", jsFileLocation:"../../revolution/js/", sliderLayout:"fullwidth", dottedOverlay:"none", delay:9000, navigation: { keyboardNavigation:"off", keyboard_direction: "horizontal", mouseScrollNavigation:"off", onHoverStop:"off", touch:{ touchenabled:"on", swipe_threshold: 75, swipe_min_touches: 1, swipe_direction: "horizontal", drag_block_vertical: false } , arrows: { style:"gyges", enable:true, hide_onmobile:false, hide_onleave:false, tmp:'', left: { h_align:"left", v_align:"center", h_offset:20, v_offset:0 }, right: { h_align:"right", v_align:"center", h_offset:20, v_offset:0 } } , }, carousel: { horizontal_align: "center", vertical_align: "center", fadeout: "on", vary_fade: "on", maxVisibleItems: 3, infinity: "on", space: 0, stretch: "off" }, gridwidth:720, gridheight:405, lazyType:"none", shadow:0, spinner:"off", stopLoop:"on", stopAfterLoops:0, stopAtSlide:1, shuffle:"off", autoHeight:"off", disableProgressBar:"on", hideThumbsOnMobile:"off", hideSliderAtLimit:0, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, debugMode:false, fallbacks: { simplifyAll:"off", nextSlideOnWindowFocus:"off", disableFocusListener:false, } }); } }); /*ready*/ /* ========================================================== */ /* Revolution Slider - Menu Page */ /* ========================================================== */ var tpj=jQuery; var revapi108; tpj(document).ready(function() { if(tpj("#rev_slider_108_1").revolution == undefined){ revslider_showDoubleJqueryError("#rev_slider_108_1"); }else{ revapi108 = tpj("#rev_slider_108_1").show().revolution({ sliderType:"carousel", jsFileLocation:"../../revolution/js/", sliderLayout:"fullwidth", dottedOverlay:"none", delay:9000, navigation: { keyboardNavigation:"off", keyboard_direction: "horizontal", mouseScrollNavigation:"off", onHoverStop:"off", arrows: { style:"metis", enable:true, hide_onmobile:true, hide_under:768, hide_onleave:false, tmp:'', left: { h_align:"left", v_align:"center", h_offset:0, v_offset:0 }, right: { h_align:"right", v_align:"center", h_offset:0, v_offset:0 } } , thumbnails: { style:"erinyen", enable:true, width:150, height:100, min_width:150, wrapper_padding:20, wrapper_color:"#000000", wrapper_opacity:"0.05", tmp:'<span class="tp-thumb-over"></span><span class="tp-thumb-image"></span><span class="tp-thumb-title">{{title}}</span><span class="tp-thumb-more"></span>', visibleAmount:9, hide_onmobile:false, hide_onleave:false, direction:"horizontal", span:true, position:"outer-bottom", space:10, h_align:"center", v_align:"bottom", h_offset:0, v_offset:0 } }, carousel: { maxRotation: 65, vary_rotation: "on", minScale: 55, vary_scale: "off", horizontal_align: "center", vertical_align: "center", fadeout: "on", vary_fade: "on", maxVisibleItems: 5, infinity: "on", space: -150, stretch: "off" }, gridwidth:600, gridheight:600, lazyType:"none", shadow:0, spinner:"off", stopLoop:"on", stopAfterLoops:0, stopAtSlide:1, shuffle:"off", autoHeight:"off", disableProgressBar:"on", hideThumbsOnMobile:"off", hideSliderAtLimit:0, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, debugMode:false, fallbacks: { simplifyAll:"off", nextSlideOnWindowFocus:"off", disableFocusListener:false, } }); } }); /*ready*/ /* ========================================================== */ /* Revolution Slider - Reservation Page (Video) */ /* ========================================================== */ var tpj=jQuery; var revapi110; tpj(document).ready(function() { if(tpj("#rev_slider_110_1").revolution == undefined){ revslider_showDoubleJqueryError("#rev_slider_110_1"); }else{ revapi110 = tpj("#rev_slider_110_1").show().revolution({ sliderType:"hero", jsFileLocation:"../../revolution/js/", sliderLayout:"fullscreen", dottedOverlay:"none", delay:20000, navigation: { }, responsiveLevels:[1240,1024,778,778], gridwidth:[1240,1024,778,480], gridheight:[600,500,400,300], lazyType:"none", parallax: { type:"mouse", origo:"slidercenter", speed:2000, levels:[2,3,4,5,6,7,12,16,10,50], }, shadow:0, spinner:"off", autoHeight:"off", fullScreenAlignForce:"off", fullScreenOffsetContainer: "", fullScreenOffset: "60px", disableProgressBar:"on", hideThumbsOnMobile:"off", hideSliderAtLimit:0, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, debugMode:false, fallbacks: { simplifyAll:"off", disableFocusListener:false, } }); } }); /*ready*/ /* ========================================================== */ /* Page Loader */ /* ========================================================== */ $('#loader').fadeOut(100); });
f3c1bb8835906e13520ed52a0554e3a797143f06
[ "JavaScript" ]
1
JavaScript
kor1k/job_new_coffee_guirrella
3f1d75d4e92b4c1715fd897687f062a887f12f96
c7ac9cdbd2d09edec3438db2574349fd3963633f
refs/heads/master
<file_sep>import React from "react"; import TableRow from "@material-ui/core/TableRow"; import TableCell from "@material-ui/core/TableCell"; import CustomerDelete from "./CustomerDelete"; const Customer = ({ id, img, name, birthday, gender, job, stateRefresh }) => { return ( <> <TableRow key={id}> <TableCell align="center">{id}</TableCell> <TableCell align="center"> <img src={img} alt="profile" width="64" height="64"></img> </TableCell> <TableCell align="center">{name}</TableCell> <TableCell align="center">{birthday}</TableCell> <TableCell align="center">{gender}</TableCell> <TableCell align="center">{job}</TableCell> <TableCell align="center"> <CustomerDelete id={id} stateRefresh={stateRefresh}></CustomerDelete> </TableCell> </TableRow> </> ); }; export default Customer; <file_sep>const fs = require("fs"); // 파일 접근 const express = require("express"); const bodyParser = require("body-parser"); const app = express(); const port = process.env.PORT || 5000; //json으로 데이터 주고 받음 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // app.get("/api/hello", (req, res) => { // res.send({ message: "Hello Express!" }); // }); const data = fs.readFileSync("./database.json"); const conf = JSON.parse(data); const mysql = require("mysql"); const connection = mysql.createConnection({ host: conf.host, user: conf.user, password: <PASSWORD>, port: conf.port, database: conf.database, }); connection.connect(); const multer = require("multer"); const upload = multer({ dest: "./upload" }); //클라이언트가 서버에 접속시 json 으로 반환해줌 app.get("/api/customers", (req, res) => { connection.query( "select * from customer where isDeleted = 0", (err, rows, fields) => { res.send(rows); } ); }); // 사용자가 image폴더에 접근하면 서버의 upload로 매핑됨 app.use("/image", express.static("./upload")); app.post("/api/customers", upload.single("image"), (req, res) => { // id, image, name, birthday, gender, job, createdDate, isDeleted const sql = "insert into customer values(null, ?, ?, ?, ?, ?, now(), 0)"; const image = "/image/" + req.file.filename; const name = req.body.name; const birthday = req.body.birthday; const gender = req.body.gender; const job = req.body.job; const params = [image, name, birthday, gender, job]; connection.query(sql, params, (err, rows, fields) => { res.send(rows); }); }); app.delete("/api/customers/:id", (req, res) => { const sql = "update customer set isDeleted = 1 where id = ?"; const params = [req.params.id]; connection.query(sql, params, (err, rows, fileds) => { res.send(rows); }); }); app.listen(port, () => console.log(`Listening on port ${port}`)); // rest api - 서버와 클라이언트가 웹 프로토콜을 기반으로 효과적으로 데이터를 주고받을 수 있게 해줌. // create - post / read - get / update - put / delete - delete // file을 서버에서 받기 위한 라이브러리 // npm i --save multer <file_sep># Management System --- ### 概要 - 顧客の情報を追加と削除できるアプリケーショ ### 技術スタック 1. JavaScript(with React) 2. Node.js 3. AWS (RDS with MySQL) ### UI - Material Design ### 動作 1. ホーム ![home](https://user-images.githubusercontent.com/50327128/108490424-14af2800-72e6-11eb-9b28-947360eb6def.JPG) 2. 追加 ![clickAddbutton](https://user-images.githubusercontent.com/50327128/108490463-1d076300-72e6-11eb-9840-56580c5fda35.JPG) ![clickAddbutton2](https://user-images.githubusercontent.com/50327128/108490469-1ed12680-72e6-11eb-8364-d80320dce4d9.JPG) ![completeAdd](https://user-images.githubusercontent.com/50327128/108490478-209aea00-72e6-11eb-9cbd-1dde3e3042fb.JPG) 3. 検索 ![search1](https://user-images.githubusercontent.com/50327128/108490497-2690cb00-72e6-11eb-8591-a61cef9cd710.JPG) ![search2](https://user-images.githubusercontent.com/50327128/108490503-27c1f800-72e6-11eb-96f1-ded2fc00744a.JPG) 4. 削除 ![delete1](https://user-images.githubusercontent.com/50327128/108490521-2bee1580-72e6-11eb-939a-925d8bf8cb82.JPG) ![delete2](https://user-images.githubusercontent.com/50327128/108490535-2e506f80-72e6-11eb-8708-002a0d857859.JPG)
830b1e6ca300bbac9baafe35e35bbabc9363a473
[ "JavaScript", "Markdown" ]
3
JavaScript
hyoilll/react-node-rds
48d3696a448583bbb3b1ac196f41f9f9adb25968
f4570e17e87c3c572cdb06486b998f9e57726ee8
refs/heads/master
<file_sep>/* * Copyright (C) 2007 The Android Open Source Project * * 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. */ package com.amoseui.music.tests; import android.app.Instrumentation; import android.content.Intent; import android.os.Bundle; /** * Base class for all launch performance Instrumentation classes. * * @hide */ @Deprecated public class LaunchPerformanceBase extends Instrumentation { public static final String LOG_TAG = "Launch Performance"; protected Bundle mResults; protected Intent mIntent; public LaunchPerformanceBase() { mResults = new Bundle(); mIntent = new Intent(Intent.ACTION_MAIN); mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); setAutomaticPerformanceSnapshots(); } /** * Launches intent, and waits for idle before returning. * * @hide */ protected void LaunchApp() { startActivitySync(mIntent); waitForIdleSync(); } } <file_sep>/* * Copyright (C) 2007 The Android Open Source Project * * 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. */ package com.amoseui.music; import android.Manifest.permission; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Bundle; import com.amoseui.music.utils.LogHelper; public class MusicBrowserActivity extends Activity { private static final String TAG = LogHelper.makeLogTag(MusicBrowserActivity.class); private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 42; public MusicBrowserActivity() { } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); LogHelper.d(TAG, "onCreate()"); if (checkSelfPermission(permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); return; } initApp(); } public void initApp() { int activeTab = MusicUtils.getIntPref(this, "activetab", R.id.artisttab); LogHelper.d(TAG, "initApp() activeTab = ", activeTab); if (activeTab != R.id.artisttab && activeTab != R.id.albumtab && activeTab != R.id.songtab && activeTab != R.id.playlisttab) { activeTab = R.id.artisttab; } MusicUtils.activateTab(this, activeTab); } @Override public void onDestroy() { LogHelper.d(TAG, "onDestroy()"); super.onDestroy(); } @Override public void onRequestPermissionsResult( int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { finish(); return; } initApp(); } } } } <file_sep>/* * Copyright (C) 2007 The Android Open Source Project * * 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. */ package com.amoseui.music; import android.app.Activity; import android.app.SearchManager; import android.content.ComponentName; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.media.AudioManager; import android.media.MediaDescription; import android.media.MediaMetadata; import android.media.browse.MediaBrowser; import android.media.session.MediaController; import android.media.session.PlaybackState; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.provider.MediaStore; import android.text.Layout; import android.text.TextUtils.TruncateAt; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.amoseui.music.utils.LogHelper; import com.amoseui.music.utils.MediaIDHelper; import com.amoseui.music.utils.MusicProvider; /* This is the Now Playing Activity */ public class MediaPlaybackActivity extends Activity implements View.OnTouchListener, View.OnLongClickListener { private static final String TAG = LogHelper.makeLogTag(MediaPlaybackActivity.class); private final Handler mHandler = new Handler(); int mInitialX = -1; int mLastX = -1; int mTextWidth = 0; int mViewWidth = 0; boolean mDraggingLabel = false; Handler mLabelScroller = new Handler() { @Override public void handleMessage(Message msg) { TextView tv = (TextView) msg.obj; int x = tv.getScrollX(); x = x * 3 / 4; tv.scrollTo(x, 0); if (x == 0) { tv.setEllipsize(TruncateAt.END); } else { Message newmsg = obtainMessage(0, tv); mLabelScroller.sendMessageDelayed(newmsg, 15); } } }; private long mStartSeekPos = 0; private long mLastSeekEventTime; private RepeatingImageButton mPrevButton; private ImageButton mPlayPauseButton; private RepeatingImageButton mNextButton; private ImageButton mRepeatButton; private ImageButton mShuffleButton; private ImageButton mQueueButton; private int mTouchSlop; private ImageView mAlbumArt; private TextView mCurrentTime; private TextView mTotalTime; private TextView mArtistName; private TextView mAlbumName; private TextView mTrackName; private LinearLayout mTrackInfo; private ProgressBar mProgress; private BitmapDrawable mDefaultAlbumArt; private Toast mToast; private MediaBrowser mMediaBrowser; // Receive callbacks from the MediaController. Here we update our state such as which queue // is being shown, the current title and description and the PlaybackState. private MediaController.Callback mMediaControllerCallback = new MediaController.Callback() { @Override public void onSessionDestroyed() { LogHelper.d(TAG, "Session destroyed. Need to fetch a new Media Session"); } @Override public void onPlaybackStateChanged(PlaybackState state) { if (state == null) { return; } LogHelper.d(TAG, "Received playback state change to state ", state.toString()); updateProgressBar(); setPauseButtonImage(); } @Override public void onMetadataChanged(MediaMetadata metadata) { if (metadata == null) { return; } LogHelper.d(TAG, "Received updated metadata: ", metadata); updateTrackInfo(); } }; private MediaBrowser.ConnectionCallback mConnectionCallback = new MediaBrowser.ConnectionCallback() { @Override public void onConnected() { Log.d(TAG, "onConnected: session token " + mMediaBrowser.getSessionToken()); if (mMediaBrowser.getSessionToken() == null) { throw new IllegalArgumentException("No Session token"); } MediaController mediaController = new MediaController( MediaPlaybackActivity.this, mMediaBrowser.getSessionToken()); mediaController.registerCallback(mMediaControllerCallback); MediaPlaybackActivity.this.setMediaController(mediaController); mRepeatButton.setVisibility(View.VISIBLE); mShuffleButton.setVisibility(View.VISIBLE); mQueueButton.setVisibility(View.VISIBLE); setRepeatButtonImage(null); setShuffleButtonImage(null); setPauseButtonImage(); updateTrackInfo(); mHandler.post(new Runnable() { @Override public void run() { long delay = updateProgressBar(); mHandler.postDelayed(this, delay); } }); } @Override public void onConnectionFailed() { Log.d(TAG, "onConnectionFailed"); } @Override public void onConnectionSuspended() { Log.d(TAG, "onConnectionSuspended"); mHandler.removeCallbacksAndMessages(null); MediaPlaybackActivity.this.setMediaController(null); } }; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { LogHelper.d(TAG, "onCreate()"); super.onCreate(icicle); setVolumeControlStream(AudioManager.STREAM_MUSIC); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.audio_player); mCurrentTime = (TextView) findViewById(R.id.currenttime); mTotalTime = (TextView) findViewById(R.id.totaltime); mProgress = (ProgressBar) findViewById(android.R.id.progress); mAlbumArt = (ImageView) findViewById(R.id.album); mArtistName = (TextView) findViewById(R.id.artistname); mAlbumName = (TextView) findViewById(R.id.albumname); mTrackName = (TextView) findViewById(R.id.trackname); mTrackInfo = (LinearLayout) findViewById(R.id.trackinfo); Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.albumart_mp_unknown); mDefaultAlbumArt = new BitmapDrawable(getResources(), b); // no filter or dither, it's a lot faster and we can't tell the difference mDefaultAlbumArt.setFilterBitmap(false); mDefaultAlbumArt.setDither(false); /* Set metadata listeners */ View v = (View) mArtistName.getParent(); v.setOnTouchListener(this); v.setOnLongClickListener(this); v = (View) mAlbumName.getParent(); v.setOnTouchListener(this); v.setOnLongClickListener(this); v = (View) mTrackName.getParent(); v.setOnTouchListener(this); v.setOnLongClickListener(this); /* Set button listeners */ mPrevButton = (RepeatingImageButton) findViewById(R.id.prev); mPrevButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getMediaController() == null) return; if (getMediaController().getPlaybackState().getPosition() < 2000) { getMediaController().getTransportControls().skipToPrevious(); } else { getMediaController().getTransportControls().seekTo(0); getMediaController().getTransportControls().play(); } } }); mPrevButton.setRepeatListener(new RepeatingImageButton.RepeatListener() { public void onRepeat(View v, long howlong, int repcnt) { scanBackward(repcnt, howlong); } }, 260); mPlayPauseButton = (ImageButton) findViewById(R.id.pause); mPlayPauseButton.requestFocus(); mPlayPauseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getMediaController() != null) { if (getMediaController().getPlaybackState().getState() != PlaybackState.STATE_PLAYING) { getMediaController().getTransportControls().play(); } else { getMediaController().getTransportControls().pause(); } } } }); mNextButton = (RepeatingImageButton) findViewById(R.id.next); mNextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getMediaController() == null) return; getMediaController().getTransportControls().skipToNext(); } }); mNextButton.setRepeatListener(new RepeatingImageButton.RepeatListener() { public void onRepeat(View v, long howlong, int repcnt) { scanForward(repcnt, howlong); } }, 260); mQueueButton = (ImageButton) findViewById(R.id.curplaylist); mQueueButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LogHelper.d(TAG, "mQueueButton onClick"); MediaBrowser.MediaItem parentItem = new MediaBrowser.MediaItem( new MediaDescription.Builder() .setMediaId(MediaIDHelper.createBrowseCategoryMediaID( MediaIDHelper.MEDIA_ID_MUSICS_BY_PLAYLIST, MediaIDHelper.MEDIA_ID_NOW_PLAYING)) .setTitle("Now Playing") .build(), MediaBrowser.MediaItem.FLAG_BROWSABLE); Intent intent = new Intent(Intent.ACTION_PICK) .setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track") .putExtra(MusicUtils.TAG_WITH_TABS, false) .putExtra(MusicUtils.TAG_PARENT_ITEM, parentItem); startActivity(intent); } }); mShuffleButton = ((ImageButton) findViewById(R.id.shuffle)); mShuffleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LogHelper.d(TAG, "Shuffle button clicked"); if (getMediaController() == null) return; Bundle extras = getMediaController().getExtras(); if (extras == null) return; MediaPlaybackService.ShuffleMode shuffleMode = MediaPlaybackService.ShuffleMode .values()[extras.getInt(MediaPlaybackService.SHUFFLE_MODE)]; MediaPlaybackService.ShuffleMode nextShuffleMode; switch (shuffleMode) { case SHUFFLE_NONE: nextShuffleMode = MediaPlaybackService.ShuffleMode.SHUFFLE_RANDOM; showToast(R.string.shuffle_on_notif); break; case SHUFFLE_RANDOM: default: nextShuffleMode = MediaPlaybackService.ShuffleMode.SHUFFLE_NONE; showToast(R.string.shuffle_off_notif); break; } setShuffleMode(nextShuffleMode); // TODO(siyuanh): Should use a callback to register changes on service side setShuffleButtonImage(nextShuffleMode); } }); mRepeatButton = ((ImageButton) findViewById(R.id.repeat)); mRepeatButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LogHelper.d(TAG, "Repeat button clicked"); if (getMediaController() == null) return; Bundle extras = getMediaController().getExtras(); if (extras == null) return; MediaPlaybackService.RepeatMode repeatMode = MediaPlaybackService.RepeatMode .values()[extras.getInt(MediaPlaybackService.REPEAT_MODE)]; MediaPlaybackService.RepeatMode nextRepeatMode; switch (repeatMode) { case REPEAT_NONE: nextRepeatMode = MediaPlaybackService.RepeatMode.REPEAT_ALL; showToast(R.string.repeat_all_notif); break; case REPEAT_ALL: nextRepeatMode = MediaPlaybackService.RepeatMode.REPEAT_CURRENT; showToast(R.string.repeat_current_notif); break; case REPEAT_CURRENT: default: nextRepeatMode = MediaPlaybackService.RepeatMode.REPEAT_NONE; showToast(R.string.repeat_off_notif); break; } setRepeatMode(nextRepeatMode); // TODO(siyuanh): Should use a callback to register changes on service side setRepeatButtonImage(nextRepeatMode); } }); if (mProgress instanceof SeekBar) { SeekBar seeker = (SeekBar) mProgress; seeker.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { boolean mmFromTouch = false; public void onStartTrackingTouch(SeekBar bar) { mLastSeekEventTime = 0; mmFromTouch = true; } public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) { if (!fromuser || (getMediaController() == null)) return; long now = SystemClock.elapsedRealtime(); if ((now - mLastSeekEventTime) > 250) { mLastSeekEventTime = now; long duration = getMediaController().getMetadata().getLong( MediaMetadata.METADATA_KEY_DURATION); long position = duration * progress / 1000; getMediaController().getTransportControls().seekTo(position); // trackball event, allow progress updates if (!mmFromTouch) { updateProgressBar(); } } } public void onStopTrackingTouch(SeekBar bar) { mmFromTouch = false; } }); } else { LogHelper.d(TAG, "Seeking not supported"); } mProgress.setMax(1000); mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); Log.d(TAG, "Creating MediaBrowser"); mMediaBrowser = new MediaBrowser(this, new ComponentName(this, MediaPlaybackService.class), mConnectionCallback, null); } TextView textViewForContainer(View v) { View vv = v.findViewById(R.id.artistname); if (vv != null) return (TextView) vv; vv = v.findViewById(R.id.albumname); if (vv != null) return (TextView) vv; vv = v.findViewById(R.id.trackname); if (vv != null) return (TextView) vv; return null; } public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); TextView tv = textViewForContainer(v); if (tv == null) { return false; } if (action == MotionEvent.ACTION_DOWN) { v.setBackgroundColor(0xff606060); mInitialX = mLastX = (int) event.getX(); mDraggingLabel = false; } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { v.setBackgroundColor(0); if (mDraggingLabel) { Message msg = mLabelScroller.obtainMessage(0, tv); mLabelScroller.sendMessageDelayed(msg, 1000); } } else if (action == MotionEvent.ACTION_MOVE) { if (mDraggingLabel) { int scrollx = tv.getScrollX(); int x = (int) event.getX(); int delta = mLastX - x; if (delta != 0) { mLastX = x; scrollx += delta; if (scrollx > mTextWidth) { // scrolled the text completely off the view to the left scrollx -= mTextWidth; scrollx -= mViewWidth; } if (scrollx < -mViewWidth) { // scrolled the text completely off the view to the right scrollx += mViewWidth; scrollx += mTextWidth; } tv.scrollTo(scrollx, 0); } return true; } int delta = mInitialX - (int) event.getX(); if (Math.abs(delta) > mTouchSlop) { // start moving mLabelScroller.removeMessages(0, tv); // Only turn ellipsizing off when it's not already off, because it // causes the scroll position to be reset to 0. if (tv.getEllipsize() != null) { tv.setEllipsize(null); } Layout ll = tv.getLayout(); // layout might be null if the text just changed, or ellipsizing // was just turned off if (ll == null) { return false; } // get the non-ellipsized line width, to determine whether scrolling // should even be allowed mTextWidth = (int) tv.getLayout().getLineWidth(0); mViewWidth = tv.getWidth(); if (mViewWidth > mTextWidth) { tv.setEllipsize(TruncateAt.END); v.cancelLongPress(); return false; } mDraggingLabel = true; tv.setHorizontalFadingEdgeEnabled(true); v.cancelLongPress(); return true; } } return false; } public boolean onLongClick(View view) { CharSequence title = null; String mime = null; String query = null; if (getMediaController() == null) { LogHelper.d(TAG, "No media controller avalable yet"); return true; } MediaMetadata metadata = getMediaController().getMetadata(); if (metadata == null) { LogHelper.d(TAG, "No metadata avalable yet"); return true; } String artist = metadata.getString(MediaMetadata.METADATA_KEY_ARTIST); String album = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM); String song = metadata.getString(MediaMetadata.METADATA_KEY_TITLE); long audioid = metadata.getLong(MediaMetadata.METADATA_KEY_MEDIA_ID); if (album == null && artist == null && song != null && song.startsWith("recording")) { LogHelper.d(TAG, "Item is not music"); return false; } if (audioid < 0) { return false; } boolean knownartist = (artist != null) && !MediaStore.UNKNOWN_STRING.equals(artist); boolean knownalbum = (album != null) && !MediaStore.UNKNOWN_STRING.equals(album); if (knownartist && view.equals(mArtistName.getParent())) { title = artist; query = artist; mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE; } else if (knownalbum && view.equals(mAlbumName.getParent())) { title = album; if (knownartist) { query = artist + " " + album; } else { query = album; } mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE; } else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) { if ((song == null) || MediaStore.UNKNOWN_STRING.equals(song)) { // A popup of the form "Search for null/'' using ..." is pretty // unhelpful, plus, we won't find any way to buy it anyway. return true; } title = song; if (knownartist) { query = artist + " " + song; } else { query = song; } mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it } else { throw new RuntimeException("shouldn't be here"); } title = getString(R.string.mediasearch, title); Intent i = new Intent(); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH); i.putExtra(SearchManager.QUERY, query); if (knownartist) { i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist); } if (knownalbum) { i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album); } i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song); i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime); startActivity(Intent.createChooser(i, title)); return true; } @Override public void onStart() { LogHelper.d(TAG, "onStart()"); super.onStart(); mMediaBrowser.connect(); } @Override public void onStop() { LogHelper.d(TAG, "onStop()"); mMediaBrowser.disconnect(); super.onStop(); } @Override public void onResume() { LogHelper.d(TAG, "onResume()"); super.onResume(); updateTrackInfo(); setPauseButtonImage(); } @Override public void onDestroy() { LogHelper.d(TAG, "onDestroy()"); super.onDestroy(); } private void scanBackward(int repcnt, long delta) { if (getMediaController() == null) return; if (repcnt == 0) { mStartSeekPos = getMediaController().getPlaybackState().getPosition(); mLastSeekEventTime = 0; } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta = delta * 10; } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40; } long newpos = mStartSeekPos - delta; if (newpos < 0) { // move to previous track getMediaController().getTransportControls().skipToPrevious(); long duration = getMediaController().getMetadata().getLong( MediaMetadata.METADATA_KEY_DURATION); mStartSeekPos += duration; newpos += duration; } if (((delta - mLastSeekEventTime) > 250) || repcnt < 0) { getMediaController().getTransportControls().seekTo(newpos); mLastSeekEventTime = delta; } updateProgressBar(); } } private void scanForward(int repcnt, long delta) { if (getMediaController() == null) return; if (repcnt == 0) { mStartSeekPos = getMediaController().getPlaybackState().getPosition(); mLastSeekEventTime = 0; } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta = delta * 10; } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40; } long newpos = mStartSeekPos + delta; long duration = getMediaController().getMetadata().getLong(MediaMetadata.METADATA_KEY_DURATION); if (newpos >= duration) { // move to next track getMediaController().getTransportControls().skipToNext(); mStartSeekPos -= duration; // is OK to go negative newpos -= duration; } if (((delta - mLastSeekEventTime) > 250) || repcnt < 0) { getMediaController().getTransportControls().seekTo(newpos); mLastSeekEventTime = delta; } updateProgressBar(); } } private void setShuffleMode(MediaPlaybackService.ShuffleMode shuffleMode) { Bundle extras = new Bundle(); extras.putInt(MediaPlaybackService.SHUFFLE_MODE, shuffleMode.ordinal()); getMediaController().getTransportControls().sendCustomAction( MediaPlaybackService.CMD_SHUFFLE, extras); } private void setShuffleButtonImage(MediaPlaybackService.ShuffleMode shuffleMode) { if (getMediaController() == null) return; Bundle extras = getMediaController().getExtras(); if (extras == null) return; if (shuffleMode == null) { shuffleMode = MediaPlaybackService.ShuffleMode .values()[extras.getInt(MediaPlaybackService.SHUFFLE_MODE)]; } switch (shuffleMode) { case SHUFFLE_RANDOM: mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn); break; case SHUFFLE_NONE: default: mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn); break; } } private void setRepeatMode(MediaPlaybackService.RepeatMode repeatMode) { Bundle extras = new Bundle(); extras.putInt(MediaPlaybackService.REPEAT_MODE, repeatMode.ordinal()); getMediaController().getTransportControls().sendCustomAction( MediaPlaybackService.CMD_REPEAT, extras); } private void setRepeatButtonImage(MediaPlaybackService.RepeatMode repeatMode) { if (getMediaController() == null) return; Bundle extras = getMediaController().getExtras(); if (extras == null) return; if (repeatMode == null) { repeatMode = MediaPlaybackService.RepeatMode .values()[extras.getInt(MediaPlaybackService.REPEAT_MODE)]; } switch (repeatMode) { case REPEAT_CURRENT: mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn); break; case REPEAT_ALL: mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn); break; case REPEAT_NONE: default: mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn); break; } } private void showToast(int resid) { if (mToast == null) { mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); } mToast.setText(resid); mToast.show(); } private void setPauseButtonImage() { if (getMediaController() == null) { return; } if (getMediaController().getPlaybackState().getState() != PlaybackState.STATE_PLAYING) { mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play); } else { mPlayPauseButton.setImageResource(android.R.drawable.ic_media_pause); } } private long updateProgressBar() { MediaController mediaController = getMediaController(); if (mediaController == null || mediaController.getMetadata() == null || mediaController.getPlaybackState() == null) { return 500; } long duration = mediaController.getMetadata().getLong(MediaMetadata.METADATA_KEY_DURATION); long pos = mediaController.getPlaybackState().getPosition(); if ((pos >= 0) && (duration > 0)) { mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000)); int progress = (int) (1000 * pos / duration); mProgress.setProgress(progress); if (mediaController.getPlaybackState().getState() == PlaybackState.STATE_PLAYING) { mCurrentTime.setVisibility(View.VISIBLE); } else { // blink the counter int vis = mCurrentTime.getVisibility(); mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE); return 500; } } else { mCurrentTime.setText("--:--"); mProgress.setProgress(1000); } // calculate the number of milliseconds until the next full second, so // the counter can be updated at just the right time long remaining = 1000 - (pos % 1000); // approximate how often we would need to refresh the slider to // move it smoothly int width = mProgress.getWidth(); if (width == 0) width = 320; long smoothrefreshtime = duration / width; if (smoothrefreshtime > remaining) return remaining; if (smoothrefreshtime < 20) return 20; return smoothrefreshtime; } private void updateTrackInfo() { LogHelper.d(TAG, "updateTrackInfo()"); if (getMediaController() == null) { return; } MediaMetadata metadata = getMediaController().getMetadata(); if (metadata == null) { return; } mTrackInfo.setVisibility(View.VISIBLE); mTrackName.setText(metadata.getString(MediaMetadata.METADATA_KEY_TITLE)); LogHelper.d(TAG, "Track Name: ", mTrackName.getText()); String artistName = metadata.getString(MediaMetadata.METADATA_KEY_ARTIST); if (artistName.equals(MusicProvider.UNKOWN)) { artistName = getString(R.string.unknown_artist_name); } mArtistName.setText(artistName); String albumName = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM); if (albumName.equals(MusicProvider.UNKOWN)) { albumName = getString(R.string.unknown_album_name); } mAlbumName.setText(albumName); Bitmap albumArt = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART); if (albumArt != null) { mAlbumArt.setImageBitmap(albumArt); } else { mAlbumArt.setImageDrawable(mDefaultAlbumArt); } mAlbumArt.setVisibility(View.VISIBLE); long duration = metadata.getLong(MediaMetadata.METADATA_KEY_DURATION); mTotalTime.setText(MusicUtils.makeTimeString(this, duration / 1000)); } } <file_sep>/* * Copyright (C) 2017 The Android Open Source Project * * 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. */ package com.amoseui.music.utils; import android.content.ContentUris; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadata; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.util.Log; import com.amoseui.music.MusicUtils; import com.amoseui.music.R; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; /* A provider of music contents to the music application, it reads external storage for any music files, parse them and store them in this class for future use. */ public class MusicProvider { // Public constants public static final String UNKOWN = "UNKNOWN"; // Uri source of this track public static final String CUSTOM_METADATA_TRACK_SOURCE = "__SOURCE__"; // Sort key for this tack public static final String CUSTOM_METADATA_SORT_KEY = "__SORT_KEY__"; private static final String TAG = "MusicProvider"; // Content select criteria private static final String MUSIC_SELECT_FILTER = MediaStore.Audio.Media.IS_MUSIC + " != 0"; private static final String MUSIC_SORT_ORDER = MediaStore.Audio.Media.TITLE + " ASC"; private final ConcurrentMap<Long, Song> mMusicListById; private final ConcurrentMap<String, Song> mMusicListByMediaId; // Categorized caches for music track data: private Context mContext; // Album Name --> list of Metadata private ConcurrentMap<String, List<MediaMetadata>> mMusicListByAlbum; // Playlist Name --> list of Metadata private ConcurrentMap<String, List<MediaMetadata>> mMusicListByPlaylist; // Artist Name --> Map of (album name --> album metadata) private ConcurrentMap<String, Map<String, MediaMetadata>> mArtistAlbumDb; private List<MediaMetadata> mMusicList; private volatile State mCurrentState = State.NON_INITIALIZED; public MusicProvider(Context context) { mContext = context; mArtistAlbumDb = new ConcurrentHashMap<>(); mMusicListByAlbum = new ConcurrentHashMap<>(); mMusicListByPlaylist = new ConcurrentHashMap<>(); mMusicListById = new ConcurrentHashMap<>(); mMusicList = new ArrayList<>(); mMusicListByMediaId = new ConcurrentHashMap<>(); mMusicListByPlaylist.put(MediaIDHelper.MEDIA_ID_NOW_PLAYING, new ArrayList<MediaMetadata>()); } public boolean isInitialized() { return mCurrentState == State.INITIALIZED; } /** * Get an iterator over the list of artists * * @return list of artists */ public Iterable<String> getArtists() { if (mCurrentState != State.INITIALIZED) { return Collections.emptyList(); } return mArtistAlbumDb.keySet(); } /** * Get an iterator over the list of albums * * @return list of albums */ public Iterable<MediaMetadata> getAlbums() { if (mCurrentState != State.INITIALIZED) { return Collections.emptyList(); } ArrayList<MediaMetadata> albumList = new ArrayList<>(); for (Map<String, MediaMetadata> artist_albums : mArtistAlbumDb.values()) { albumList.addAll(artist_albums.values()); } return albumList; } /** * Get an iterator over the list of playlists * * @return list of playlists */ public Iterable<String> getPlaylists() { if (mCurrentState != State.INITIALIZED) { return Collections.emptyList(); } return mMusicListByPlaylist.keySet(); } public Iterable<MediaMetadata> getMusicList() { return mMusicList; } /** * Get albums of a certain artist */ public Iterable<MediaMetadata> getAlbumByArtist(String artist) { if (mCurrentState != State.INITIALIZED || !mArtistAlbumDb.containsKey(artist)) { return Collections.emptyList(); } return mArtistAlbumDb.get(artist).values(); } /** * Get music tracks of the given album */ public Iterable<MediaMetadata> getMusicsByAlbum(String album) { if (mCurrentState != State.INITIALIZED || !mMusicListByAlbum.containsKey(album)) { return Collections.emptyList(); } return mMusicListByAlbum.get(album); } /** * Get music tracks of the given playlist */ public Iterable<MediaMetadata> getMusicsByPlaylist(String playlist) { if (mCurrentState != State.INITIALIZED || !mMusicListByPlaylist.containsKey(playlist)) { return Collections.emptyList(); } return mMusicListByPlaylist.get(playlist); } /** * Return the MediaMetadata for the given musicID. * * @param musicId The unique, non-hierarchical music ID. */ public Song getMusicById(long musicId) { return mMusicListById.containsKey(musicId) ? mMusicListById.get(musicId) : null; } /** * Return the MediaMetadata for the given musicID. * * @param musicId The unique, non-hierarchical music ID. */ public Song getMusicByMediaId(String musicId) { return mMusicListByMediaId.containsKey(musicId) ? mMusicListByMediaId.get(musicId) : null; } /** * Very basic implementation of a search that filter music tracks which title containing * the given query. */ public Iterable<MediaMetadata> searchMusic(String titleQuery) { if (mCurrentState != State.INITIALIZED) { return Collections.emptyList(); } ArrayList<MediaMetadata> result = new ArrayList<>(); titleQuery = titleQuery.toLowerCase(); for (Song song : mMusicListByMediaId.values()) { if (song.getMetadata() .getString(MediaMetadata.METADATA_KEY_TITLE) .toLowerCase() .contains(titleQuery)) { result.add(song.getMetadata()); } } return result; } /** * Get the list of music tracks from disk and caches the track information * for future reference, keying tracks by musicId and grouping by genre. */ public void retrieveMediaAsync(final MusicProviderCallback callback) { Log.d(TAG, "retrieveMediaAsync called"); if (mCurrentState == State.INITIALIZED) { // Nothing to do, execute callback immediately callback.onMusicCatalogReady(true); return; } // Asynchronously load the music catalog in a separate thread new AsyncTask<Void, Void, State>() { @Override protected State doInBackground(Void... params) { if (mCurrentState == State.INITIALIZED) { return mCurrentState; } mCurrentState = State.INITIALIZING; if (retrieveMedia()) { mCurrentState = State.INITIALIZED; } else { mCurrentState = State.NON_INITIALIZED; } return mCurrentState; } @Override protected void onPostExecute(State current) { if (callback != null) { callback.onMusicCatalogReady(current == State.INITIALIZED); } } } .execute(); } public synchronized boolean retrieveAllPlayLists() { Cursor cursor = mContext.getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, null, null, null); if (cursor == null) { Log.e(TAG, "Failed to retreive playlist: cursor is null"); return false; } if (!cursor.moveToFirst()) { Log.d(TAG, "Failed to move cursor to first row (no query result)"); cursor.close(); return true; } int idColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists._ID); int nameColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME); int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.DATA); do { long thisId = cursor.getLong(idColumn); String thisPath = cursor.getString(pathColumn); String thisName = cursor.getString(nameColumn); Log.i(TAG, "PlayList ID: " + thisId + " Name: " + thisName); List<MediaMetadata> songList = retreivePlaylistMetadata(thisId, thisPath); LogHelper.i(TAG, "Found ", songList.size(), " items for playlist name: ", thisName); mMusicListByPlaylist.put(thisName, songList); } while (cursor.moveToNext()); cursor.close(); return true; } public synchronized List<MediaMetadata> retreivePlaylistMetadata( long playlistId, String playlistPath) { Cursor cursor = mContext.getContentResolver().query(Uri.parse(playlistPath), null, MediaStore.Audio.Playlists.Members.PLAYLIST_ID + " == " + playlistId, null, null); if (cursor == null) { Log.e(TAG, "Failed to retreive individual playlist: cursor is null"); return null; } if (!cursor.moveToFirst()) { Log.d(TAG, "Failed to move cursor to first row (no query result for playlist)"); cursor.close(); return null; } List<Song> songList = new ArrayList<>(); int idColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members._ID); int audioIdColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID); int orderColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.PLAY_ORDER); int audioPathColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.DATA); int audioNameColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE); do { long thisId = cursor.getLong(idColumn); long thisAudioId = cursor.getLong(audioIdColumn); long thisOrder = cursor.getLong(orderColumn); String thisAudioPath = cursor.getString(audioPathColumn); Log.i(TAG, "Playlist ID: " + playlistId + " Music ID: " + thisAudioId + " Name: " + audioNameColumn); if (!mMusicListById.containsKey(thisAudioId)) { LogHelper.d(TAG, "Music does not exist"); continue; } Song song = mMusicListById.get(thisAudioId); song.setSortKey(thisOrder); songList.add(song); } while (cursor.moveToNext()); cursor.close(); songList.sort(new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { long key1 = s1.getSortKey(); long key2 = s2.getSortKey(); if (key1 < key2) { return -1; } else if (key1 == key2) { return 0; } else { return 1; } } }); List<MediaMetadata> metadataList = new ArrayList<>(); for (Song song : songList) { metadataList.add(song.getMetadata()); } return metadataList; } private synchronized boolean retrieveMedia() { if (mContext.checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { return false; } Cursor cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, MUSIC_SELECT_FILTER, null, MUSIC_SORT_ORDER); if (cursor == null) { Log.e(TAG, "Failed to retreive music: cursor is null"); mCurrentState = State.NON_INITIALIZED; return false; } if (!cursor.moveToFirst()) { Log.d(TAG, "Failed to move cursor to first row (no query result)"); cursor.close(); return true; } int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID); int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE); int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA); do { Log.i(TAG, "Music ID: " + cursor.getString(idColumn) + " Title: " + cursor.getString(titleColumn)); long thisId = cursor.getLong(idColumn); String thisPath = cursor.getString(pathColumn); MediaMetadata metadata = retrievMediaMetadata(thisId, thisPath); Log.i(TAG, "MediaMetadata: " + metadata); if (metadata == null) { continue; } Song thisSong = new Song(thisId, metadata, null); // Construct per feature database mMusicList.add(metadata); mMusicListById.put(thisId, thisSong); mMusicListByMediaId.put(String.valueOf(thisId), thisSong); addMusicToAlbumList(metadata); addMusicToArtistList(metadata); } while (cursor.moveToNext()); cursor.close(); return true; } private synchronized MediaMetadata retrievMediaMetadata(long musicId, String musicPath) { LogHelper.d(TAG, "getting metadata for music: ", musicPath); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); Uri contentUri = ContentUris.withAppendedId( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, musicId); if (!(new File(musicPath).exists())) { LogHelper.d(TAG, "Does not exist, deleting item"); mContext.getContentResolver().delete(contentUri, null, null); return null; } try { retriever.setDataSource(mContext, contentUri); } catch (RuntimeException e) { // TODO(amoseui): fix the error LogHelper.e(TAG, "setDataSource error: ", musicPath); return null; } String title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); String album = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); String artist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); String durationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); long duration = durationString != null ? Long.parseLong(durationString) : 0; MediaMetadata.Builder metadataBuilder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, String.valueOf(musicId)) .putString(CUSTOM_METADATA_TRACK_SOURCE, musicPath) .putString(MediaMetadata.METADATA_KEY_TITLE, title != null ? title : UNKOWN) .putString(MediaMetadata.METADATA_KEY_ALBUM, album != null ? album : UNKOWN) .putString( MediaMetadata.METADATA_KEY_ARTIST, artist != null ? artist : UNKOWN) .putLong(MediaMetadata.METADATA_KEY_DURATION, duration); byte[] albumArtData = retriever.getEmbeddedPicture(); Bitmap bitmap; if (albumArtData != null) { bitmap = BitmapFactory.decodeByteArray(albumArtData, 0, albumArtData.length); bitmap = MusicUtils.resizeBitmap(bitmap, getDefaultAlbumArt()); metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap); } retriever.release(); return metadataBuilder.build(); } private Bitmap getDefaultAlbumArt() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeStream( mContext.getResources().openRawResource(R.drawable.albumart_mp_unknown), null, opts); } private void addMusicToAlbumList(MediaMetadata metadata) { String thisAlbum = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM); if (thisAlbum == null) { thisAlbum = UNKOWN; } if (!mMusicListByAlbum.containsKey(thisAlbum)) { mMusicListByAlbum.put(thisAlbum, new ArrayList<MediaMetadata>()); } mMusicListByAlbum.get(thisAlbum).add(metadata); } private void addMusicToArtistList(MediaMetadata metadata) { String thisArtist = metadata.getString(MediaMetadata.METADATA_KEY_ARTIST); if (thisArtist == null) { thisArtist = UNKOWN; } String thisAlbum = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM); if (thisAlbum == null) { thisAlbum = UNKOWN; } if (!mArtistAlbumDb.containsKey(thisArtist)) { mArtistAlbumDb.put(thisArtist, new ConcurrentHashMap<String, MediaMetadata>()); } Map<String, MediaMetadata> albumsMap = mArtistAlbumDb.get(thisArtist); MediaMetadata.Builder builder; long count = 0; Bitmap thisAlbumArt = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART); if (albumsMap.containsKey(thisAlbum)) { MediaMetadata album_metadata = albumsMap.get(thisAlbum); count = album_metadata.getLong(MediaMetadata.METADATA_KEY_NUM_TRACKS); Bitmap nAlbumArt = album_metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART); builder = new MediaMetadata.Builder(album_metadata); if (nAlbumArt != null) { thisAlbumArt = null; } } else { builder = new MediaMetadata.Builder(); builder.putString(MediaMetadata.METADATA_KEY_ALBUM, thisAlbum) .putString(MediaMetadata.METADATA_KEY_ARTIST, thisArtist); } if (thisAlbumArt != null) { builder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, thisAlbumArt); } builder.putLong(MediaMetadata.METADATA_KEY_NUM_TRACKS, count + 1); albumsMap.put(thisAlbum, builder.build()); } public synchronized void updateMusic(String musicId, MediaMetadata metadata) { Song song = mMusicListByMediaId.get(musicId); if (song == null) { return; } String oldGenre = song.getMetadata().getString(MediaMetadata.METADATA_KEY_GENRE); String newGenre = metadata.getString(MediaMetadata.METADATA_KEY_GENRE); song.setMetadata(metadata); // if genre has changed, we need to rebuild the list by genre if (!oldGenre.equals(newGenre)) { // buildListsByGenre(); } } enum State {NON_INITIALIZED, INITIALIZING, INITIALIZED} public interface MusicProviderCallback { void onMusicCatalogReady(boolean success); } } <file_sep># android-music-renewal [![Build Status](https://travis-ci.org/amoseui/android-music-renewal.svg?branch=master)](https://travis-ci.org/amoseui/android-music-renewal) Renewal of https://android.googlesource.com/platform/packages/apps/Music <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 28 buildToolsVersion "28.0.3" defaultConfig { applicationId "com.amoseui.music" minSdkVersion 1 targetSdkVersion 28 versionCode 1 versionName "0.0.1" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } debug { minifyEnabled false } } useLibrary 'android.test.base' useLibrary 'android.test.mock' useLibrary 'android.test.runner' lintOptions { abortOnError false } } <file_sep>/* * Copyright (C) 2014 The Android Open Source Project * * 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. */ package com.amoseui.music.utils; import android.media.MediaMetadata; import android.os.Parcel; import android.os.Parcelable; /** * Holder class that encapsulates a MediaMetadata and allows the actual metadata to be modified * without requiring to rebuild the collections the metadata is in. */ public class Song implements Parcelable { public static final Parcelable.Creator<Song> CREATOR = new Parcelable.Creator<Song>() { public Song createFromParcel(Parcel in) { MediaMetadata metadata = in.readParcelable(null); long songId = in.readLong(); long sortKey = in.readLong(); return new Song(songId, metadata, sortKey); } public Song[] newArray(int size) { return new Song[size]; } }; private MediaMetadata mMetadata; private long mSongId; private long mSortKey; public Song(long songId, MediaMetadata metadata, Long sortKey) { mMetadata = metadata; mSongId = songId; if (sortKey != null) { mSortKey = sortKey; } } public long getSongId() { return mSongId; } public long getSortKey() { return mSortKey; } public void setSortKey(long sortKey) { mSortKey = sortKey; } public MediaMetadata getMetadata() { return mMetadata; } public void setMetadata(MediaMetadata metadata) { mMetadata = metadata; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || o.getClass() != Song.class) { return false; } Song that = (Song) o; return mSongId == that.getSongId(); } @Override public int hashCode() { return Long.hashCode(mSongId); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeLong(mSortKey); out.writeLong(mSongId); out.writeParcelable(mMetadata, flags); } }
7edb84383c60b87bf4957dbc970c6788bdc52dcf
[ "Markdown", "Java", "Gradle" ]
7
Java
amoseui/android-music-renewal
1889e1cc10f62554ae2d00bd31c9f3dee256d8e5
b2a68f3c996e1a26b1a5114b672806f1c2ee6b84
refs/heads/master
<repo_name>wjessop/sectionwriter<file_sep>/examples/example.go package main import ( "fmt" "os" "sync" sw "github.com/wjessop/sectionwriter" ) var data = []byte("0123456789abcdefghij") func main() { f, err := os.OpenFile("somefile", os.O_RDWR|os.O_CREATE, 0755) if err != nil { panic(err) } defer f.Close() // Create a window onto the file starting at byte 0 that is 10 bytes in length. s1 := sw.NewSectionWriter(f, 0, 10) // Create a window onto the file starting at byte 10 that is 10 bytes in length s2 := sw.NewSectionWriter(f, 10, 10) var wg sync.WaitGroup wg.Add(2) // Concurrent writes thread safe go func() { // Write to the first section defer wg.Done() n, err := s1.Write(data[0:10]) fmt.Printf("Wrote %d bytes\n", n) if err != nil { panic(err) } }() go func() { // Write to the second section defer wg.Done() n, err := s2.Write(data[10:len(data)]) fmt.Printf("Wrote %d bytes\n", n) if err != nil { panic(err) } }() wg.Wait() } <file_sep>/sectionwriter.go package sectionwriter import "io" // NewSectionWriter returns a SectionWriter that writes to w // starting at offset off and stops after n bytes. func NewSectionWriter(w io.WriterAt, off int64, n int64) *SectionWriter { return &SectionWriter{w, off, off + n} } // SectionWriter implements Write, Seek, and WriteAt on a section // of an underlying WriterAt. type SectionWriter struct { w io.WriterAt off int64 limit int64 } // Write writes the data in p to the underlying WriterAt (w). // When len(p) is greater than the space left in w, bytes that // can be written in the remaining space will be, and the // number of bytes written along with an io.ErrShortWrite will // be returned func (s *SectionWriter) Write(p []byte) (n int, err error) { if max := s.limit - s.off; int64(len(p)) > max { p = p[0:max] err = io.ErrShortWrite } n, writeErr := s.w.WriteAt(p, s.off) s.off += int64(n) if writeErr != nil { err = writeErr return } return } <file_sep>/sectionwriter_test.go package sectionwriter_test import ( "io" "testing" "github.com/stretchr/testify/assert" "github.com/kdar/stringio" sw "github.com/wjessop/sectionwriter" ) func isSectionWriter(t interface{}) bool { switch t.(type) { case *sw.SectionWriter: return true default: return false } } func TestNewSectionWriter(t *testing.T) { sio := stringio.New() s := sw.NewSectionWriter(sio, 10, 100) assert.True(t, isSectionWriter(s), "should be a SectionWriter") } func TestWrite(t *testing.T) { data := []byte("0123456789abcdefghij") sio := stringio.New() s1 := sw.NewSectionWriter(sio, 0, 10) s2 := sw.NewSectionWriter(sio, 10, 10) n1, err1 := s1.Write(data[0:10]) n2, err2 := s2.Write(data[10:len(data)]) assert.NoError(t, err1, "Write 1 should not error") assert.NoError(t, err2, "Write 2 should not error") assert.Equal(t, 10, n1, "Write 1 should write 10 bytes") assert.Equal(t, 10, n2, "Write 2 should write 10 bytes") assert.Equal(t, data, sio.GetValueBytes(), "output IO object should match input") } type NopeWriter struct { } func (n *NopeWriter) WriteAt(p []byte, off int64) (int, error) { return 0, io.EOF } func TestWriteError(t *testing.T) { s := sw.NewSectionWriter(&NopeWriter{}, 0, 10) n, err := s.Write([]byte("foo")) assert.Equal(t, 0, n, "bytes written should be 0") assert.EqualError(t, err, "EOF", "error should be EOF") } func TestReturnsShortWriteWhenPassedTooMuchData(t *testing.T) { sio := stringio.New() s := sw.NewSectionWriter(sio, 5, 5) n, err := s.Write([]byte("1234567")) assert.Equal(t, 5, n, "bytes written should be 5") assert.EqualError(t, err, "short write", "error should be ErrShortWrite") } func TestSerialWritesAdvancesOffset(t *testing.T) { sio := stringio.New() s := sw.NewSectionWriter(sio, 0, 10) s.Write([]byte("01234")) s.Write([]byte("56789")) assert.Equal(t, "0123456789", sio.GetValueString()) } <file_sep>/README.md # Section Writer SectionWriter is a Go library that allows for creating windows into a file for writing, much the same as the SectionReader in the standard library does. These SectionWriters are safe for concurrent writing as long as the windows do not overlap, it is your responsibility to make sure this is the case. The use case for me is downloading sections of a file concurrently and writing them to sections of a local file. SectionWriter, and NewSectionWriter, accept anything that conforms to [the io.WriterAt interface](https://golang.org/pkg/io/#WriterAt): ```go type WriterAt interface { WriteAt(p []byte, off int64) (n int, err error) } ``` ## Usage ```go package main import ( "fmt" "os" "sync" sw "github.com/wjessop/sectionwriter" ) var data = []byte("0123456789abcdefghij") func main() { f, err := os.OpenFile("somefile", os.O_RDWR|os.O_CREATE, 0755) if err != nil { panic(err) } defer f.Close() // Create a window onto the file starting at byte 0 that is 10 bytes in length. s1 := sw.NewSectionWriter(f, 0, 10) // Create a window onto the file starting at byte 10 that is 10 bytes in length s2 := sw.NewSectionWriter(f, 10, 10) var wg sync.WaitGroup wg.Add(2) // Concurrent writes thread safe go func() { // Write to the first section defer wg.Done() n, err := s1.Write(data[0:10]) fmt.Printf("Wrote %d bytes\n", n) if err != nil { panic(err) } }() go func() { // Write to the second section defer wg.Done() n, err := s2.Write(data[10:len(data)]) fmt.Printf("Wrote %d bytes\n", n) if err != nil { panic(err) } }() wg.Wait() } ``` You can run this example yourself: ``` $ go run examples/example.go Wrote 10 bytes Wrote 10 bytes $ cat somefile 0123456789abcdefghij ``` ## License MIT, see LICENSE file
2d0ddfe725f5cafa65062b31f3e2eae57ab6a3ff
[ "Markdown", "Go" ]
4
Go
wjessop/sectionwriter
f3ebd13c8f1a37ce33c6106ea51822191a54495f
9b0b9e17c598b2fab4ef43d2444714b20a39ba51
refs/heads/master
<repo_name>ABahirat/Microtubule-Analysis<file_sep>/test_scripts/test_bundles_noise.sh cd .. python hmm.py -L data/bundles_lengths_noise_1.csv -S data/bundles_states_1.csv -O data/bundles_lengths_noise_2.csv -T data/bundles_states_2.csv -A viterbi -B -0.2,0.0,0.2 <file_sep>/test_scripts/test_singles.sh cd .. python hmm.py -L data/singles_lengths_1.csv -S data/singles_states_1.csv -O data/singles_lengths_2.csv -T data/singles_states_2.csv -A viterbi -B -0.2,-0.1,0.0,0.1,0.2 <file_sep>/analytics.py import matplotlib.pyplot as plt import os import hmm import numpy as np import matplotlib.patches as mpatches import collections # Initialize different types of bins bins = [] bins.append([-0.2,0.0,0.2]) bins.append([-0.2,-0.1,0.0,0.1,0.2]) bins.append([-0.3,-0.1,0.0,0.1,0.3]) bins.append([-0.3,-0.2,0.0,0.2,0.3]) bins.append([-0.4,-0.2,0.0,0.2,0.4]) bins.append([-0.3,-0.2,-0.1,0.0,0.1,0.2,0.3]) bins.append([-0.3,-0.25,-0.2,-0.15,-0.1,-0.05,0.0,0.05,0.1,0.15,0.2,0.25,0.3]) # Set different length files length_files = [] length_files.append('singles_lengths_1.csv') length_files.append('singles_lengths_2.csv') length_files.append('bundles_lengths_1.csv') length_files.append('bundles_lengths_2.csv') length_files.append('singles_lengths_noise_1.csv') length_files.append('singles_lengths_noise_2.csv') length_files.append('bundles_lengths_noise_1.csv') length_files.append('bundles_lengths_noise_2.csv') length_files.append('singles_lengths_noise_3.csv') length_files.append('singles_lengths_noise_4.csv') length_files.append('bundles_lengths_noise_3.csv') length_files.append('bundles_lengths_noise_4.csv') # Set different state files state_files = [] state_files.append('singles_states_1.csv') state_files.append('singles_states_2.csv') state_files.append('bundles_states_1.csv') state_files.append('bundles_states_2.csv') state_files.append('singles_states_1.csv') state_files.append('singles_states_2.csv') state_files.append('bundles_states_1.csv') state_files.append('bundles_states_2.csv') state_files.append('singles_states_1.csv') state_files.append('singles_states_2.csv') state_files.append('bundles_states_1.csv') state_files.append('bundles_states_2.csv') def generate_state_distributions(): # Calculate distrobutions in state files for state_file in state_files: # Get states from file states = [] with open('data/'+state_file, 'r') as sf: states_raw = [] for line in sf: states_raw = line.split(',') states = states + [int(i) for i in states_raw] # Get unqiue values in states to see what states possible states_set = list(set(states)) # Count number of each of the possible states counts = [states.count(i) for i in states_set] # Create bar grah state_file = state_file[:-4] # Remove .csv from name plt.bar(states_set, counts, align='center', alpha=0.5) plt.xticks(states_set) plt.xlabel('States') plt.title('State Distribution For File \''+state_file+'\'') plt.savefig('plots/state_distributions/'+state_file+'_distribution.png') plt.clf() # clear figure def generate_length_distributions(): # Calculate distrobutions in bin files for length_file in length_files: bin_number = 0 # Run every bin on each file for data_bin in bins: lengths = [] lengths.append(0) # Get lengths from file with open('data/'+length_file, 'r') as lf: lengths_raw = [] previous_end = None for line in lf: length_raw = line.split(',') if previous_end: # Handle the previous lines last value minus first value of new line lengths.append(hmm.bin(float(length_raw[0])-float(previous_end),data_bin)) previous_end = length_raw[-1] for i in range(1,len(length_raw)): # Find differences between value before lengths = lengths + [hmm.bin(float(length_raw[i])-float(length_raw[i-1]),data_bin)] # Get possible bins lengths_set = data_bin # Count number of each of the possible states counts = [lengths.count(i) for i in lengths_set] # Remove .csv form name length_file_clean = length_file[:-4] # Make incrementing list to size of length set for x position x_position = list(range(0,len(lengths_set))) # Create bar grah plt.bar(x_position, counts, align='center', alpha=0.5) plt.xticks(x_position,lengths_set) plt.xlabel('Bins') plt.title('Bin Distribution For File \''+length_file_clean+'\' with bin '+str(bin_number)) plt.savefig('plots/length_distributions/'+length_file_clean+'_bin-'+str(bin_number)+'_distribution.png') plt.clf() # clear figure bin_number += 1 def generate_length_state_distributions(): # This would do the same thing as 'generate_length_distributions()' except the bar graphs would have # each of the bars made up of the number of each of the states it is made up of. # For example if 30 samples belonged to bin 0.0, the bar for that bin would be made up of 3 sections, # one section for each possible state, showing how much of each of the things in that bin are made up of which states for j in range(0, len(length_files)): bin_number = 0 # Run every bin on each file for data_bin in bins: lengths = [] lengths.append(0) # Get lengths from file with open('data/'+length_files[j], 'r') as lf: lengths_raw = [] previous_end = None for line in lf: length_raw = line.split(',') if previous_end: # Handle the previous lines last value minus first value of new line lengths.append(hmm.bin(float(length_raw[0])-float(previous_end),data_bin)) previous_end = length_raw[-1] for i in range(1,len(length_raw)): # Find differences between value before lengths = lengths + [hmm.bin(float(length_raw[i])-float(length_raw[i-1]),data_bin)] # Get states from file states = [] with open('data/'+state_files[j], 'r') as sf: states_raw = [] for line in sf: states_raw = line.split(',') states = states + [int(i) for i in states_raw] print('data/'+state_files[j]+'={0}'.format(len(states))) print('data/'+length_files[j]+'={0}'.format(len(lengths))) # Get unqiue values in states to see what states possible states_set = list(set(states)) bin_states = {} lengths_set = data_bin for k in range(0, len(lengths_set)): bin_states[lengths_set[k]] = {} bin_states[lengths_set[k]][0] = 0 bin_states[lengths_set[k]][1] = 0 bin_states[lengths_set[k]][2] = 0 for k in range(0,len(states)): bin_states[lengths[k]][states[k]] += 1 # Remove .csv form name length_file_clean = length_files[j][:-4] state_file = state_files[j][:-4] x_position = list(range(0,len(lengths_set))) #print bin_states; n_groups = len(x_position) opacity = 0.7 bar_width = 0.25 index = np.arange(n_groups) zero_state_list = [] one_state_list = [] two_state_list = [] orderedList = [] for key in bin_states: orderedList.append(key) orderedList.sort() for key in orderedList: zero_state_list.append(bin_states[key][0]) one_state_list.append(bin_states[key][1]) two_state_list.append(bin_states[key][2]) rects1 = plt.bar(index, zero_state_list, bar_width, alpha=opacity, color='b', label='state 0') rects2 = plt.bar(index + bar_width, one_state_list, bar_width, alpha=opacity, color='r', label='state 1') rects3 = plt.bar(index + 2*bar_width, two_state_list, bar_width, alpha=opacity, color='g', label='state 2') plt.xlabel('Bins') plt.ylabel('Count') plt.xticks(index + 2*bar_width / 2, data_bin) plt.legend() plt.title('State Distribution For File \''+length_file_clean+'\' with bin '+str(bin_number)) plt.savefig('plots/length_state_distributions/'+length_file_clean+'_bin-'+str(bin_number)+'_distribution.png') #plt.tight_layout() plt.clf() # clear figure bin_number += 1 return def generate_probability_tables(): # Generate nice looking emission and transion probability tables if(len(length_files) != len(state_files)): print("Need same number of states and lengths files") return bin_number = 0 # Run every bin on each file for data_bin in bins: for i in range(len(length_files)): training = hmm.do_train('data/'+length_files[i],'data/'+state_files[i],data_bin) emissions = training['emissions'] transitions = training['transitions'] del emissions[99999] del emissions[-99999] del transitions[99999] del transitions[-99999] print("Building emission tables...") rows = [] cell_text = [] for key in emissions: rows.append(key) columns = [] values = [] del emissions[key][99999] del emissions[key][-99999] for key2 in emissions[key]: columns.append(key2) values = values + [emissions[key][key2]] cell_text.append(values) length_file_clean = length_files[i][:-4] state_file_clean = state_files[i][:-4] nrows, ncols = len(rows)+1, len(columns) hcell, wcell = 1.3, 2. hpad, wpad = 1, 1 fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) ax = fig.add_subplot(111) ax.axis('off') plt.title('Emission probability table for \''+length_file_clean+'/'+state_file_clean+'\' with bin '+str(bin_number)) the_table = ax.table(cellText=cell_text, colLabels=columns, rowLabels=rows, loc='center') #plt.show() plt.savefig('plots/probability_tables/emission_'+length_file_clean+'-'+state_file_clean+'_bin-'+str(bin_number)+'.png') plt.clf() # clear figure print("Building transition tables...") rows = [] cell_text = [] for key in transitions: rows.append(key) columns = [] values = [] del transitions[key][99999] del transitions[key][-99999] for key2 in transitions[key]: columns.append(key2) values = values + [transitions[key][key2]] cell_text.append(values) length_file_clean = length_files[i][:-4] state_file_clean = state_files[i][:-4] nrows, ncols = len(rows)+1, len(columns) hcell, wcell = 1.3, 2. hpad, wpad = 1, 1 fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) ax = fig.add_subplot(111) ax.axis('off') plt.title('Transition probability table for \''+length_file_clean+'/'+state_file_clean+'\'') the_table = ax.table(cellText=cell_text, colLabels=columns, rowLabels=rows, loc='center') #plt.show() plt.savefig('plots/probability_tables/transition_'+length_file_clean+'-'+state_file_clean+'.png') plt.clf() # clear figure bin_number += 1 return def generate_bin_accuracy(): # Generate plots showing viterbi accuracy vs each bin colors = ['#DAF7A6','#FFC300','#FF5733','#C70039','#900C3F','#48C9B0','#A551CF','#16A085','#AEB6BF','#515A5A'] if(len(length_files) < 2): print("Need to provide at least two sets of data, one for training and one for testing") return if(len(state_files) < 2): print("Need to provide at least two sets of data, one for training and one for testing") return if(len(length_files) != len(state_files)): print("Need same number of states and lengths files") return length = len(length_files) if length % 2 == 1: length -= 1 for i in range(0,length,2): training_lengths_file = 'data/'+length_files[i] testing_lengths_file = 'data/'+length_files[i+1] training_states_file = 'data/'+state_files[i] testing_states_file = 'data/'+state_files[i+1] fig = plt.figure(1) ax = plt.gca() fig2 = plt.figure(2) ax2 = plt.gca() bin_number = 0 # Run every bin on each file for data_bin in bins: training = hmm.do_train(training_lengths_file,training_states_file,data_bin) accuracy,f1_macro,f1_weighted = hmm.run_viterbi(testing_lengths_file,testing_states_file,training,data_bin) ax.scatter(len(data_bin),accuracy, c=colors[bin_number], label='bin '+str(bin_number)) ax2.scatter(len(data_bin),f1_weighted, c=colors[bin_number], label='bin '+str(bin_number)) bin_number += 1 training_lengths = length_files[i][:-4] training_states = state_files[i][:-4] testing_lengths = length_files[i+1][:-4] testing_states = state_files[i+1][:-4] box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend() box = ax2.get_position() ax2.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax2.legend() plt.figure(1) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.title('Bin Size vs. Accuracy') plt.ylabel('Accuracy') plt.xlabel('Bin Size') plt.savefig('plots/bin_accuracy/accuracy_train-'+training_lengths+'-'+training_states+'_test-'+testing_lengths+'-'+testing_states+'.png') plt.clf() plt.figure(2) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.title('Bin Size vs. F-Measure') plt.ylabel('F-Meausre') plt.xlabel('Bin Size') plt.savefig('plots/bin_accuracy/fmeasure_train-'+training_lengths+'-'+training_states+'_test-'+testing_lengths+'-'+testing_states+'.png') #plt.show() plt.clf() return def exit_program(): print("Exiting!") exit(0) def run_all(): print("~Generating state distrobution plots...") generate_state_distributions() print("~Generating length distrobution plots...") generate_length_distributions() print("~Generating length state distrobution plots...") generate_length_state_distributions() print("~Generating probability tables...") generate_probability_tables() print("~Generating bin accuracy plots...") generate_bin_accuracy() return def print_menu_options(): print("---Analytics program for microtubule hmm project---") print("Menu Options:") print("1: Generate State Distribution Plots") print("2: Generate Length Distribution Plots") print("3: Generate Length State Distribution Plots") print("4: Generate Probability Tables Distribution Plots") print("5: Generate Generate Bin Distribution Plots") print("6: Run All") print("0: Exit") menu_actions = { '0' : exit_program, '1' : generate_state_distributions, '2' : generate_length_distributions, '3' : generate_length_state_distributions, '4' : generate_probability_tables, '5' : generate_bin_accuracy, '6' : run_all, } # Run using menu os.system('clear') while True: print_menu_options() choice = raw_input(">> ") try: menu_actions[choice]() choice = raw_input("Finished! Press Enter to continue...") os.system('clear') except KeyError: os.system('clear') print "Invalid selection, please try again.\n" <file_sep>/test_scripts/test_singles_noise_2.sh cd .. python hmm.py -L data/singles_lengths_noise_3.csv -S data/singles_states_1.csv -O data/singles_lengths_noise_4.csv -T data/singles_states_2.csv -A viterbi -B -0.2,0.0,0.2 <file_sep>/test_scripts/test_bundles.sh cd .. python hmm.py -L data/bundles_lengths_1.csv -S data/bundles_states_1.csv -O data/bundles_lengths_2.csv -T data/bundles_states_2.csv -A viterbi -B -0.2,-0.1,0.0,0.1,0.2 <file_sep>/README.md # HMM for microtubule state anylsis This is a program for the purpose of determining the state of microtubles given length data. It does this using Hidden Markov Models and the Viterbi algorithm ## How to run This program is run using command line arguments. It can either be run with truth data or with an output data file that the program will dump the results into. The program has the following options: - -L specifies lengths file to be trained on - -S specifies states file to be trained on - -O specifies observation file to run algorithm on - -T specifies the truth data to check the algorithm against - -A specifies the algorithm to run (currently only viterbi) - -B specifies the bins to use for observations - -W specifies the file to write the output to if running without truth data For example the program can be run with truth data with the following: `python hmm.py -L lengths.csv -S states.cvs -O obs.csv -T truth.csv -A viterbi -B -0.2,-0.1,0.0,0.1,0.2` Or with no truth data but an output file: `python hmm.py -L lengths.csv -S states.cvs -O obs.csv -W output.csv -A viterbi -B -0.2,-0.1,0.0,0.1,0.2` There are lots of example BASH test scripts in the test scripts directory that are examples as well. ## Analytics The analytics file has a menu system where you can decide which tests to run. To see examples of what each of the tests are check out the plots file. The names of the plots are autogenerated based on the files they are run on. These files are decided in the lists for the truth and observations at the top of the anayltics.py file. To add more tests all you need to do is add more oberservations and cooresponding truth files. For testing the accuracy there needs to be an even number of files in the the top lists. The program will use the first oberservation and truth list items and train on those. Then it will run viterbi on the second item in the oberservations list and check it with the second item in the truth list. It will then do this with the 3rd and 4th and so on. These specitifcaitons don't need to be followed if the accuracy meassures are not used when running the analytics. <file_sep>/test_scripts/test_bundles_noise_2.sh cd .. python hmm.py -L data/bundles_lengths_noise_3.csv -S data/bundles_states_1.csv -O data/bundles_lengths_noise_4.csv -T data/bundles_states_2.csv -A viterbi -B -0.2,0.0,0.2 <file_sep>/test_scripts/test_singles_noise.sh cd .. python hmm.py -L data/singles_lengths_noise_1.csv -S data/singles_states_1.csv -O data/singles_lengths_noise_2.csv -T data/singles_states_2.csv -A viterbi -B -0.2,0.0,0.2 <file_sep>/hmm.py ###################################################################################### # File : hmm.py # Purpose : Hidden Markov Model for microtuule analysis # Developers : <NAME>, <NAME>, <NAME> # <NAME>, <NAME>, <NAME> ###################################################################################### # # Sample command line arguments to run program: # # python hmm.py -L lengths.csv -S states.cvs -O obs.csv -T truth.csv -A viterbi # # or if running without truth data: # python hmm.py -L lengths.csv -S states.cvs -O obs.csv -W output.csv -A viterbi # # -L specifies lengths file to be trained on # -S specifies states file to be trained on # -O specifies observation file to run algorithm on # -T specifies the truth data to check the algorithm against # -A specifies the algorithm to run # -B specifies the bins to use for observations # # -W specifies the file to write the output to if running without truth data # ###################################################################################### # # References: <NAME> 2016 # alexokeson_hw1.py # Formatting of the header comment # ###################################################################################### import os, sys, getopt, operator import numpy as np from sklearn.metrics import f1_score, classification_report, confusion_matrix ###################################################################################### # Print Usage Function # Prints proper way to use program when arguments are incorrect # # Returns None # ###################################################################################### def print_usage(): print 'hmm.py -L <training lengths file> -S <training states file> -O <observations file> -T <truth states> -A <algorithm> -B <bins>' return ###################################################################################### # Handle Args Function # Takes command line arguments and returns the correctly populated variables # Prints out usage if incorrectly formatted # # Returns the file name # ###################################################################################### def handle_args(argv): try: opts, args = getopt.getopt(argv,"hO:o:T:t:A:a:S:s:L:l:B:b:W:w") except getopt.GetoptError: print_usage() sys.exit(0) if len(opts) != 6: print('Invalid number of arguments') print('Expected 6 arguments, got {0}'.format(len(opts))) print_usage() sys.exit(0) training_lengths_file = None training_states_file = None observations_file = None truth_states_file = None output_file = None algorithm = None bins = None for opt, arg in opts: if opt == '-h': print_usage() sys.exit() elif opt in ("-L", "-l"): training_lengths_file = arg elif opt in ("-S", "-s"): training_states_file = arg elif opt in ("-O", "-o"): observations_file = arg elif opt in ("-T", "-t"): truth_states_file = arg elif opt in ("-A", "-a"): algorithm = arg elif opt in ("-W", "-w"): output_file = arg elif opt in ("-B", "-b"): bins = arg.split(',') bins = [float(i) for i in bins] else: print("Unknown argument option: {0}".format(opt)) print_usage() exit(0) files = {} files['training_lengths'] = training_lengths_file files['training_states'] = training_states_file files['observations'] = observations_file files['truth_states'] = truth_states_file files['output'] = output_file return files,algorithm,bins ###################################################################################### # Print Menu Options Function # Prints menu options # # Returns None # ###################################################################################### def print_menu_options(): print "HMM Microtubule Analysis" print "0: Exit" print "1: Train" print "2: Viterbi" print "3: Forwards/Backwards" return ###################################################################################### # Bin Function # Given some float, will return a binned float in the set of bins currently in use # # Returns binned float # ###################################################################################### def bin(value,bin_list): bins = bin_list best = 999999 dist = 999999 for i in range(len(bins)): new = abs(bins[i] - value) if(abs(new) < dist): best = bins[i] dist = abs(new) #print str(value) + " -> " + str(best) return best ###################################################################################### # Train HMM Function # Train hmm on data file # # Returns training probabilities # ###################################################################################### def do_train(flengths, fstates, bin_list): print "Starting training..." pair_list = [] length_matrix = [] state_matrix = [] length_height = 0 state_height = 0 print "Parsing file..." with open(flengths, 'r') as lengths: with open(fstates, 'r') as states: for line in lengths: length_height += 1 length_matrix.append((line.rstrip()).split(',')) for line in states: state_height += 1 state_matrix.append((line.rstrip()).split(',')) if length_height != state_height or len(length_matrix[0]) != len(state_matrix[0]): print "matrices not same size" exit(0) for i in range(length_height): pair_list.append((-99999.,-99999)) # using -999 as start state/value for j in range(len(length_matrix[0])-1): #print pair_list newlength = bin(float(length_matrix[i][j+1]) - float(length_matrix[i][j]),bin_list) #get diff of lengths and bin #print(float(length_matrix[i][j+1]) - float(length_matrix[i][j])) #get diff of lengths and bin # no .1 are being set here pair_list.append((newlength,state_matrix[i][j])) pair_list.append((99999.,99999)) # using 999 as end state/value print "Done parsing..." transition_prob = {} emission_prob = {} transition_prob_fwdbkw = {} start_prob = {} state_data = {} length_data = {} state_count = {} #contains count of each state states_set = set() lengths_set = set() print "Storing occurences of states in dictionary... " for length, state in pair_list: if state not in state_count.keys(): stateCount = 0 for length1, state1 in pair_list: if state == state1: stateCount += 1 state_count[state] = stateCount states_set.add(state) lengths_set.add(length) print "Creating starting probabilities... " for state in states_set: if state == -99999: start_prob[state] = 1 else: start_prob[state] = 0 print "Creating dictionaries..." for state in states_set: if state not in state_data.keys(): state_data[state] = {} transition_prob[state] = {} for state1 in states_set: if state1 not in state_data[state] and state1 not in transition_prob[state]: #if state combination does not exist state_data[state][state1] = 0 transition_prob[state][state1] = 0 for length in lengths_set: #if state not in length_data.keys() and state not in emission_prob.keys(): length_data[length] = {} #emission_prob[state] = {} for state in states_set: # if length not in length_data[length] and state not in emission_prob[state]: emission_prob[state] = {} length_data[length][state] = 0 emission_prob[state][length] = 0 print "Appending values to dictionaries... " for length, state in pair_list: length_data[length][state]+=1 for x in range(0, len(pair_list)): if x == len(pair_list) -1: break first_state = pair_list[x][1] second_state = pair_list[x+1][1] state_data[first_state][second_state] +=1 print "Storing emission and transition probabilities... " for state in states_set: for state1 in states_set: #if transition_prob[tag1][tag] == 0: transition_prob[state1][state] = float(state_data[state1][state])/float(state_count[state]) for length in lengths_set: for state in states_set: #if emission_prob[tag][word] == 0: emission_prob[state][length] = float(length_data[length][state])/float(state_count[state]) training = {} training['states'] = states_set training['starts'] = start_prob training['transitions'] = transition_prob training['emissions'] = emission_prob return training #returns a dictionary with set of states, and the start, transition and emission probabilities ###################################################################################### # Train HMM Function # Setup for training hmm # # Returns training probabilities # ###################################################################################### def train_hmm(): input_file = raw_input("Input lengths file to use for training: ") raw_input("Press enter to continue...") if not os.path.isfile(input_file): print "File must exist" sys.exit(2) input_file2 = raw_input("Input states file to use for training: ") raw_input("Press enter to continue...") if not os.path.isfile(input_file2): print "File must exist" sys.exit(2) return do_train(input_file,input_file2) ###################################################################################### # Train HMM Function # Set up from running viterbi # # Returns total accuracy and f scores # ###################################################################################### def run_viterbi(observations_file,truth_file,training,bin_list,output_file): print("\nRunning Viterbi...") # Open observation and truth data files # Find diffences between previous values for obs # Put into bins obs = [] with open(observations_file, 'r') as observations: for line in observations: obs_raw = line.split(',') obs_diff = [] obs_diff.append(0) for i in range(1,len(obs_raw)): obs_diff.append(bin(float(obs_raw[i])-float(obs_raw[i-1]),bin_list)) obs.append(obs_diff) truth = [] if truth_file: with open(truth_file, 'r') as truth_data: for line in truth_data: truth_raw = line.split(',') truth.append([float(i) for i in truth_raw]) # Feed each list of observations and truth data into viterbi # Do metrics calculations total_results = [] total_truth = [] for i in range(len(obs)): print("Running line {0} of {1} in observation file...".format(i,len(obs))) results = viterbi(obs[i],training['states'],training['starts'],training['transitions'],training['emissions']) newresults = [] for result in results[1:len(results)-1]: newresults.append(float(result)) if truth: calculate_metrics(newresults, truth[i][:len(truth[i])-1]) total_truth = total_truth + truth[i][:len(truth[i])-1] total_results = total_results + newresults else: with open(output_file,'a') as output: for item in newresults: output.write("%s," % item) output.write('\n') # Calculate total metric of viterbi print("Calculating total accuracy...") accuracy = None f1_macro = None f1_weighted = None if total_truth: accuracy,f1_macro,f1_weighted = calculate_metrics(total_results, total_truth) return accuracy, f1_macro,f1_weighted ###################################################################################### # Train HMM Function # Set up for running forward backward # # NOT CURRENTLY WORKING # # Returns training probabilities # ###################################################################################### def run_fwd_bkw(observations_file,truth_file,training): print("\nRunning Forward Backward...") # Open observation and truth data files # Find diffences between previous values for obs # Put into bins obs = [] with open(observations_file, 'r') as observations: for line in observations: obs_raw = line.split(',') obs_diff = [] obs_diff.append(0) for i in range(1,len(obs_raw)): obs_diff.append(bin(float(obs_raw[i])-float(obs_raw[i-1]))) obs.append(obs_diff) truth = [] with open(truth_file, 'r') as truth_data: for line in truth_data: truth_raw = line.split(',') truth.append([float(i) for i in truth_raw]) # Feed each list of observations and truth data into viterbi # Do metrics calculations total_results = [] total_truth = [] end_state = 99999 for i in range(len(obs)): print("Running line {0} of {1} in observation file...".format(i,len(obs))) results = fwd_bkw(obs[i],training['states'],training['starts'],training['transitions'],training['emissions'], end_state) newresults = [] for result in results[1:len(results)-1]: newresults.append(float(result)) calculate_metrics(newresults, truth[i][:len(truth[i])-1]) total_results = total_results + newresults total_truth = total_truth + truth[i][:len(truth[i])-1] # Calculate total metric of viterbi print("Calculating total accuracy...") #print total_results #print total_truth calculate_metrics(total_results, total_truth) return ###################################################################################### #dptable function, used for printing dictionary ###################################################################################### def dptable(V): # Print a table of steps from dictionary yield " ".join(("%12d" % i) for i in range(len(V))) for state in V[0]: yield "%.7s: " % state + " ".join("%.7s" % ("%f" % v[state]["prob"]) for v in V) ###################################################################################### # Viterbi Function # Source: https://en.wikipedia.org/wiki/Viterbi_algorithm # Runs viterbi using previously calculated probabilities # Prints out accuracy calculations # # Returns list of predicted states # ###################################################################################### def viterbi(obs, states, start_p, trans_p, emit_p): #stat_p, trans_p and emit_p all are dictionaries returnList = [] V = [{}] #V is a list of dictionaries, each of the dictionaries is a time which has a dictionary of states #print start_p #print trans_p #print emit_p obs = [-99999.] + obs[1:] + [99999.] #print obs #print obs[0] #Calculate V0, x for all states x, where 0 is time for st in states: #index = 0 #if obs[0] in emit_p[st]: # index = emit_p[st][obs[0]] V[0][st] = {"prob": start_p[st], "prev": None}# * emit_p[st][obs[0]], "prev": None} #print emit_p[st][obs[0]] #emit_p is pr(evidence | state), first dictionary contains key "prob" = start_pr for the state * emp_p for the state and "prev" none #obs is evidence at each time #obs[0] is Normal #V[0][st] = {"prob": start_p[st] * index, "prev": None} # Run Viterbi when t > 0 #print v[0][st] results in for t in range(1, len(obs)): #loop through all observations, starting at second one, already looked at normal above V.append({}) #append dictionary to V for st in states: #v[t-1][prev_st]["prob"] is probability of being in prev_st at t-1 #calculate previous time through loop #trans_p[prev_st][st] is transition probabilities max_prob = max(V[t-1][prev_st]["prob"]*trans_p[prev_st][st]*emit_p[st][obs[t]] for prev_st in states) # #print V[0] for prev_st in states: #incorporating evidence if V[t-1][prev_st]["prob"] * trans_p[prev_st][st] * emit_p[st][obs[t]] == max_prob: #emit_p[st][obs[t]] is emission probability of seeing observation in this state #obst[t] is observation at time t #print "emission prob: " + emit_p[st] #print "obs: " + obs[t] #print(t) #print(emit_p[st][obs[t]]) #print V[t] #max_prob = max_tr_prob * emit_p[st][obs[t]] #store V for time t in state st V[t][st] = {"prob": max_prob, "prev": prev_st} break #print t #print V[t] for line in dptable(V): #print line pass opt = [] # The highest probability #print V[-1].values() max_prob = max(value["prob"] for value in V[-1].values()) previous = None # Get most probable state and its backtrack for st, data in V[-1].items(): #print st, data if data["prob"] == max_prob: opt.append(st) previous = st break # Follow the backtrack till the first observation for t in range(len(V) - 2, -1, -1): opt.insert(0, V[t + 1][previous]["prev"]) previous = V[t + 1][previous]["prev"] returnList.append(str(opt)) #print 'The steps of states are ' + ' '.join(str(opt)) + ' with highest probability of %s' % float(max_prob) return opt #returnList ###################################################################################### # Forward/Backward Algorithm # Source: https://en.wikipedia.org/wiki/Forward-backward_algorithm # # NOT CURRENTLY WORKING! # # ###################################################################################### def fwd_bkw(observations, states, start_prob, trans_prob, emm_prob, end_st): # forward part of the algorithm fwd = [] f_prev = {} for i, observation_i in enumerate(observations): f_curr = {} for st in states: if i == 0: # base case for the forward part prev_f_sum = start_prob[st] else: prev_f_sum = sum(f_prev[k]*trans_prob[k][st] for k in states) f_curr[st] = emm_prob[st][observation_i] * prev_f_sum fwd.append(f_curr) f_prev = f_curr p_fwd = sum(f_curr[k] * trans_prob[k][end_st] for k in states) # backward part of the algorithm bkw = [] b_prev = {} for i, observation_i_plus in enumerate(reversed(observations[1:]+(None,))): b_curr = {} for st in states: if i == 0: # base case for backward part b_curr[st] = trans_prob[st][end_st] else: b_curr[st] = sum(trans_prob[st][l] * emm_prob[l][observation_i_plus] * b_prev[l] for l in states) bkw.insert(0,b_curr) b_prev = b_curr p_bkw = sum(start_prob[l] * emm_prob[l][observations[0]] * b_curr[l] for l in states) # merging the two parts posterior = [] for i in range(len(observations)): posterior.append({st: fwd[i][st] * bkw[i][st] / p_fwd for st in states}) assert p_fwd == p_bkw #return fwd, bkw, posterior return posterior ###################################################################################### # Calculate Metrics Function # Calculate the metrics of how well the the results match the truth data # # Returns accuracy and f1 scores # ######################################################################################s def calculate_metrics(results, truth_data): if len(results) != len(truth_data): print("Different lengths of results and truth data!") print("Results Length: {0}\t Truth Data Length: {1}".format(len(results),len(truth_data))) return results_len = len(results) # Calculate Accuracy correct = 0.0 for i in range(results_len): if results[i] == truth_data[i]: correct += 1 accuracy = float(correct)/float(results_len) print("Overall Accuracy:\t{0}".format(accuracy)) # Calculate f-measure f1_macro = f1_score(truth_data, results, average='macro') f1_weighted = f1_score(truth_data, results, average='weighted') print("F-measure macro:\t{0}".format(f1_macro)) print("F-measure weighred:\t{0}".format(f1_weighted)) # Classification report report = classification_report(truth_data, results, digits=4) print("Report:\n{0}".format(report)) # Confusion matrix matrix = confusion_matrix(truth_data,results) print("Confusion Matrix:") print(matrix) print("\nFinished results!") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") return accuracy, f1_macro, f1_weighted ###################################################################################### # Main Function # Calls functions to handle arguments, read in the sequences, and calculate alignments # and then with found distance matrix caculates tree using UPGMA # # Returns None # ###################################################################################### def main(argv): print("\n=== Program for using a hiddon markov model to do microtubule analysis ===\n") # Get command line arguments files,algo,bins = handle_args(argv) print("Training Lengths File:\t{0}".format(files['training_lengths'])) print("Training States File:\t{0}".format(files['training_states'])) print("Observations_file:\t{0}".format(files['observations'])) print("Truth States File:\t{0}".format(files['truth_states'])) print("Output File:\t{0}".format(files['output'])) print("Algorithm:\t\t{0}".format(algo)) print training = do_train(files['training_lengths'],files['training_states'],bins) run_viterbi(files['observations'],files['truth_states'],training,bins,files['output']) ###run_fwd_bkw(files['observations'],files['truth_states'],training) return ###################################################################################### # Call of main function starting the program # ###################################################################################### if __name__ == "__main__": main(sys.argv[1:])
2501a09693cd0063330eaba63828825b4111eb36
[ "Markdown", "Python", "Shell" ]
9
Shell
ABahirat/Microtubule-Analysis
731efbedff80126edca011def1b900acaa4ad571
9c44dcc022905450c6cf608c35cf9c48533e8595
refs/heads/master
<file_sep>const { Heatmap } = G2Plot; // REQUIRED: import from G2Plot const heatmap_data = [ { name: '4', year: 'A', rain: 0 }, { name: '4', year: 'B', rain: 80 }, { name: '4', year: 'C', rain: 80 }, { name: '4', year: 'D', rain: 80 }, { name: '5', year: 'A', rain: 80 }, { name: '5', year: 'B', rain: 10 }, { name: '5', year: 'C', rain: 80 }, { name: '5', year: 'D', rain: 80 }, { name: '6', year: 'A', rain: 30 }, { name: '6', year: 'B', rain: 100 }, { name: '6', year: 'C', rain: 60 }, { name: '6', year: 'D', rain: 60 }, { name: '7', year: 'A', rain: 100 }, { name: '7', year: 'B', rain: 80 }, { name: '7', year: 'C', rain: 60 }, { name: '7', year: 'D', rain: 80 }, { name: '8', year: 'A', rain: 100 }, { name: '8', year: 'B', rain: 10 }, { name: '8', year: 'C', rain: 80 }, { name: '8', year: 'D', rain: 10 }, { name: '9', year: 'A', rain: 60 }, { name: '9', year: 'B', rain: 80 }, { name: '9', year: 'C', rain: 60 }, { name: '9', year: 'D', rain: 30 }, { name: '10', year: 'A', rain: 80 }, { name: '10', year: 'B', rain: 10 }, { name: '10', year: 'C', rain: 10 }, { name: '10', year: 'D', rain: 80 }, ]; const heatmap = new Heatmap('heatmap', { height: 200, width: 200, autoFit: false, data: heatmap_data, isStack: true, padding: 20, xField: 'year', yField: 'name', colorField: 'rain', color: ['#436FD4', '#5B8FF9', '#87B3FF', '#B0D0FF', '#D9E9FF'], label: null, legend: false, areaStyle: { fillOpacity: 0.7, }, heatmapStyle: { stroke: '#fff', lineWidth: 4, }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); heatmap.render(); <file_sep>import * as path from 'path'; import { CHART_ID_OPTIONS, ChartID } from '@antv/ckb'; import * as fse from 'fs-extra'; import * as inquirer from 'inquirer'; import { SVG_DIR, CHART_TS_DIR, THUMBNAILS_TS_PATH } from './consts'; import { ensureAndResetDir, idToName, pureFileName } from './utils'; interface ChartInfo { chartId: string; chartName: string; svgCode: string; } interface Params { chartTsDir: string; thumbnailsTsPath: string; svgDir: string; strict: boolean; } /** * Template of a chart file. * * chartId.toUpperCase(): variable name must be in lowerCamelCase, PascalCase or UPPER_CASE */ const fileTemplate = ({ chartId, chartName, svgCode }: ChartInfo) => `// ${chartId} import { ChartImageInfo } from '../../interfaces'; const ${chartId.toUpperCase()}: ChartImageInfo = { id: '${chartId}', name: '${chartName}', svgCode: '${svgCode}', }; export default ${chartId.toUpperCase()}; `; /** * Template of `thumbnails.ts` file * * @param chartFiles */ const thumbnailsTemplate = (chartFiles: string[]) => `// generated file thumbnails.ts import { ChartImageInfo } from '../interfaces'; ${chartFiles.map((file: string) => `import ${file.toUpperCase()} from './charts/${file}';`).join('\n')} const Thumbnails: Partial<Record<string, ChartImageInfo>> = { ${chartFiles.map((file: string) => ` ${file}: ${file.toUpperCase()}`).join(',\n')}, }; export default Thumbnails; export const THUMBNAIL_IDS = [${chartFiles.map((file) => `'${file}'`).join(', ')}] as const; export type ThumbnailID = typeof THUMBNAIL_IDS[number]; export function isThumbnailID(id: string): id is ThumbnailID { return THUMBNAIL_IDS.includes(id as ThumbnailID); } export { ${chartFiles.map((file: string) => ` ${file.toUpperCase()}`).join(',\n')}, }; `; /** * Extract svg images, optimize svg codes and then generate corresponding ts file. * * @param Params.chartTsDir directory for exporting ts files for charts. * @param Params.thumbnailsTsPath path for exporting thumbnails.ts. * @param Params.svgDir directory of svg files. * @param Params.strict whether allow chart ids outside AVA CKB. Default false. */ const generateTsFiles = async ({ chartTsDir, thumbnailsTsPath, svgDir, strict }: Params) => { // get all charts const validFiles: string[] = []; const questions: inquirer.Question[] = []; const notices: string[] = []; const svgDirExists = await fse.pathExists(svgDir); if (!svgDirExists) return; const svgFiles = await fse.readdir(svgDir); if (!svgFiles || svgFiles.length === 0) return; svgFiles.forEach((file) => { const fileExtName = path.extname(file); const fileName = path.basename(file, fileExtName); if (fileExtName !== '.svg') { notices.push(`WARN: File ${file} is not with .svg and it has been ignored.`); } else if (CHART_ID_OPTIONS.includes(fileName as ChartID)) { // `file` should be a ChartID validFiles.push(file); } else { questions.push({ default: false, message: `The name of file ${file} is not a ChartID. Still want to add it?`, name: file, type: 'confirm', }); } }); notices.forEach((notice) => console.log(notice)); if (strict) { questions.forEach(({ name }) => console.log(`The name of file ${name} is not a ChartID. It has been ignored.`)); } else { await inquirer.prompt(questions).then(async (answers) => { await Promise.all( Object.keys(answers).map(async (file) => { if (answers[file]) { validFiles.push(file); } }) ); }); } // clear charts await ensureAndResetDir(chartTsDir); // generate ts files await Promise.all( validFiles.map(async (svgFile) => { const fileExtName = path.extname(svgFile); const fileName = path.basename(svgFile, fileExtName); const svgFilePath = path.join(process.cwd(), svgDir, svgFile); const svgCode = await fse.readFile(svgFilePath as string, { encoding: 'utf8' }); const tsFilePath = path.join(process.cwd(), chartTsDir, `${fileName}.ts`); await fse.writeFile(tsFilePath, fileTemplate({ chartId: fileName, chartName: idToName(fileName), svgCode })); }) ); // update thumbnails.ts await fse.writeFile(thumbnailsTsPath, thumbnailsTemplate(validFiles.map((file) => pureFileName(file)).sort())); }; // exe script (async () => { const myArgs = process.argv.slice(2); const isStrictMode = myArgs.length > 0 && myArgs[0] === 'strict'; await generateTsFiles({ chartTsDir: CHART_TS_DIR, thumbnailsTsPath: THUMBNAILS_TS_PATH, svgDir: SVG_DIR, strict: isStrictMode, }); console.log('extract svg done!'); })(); <file_sep>describe('init test', () => { test('temp', () => { expect(1).toBe(1); }); }); <file_sep>const { Area } = G2Plot; // REQUIRED: import from G2Plot const area_data = [ { year: 2016, value: 150 }, { year: 2017, value: 90 }, { year: 2018, value: 180 }, { year: 2019, value: 170 }, { year: 2020, value: 240 }, ]; const area = new Area('area_chart', { height: 200, width: 200, autoFit: false, data: area_data, xField: 'year', yField: 'value', padding: [10, 20, 20, 40], xAxis: { range: [0, 1], label: { style: { fontSize: 12, }, offset: 4, }, }, yAxis: { tickInterval: 100, label: { style: { fontSize: 12, }, }, }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); area.render(); <file_sep>import Thumbnails from './generated/thumbnails'; export default Thumbnails; export * from './generated/thumbnails'; <file_sep>const { Area: StackedArea } = G2Plot; // REQUIRED: import from G2Plot const stacked_area_data = [ { name: 'London', year: '2016', rain: 65 }, { name: 'London', year: '2017', rain: 57 }, { name: 'London', year: '2018', rain: 90 }, { name: 'London', year: '2019', rain: 85 }, { name: 'London', year: '2020', rain: 120 }, { name: 'Berlin', year: '2016', rain: 80 }, { name: 'Berlin', year: '2017', rain: 45 }, { name: 'Berlin', year: '2018', rain: 90 }, { name: 'Berlin', year: '2019', rain: 85 }, { name: 'Berlin', year: '2020', rain: 120 }, ]; const stackedArea = new StackedArea('stacked_area_chart', { height: 200, width: 200, autoFit: false, data: stacked_area_data, isStack: true, xField: 'year', yField: 'rain', seriesField: 'name', label: null, legend: false, color: chartColors, xAxis: { range: [0, 1], }, areaStyle: { fillOpacity: 0.3, }, yAxis: { max: 300, tickCount: 3, }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); stackedArea.render(); <file_sep>const { Area: PercentStackedArea } = G2Plot; // REQUIRED: import from G2Plot const percent_stacked_area_data = [ { country: 'Europe', year: '2016', value: 35 }, { country: 'Europe', year: '2017', value: 52 }, { country: 'Europe', year: '2018', value: 30 }, { country: 'Europe', year: '2019', value: 40 }, { country: 'Europe', year: '2020', value: 10 }, { country: 'Africa', year: '2016', value: 39 }, { country: 'Africa', year: '2017', value: 24 }, { country: 'Africa', year: '2018', value: 25 }, { country: 'Africa', year: '2019', value: 20 }, { country: 'Africa', year: '2020', value: 40 }, { country: 'Asia', year: '2016', value: 26 }, { country: 'Asia', year: '2017', value: 24 }, { country: 'Asia', year: '2018', value: 45 }, { country: 'Asia', year: '2019', value: 40 }, { country: 'Asia', year: '2020', value: 50 }, ]; const percentStackedArea = new PercentStackedArea('percent_stacked_area_chart', { height: 200, width: 200, autoFit: false, data: percent_stacked_area_data, color: chartColors, xField: 'year', yField: 'value', seriesField: 'country', areaStyle: { fillOpacity: 0.3, }, padding: [10, 20, 24, 40], isPercent: true, startOnZero: true, xAxis: { range: [0, 1], }, yAxis: { label: { formatter: (value) => { return `${value * 100}%`; }, }, tickCount: 3, }, legend: false, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); percentStackedArea.render(); <file_sep>const { Histogram } = G2Plot; // REQUIRED: import from G2Plot const histogram_data = [ { value: 2 }, { value: 2 }, { value: 3 }, { value: 3 }, { value: 3 }, { value: 4 }, { value: 4 }, { value: 4 }, { value: 4 }, { value: 5 }, { value: 5 }, { value: 5 }, { value: 5 }, { value: 5 }, { value: 5 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 6 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 7 }, { value: 8 }, { value: 8 }, { value: 8 }, { value: 9 }, ]; const histogram = new Histogram('histogram', { height: 200, width: 200, autoFit: false, data: histogram_data, binField: 'value', binWidth: 1, yAxis: { min: 0, max: 12, tickCount: 3 }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); histogram.render(); <file_sep>import rollupConfig from '../../rollup.config'; export default rollupConfig('ts', { input: './src/index.ts', output: { name: 'Thumbnails', }, }); <file_sep>import * as path from 'path'; import { CHART_ID_OPTIONS, ChartID } from '@antv/ckb'; import * as fse from 'fs-extra'; import { GITHUB_IMAGE_PATH_PREFIX, SVG_DIR } from './consts'; const START_SIGN = '<!-- PREVIEW START -->'; const END_SIGN = '<!-- PREVIEW END -->'; /** * Template for images in README. */ const genPreviewHTML = (fileNames: string[]) => ` <div style="display: flex; flex-flow: row wrap;"> ${fileNames .map((file: string) => ` <kbd><img src="${GITHUB_IMAGE_PATH_PREFIX}${file}" width="200" height="200"></kbd>`) .join('\n')} </div> `; /** * Update all svg thumbnails in README. */ const updateReadmePreview = async () => { const README = 'README.md'; const readmePath = path.join(process.cwd(), README); const readmeContent = await fse.readFile(readmePath, { encoding: 'utf8' }); const lines = readmeContent.split('\n'); const files = await fse.readdir(SVG_DIR); const validFiles = files.filter((f) => CHART_ID_OPTIONS.includes(path.basename(f, path.extname(f)) as ChartID)); const previewContent = genPreviewHTML(validFiles); const previewLines = previewContent.split('\n'); let startSignIndex: number; let endSignIndex: number; for (let i = 0; i < lines.length; i += 1) { if (lines[i] === START_SIGN) { startSignIndex = i; } if (lines[i] === END_SIGN) { endSignIndex = i; break; } } if (startSignIndex && endSignIndex) { lines.splice(startSignIndex + 1, endSignIndex - startSignIndex - 1, ...previewLines); const newReadmeContent = lines.join('\n'); await fse.writeFile(readmePath, newReadmeContent); } }; (async () => { await updateReadmePreview(); })(); <file_sep>const { Pie: DonutPie } = G2Plot; // REQUIRED: import from G2Plot const donut_pie_data = [ { type: 'A', value: 27 }, { type: 'B', value: 36 }, { type: 'C', value: 12 }, ]; const donutPie = new DonutPie('donut_chart', { height: 200, width: 200, autoFit: false, padding: 20, data: donut_pie_data, angleField: 'value', colorField: 'type', radius: 1, innerRadius: 0.6, color: chartColors, label: { type: 'inner', offset: '-50%', content: '{name}', autoRotate: false, style: { textAlign: 'center', fontSize: 14, }, }, legend: false, statistic: { title: false, content: { formatter: () => '', }, }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); donutPie.render(); <file_sep>import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import typescript from '@rollup/plugin-typescript'; import { terser } from 'rollup-plugin-terser'; export default (type, options) => { const configs = { input: options.input, output: { file: './dist/index.min.js', format: 'umd', sourcemap: false, ...options.output, }, plugins: [resolve(), commonjs(), typescript(), terser()], }; if (type === 'react') { configs.external = ['react', 'react-dom']; } return configs; }; <file_sep># AntV/Thumbnails Thumbnail images for different chart types from [CKB](https://github.com/antvis/AVA/tree/master/packages/knowledge). <!-- THE PREVIEW PARTS BELOW ARE GENERATED BY SCRIPTS. DON'T TOUCH! --> <!-- PREVIEW START --> <div style="display: flex; flex-flow: row wrap;"> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/area_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/bar_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/bubble_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/column_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/donut_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/grouped_bar_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/grouped_column_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/heatmap.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/histogram.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/line_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/percent_stacked_area_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/percent_stacked_bar_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/percent_stacked_column_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/pie_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/radar_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/scatter_plot.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/stacked_area_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/stacked_bar_chart.svg" width="200" height="200"></kbd> <kbd><img src="https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/stacked_column_chart.svg" width="200" height="200"></kbd> </div> <!-- PREVIEW END --> ## Usage ### Use as Data in Object ```ts import Thumbnails from '@antv/thumbnails'; if (Thumbnails.pie_chart) { const { id, name, svgCode } = Thumbnails.pie_chart; console.log(id, name, svgCode); } }); ``` ```ts import { BAR_CHART } from '@antv/thumbnails'; const { id, name, svgCode } = BAR_CHART; console.log(id, name, svgCode); ``` The ChartIDs are listed in: [AVA/CKB](https://github.com/antvis/AVA/blob/master/packages/knowledge/src/chartID.ts). ### Use as React Component ```tsx import Thumbnails, { Thumbnail, PIE_CHART } from '@antv/thumbnails'; // Thumbnail is the React Component // ... // define a chart id from 'AVA/CKB' <Thumbnail chart={'pie_chart'} /> // get the svg code from Thumbnails object <Thumbnail svg={Thumbnails.pie_chart.svgCode} /> // get the svg code from specific chart thumbnail object <Thumbnail svg={PIE_CHART.svgCode} /> // with other img HTML attributes <Thumbnail chart={'pie_chart'} alt={'pie'} width={80} /> ``` For example: ```tsx import * as React from 'react'; import Thumbnails, { Thumbnail } from '@antv/thumbnails'; class App extends React.Component<{}> { constructor(props: {}) { super(props); } public render() { return ( <div className="symbols"> {Object.keys(Thumbnails).map((chart) => { const { svgCode, name } = Thumbnails[chart]; return ( <div className="symbol-img-container"> <Thumbnail svg={svgCode} alt={name} width={200} /> </div> ); })} </div> ); } } export default App; ``` ## Development Run this command to setup all: ```bash npm run one-stop-setup ``` Run this command and then visit <http://localhost:8299/>. ```bash npm run start:demo ``` If you can see the demo page well, it means that all setups have been successfully completed. <file_sep>// generated file thumbnails.ts import { ChartImageInfo } from '../interfaces'; import AREA_CHART from './charts/area_chart'; import BAR_CHART from './charts/bar_chart'; import BUBBLE_CHART from './charts/bubble_chart'; import COLUMN_CHART from './charts/column_chart'; import DONUT_CHART from './charts/donut_chart'; import GROUPED_BAR_CHART from './charts/grouped_bar_chart'; import GROUPED_COLUMN_CHART from './charts/grouped_column_chart'; import HEATMAP from './charts/heatmap'; import HISTOGRAM from './charts/histogram'; import LINE_CHART from './charts/line_chart'; import PERCENT_STACKED_AREA_CHART from './charts/percent_stacked_area_chart'; import PERCENT_STACKED_BAR_CHART from './charts/percent_stacked_bar_chart'; import PERCENT_STACKED_COLUMN_CHART from './charts/percent_stacked_column_chart'; import PIE_CHART from './charts/pie_chart'; import RADAR_CHART from './charts/radar_chart'; import SCATTER_PLOT from './charts/scatter_plot'; import STACKED_AREA_CHART from './charts/stacked_area_chart'; import STACKED_BAR_CHART from './charts/stacked_bar_chart'; import STACKED_COLUMN_CHART from './charts/stacked_column_chart'; import STEP_LINE_CHART from './charts/step_line_chart'; const Thumbnails: Partial<Record<string, ChartImageInfo>> = { area_chart: AREA_CHART, bar_chart: BAR_CHART, bubble_chart: BUBBLE_CHART, column_chart: COLUMN_CHART, donut_chart: DONUT_CHART, grouped_bar_chart: GROUPED_BAR_CHART, grouped_column_chart: GROUPED_COLUMN_CHART, heatmap: HEATMAP, histogram: HISTOGRAM, line_chart: LINE_CHART, percent_stacked_area_chart: PERCENT_STACKED_AREA_CHART, percent_stacked_bar_chart: PERCENT_STACKED_BAR_CHART, percent_stacked_column_chart: PERCENT_STACKED_COLUMN_CHART, pie_chart: PIE_CHART, radar_chart: RADAR_CHART, scatter_plot: SCATTER_PLOT, stacked_area_chart: STACKED_AREA_CHART, stacked_bar_chart: STACKED_BAR_CHART, stacked_column_chart: STACKED_COLUMN_CHART, step_line_chart: STEP_LINE_CHART, }; export default Thumbnails; export const THUMBNAIL_IDS = [ 'area_chart', 'bar_chart', 'bubble_chart', 'column_chart', 'donut_chart', 'grouped_bar_chart', 'grouped_column_chart', 'heatmap', 'histogram', 'line_chart', 'percent_stacked_area_chart', 'percent_stacked_bar_chart', 'percent_stacked_column_chart', 'pie_chart', 'radar_chart', 'scatter_plot', 'stacked_area_chart', 'stacked_bar_chart', 'stacked_column_chart', 'step_line_chart', ] as const; export type ThumbnailID = typeof THUMBNAIL_IDS[number]; export function isThumbnailID(id: string): id is ThumbnailID { return THUMBNAIL_IDS.includes(id as ThumbnailID); } export { AREA_CHART, BAR_CHART, BUBBLE_CHART, COLUMN_CHART, DONUT_CHART, GROUPED_BAR_CHART, GROUPED_COLUMN_CHART, HEATMAP, HISTOGRAM, LINE_CHART, PERCENT_STACKED_AREA_CHART, PERCENT_STACKED_BAR_CHART, PERCENT_STACKED_COLUMN_CHART, PIE_CHART, RADAR_CHART, SCATTER_PLOT, STACKED_AREA_CHART, STACKED_BAR_CHART, STACKED_COLUMN_CHART, STEP_LINE_CHART, }; <file_sep>const { Scatter: BubbleScatter } = G2Plot; // REQUIRED: import from G2Plot const bubbleMap = { A: 0, B: 1, C: 2, D: 3, E: 4, F: 5, G: 6, }; const bubble_scatter_data = [ { HA: 'A', Team: 'Torino', xGconceded: 5.3, Shotconceded: 200, Result: 17 }, { HA: 'B', Team: 'Atalanta', xGconceded: 4.2, Shotconceded: 100, Result: 50 }, { HA: 'C', Team: 'Milan', xGconceded: 7.4, Shotconceded: 220, Result: 50 }, { HA: 'D', Team: 'Chievo', xGconceded: 7.4, Shotconceded: 100, Result: 50 }, { HA: 'E', Team: 'Bologna', xGconceded: 3.7, Shotconceded: 230, Result: 25 }, { HA: 'F', Team: 'Frosinone', xGconceded: 6.4, Shotconceded: 160, Result: 10 }, { HA: 'G', Team: 'Lazio', xGconceded: 5.5, Shotconceded: 160, Result: 15 }, ]; const bubbleScatterPlot = new BubbleScatter('bubble_chart', { height: 200, width: 200, autoFit: false, data: bubble_scatter_data, xField: 'xGconceded', yField: 'Shotconceded', colorField: 'HA', sizeField: 'Result', xAxis: { min: 2, max: 10, label: null, line: null, }, yAxis: { min: 0, max: 300, label: null, line: null, grid: null, }, size: [8, 40], shape: 'circle', color: chartColors, pointStyle: (item) => { return { fillOpacity: 0.6, stroke: chartColors[bubbleMap[item.HA]], lineWidth: 1, strokeOpacity: 1, }; }, legend: false, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); bubbleScatterPlot.render(); <file_sep>import * as path from 'path'; import * as os from 'os'; import puppeteer from 'puppeteer'; import * as fse from 'fs-extra'; import SVGO from 'svgo'; import { SVGO_SETTINGS } from './svgo-settings'; import { CODE_DIR, SVG_DIR, DEFAULT_HTMLPATH } from './consts'; import { ensureAndResetDir } from './utils'; const svgo: SVGO = new SVGO(SVGO_SETTINGS); /** * Extract svg code of each chart from headless webpage * and save these svg files to specific directory. * * @param url URL of headless webpage. * @param ids chart ids | file names under code dir. * @param svgDir path for exporting svg files. * @param screenshotPath path for saving a screenshot of the headless webpage. (optional) */ export const getSVGs = async (url: string, ids: string[], svgDir: string, screenshotPath = '') => { const browser = await puppeteer.launch(); const page = await browser.newPage(); page.setViewport({ width: 1376, height: 768, }); await page.goto(url); await page.waitForTimeout(3000); await ensureAndResetDir(svgDir); await Promise.all( ids.map(async (id) => { const svgCode = await page.evaluate((id) => document.querySelector(`#${id} svg`)?.outerHTML, id); if (svgCode) { const { data: optSvg } = await svgo.optimize(svgCode); await fse.writeFile(path.join(svgDir, `${id}.svg`), optSvg); } }) ); if (screenshotPath) { await page.screenshot({ path: screenshotPath }); } await browser.close(); }; // exe script (async () => { const chartCodeFiles = await fse.readdir(CODE_DIR); const ids = chartCodeFiles.map((file) => path.basename(file, path.extname(file))); const DESKTOP = path.join(os.homedir(), 'Desktop'); await getSVGs( `file:${path.join(process.cwd(), DEFAULT_HTMLPATH)}`, ids, SVG_DIR, path.join(DESKTOP, 'thumbPage.png') ); })(); <file_sep>// bubble_chart import { ChartImageInfo } from '../../interfaces'; const BUBBLE_CHART: ChartImageInfo = { id: 'bubble_chart', name: 'Bubble Chart', svgCode: '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" style="width:200px;height:200px;vertical-align:middle" display="inline-block"><path fill="transparent" d="M0 0h200v200H0z"/><g><g fill-opacity=".6"><path fill="#5B8FF9" stroke="#5B8FF9" d="M68.9 66.667a13.6 13.6 0 1027.2 0 13.6 13.6 0 10-27.2 0"/><path fill="#5AD8A6" stroke="#5AD8A6" d="M15 133.333a40 40 0 1080 0 40 40 0 10-80 0"/><path fill="#FF9845" stroke="#FF9845" d="M95 53.333a40 40 0 1080 0 40 40 0 10-80 0"/><path fill="#F6BD16" stroke="#F6BD16" d="M95 133.333a40 40 0 1080 0 40 40 0 10-80 0"/><path fill="#A37FDB" stroke="#A37FDB" d="M22.5 46.667a20 20 0 1040 0 20 20 0 10-40 0"/><path fill="#1E9493" stroke="#1E9493" d="M102 93.333a8 8 0 1016 0 8 8 0 10-16 0"/><path fill="#FF99C3" stroke="#FF99C3" d="M75.5 93.333a12 12 0 1024 0 12 12 0 10-24 0"/></g></g></svg>', }; export default BUBBLE_CHART; <file_sep>const { Column } = G2Plot; // REQUIRED: import from G2Plot const column_data = [ { category: 'A', value: 140 }, { category: 'B', value: 115 }, { category: 'C', value: 260 }, { category: 'D', value: 220 }, ]; const column = new Column('column_chart', { height: 200, width: 200, autoFit: false, data: column_data, xField: 'category', yField: 'value', xAxis: { label: { autoHide: true, autoRotate: false, }, }, minColumnWidth: 20, maxColumnWidth: 20, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); column.render(); <file_sep>const { Pie } = G2Plot; // REQUIRED: import from G2Plot const pie_data = [ { type: 'A', value: 35 }, { type: 'B', value: 50 }, { type: 'C', value: 15 }, ]; const pie = new Pie('pie_chart', { height: 200, width: 200, autoFit: false, data: pie_data, padding: 20, angleField: 'value', colorField: 'type', color: chartColors, label: { type: 'inner', offset: '-50%', content: '{name}', autoRotate: false, style: { textAlign: 'center', fontSize: 14, }, }, legend: false, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); pie.render(); <file_sep>import * as path from 'path'; import { CHART_ID_OPTIONS, ChartID } from '@antv/ckb'; import * as inquirer from 'inquirer'; import * as fse from 'fs-extra'; import { CODE_DIR, DEFAULT_HTMLPATH } from './consts'; import { sortObjByKey } from './utils'; interface Params { codeDir: string; htmlPath: string; strict?: boolean; } /** * Generate a HTML page that contains all chart doms by G2Plot. * * @param Params.codeDir directory of G2Plot source code templates. * @param Params.htmlPath path of the generated html file. * @param Params.strict whether allow chart ids outside AVA CKB. Default false. */ export const generateSampleHTML = async ({ codeDir, htmlPath, strict = false }: Params) => { const validFiles: string[] = []; const chartCodeMap: Record<string, string> = {}; const questions: inquirer.Question[] = []; const notices: string[] = []; // read js files of chart samples const codeDirExists = await fse.pathExists(codeDir); if (!codeDirExists) return; const chartCodeFiles = await fse.readdir(codeDir); if (!chartCodeFiles || chartCodeFiles.length === 0) return; chartCodeFiles.forEach((file) => { const fileExtName = path.extname(file); const fileName = path.basename(file, fileExtName); if (fileExtName !== '.js') { notices.push(`WARN: File ${file} is not with .js and it has been ignored.`); } else if (CHART_ID_OPTIONS.includes(fileName as ChartID)) { // The name of `file` should be a ChartID validFiles.push(file); } else { questions.push({ default: false, message: `The name of file ${file} is not a ChartID. Still want to add it?`, name: file, type: 'confirm', }); } }); notices.forEach((notice) => console.log(notice)); if (strict) { questions.forEach(({ name }) => console.log(`WARN: The name of file ${name} is not a ChartID. It has been ignored.`) ); } else { await inquirer.prompt(questions).then(async (answers) => { await Promise.all( Object.keys(answers).map(async (file) => { if (answers[file]) { validFiles.push(file); } }) ); }); } // collect: chartID - G2Plot code string await Promise.all( validFiles.map(async (file) => { const fileExtName = path.extname(file); const fileName = path.basename(file, fileExtName); const filePath = path.join(process.cwd(), codeDir, file); const result = await fse.readFile(filePath as string, { encoding: 'utf8' }); chartCodeMap[fileName] = result; }) ); const sortedChartCodeMap = sortObjByKey(chartCodeMap); // generate html file const htmlFile = `<html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Code</title> <style> .chart_wrapper { display: flex; flex-wrap: wrap; } .chart_item { margin: 15px; } </style> <script type="text/javascript" src="https://unpkg.com/@antv/g2plot@latest/dist/g2plot.min.js"></script> </head> <body> <div class="chart_wrapper"> ${Object.keys(sortedChartCodeMap) .map((chartID) => `<div id="${chartID}" class="chart_item"></div>`) .join('\n\t\t')} </div> </body> <script> document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('svg').forEach(function(svg) { svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); }); }); </script> <script> const chartColors = ['#5B8FF9', '#5AD8A6', '#FF9845', '#F6BD16', '#A37FDB', '#1E9493', '#FF99C3']; </script> ${Object.values(sortedChartCodeMap) .map((code) => `<script>${code}</script>`) .join('\n')} </html> `; await fse.ensureDir(path.dirname(htmlPath)); await fse.writeFile(htmlPath, htmlFile); }; // exe script (async () => { const myArgs = process.argv.slice(2); const isStrictMode = myArgs.length > 0 && myArgs[0] === 'strict'; await generateSampleHTML({ codeDir: CODE_DIR, htmlPath: DEFAULT_HTMLPATH, strict: isStrictMode }); console.log('Sample html page generated!'); })(); <file_sep>// CONSTANTS export const CORE_PACKAGE_DIR = 'packages/core'; export const CODE_DIR = 'packages/core/src/code/'; export const SVG_DIR = 'packages/core/src/generated/svgs/'; export const CHART_TS_DIR = 'packages/core/src/generated/charts/'; export const DEFAULT_HTMLPATH = 'packages/core/src/generated/code.html'; export const THUMBNAILS_TS_PATH = 'packages/core/src/generated/thumbnails.ts'; export const GITHUB_IMAGE_PATH_PREFIX = 'https://github.com/antvis/thumbnails/blob/master/packages/core/src/generated/svgs/'; <file_sep>const { Column: PercentStackedColumn } = G2Plot; // REQUIRED: import from G2Plot const percent_stacked_column_data = [ { country: 'Europe', year: 'A', value: 48 }, { country: 'Europe', year: 'B', value: 52 }, { country: 'Europe', year: 'C', value: 10 }, { country: 'Europe', year: 'D', value: 20 }, { country: 'Africa', year: 'A', value: 26 }, { country: 'Africa', year: 'B', value: 24 }, { country: 'Africa', year: 'C', value: 45 }, { country: 'Africa', year: 'D', value: 40 }, { country: 'Asia', year: 'A', value: 26 }, { country: 'Asia', year: 'B', value: 24 }, { country: 'Asia', year: 'C', value: 45 }, { country: 'Asia', year: 'D', value: 40 }, ]; const percentStackedColumn = new PercentStackedColumn('percent_stacked_column_chart', { height: 200, width: 200, autoFit: false, data: percent_stacked_column_data, color: chartColors, xField: 'year', yField: 'value', seriesField: 'country', maxColumnWidth: 16, isPercent: true, isStack: true, yAxis: { label: { formatter: (value) => { return `${value * 100}%`; }, }, tickCount: 3, }, legend: false, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); percentStackedColumn.render(); <file_sep>const { Bar: GroupedBar } = G2Plot; // REQUIRED: import from G2Plot const grouped_bar_data = [ { name: 'London', month: 'A', rain: 140 }, { name: 'London', month: 'B', rain: 115 }, { name: 'London', month: 'C', rain: 260 }, { name: 'London', month: 'D', rain: 220 }, { name: 'Berlin', month: 'A', rain: 160 }, { name: 'Berlin', month: 'B', rain: 150 }, { name: 'Berlin', month: 'C', rain: 290 }, { name: 'Berlin', month: 'D', rain: 260 }, ]; const groupedBar = new GroupedBar('grouped_bar_chart', { height: 200, width: 200, autoFit: false, data: grouped_bar_data, isGroup: true, xField: 'rain', yField: 'month', seriesField: 'name', label: null, legend: false, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); groupedBar.render(); <file_sep>const { Bar } = G2Plot; // REQUIRED: import from G2Plot const bar_data = [ { category: 'A', value: 140 }, { category: 'B', value: 115 }, { category: 'C', value: 260 }, { category: 'D', value: 220 }, ]; const bar = new Bar('bar_chart', { height: 200, width: 200, autoFit: false, data: bar_data, xField: 'value', yField: 'category', padding: [10, 20, 20, 20], xAxis: { tickInterval: 100, label: { style: { fontSize: 12, }, offset: 4, }, }, yAxis: { label: { style: { fontSize: 12, }, }, }, minColumnWidth: 20, maxColumnWidth: 20, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); bar.render(); <file_sep>const { Column: StackedColumn } = G2Plot; // REQUIRED: import from G2Plot const stacked_column_data = [ { name: 'London', month: 'A', rain: 80 }, { name: 'London', month: 'B', rain: 60 }, { name: 'London', month: 'C', rain: 130 }, { name: 'London', month: 'D', rain: 120 }, { name: 'Berlin', month: 'A', rain: 80 }, { name: 'Berlin', month: 'B', rain: 60 }, { name: 'Berlin', month: 'C', rain: 130 }, { name: 'Berlin', month: 'D', rain: 120 }, ]; const stackedColumn = new StackedColumn('stacked_column_chart', { height: 200, width: 200, autoFit: false, data: stacked_column_data, isStack: true, xField: 'month', yField: 'rain', seriesField: 'name', label: null, legend: false, maxColumnWidth: 16, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); stackedColumn.render(); <file_sep>import { ChartID, CKBJson } from '@antv/ckb'; import Thumbnails, { BAR_CHART } from '../src/index'; test('index', () => { const ckb = CKBJson(); const keys: ChartID[] = Object.keys(Thumbnails) as ChartID[]; keys.forEach((key) => { const obj = Thumbnails[key]; expect(!!obj).toBe(true); if (obj) { expect(obj.id).toBe(key); expect(obj.name).toBe(ckb[key].name); expect(!obj.svgCode).toBe(false); } }); }); test('object pie', () => { if (Thumbnails.pie_chart) { const { id, name, svgCode } = Thumbnails.pie_chart; console.log(id, name, svgCode); } }); test('object bar', () => { const { id, name, svgCode } = BAR_CHART; console.log(id, name, svgCode); }); <file_sep>import * as path from 'path'; import * as fse from 'fs-extra'; import { ChartID, CHART_ID_OPTIONS, CKBJson } from '@antv/ckb'; export async function ensureAndResetDir(dir: string): Promise<void> { const dirExists = await fse.pathExists(dir); if (dirExists) { const existFiles = await fse.readdir(dir); const existFilesPaths = existFiles.map((file) => path.join(process.cwd(), dir, file)); await Promise.all( existFilesPaths.map(async (path) => { await fse.remove(path); }) ); } await fse.ensureDir(dir); } export function CKBChartNameOfID(id: ChartID): string { const ckb = CKBJson(); if (CHART_ID_OPTIONS.includes(id) && ckb[id].name) return ckb[id].name; return null; } export function dashStrToSpaceTitleStr(id: string): string { return id .split('_') .map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()) .join(' '); } export function idToName(id: string): string { return CKBChartNameOfID(id as ChartID) || dashStrToSpaceTitleStr(id); } export function pureFileName(filePath: string): string { const extName = path.extname(filePath); return path.basename(filePath, extName); } export function sortObjByKey(unsortedObject: object) { /* eslint-disable no-param-reassign */ const reducer = (obj: object, key: string) => { obj[key] = unsortedObject[key]; return obj; }; /* eslint-enable no-param-reassign */ const sortedObj = Object.keys(unsortedObject) .sort() .reduce(reducer, {}); return sortedObj; } <file_sep>const { Line: StepLine } = G2Plot; // REQUIRED: import from G2Plot const step_line_data = [ { country: 'Europe', year: '2016', value: 175 }, { country: 'Europe', year: '2017', value: 260 }, { country: 'Europe', year: '2018', value: 150 }, { country: 'Europe', year: '2019', value: 200 }, { country: 'Europe', year: '2020', value: 120 }, { country: 'Africa', year: '2016', value: 80 }, { country: 'Africa', year: '2017', value: 48 }, { country: 'Africa', year: '2018', value: 100 }, { country: 'Africa', year: '2019', value: 40 }, { country: 'Africa', year: '2020', value: 80 }, ]; const stepLine = new StepLine('step_line_chart', { height: 200, width: 200, autoFit: false, data: step_line_data, xField: 'year', yField: 'value', seriesField: 'country', stepType: 'hvh', legend: false, xAxis: { range: [0, 1], }, yAxis: { max: 300, tickCount: 3, }, animation: false, // REQUIRED: NO animation renderer: 'svg', // REQUIRED: render into svg }); stepLine.render();
a85ab467d858b86f94dca196fffdf5033aa652d8
[ "JavaScript", "TypeScript", "Markdown" ]
28
JavaScript
antvis/thumbnails
f6704ecf64048343e747e68c42b06f34b45635d5
6ad6a01a153391eeb7fb6953c3a1bda0e94c62a2
refs/heads/master
<file_sep>/** * `Namespace` constructor. * * @api private */ function Namespace(name, parent) { this.name = name || ''; this.parent = parent || null; }; /** * Fully qualified name. * * Examples: * * ns.qname(); * // => "net:http" * * ns.qname('www'); * // => "net:http:www" * * @param {String} name * @return {String} * @api protected */ Namespace.prototype.qname = function(name) { var qual = name; var ns = this; while (ns) { qual = (ns.name.length) ? (ns.name + (qual ? ':' + qual : '')) : (qual); ns = ns.parent; } return qual || ''; } /** * Expose `Namespace`. */ exports = module.exports = Namespace; /** * Resolves `to` to an absolute namespace. * * If `to` isn't already in absolute form, it will be treated as relateive to * `from`. A caret (^) is used to indicate a parent namespace. * * @param {String} from * @param {String} to * @return {String} * @api public */ exports.resolve = function(from, to) { var comps = to.split(':'); if (to[0] != ':') { // `to` is relative to from (iow, `to` is not absolute) comps = (from.length ? from.split(':') : []).concat(comps); } // filter out empty components comps = comps.filter(function(c) { return c.length != 0 }); // reduce "up-namespace"'d components out, accumulating into `res` var res = [] , ic = 0; // ignore count comps.reduceRight(function(prev, cur) { if (prev == '^') { ic++; } else if (cur != '^') { ic = ic ? ic - 1 : 0; if (!ic) { res.unshift(cur); } } return cur; }, null); return res.join(':'); } <file_sep>/** * `TaskCtx` constructor. * * Task functions will be invoked within a context established by this class. * The context binds the task to the `rivet` instance, and exposes command line * arguments and a shared `scratch`. * * @api private */ function TaskCtx(rivet) { this.argv = rivet.argv; this.scratch = rivet.scratch; this._rivet = rivet; }; /** * Expose `TaskCtx`. */ module.exports = TaskCtx; <file_sep>var Task = require('../lib/task') , should = require('should') describe('Task', function() { describe('constructor with name', function() { var t = new Task('foo'); it('should have correct name', function() { t.name.should.equal('foo'); }) it('should not have prereqs', function() { t._prereqs.should.be.an.instanceOf(Array); t._prereqs.should.have.length(0); }) it('should not have functions', function() { t._fns.should.be.an.instanceOf(Array); t._fns.should.have.length(0); }) it('should not have been executed', function() { t._execd.should.be.false; }) }) describe('.prereqs with string argument', function() { var t = new Task('foo'); t.prereqs('x'); t.prereqs('y'); it('should have prereqs', function() { t._prereqs.should.be.an.instanceOf(Array); t._prereqs.should.have.length(2); t._prereqs[0].should.be.equal('x'); t._prereqs[1].should.be.equal('y'); }) }) describe('.prereqs with array argument', function() { var t = new Task('foo'); t.prereqs(['a', 'b']); t.prereqs(['x', 'y']); it('should have prereqs', function() { t._prereqs.should.be.an.instanceOf(Array); t._prereqs.should.have.length(4); t._prereqs[0].should.be.equal('a'); t._prereqs[1].should.be.equal('b'); t._prereqs[2].should.be.equal('x'); t._prereqs[3].should.be.equal('y'); }) }) describe('.fn with function argument', function() { var t = new Task('foo'); function x() {}; function y() {}; t.fn(x); t.fn(y); it('should have functions', function() { t._fns.should.be.an.instanceOf(Array); t._fns.should.have.length(2); t._fns[0].should.be.equal(x); t._fns[1].should.be.equal(y); }) }) describe('.fn with array argument', function() { var t = new Task('foo'); function a() {}; function b() {}; function x() {}; function y() {}; t.fn([a, b]); t.fn([x, y]); it('should have functions', function() { t._fns.should.be.an.instanceOf(Array); t._fns.should.have.length(4); t._fns[0].should.be.equal(a); t._fns[1].should.be.equal(b); t._fns[2].should.be.equal(x); t._fns[3].should.be.equal(y); }) }) }) <file_sep>module.exports = function(rivet) { rivet.desc('say hello') rivet.target('hello', function() { this.step(function(done) { setTimeout(function() { console.log('Hello!'); done(); }, 1000); }) this.step(function() { console.log('How are you?') }) }); rivet.alias('default', 'hello'); } <file_sep>#!/usr/bin/env node var rivet = require('../') , path = require('path') , optimist = require('optimist') , argv = optimist .usage('$0 [-f file] {options} targets') .alias('f', 'file').default('f', 'tasks.js').describe('f', 'file containing tasks to load') .alias('T', 'tasks').default('T', false).describe('T', 'display tasks') .alias('n', 'dry-run').default('n', false).describe('n', 'do a dry run without executing tasks') .alias('t', 'trace').default('t', false).describe('t', 'turn on execute tracing') .alias('h', 'help') .argv if (argv.help) { optimist.showHelp(); } else if (argv.tasks) { var file = rivet.utils.findupSync(process.cwd(), argv.file); if (!file) { return console.error('No "tasks.js" file found'); } process.chdir(path.dirname(file)); rivet.cli.tasks(file, argv); } else { var file = rivet.utils.findupSync(process.cwd(), argv.file); if (!file) { return console.error('No "tasks.js" file found'); } process.chdir(path.dirname(file)); rivet.cli.exec(file, argv._.length ? argv._ : [ 'default' ], argv); } <file_sep>/** * Module dependencies. */ var path = require('path') , fs = require('fs') , existsSync = fs.existsSync || path.existsSync // < 0.8 compat /** * Find file named `name` starting in `dir`, searching parent directories until * found. * * @param {String} path * @param {String} name * @return {String} * @api public */ exports.findupSync = function(dir, name) { var fpath = path.join(dir, name); if (existsSync(fpath)) { return fpath; } var pdir = path.resolve(dir, '..'); return pdir === dir ? null : exports.findupSync(pdir, name); } <file_sep># Rivet Rivet is a task-based build tool, scripted in JavaScript and executed using [Node.js](http://nodejs.org/). Similar to [make](http://www.gnu.org/software/make/) or [rake](http://rake.rubyforge.org/), it can be used in any scenario that can be broken into tasks, from building native and web applications to automating deployment procedures. ## Installation $ npm install -g rivet ## Usage From the command line, simply use rivet to execute a task. $ rivet hello Tasks are declared in a rivet file, by default named "tasks.js". #### Declaring a Task Tasks are declared using `rivet.task()`, and given a name, optional prerequisites, and a function to execute. module.exports = function(rivet) { rivet.desc('say hello') rivet.task('hello', function() { console.log('Hello!'); }); } All rivet files export a function using standard `module.exports` boilerplate. For brevity, this is omitted from further examples. Asynchronous tasks are as easy as accepting a `done` callback and invoking it when the task completes. rivet.task('hello', function(done) { setTimeout(function() { console.log('Hello! (in a little while)'); done(); }, 1000); }); #### Prerequisites (and The Scratch!) In many cases, a task often requires that another task execute first. These are known as prerequisites. Rivet ensures that all prerequisites have been executed prior to any task that requires them. rivet.task('hello', 'lookup_name', function() { console.log('Hello ' + this.scratch.name + '!'); }); rivet.task('lookup_name', function() { this.scratch.name = 'Dave'; }); Also demonstrated here is what's known as the "scratch". This is a shared area that any task can write to or read from, making it convenient to pass data between tasks. #### Namespaces Tasks can be grouped into namespaces, making it easy to organize related tasks and limit there scope in larger projects. rivet.namespace('formal', function() { rivet.task('hello', function() { console.log('Hello, sir!'); }); rivet.task('greet', 'hello', function() { console.log('How may I be of assistance?'); }); }); Prerequisites resolve within the current namespace. Relative namespaces can be used to refer to parent namespaces if necessary. rivet.namespace('informal', function() { rivet.task('greet', '^:hello', function() { console.log('What can I help you with?'); }); }); The use of a caret (^) is used to refer to a parent namespace. These can be strung together as needed. For example, `^:^:hello` would reference the `hello` task in the grandparent namespace. #### Multi-Step Tasks A single task can be declared multiple times. In this case, each function is additive. When the task is executed, each step will be invoked in sequence. rivet.task('archive', function(done) { copy(['app.js', 'utils.js'], 'output', done); }) rivet.task('archive', function(done) { zip('output', 'output.zip', done); }) Rivet provides syntactic sugar in the form of "targets" and "steps", which lets this be expressed in a form that is more clear. rivet.target('archive', function() { this.step(function(done) { copy(['app.js', 'utils.js'], 'output', done); }) this.step(function(done) { zip('output', 'output.zip', done); }) }); This is an effective way to break up a set of asynchronous operations, writing them as if they were sequential commands. ## FAQ ##### How is Rivet different from Jake? Rivet is conceptually the same as [Jake](https://github.com/mde/jake/). I was using Jake for this purpose, but ultimately found it lacking for the following reasons: 1. Jake treats asynchronous tasks as second-class, requiring extra options to enable them. This works against the Node.js grain. 2. Tasks are not "additive", in that they can't be redeclared. I found that this tended to result in unnecessary verbosity and nested callbacks. 3. Prerequisites don't resolve within the containing namespace. This limited the effectiveness of using namespaces and resulted in parent namespaces being peppered throughout separate files. All of these things could (and should, IMO) be fixed in Jake. However, after attempting to do that, I concluded that it would be simpler to start from a fresh codebase where other simplifying assumptions could be made. ##### How is Rivet different from Grunt? [Grunt](https://github.com/cowboy/grunt) does away with prerequisites and centralizes configuration while tying that configuration to the type of task. While this approach certainly works, it doesn't suit my own personal tastes. I prefer to decouple the implementation of tasks from their configuration. By embracing the functional aspects of JavaScript, and setup functions popularized by [Connect](http://www.senchalabs.org/connect/) and [Express](http://expressjs.com/) middleware, it is easy to write succinct tasks with declarative, inline configuration. For example: function zip(dir, zipfile) { return function(done) { var command = 'zip -r ' + zipfile + ' ' + dir; exec(command, done) } } task('zip_app', zip('app', 'app.zip')); task('zip_plugins, zip('plugins', 'plugins.zip')); While completely subjective, I find this much more aesthetically pleasing. This syntax also makes it easy to retain prerequisites, which are too useful to be unsupported by a build tool. ## Tests $ npm install --dev $ make test [![Build Status](https://secure.travis-ci.org/jaredhanson/rivet.png)](http://travis-ci.org/jaredhanson/rivet) ## Credits - [<NAME>](http://github.com/jaredhanson) ## License (The MIT License) Copyright (c) 2012 <NAME> 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. <file_sep>var Namespace = require('../lib/namespace') , resolve = Namespace.resolve , should = require('should') describe('Namespace', function() { describe('root namespace', function() { var ns = new Namespace(); it('should have empty name', function() { ns.name.should.be.equal(''); }) it('should not have a parent namespace', function() { should.not.exist(ns.parent); }) it('should return correct qname', function() { ns.qname().should.be.equal(''); }) it('should return correct qname of child task', function() { ns.qname('task').should.be.equal('task'); }) }) describe('namespace', function() { var ns = new Namespace('foo'); it('should have empty name', function() { ns.name.should.be.equal('foo'); }) it('should not have a parent namespace', function() { should.not.exist(ns.parent); }) it('should return correct qname', function() { ns.qname().should.be.equal('foo'); }) it('should return correct qname of child task', function() { ns.qname('task').should.be.equal('foo:task'); }) }) describe('child namespace', function() { var net = new Namespace('net'); var ns = new Namespace('http', net); it('should have empty name', function() { ns.name.should.be.equal('http'); }) it('should have a parent namespace', function() { should.exist(ns.parent); }) it('should return correct qname', function() { ns.qname().should.be.equal('net:http'); }) it('should return correct qname of child task', function() { ns.qname('task').should.be.equal('net:http:task'); }) }) describe('resolve', function() { it('should resolve against root namespace', function() { resolve('', 'foo').should.be.equal('foo'); }) it('should resolve against namespace', function() { resolve('net', 'foo').should.be.equal('net:foo'); }) it('should resolve against two-level namespace', function() { resolve('net:http', 'foo').should.be.equal('net:http:foo'); }) it('should resolve absolute against root namespace', function() { resolve('', ':foo').should.be.equal('foo'); }) it('should resolve absolute against namespace', function() { resolve('net', ':foo').should.be.equal('foo'); }) it('should resolve absolute against two-level namespace', function() { resolve('net:http', ':foo').should.be.equal('foo'); }) it('should resolve relative against namespace', function() { resolve('net', '^:foo').should.be.equal('foo'); }) it('should resolve relative against two-level namespace', function() { resolve('net:http', '^:foo').should.be.equal('net:foo'); }) it('should resolve two-level relative against two-level namespace', function() { resolve('net:http', '^:^:foo').should.be.equal('foo'); }) it('should resolve two-level relative against three-level namespace', function() { resolve('net:http:www', '^:^:foo').should.be.equal('net:foo'); }) it('should resolve too many ups against namespace to root', function() { resolve('net', '^:^:foo').should.be.equal('foo'); }) it('should resolve too many ups against two-level namespace to root', function() { resolve('net:http', '^:^:^:foo').should.be.equal('foo'); }) }) }) <file_sep>module.exports = function(rivet) { rivet.task('hello', function() { console.log('Hello!'); }); rivet.namespace('formal', function() { rivet.task('hello', function() { console.log('Hello, sir!'); }); // dependency is on this namespace's `hello` task. rivet.task('greet', 'hello', function() { console.log('How may I be of assistance?'); }); }); rivet.namespace('informal', function() { // dependency is on parent namespace's `hello` task // as indicated by "^" indicator rivet.task('greet', '^:hello', function() { console.log('How may I be of assistance?'); }); }); rivet.alias('default', 'hello'); } <file_sep>module.exports = function(rivet) { // Tasks are additive. Declaring the same task twice will cause any // functions to execute in sequence. In the case of async tasks, this // sequence proceeds as each function calls `done()`. rivet.desc('say hello') rivet.task('hello', function(done) { setTimeout(function() { console.log('Hello!'); done(); }, 1000); }); rivet.task('hello', function(done) { setTimeout(function() { console.log('How are you?'); done(); }, 1000); }); rivet.alias('default', 'hello'); } <file_sep>module.exports = function(rivet) { rivet.desc('say hello') rivet.task('hello', function() { console.log('Hello!'); }); // $ rivet hello-name --name Dave rivet.desc('say hello to someone') rivet.task('hello-name', function() { console.log('Hello ' + this.argv.name + '!'); }); rivet.alias('default', 'hello'); } <file_sep>/** * Module dependencies. */ var path = require('path') , rivet = require('..') /** * Display `tasks` in rivet `file`. * * @param {String} file * @api protected */ module.exports = function exec(file, options) { options = options || {}; require(file)(rivet); Object.keys(rivet._tasks || {}).sort().forEach(function(name) { var task = rivet._tasks[name]; if (task.desc || options.all) { // TODO: improve formatting of this output console.log('%s -> %s', task.name, task.desc || ''); } }) } <file_sep>/** * Module dependencies. */ var path = require('path') , rivet = require('..') /** * Executes `tasks` in rivet `file`. * * @param {String} file * @param {Array} tasks * @api protected */ module.exports = function exec(file, tasks, options) { require(file)(rivet); rivet.run(tasks, options, function(err) { if (err) { console.error(err.message); if (options.trace) { console.error(err.stack); } return process.exit(-1); } return process.exit(); }); }
a46d6e1ebb279e1845392e370c4f96b813a5e81d
[ "JavaScript", "Markdown" ]
13
JavaScript
jaredhanson/rivet
d59849034d215a9fb3e577ed4a6be4d4aa0b8e93
78e37c47ad943d0e8d1ee21ed60e9869293a413f
refs/heads/main
<file_sep>package controller; import java.util.List; import user.Student; public interface TestDao { public List<Student> getAllStudent(); } <file_sep>/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 80013 Source Host : localhost:3306 Source Database : student Target Server Type : MYSQL Target Server Version : 80013 File Encoding : 65001 Date: 2020-12-20 21:32:49 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `student` -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `title` varchar(255) COLLATE utf8_bin NOT NULL, `content` varchar(255) COLLATE utf8_bin DEFAULT NULL, `time` int(14) DEFAULT NULL, PRIMARY KEY (`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ('A2', '机械学院2018级硕士研究生以及留学生学位...', '20191220'); INSERT INTO `student` VALUES ('ACB', '机械学院“线上教学”平稳运行', '20200309'); INSERT INTO `student` VALUES ('MODE', '机械学院开展2020级新生专业教育讲座', '20200917'); INSERT INTO `student` VALUES ('abc', '省机械工程会考察我院陈涛老师科研....', '20200919'); INSERT INTO `student` VALUES ('img/1.png', '我院召开教学工作专题研讨会', '20191125'); INSERT INTO `student` VALUES ('img/2.png', '我院举行期中教学会谈', '20191206'); INSERT INTO `student` VALUES ('img/3.png', '机械学院举报“世界精神卫生日”主题班', '20201013'); INSERT INTO `student` VALUES ('img/4.png', '机械学院“线上教学”平稳运行', '20200309'); INSERT INTO `student` VALUES ('“211”工程高校', '机械学院《智造中国》学生讲党课第8讲....', '20200701'); INSERT INTO `student` VALUES ('便民服务', '机械学院党委荣获“先进基层组织”容....', '20200702'); INSERT INTO `student` VALUES ('党建与思想政治', '机械工程与自动化学院召开9月份中心组....', '20200918'); INSERT INTO `student` VALUES ('友情链接', '机械学院《智造中国》学生讲党课第6讲....', '20200925'); INSERT INTO `student` VALUES ('国家有关部委', '机械学院新手参观实验室', '20201005'); INSERT INTO `student` VALUES ('学工动态', '机械学院18级召开年纪大会强调学风教育', '20201006'); INSERT INTO `student` VALUES ('教学与科研', '机械学院第78期团校开课', '20200702'); INSERT INTO `student` VALUES ('档群,行政部门', '机械工程与自动化学院召开6月份中心组', '20200625'); INSERT INTO `student` VALUES ('直属,教学单位', '机械学院组织新手开展“阳光健康跑”', '20201012'); INSERT INTO `student` VALUES ('相关高校', '机械学院“专题做党课”开讲', '20200710'); <file_sep>package controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import sql.DBUtil; import user.Student; public class TestDaoImpl implements TestDao{ private Connection conn = null; private PreparedStatement pstmt = null; public TestDaoImpl(Connection conn) { this.conn = conn; } @Override public List<Student> getAllStudent() { // TODO Auto-generated method stub List<Student> list = new ArrayList(); String sql = "select * from student"; try { this.pstmt = this.conn.prepareStatement(sql); ResultSet rs = this.pstmt.executeQuery(); while(rs.next()) { Student s = new Student(); s.setTitle(rs.getString("title")); s.setContent(rs.getString("content")); s.setTime(rs.getInt("time")); list.add(s); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
682cb3ba98b3b5f600186b79f624eb135e2baf7d
[ "Java", "SQL" ]
3
Java
Meiqinzhou/Web08-News
875d04040b03be4d5b3b0026f466d00e421c4654
e17b160bf6429ca9516497c6f16a6af52b54067d
refs/heads/master
<repo_name>balakrishnacarnation/real-time-weather<file_sep>/src/App.js import React, { Component } from 'react'; import './App.css'; // import uuidv4 from 'uuid/v4' import Amplify, { PubSub } from 'aws-amplify'; import { AWSIoTProvider } from '@aws-amplify/pubsub/lib/Providers'; import request from 'request'; Amplify.configure({ Auth: { identityPoolId: process.env.REACT_APP_IDENTITY_POOL_ID, region: process.env.REACT_APP_REGION, userPoolId: process.env.REACT_APP_USER_POOL_ID, userPoolWebClientId: process.env.REACT_APP_USER_POOL_WEB_CLIENT_ID } }); Amplify.addPluggable(new AWSIoTProvider({ aws_pubsub_region: process.env.REACT_APP_REGION, aws_pubsub_endpoint: `wss://${process.env.REACT_APP_MQTT_ID}.iot.${process.env.REACT_APP_REGION}.amazonaws.com/mqtt`, })); class App extends Component { constructor(props) { super(props); this.state = this.getInitialState(); } getInitialState = () => { let state = { loading: true, // userMessage: "", // incomingMessage: "", data: false, error: false, closed: false, zip: false, celsius: false, fahrenheit: false, }; return state; }; // publishMessage = () => { // Amplify.PubSub.publish('real-time-weather', { message: this.state.userMessage, msgId: uuidv4() }); // } getCurrentWeather = () => { request(`${process.env.REACT_APP_API_URL}/api/weather?zipCode=97205`, (error, response, body) => { if(error) { this.setState({ error }); } else { body = JSON.parse(body); let weather = JSON.parse(JSON.parse(body.Item.weather)); console.log(weather) let zip = body.Item.zip; let celsius = weather.list[0].main.temp - 273; let fahrenheit = Math.floor(celsius * (9/5) + 32); this.setState({ zip, celsius, fahrenheit, loading: false }); } }); } componentDidMount = () => { this.setState({ loading: true }); this.getCurrentWeather(); Amplify.PubSub.subscribe('real-time-weather').subscribe({ next: data => { let weather = JSON.parse(data.value.weather); console.log(weather) let zip = data.value.zip; let celsius = weather.list[0].main.temp - 273; let fahrenheit = Math.floor(celsius * (9/5) + 32); this.setState({ zip, celsius, fahrenheit, loading: false }); }, error: error => this.setState({ error }), close: () => this.setState({ closed: true }), }); } handleChange = (e) => { this.setState({[e.target.name]: e.target.value}); } render = () => { if (this.state.loading) { return <h1>Loading..</h1> } else if (this.state.error) { return <h1>Error..</h1> } return ( <div className="App"> <h1>Realtime Portland Weather</h1> {/* <input type="text" id="message" value={this.state.userMessage} onChange={this.handleChange} name="userMessage"/> <button onClick={this.publishMessage}>Publish Message</button> */} <p>ZipCode: {this.state.zip ? this.state.zip : ""}</p> <p>{this.state.celsius ? `${this.state.celsius} °C` : ""}</p> <p>{this.state.fahrenheit ? `${this.state.fahrenheit} °F` : ""}</p> <p>{this.state.weather ? this.state.weather : ""}</p> </div> ); } }; export default App; <file_sep>/backend/main.js 'use strict'; require('dotenv').config(); const AWS = require('aws-sdk'); const request = require('request'); const main = {}; const zipCode = '97205'; const topicName = 'real-time-weather'; const tableName = 'real-time-weather-data'; const region = 'us-west-2'; const weatherApiId = process.env.WEATHER_API_ID; const mqttEndpoint = `${process.env.MQTT_ID}.iot.${region}.amazonaws.com`; main.handler = async (event, context) => { console.log('event', event); try { let weather = await main.getWeather(zipCode); console.log('weather', weather); await main.updateDynamoDB({ 'zip': zipCode, 'weather': JSON.stringify(weather) }); await main.publishWeatherUpdates({ 'zip': zipCode, 'weather': weather }); } catch (error) { console.log('error', error); return error; } }; main.getWeather = (query) => { return new Promise((resolve, reject) => { request(`https://api.openweathermap.org/data/2.5/forecast?zip=${query}&APPID=${weatherApiId}`, (error, response, body) => { if(error) reject(error); else resolve(body); }); }); }; main.publishWeatherUpdates = (payload) => { return new Promise((resolve, reject) => { let iotdata = new AWS.IotData({endpoint: mqttEndpoint}); let params = { topic: topicName, payload: JSON.stringify(payload), qos: 0 }; iotdata.publish(params, (err, data) => { if(err) reject(err); else resolve(data); }); }); }; main.updateDynamoDB = (item) => { return new Promise((resolve, reject) => { let documentClient = new AWS.DynamoDB.DocumentClient(); let params = { TableName: tableName, Item: item }; documentClient.put(params, (err, data) => { if (err) reject(err); else resolve(data); }); }); }; module.exports = main;
eb2c3ae050e2c4c5d64b407c769f5e4b2280f770
[ "JavaScript" ]
2
JavaScript
balakrishnacarnation/real-time-weather
5106e92eedd68820c4bfb04b099bd0b77e8e5e51
6474f88f49b49cb6e41212be10560fe59eea2c20
refs/heads/master
<file_sep>module Concerns::Memorable end<file_sep>module Concerns::Findable def find_by_name(name) @selectedObject = nil self.all.each do |currObject| if currObject.name == name @selectedObject = currObject end end @selectedObject end def find_or_create_by_name(name) @selectedObject = nil if find_by_name(name) != nil find_by_name(name) else self.new(name) end end end<file_sep>class MusicLibraryController def initialize(path = "./db/mp3s") @path = path MusicImporter.new(path).import end def call input = nil until input == "exit" input = gets.strip.downcase.chomp case input when "list songs" list_songs when "list artists" list_artists when "list genres" list_genres when "play song" play_song when "list artist" list_artist when "list genre" list_genre else puts "Invalid entry - please try again" end end end def list_songs Song.all.each do |song| puts "#{Song.all.index(song) + 1}. #{song.artist.name} - #{song.name} - #{song.genre.name}" end end def list_artists Artist.all.each do |artist| puts "#{artist.name}" end end def list_genres Genre.all.each do |genre| puts "#{genre.name}" end end def play_song puts "Please select a song:" Song.all.each_with_index do |song, index| puts "#{index + 1}. #{song.artist.name} - #{song.name} - #{song.genre.name}" end song_input = gets.chomp.to_i if song_input <= (Song.all.size + 1) song = Song.all[song_input - 1] puts "Playing #{song.artist.name} - #{song.name} - #{song.genre.name}" end end def list_artist puts "Please select an artist:" artist_input = gets.strip.chomp if Artist.find_by_name(artist_input).nil? puts "Artist not found, please try again" else artist = Artist.find_by_name(artist_input) artist.songs.each do |song| puts "#{artist.name} - #{song.name} - #{song.genre.name}" end end end def list_genre puts "Please select a genre:" genre_input = gets.strip.chomp if Genre.find_by_name(genre_input).nil? puts "Genre not found, please try again" else genre = Genre.find_by_name(genre_input) genre.songs.each do |song| puts "#{song.artist.name} - #{song.name} - #{genre.name}" end end end end
e9ff2fa5b3237ce9e08f906636d85412769fc343
[ "Ruby" ]
3
Ruby
eliyooy/ruby-music-library-cli-v-000
310a6eb2ae77073920cbdbe717790ea45c7c9c8b
f331aff7c0868c63b24693160b9eba5532906145
refs/heads/master
<repo_name>AlexS7/AncientGreek<file_sep>/grails-app/assets/javascripts/dynamicFileUploaderFieldAdder.js /** * Created by alex on 27/06/15. */ $( document ).ready(function() { $(".addCitationFile").click(function () { var originalField = $('.citationFilesUploaderWrapper').last(); var newFileInput = $('<input/>'). attr('type', 'file'). attr('id', 'citationFileUploader'). addClass("citationFileUploader"). attr("name","citationFilesUploader"); originalField.after(newFileInput); $('.citationFilesUploaderWrapper').last().next().wrap("<div class='citationFilesUploaderWrapper'></div>"); }); $(".addDescFile").click(function () { var originalField = $('.descriptionFilesUploadWrapper').last(); var newFileInput = $('<input/>'). attr('type', 'file'). attr('id', 'citationFileUploader'). addClass("citationFileUploader"). attr("name","citationFilesUploader"); originalField.after(newFileInput); $('.descriptionFilesUploadWrapper').last().next().wrap("<div class='descriptionFilesUploadWrapper'></div>"); }); });
dd96d03b3959147a0163fa6cb60dc9d9005f0170
[ "JavaScript" ]
1
JavaScript
AlexS7/AncientGreek
b141074ecbd615a7722dc7636b62dbe5bf6b77d9
3900262a0fddb9dcfeff952465d278e5adcd5b2e
refs/heads/main
<file_sep>import os from subprocess import call, check_output from configobj import ConfigObj import re import email import notmuch config = ConfigObj(".davemailrc") for maildir in config: # Prevent the new tag from being mapped to a folder. if "new" in config[maildir]["tag_folder_mapping"]: del config[maildir]["tag_folder_mapping"]["new"] def move_messages(query_string, maildir, destination_folder): with notmuch.Database(mode=notmuch.Database.MODE.READ_WRITE) as db: query = db.create_query(query_string) for message in query.search_messages(): old_filename = message.get_filename() path, filename = os.path.split(old_filename) cur_new = path.split(os.sep)[-1] # We strip the ,U=nnn infix from the filename so that mbsync isn't # confused when using the native storage scheme. # https://sourceforge.net/p/isync/mailman/message/33359742/ new_filename = os.path.join(db.get_path(), maildir, destination_folder, cur_new, re.sub(",U=[0-9]+", "", filename)) # If the old file no longer exists, or the new one already does then we # simply skip this message for now. try: os.renames(old_filename, new_filename) except OSError: continue # We add the new filename to the notmuch database before removing the old # one so that the notmuch tags are preserved for the message. db.add_message(new_filename) db.remove_message(old_filename) def move_tagged_messages(): for maildir in config: if config[maildir].as_bool("maintain_tag_folder_mapping"): default_folder = config[maildir]["default_folder"] for tag, folder in config[maildir]["tag_folder_mapping"].iteritems(): # First we move tagged messages into the folder. move_messages("tag:%s AND NOT folder:\"%s/%s\" AND path:%s/**" % (tag, maildir, folder, maildir), maildir, folder) # Then untagged messages out. move_messages("NOT tag:%s AND folder:\"%s/%s\"" % (tag, maildir, folder), maildir, default_folder) def tag_messages(query_string, tag): # We tag/untag the messages by calling the notmuch command here since # the Python notmuch API doesn't provide a way to tag messages without # iterating through them. call(["notmuch", "tag", tag, query_string]) def tag_moved_and_new_messages(): for maildir in config: # Tag messages based on their maildir tag_messages("path:%s/**" % (maildir), "+" + maildir) for tag, folder in config[maildir]["tag_folder_mapping"].iteritems(): if config[maildir].as_bool("maintain_tag_folder_mapping"): # Tag / untag all messages if maintaining tag to folder mapping tag_messages("NOT folder:\"%s/%s\" AND path:%s/**" % (maildir, folder, maildir), "-" + tag) tag_messages("folder:\"%s/%s\"" % (maildir, folder), "+" + tag) elif config[maildir].as_bool("tag_new_messages"): # Otherwise only tag new messages which were already filed e.g. spam tag_messages("folder:\"%s/%s\" AND tag:new" % (maildir, folder), "+" + tag) def tag_muted_threads(): # New messages in muted threads won't have the muted tag yet, so to avoid # those showing up in searches we take care to tag them now. # See https://notmuchmail.org/excluding/ muted_threads = check_output( ["notmuch", "search", "--output=threads", "tag:muted"] ).decode("utf-8").replace(os.linesep, " ").strip() tag_messages(muted_threads, "+muted") def header_matches(filename, header_name, regexp): with open(filename, "rb") as f: message = email.message_from_binary_file(f) for header_value in message.get_all(header_name, []): if regexp.match(header_value): return True return False # Occasionally it's useful to tag messages based on a header value which notmuch # doesn't index. For the messages matching the query, assign the tag if the # message header exists and matches the given regexp. *Warning slow!* def tag_other_header_match(query_string, header_name, regexp, tags): regexp = re.compile(regexp) with notmuch.Database(mode=notmuch.Database.MODE.READ_WRITE) as db: query = db.create_query(query_string) for message in query.search_messages(): if header_matches(message.get_filename(), header_name, regexp): for tag in tags.split(): if tag[0] == "+": message.add_tag(tag[1:]) elif tag[0] == "-": message.remove_tag(tag[1:]) def update_database(): call(["notmuch", "new"]) def run_emacs_hook(hook_name): with open(os.devnull, "w") as devnull: call(["emacsclient", "-e", "(run-hooks '" + hook_name + ")"], stdout=devnull, stderr=devnull) <file_sep>#!/bin/bash while [ TRUE ];do if [ `nmcli networking connectivity` = 'full' ] then python3 presync.py && \ mbsync -a && \ python3 postsync.py fi echo 'Waiting...' read -t 120 done <file_sep># Davemail ## Introduction My email setup, now under source control as it is getting rather complex! 0. My personal emails come into my [FastMail][1] account. 1. [mbsync][2] is used to keep a local copy of my emails synchronised using IMAP. (Much more efficient and reliably than [offlineimap][3] once set up correctly. Unfortunately setting it up correctly [wasn't trivial][4]). 2. My pre and post synchronisation scripts are run which take care of the tag to folder mapping as specified in .davemailrc. For example, a message with the tag `inbox` should be moved to the `INBOX` folder, and a message with no relevant tags should be moved to the `Archive` folder. 3. Those scripts also run my pre and post synchronisation hooks in Emacs, which I then use to update my modeline display etc. 4. [Notmuch][6] Emacs client is then used for reading and tagging message. [Gnus alias][7] for handling my different email identities + signatures. 5. Outgoing emails are sent using [msmtp][8], back out via FastMail's servers. 6. [vdirsyncer][9] synchronises my personal contacts and calendars with FastMail so that I have a local copy to use for address completion etc. ## Usage _(Not actually supposed to be used by other people...)_ 1. Install Emacs, Notmuch, msmtp, isync, gpg, libsecret-tools, vdirsyncer etc. 2. Install Python and configobj. 3. Set up [my Emacs config][5]. 4. Store email server passwords e.g. `secret-tool store --label="Email: <EMAIL>" email <EMAIL>` 5. Set up symlinks for the configuration files: ``` ln -s ~/path/to/davemail/.mbsyncrc ~/ ln -s ~/path/to/davemail/.msmtprc ~/ ln -s ~/path/to/davemail/.notmuch-config ~/ ln -s ~/path/to/davemail/.vdirsyncerrc ~/.config/vdirsyncer/config ``` - Run `./syncmail` to do a complete mail synchronisation every two minutes. - Press Enter to have the script synchronise again immediately. - Run `vdirsyncer sync` to synchronise personal contacts and calendar with Fastmail. ## TODO - `maintain_tag_folder_mapping` does not behave well when enabled for multiple accounts if an email is forwarded between the accounts. It is moved to the first account's Maildir, even if the mail should exist in both Maildirs. That, in turn, screws up the tags. - Figure out how to consider the address the original email was to when forwarding emails. Currently, the wrong alias is often used. - [Set up imapnotify to trigger mbsync, rather than polling.][10] - Sending emails using msmtp blocks Emacs, which sucks when the connection to Fastmail is slow. - Finish the old message archiving functionality? - Perhaps replace some of davemail.py with [imapfilter][11]? - Have notmuch use my local copy of my contacts [for address completion][12] as well as the notmuch database. (See `notmuch-address-command`.) - Use [syncmaildir][13] instead of IMAP? - Replace msmtp with [nullmailer][14]? - Figure out how to get Outlook SSO working for my work emails. [1]: https://fastmail.com [2]: http://isync.sourceforge.net/mbsync.html [3]: http://www.offlineimap.org [4]: http://isync.sourceforge.net/mbsync.html#INHERENT%20PROBLEMS [5]: https://github.com/kzar/emacs.d [6]: https://notmuchmail.org/ [7]: https://www.emacswiki.org/emacs/GnusAlias [8]: http://msmtp.sourceforge.net/ [9]: https://vdirsyncer.pimutils.org/en/stable/index.html [10]: https://martinralbrecht.wordpress.com/2016/05/30/handling-email-with-emacs/ [11]: https://raymii.org/s/blog/Filtering_IMAP_mail_with_imapfilter.html [12]: https://notmuchmail.org/emacstips/#index13h2 [13]: http://syncmaildir.sourceforge.net/ [14]: http://www.troubleshooters.com/linux/nullmailer/ <file_sep>import davemail if __name__ == "__main__": # Take care to move messages which were tagged after synchronisation started. davemail.move_tagged_messages() # Now we can update the database. davemail.update_database() # Tidy up our tags, removing "new" and adding others based on folder. davemail.tag_moved_and_new_messages() davemail.tag_messages("tag:new AND from:<EMAIL> AND " + "subject:'reminder'", "+muted") davemail.tag_other_header_match("tag:new", "X-Original-Delivered-to", ".*suboptimal\.co\.uk$", "+suboptimal") davemail.tag_muted_threads() davemail.tag_messages("tag:new", "-new") davemail.run_emacs_hook("notmuch-postsync-hook") <file_sep>import davemail if __name__ == "__main__": davemail.run_emacs_hook("notmuch-presync-hook") davemail.move_tagged_messages()
dcfd290d47090d38eaa86a20e01fc935ee8e407e
[ "Markdown", "Python", "Shell" ]
5
Python
kzar/davemail
9b8f9ee966d28e74ac74f2d41b9a68deda022567
259713e3fa6d2aad81fdf243b6d194bc77ca74fb
refs/heads/master
<repo_name>Jimam-Tamimi/django-chatbot<file_sep>/home/urls.py from django.urls import path from django.urls.conf import include from home import views urlpatterns = [ path('',views.index) ] <file_sep>/home/admin.py from django.contrib import admin from home.models import Tag, Message, Reply, Data, MessageException # Register your models here. admin.site.register((Tag, Message, Reply, Data, MessageException)) <file_sep>/home/migrations/0004_auto_20210715_1307.py # Generated by Django 3.2.5 on 2021-07-15 07:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0003_auto_20210715_1305'), ] operations = [ migrations.AlterField( model_name='data', name='answer', field=models.ManyToManyField(to='home.Answer'), ), migrations.AlterField( model_name='data', name='question', field=models.ManyToManyField(to='home.Question'), ), migrations.AlterField( model_name='data', name='tag', field=models.ManyToManyField(to='home.Tag'), ), ] <file_sep>/home/migrations/0008_message_index.py # Generated by Django 3.2.5 on 2021-07-16 03:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0007_messageexception'), ] operations = [ migrations.AddField( model_name='message', name='index', field=models.PositiveBigIntegerField(blank=True, default=0, null=True, verbose_name='Index'), ), ] <file_sep>/home/migrations/0006_data_index.py # Generated by Django 3.2.5 on 2021-07-16 00:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0005_auto_20210716_0005'), ] operations = [ migrations.AddField( model_name='data', name='index', field=models.PositiveBigIntegerField(blank=True, default=0, null=True, verbose_name='Index'), ), ] <file_sep>/home/models.py from django.db import models # Create your models here. class Tag(models.Model): tag = models.CharField("Data Tag", max_length=50, blank=False, default="blank") def __str__(self): return str(self.tag) class Message(models.Model): message = models.CharField("Message", max_length=500, blank=False, null=False, default="blank") index = models.PositiveBigIntegerField('Index', default=0, null=True, blank=True) class Meta: ordering = ['-index'] def __str__(self): return str(self.message) class Reply(models.Model): reply = models.CharField("Reply", max_length=500, blank=False, null=False, default="blank") def __str__(self): return str(self.reply) class Data(models.Model): tag = models.ManyToManyField(Tag) message = models.ManyToManyField(Message) reply = models.ManyToManyField(Reply) index = models.PositiveBigIntegerField('Index', default=0, null=True, blank=True) class Meta: ordering = ['-index'] def __str__(self): return str("".join(message.message + " | " for message in self.message.all().order_by('-index') )) class MessageException(models.Model): message = models.CharField("Exception Message", max_length=200, null=False, blank=False) def __str__(self): return str(self.message) <file_sep>/home/migrations/0002_auto_20210715_1303.py # Generated by Django 3.2.5 on 2021-07-15 07:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='answer', name='question', ), migrations.RemoveField( model_name='question', name='tag', ), migrations.CreateModel( name='Data', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('answer', models.ManyToManyField(to='home.Answer')), ('question', models.ManyToManyField(to='home.Question')), ('tag', models.ManyToManyField(to='home.Tag')), ], ), ] <file_sep>/api/intelligence.py import wikipedia from datetime import datetime stop_words = {'tell', 'me', 'about', 'can', 'your','you', 'please', 'plz', 'what', 'do', 'you', 'know'} timeQuery = [ 'what is the time', 'tell me the time', 'the time' ] def tellMeAbout(message): messageList = message.split() for word in stop_words: if(word in messageList): messageList.remove(word) topic = "".join(f"{word} " for word in messageList) topic = topic.strip() print(topic) try: return wikipedia.summary(topic, sentences = 1) except Exception: return "Couldn't find anything about this topic." def getCurrentTime(): currentTime = datetime.now() currentTimeStr = str(f"{currentTime.hour} hour and {currentTime.minute} minute") return currentTimeStr def advanceMessages(message): if('about' in message or 'what is' in message or "do you know" in message): return tellMeAbout(message) elif('the time' in message or 'current time' in message): return getCurrentTime() else: return None <file_sep>/home/migrations/0009_auto_20210716_0926.py # Generated by Django 3.2.5 on 2021-07-16 03:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0008_message_index'), ] operations = [ migrations.AlterModelOptions( name='data', options={'ordering': ['-index']}, ), migrations.AlterModelOptions( name='message', options={'ordering': ['-index']}, ), ] <file_sep>/api/views.py from math import trunc from django.http.response import JsonResponse from django.shortcuts import render from json import loads from home.models import MessageException, Data from random import choice from difflib import SequenceMatcher from api import intelligence # Create your views here. def getResponse(reuqest): def strInStr(userMessage, message): userMessageList = list(userMessage.lower()) messageList = list(message.lower()) for char in messageList: if(char in userMessageList): continue else: return False break return True def getReply(userMessage): for data in Data.objects.all().order_by("-index"): for message in data.message.all().order_by("-index"): if(userMessage.lower() in message.message.lower() or strInStr(userMessage, message.message)): userMessageLength = len(userMessage) messageLength = len(message.message) print( messageLength / userMessageLength) if(messageLength / userMessageLength < 2 or messageLength / userMessageLength > .5): matchQuestionRatio = SequenceMatcher(None,userMessage.lower(), message.message.lower()).ratio() if(matchQuestionRatio >= .65): randReply = choice(data.reply.all()).reply data.index += 1 data.save() message.index += 1 message.save() return randReply return None requestData = loads(reuqest.body) userMessage = requestData['message'].lower() if(len(Data.objects.all()) == 0): return JsonResponse({"satus": True, "reply": "Please contact with the developer."}) reply = getReply(userMessage) if(reply is not None): context = { "status": True, "reply": reply } else: moreMessageAnswer = intelligence.advanceMessages(userMessage) if(moreMessageAnswer is not None): context = { "status": True, "reply": moreMessageAnswer } return JsonResponse(context) else: messageException = MessageException.objects.all() context = { "status": True, "reply": choice(messageException).message } return JsonResponse(context)<file_sep>/home/migrations/0007_messageexception.py # Generated by Django 3.2.5 on 2021-07-16 01:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0006_data_index'), ] operations = [ migrations.CreateModel( name='MessageException', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.CharField(max_length=200, verbose_name='Exception Message')), ], ), ] <file_sep>/home/context_processors.py from django.conf import settings def get_base_url(request): return { 'BASE_URL': settings.BASE_URL } <file_sep>/static/home/js/app.js let allMessageSection = document.getElementById('all-message') allMessageSection.scrollTop = allMessageSection.scrollHeight; let msgSectionOpener = document.getElementById('msg-section-opener') let msgSection = document.getElementById('msg-section') let msgSectionClose = document.getElementById('msg-section-close') let msgSectionExpand = document.getElementById('msg-section-expand') let sendMessageBtn = document.getElementById('send-message') let message = document.getElementById('message') let btnModeToggler = document.getElementsByClassName('btn-mode-toggler') let listeninInfo = document.getElementById('listening-info') let TEXT_MODE = true let COMMAND_MODE = false // for voice var msg = new SpeechSynthesisUtterance(); let voices; function setSpeech() { return new Promise( function (resolve, reject) { let synth = window.speechSynthesis; let id; id = setInterval(() => { if (synth.getVoices().length !== 0) { resolve(synth.getVoices()); clearInterval(id); } }, 10); } ) } let s = setSpeech(); s.then((voicesVar) => {voices = voicesVar; msg.voice = voices[2]; }); msg.volume = 1; // From 0 to 1 msg.rate = .95; // From 0.1 to 10 msg.pitch = 1; // From 0 to 2 msg.lang = 'es-US'; // for speach recognition let speechRecognition = new webkitSpeechRecognition() || SpeechRecognition() ; // String for the Final Transcript let final_transcript = ""; // Set the properties for the Speech Recognition object speechRecognition.continuous = true; speechRecognition.interimResults = true; speechRecognition.lang = 'en-US' speechRecognition.onstart = () => { // Show the Status Element listeninInfo.classList.add('active') }; speechRecognition.onend = () => { // Hide the Status Element listeninInfo.classList.remove('active') if(COMMAND_MODE){ speechRecognition.start() } }; speechRecognition.onresult = (event) => { // Create the interim transcript string locally because we don't want it to persist like final transcript let interim_transcript = ""; // Loop through the results from the speech recognition object. for (let i = event.resultIndex; i < event.results.length; ++i) { // If the result item is Final, add it to Final Transcript, Else add it to Interim transcript if (event.results[i].isFinal) { final_transcript += event.results[i][0].transcript; } else { message.value = event.results[i][0].transcript; } } message.value = final_transcript final_transcript = "" }; msgSectionOpener.addEventListener('click', (e)=>{ // hide the msg section openner e.currentTarget.classList.add('hide') // show the msg section msgSection.classList.remove('hide') }) msgSectionClose.addEventListener('click', (e)=>{ // show the msg section openner msgSectionOpener.classList.remove("hide") // hide the msg section msgSection.classList.add("hide") }) msgSectionExpand.addEventListener('click', (e)=>{ msgSection.classList.toggle('expand') let actionIcon = e.currentTarget.innerHTML if(e.currentTarget.children[0].classList.contains('fa-compress')){ e.currentTarget.children[0].classList.replace('fa-compress', "fa-expand") } else{ e.currentTarget.children[0].classList.replace('fa-expand', "fa-compress") } }) // running sendMsg function onclick of send message button sendMessageBtn.addEventListener('click', (e)=>{ let msg = message.value sendMessage(msg) }) // sending message on enter key press message.addEventListener("keyup", (event) => { if (event.key === "Enter") { event.preventDefault(); let msg = message.value msg = msg.replace(/[^a-zA-Z ]/g, "") // removing all spacol charecter msg = msg.replace(/\s+/g, ' ').trim() // removing extra spaces sendMessage(msg) } }) // function for showing message to frontend function sendMessage(msg) { if(msg.replaceAll(' ', '') == ''){ return } allMessageSection.innerHTML += ` <div class="message"> <div class="sent message-status"> <p>${msg}</p> </div> </div> ` sendMessageToApi(msg) message.value = '' allMessageSection.scrollTop = allMessageSection.scrollHeight; } function speak(text) { text = text.replaceAll(':', '') text = text.replaceAll(';', '') text = text.replaceAll('(', '') text = text.replaceAll(')', '') msg.text = `${text}`; speechSynthesis.speak(msg); } function sendMessageToApi(msg) { const data = { message: msg }; fetch(`${BASE_URL}api/message/get-response/`, { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { showReply(data.reply) }) .catch((error) => { // console.error('Error:', error); }); } function showReply(msg) { allMessageSection.innerHTML += ` <div class="message"> <div class="got message-status"> <p>${msg}</p> </div> </div> ` if(COMMAND_MODE){ speak(msg) } allMessageSection.scrollTop = allMessageSection.scrollHeight; } let modeOptionsToggler = document.getElementById('mode-options-toggler') modeOptionsToggler.addEventListener('click', (e)=>{ let modeOptionsDivId = e.currentTarget.getAttribute('data-toggle') let modeOptionsDiv = document.getElementById(modeOptionsDivId) modeOptionsDiv.classList.toggle('show') Array.from(btnModeToggler).forEach(element => { element.addEventListener('click', (e) =>{ handleMode(element.getAttribute('mode')) Array.from(btnModeToggler).forEach(element2 => { if(element2 == element){ element2.classList.add('active') } else{ element2.classList.remove('active') } }); modeOptionsToggler.click() return " " }) }); }) function handleMode(mode) { if(TEXT_MODE && mode == 'command'){ activateCommandMode() } else if (COMMAND_MODE && mode == 'text'){ activateTextMode() } } function activateCommandMode() { speechRecognition.start() TEXT_MODE = false COMMAND_MODE = true } function activateTextMode() { TEXT_MODE = true COMMAND_MODE = false speechRecognition.stop() }<file_sep>/api/urls.py from django.urls import path from django.urls.conf import include from api import views urlpatterns = [ path('message/get-response/' , views.getResponse) ]<file_sep>/home/migrations/0005_auto_20210716_0005.py # Generated by Django 3.2.5 on 2021-07-15 18:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0004_auto_20210715_1307'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.CharField(default='blank', max_length=500, verbose_name='Message')), ], ), migrations.CreateModel( name='Reply', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('reply', models.CharField(default='blank', max_length=500, verbose_name='Reply')), ], ), migrations.RemoveField( model_name='data', name='answer', ), migrations.RemoveField( model_name='data', name='question', ), migrations.DeleteModel( name='Answer', ), migrations.DeleteModel( name='Question', ), migrations.AddField( model_name='data', name='message', field=models.ManyToManyField(to='home.Message'), ), migrations.AddField( model_name='data', name='reply', field=models.ManyToManyField(to='home.Reply'), ), ] <file_sep>/home/migrations/0003_auto_20210715_1305.py # Generated by Django 3.2.5 on 2021-07-15 07:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_auto_20210715_1303'), ] operations = [ migrations.AlterField( model_name='answer', name='answer', field=models.CharField(default='blank', max_length=500, verbose_name='Answer'), ), migrations.AlterField( model_name='data', name='answer', field=models.ManyToManyField(default='blank', to='home.Answer'), ), migrations.AlterField( model_name='data', name='question', field=models.ManyToManyField(default='blank', to='home.Question'), ), migrations.AlterField( model_name='data', name='tag', field=models.ManyToManyField(default='blank', to='home.Tag'), ), migrations.AlterField( model_name='question', name='question', field=models.CharField(default='blank', max_length=500, verbose_name='Question'), ), migrations.AlterField( model_name='tag', name='tag', field=models.CharField(default='blank', max_length=50, verbose_name='Data Tag'), ), ]
f61e46968578d68f6141d2b6a63c148a97badbe6
[ "JavaScript", "Python" ]
16
Python
Jimam-Tamimi/django-chatbot
e9abba28369c61a61b57a691b22dd2c44559f50b
8f5afffbecd65ea496476f84f57445e18d090cb2
refs/heads/master
<file_sep>import logging import os import time from logging.handlers import RotatingFileHandler import requests import telegram from dotenv import load_dotenv load_dotenv() PRACTICUM_TOKEN = os.getenv("PRACTICUM_TOKEN") TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN') CHAT_ID = os.getenv('TELEGRAM_CHAT_ID') URL_PRACTICUM_API = 'https://praktikum.yandex.ru/api/' BOT = telegram.Bot(token=TELEGRAM_TOKEN) logger = logging.getLogger("Botlog") logger.setLevel(logging.INFO) if os.environ.get('DYNO') is not None: stream_handler = logging.StreamHandler() logger.addHandler(stream_handler) else: file_handler = RotatingFileHandler("Botlog.log", maxBytes=1024 * 1024, backupCount=2) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) logger.addHandler(file_handler) def parse_homework_status(homework): status = homework.get('status') homework_name = homework.get('homework_name') statuses_types = { 'approved': 'Ревьюеру всё понравилось, можно приступать к ' 'следующему уроку.', 'rejected': 'К сожалению в работе нашлись ошибки.' } verdict = statuses_types.get(status) if verdict is None or homework_name is None: return 'Неизвестная структура ответа сервера.' return f'У вас проверили работу "{homework_name}"!\n\n{verdict}' def get_homework_statuses(current_timestamp): params = { 'from_date': current_timestamp } headers = {'Authorization': f'OAuth {PRACTICUM_TOKEN}'} method = 'user_api/homework_statuses/' try: response = requests.get(f'{URL_PRACTICUM_API}{method}', headers=headers, params=params) homework_statuses = response.json() except requests.exceptions.RequestException: logger.exception('Произошла ошибка при запросе данных с сервера:') empty_dict = {} return empty_dict except ValueError: logger.exception('Ответ сервера не в формате JSON:') empty_dict = {} return empty_dict return homework_statuses def send_message(message): return BOT.send_message(chat_id=CHAT_ID, text=message) def main(): current_timestamp = int(time.time()) logger.info('Бот запущен.') while True: try: new_homework = get_homework_statuses(current_timestamp) if new_homework.get('current_date') is None: current_timestamp = int(time.time()) if new_homework.get('homeworks'): send_message( parse_homework_status(new_homework.get('homeworks')[0])) logger.info('Сообщение успешно отправлено.') current_timestamp = new_homework.get('current_date') time.sleep(300) except Exception as e: print(f'Бот упал с ошибкой: {e}') time.sleep(5) continue if __name__ == '__main__': main()
d8ac7ac08844c08b206c770cb70f720821aced54
[ "Python" ]
1
Python
Jejevkin/api_sp1_bot
af68bee7446e460ae66cd659d293a57faf244d02
2edb251d4ff79d96c43570e7ebca727e1808a199
refs/heads/master
<repo_name>alejandrochang/AA_Projects<file_sep>/KnightPathFinder.rb class KinghtPathFinder def initialize(start) @start = start @root_node = root_node end def end end
7c8a789a9926afabfd823a109144562bb1ec509d
[ "Ruby" ]
1
Ruby
alejandrochang/AA_Projects
e72c720b2c478d238f7b96548aac930d91cae342
800d75d3edd658dfce0e05c815e019a824ec112b
refs/heads/master
<repo_name>jesusodallem192/paises_js<file_sep>/index.js const listaPaises = document.getElementById("lista-paises") const decripcionPais = document.getElementById("descripcion-pais") const extraerTodosLosPaises = () => { fetch ("#").then( (response) => { return response.json() }).then((data) => { console.log(data) perrosDos.innerHTML=` ` })
720f80b1d3b9f1af4ebe51b1d8ff8cc8e7de930d
[ "JavaScript" ]
1
JavaScript
jesusodallem192/paises_js
f932fb8aff09d3be33d440d187850c5210742f61
fb5213d91ab05b9c2cfe9eec998dec0dec0473fa
refs/heads/main
<repo_name>DaniilE2000/photo_assess_service<file_sep>/commands/CommandsController.php <?php namespace app\commands; use yii\console\Controller; use yii\httpclient\Client; class CommandsController extends Controller { public function actionPostTest() { $file = curl_file_create('./files/1.jpg'); $ch = curl_init('http://localhost:8080/'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, ['name' => 'Kesha', 'photo' => $file]); $result = curl_exec($ch); curl_close($ch); } public function actionGetTest() { $ch = curl_init('http://localhost:8080/?task_id=30'); curl_exec($ch); curl_close($ch); } } ?><file_sep>/views/main/error.php <?php /* @var $this yii\web\View */ /* @var $name string */ /* @var $message string */ /* @var $exception Exception */ $this->title = $name ?> <?php echo '<pre>'; print_r($message); echo '<pre></pre>'; print_r($exception); echo '<pre>'; ?><file_sep>/components/FileUploader.php <?php namespace app\components; class FileUploader { public bool $isUploaded; private string $realFilename = ''; public function __construct(string $tempFilename, string $extension, string $uploadPath) { $this->realFilename = \md5(\time()) . '.' . $extension; $this->isUploaded = \move_uploaded_file($tempFilename, $uploadPath . '/' . $this->realFilename); } public function getFilename(): string|null { return ($this->realFilename !== '') ? $this->realFilename : null; } } ?><file_sep>/controllers/MainController.php <?php namespace app\controllers; use app\components\FileUploader; use app\models\Results; use app\models\Tasks; use app\models\UploadFile; use app\models\UserInfo; use app\queue\TaskJob; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\UploadedFile; class MainController extends Controller { public $enableCsrfValidation = false; const RESPONSE_STATUS_NOT_FOUND = 'not_found'; const RESPONSE_STATUS_WAIT = 'wait'; const RESPONSE_STATUS_READY = 'ready'; /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } private function setCORSPositive() { $headers = Yii::$app->response->headers; $headers->add('Access-Control-Allow-Origin', '*'); $headers->add('Access-Control-Allow-Headers', '*'); $headers->add('Access-Control-Allow-Methods', '*'); $headers->add('Access-Control-Allow-Credentials', 'true'); } private function respond(string $responseStatus, ...$args) { $response = Yii::$app->response; switch($responseStatus) { case self::RESPONSE_STATUS_READY: $response->statusCode = 200; // OK. $response->content = json_encode([ 'status' => $responseStatus, 'result' => $args[0], ]); return; case self::RESPONSE_STATUS_WAIT: $response->statusCode = 425; //Too Early break; case self::RESPONSE_STATUS_NOT_FOUND: $response->statusCode = 404; // Not Found break; } $response->content = json_encode([ 'status' => $responseStatus, 'result' => null, ]); } private function notFound() { $response = Yii::$app->response; $response->statusCode = 404; // Not Found $response->content = json_encode([ 'status' => 'not_found', 'result' => null, ]); } private function wait() { $response = Yii::$app->response; $response->statusCode = 425; //Too Early $response->content = json_encode([ 'status' => 'wait', 'result' => null, ]); } private function ready($result) { $response = Yii::$app->response; $response->statusCode = 425; //Too Early $response->content = json_encode([ 'status' => 'wait', 'result' => null, ]); } private function processGet(int $task_id) { $task = Tasks::findOne($task_id); if (!$task) { return $this->respond(self::RESPONSE_STATUS_NOT_FOUND); } if ($task->status === 'wait') { return $this->respond(self::RESPONSE_STATUS_WAIT); } $result = Results::findOne($task->id)->result; return $this->respond(self::RESPONSE_STATUS_READY, $result); } private function findUserRecordId(string $name, string $filename) { $user_info = UserInfo::find()->select(['task_id'])->where('`user_name` = "' . $name . '" AND `file_name` = "' . $filename . '"') ->asArray()->one(); return $user_info ? $user_info['task_id'] : null; } private function processPost(string $name) { $response = Yii::$app->response; $photoFile = $_FILES['photo']; if ($task_id = $this->findUserRecordId($name, $photoFile['name'])) { $response->statusCode = 208; // Already reported. $resultRecord = Results::findOne($task_id); $response->content = json_encode([ 'status' => 'received', 'task' => $task_id, 'result' => $resultRecord->result, ]); return; } $response->statusCode = 202; // Accepted. $uploadPath = realpath('../temp-img-folder'); $fileUploader = new FileUploader($photoFile['tmp_name'], pathinfo($photoFile['name'], PATHINFO_EXTENSION), $uploadPath); $task = new Tasks(); $task->save(); $userInfo = new UserInfo(); $userInfo->saveAs($task->id, $name, $photoFile['name']); Yii::$app->queue->push(new TaskJob([ 'task_id' => $task->id, 'data' => [ 'status' => 'init', 'name' => $name, 'filepath' => $uploadPath . '/' . $fileUploader->getFilename(), ], ])); if ($fileUploader->isUploaded) { $response->content = json_encode([ 'status' => 'received', 'task' => $task->id, 'result' => null, ]); } else { $response->content = json_encode([ 'status' => false, 'message' => 'Not Uploaded', ]); } } public function actionIndex() { Yii::$app->request->enableCsrfValidation = false; Yii::$app->request->enableCookieValidation = false; $request = Yii::$app->request; $this->setCORSPositive(); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; switch($request->method) { case 'GET': $task_id = $request->get('task_id'); return $this->processGet($task_id); break; case 'POST': $name = $request->post('name'); return $this->processPost($name); break; default: return $request->method; } return $this->notFound(); } } ?> <file_sep>/models/Results.php <?php namespace app\models; use yii\db\ActiveRecord; /** @property int $task_id */ /** @property float $result */ class Results extends ActiveRecord { public function rules() { return [ [['task_id'], 'required'], [['result'], 'double'], ]; } public function getTask() { return $this->hasOne(Tasks::class, ['id' => 'task_id']); } } ?> <file_sep>/models/UserInfo.php <?php namespace app\models; use yii\db\ActiveRecord; /** @property int $task_id */ /** @property string $user_name */ /** @property string $file_name */ class UserInfo extends ActiveRecord { public static function tableName() { return 'user_info'; } public function rules() { return [ [['task_id', 'user_name', 'file_name'], 'required'], [['user_name', 'file_name'], 'string', 'length' => [1, 100]], ]; } public function getTask() { return $this->hasOne(Tasks::class, ['id' => 'task_id']); } public function saveAs(int $id, string $userName, string $filename) { $this->task_id = $id; $this->user_name = $userName; $this->file_name = $filename; $this->save(); } } ?> <file_sep>/db_dump/photo_processing_db.sql -- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Хост: localhost -- Время создания: Ноя 01 2021 г., 02:16 -- Версия сервера: 8.0.25 -- Версия PHP: 8.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- База данных: `photo_processing_db` -- -- -------------------------------------------------------- -- -- Структура таблицы `migration` -- CREATE TABLE `migration` ( `version` varchar(180) NOT NULL, `apply_time` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -- Дамп данных таблицы `migration` -- INSERT INTO `migration` (`version`, `apply_time`) VALUES ('m000000_000000_base', 1635723569), ('yii\\queue\\db\\migrations\\M161119140200Queue', 1635723642), ('yii\\queue\\db\\migrations\\M170307170300Later', 1635723642), ('yii\\queue\\db\\migrations\\M170509001400Retry', 1635723642), ('yii\\queue\\db\\migrations\\M170601155600Priority', 1635723642); -- -------------------------------------------------------- -- -- Структура таблицы `queue` -- CREATE TABLE `queue` ( `id` int NOT NULL, `channel` varchar(255) NOT NULL, `job` blob NOT NULL, `pushed_at` int NOT NULL, `ttr` int NOT NULL, `delay` int NOT NULL DEFAULT '0', `priority` int UNSIGNED NOT NULL DEFAULT '1024', `reserved_at` int DEFAULT NULL, `attempt` int DEFAULT NULL, `done_at` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -------------------------------------------------------- -- -- Структура таблицы `results` -- CREATE TABLE `results` ( `task_id` int NOT NULL, `result` float NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -------------------------------------------------------- -- -- Структура таблицы `tasks` -- CREATE TABLE `tasks` ( `id` int NOT NULL, `status` set('wait','ready') NOT NULL DEFAULT 'wait' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -------------------------------------------------------- -- -- Структура таблицы `user_info` -- CREATE TABLE `user_info` ( `task_id` int NOT NULL, `user_name` varchar(100) NOT NULL, `file_name` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `migration` -- ALTER TABLE `migration` ADD PRIMARY KEY (`version`); -- -- Индексы таблицы `queue` -- ALTER TABLE `queue` ADD PRIMARY KEY (`id`), ADD KEY `channel` (`channel`), ADD KEY `reserved_at` (`reserved_at`), ADD KEY `priority` (`priority`); -- -- Индексы таблицы `results` -- ALTER TABLE `results` ADD PRIMARY KEY (`task_id`); -- -- Индексы таблицы `tasks` -- ALTER TABLE `tasks` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `user_info` -- ALTER TABLE `user_info` ADD PRIMARY KEY (`task_id`), ADD UNIQUE KEY `user_name_2` (`user_name`,`file_name`), ADD KEY `user_name` (`user_name`,`file_name`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `queue` -- ALTER TABLE `queue` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=35; -- -- AUTO_INCREMENT для таблицы `tasks` -- ALTER TABLE `tasks` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33; -- -- Ограничения внешнего ключа сохраненных таблиц -- -- -- Ограничения внешнего ключа таблицы `results` -- ALTER TABLE `results` ADD CONSTRAINT `results_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `tasks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `user_info` -- ALTER TABLE `user_info` ADD CONSTRAINT `user_info_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `tasks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/models/Tasks.php <?php namespace app\models; use yii\db\ActiveRecord; /** @property int $id */ /** @property string $status */ class Tasks extends ActiveRecord { public function rules() { return [ [['id'], 'safe'], [['status'], 'in', 'range' => ['wait', 'ready']], [['status'], 'default', 'value' => 'wait'], ]; } } ?> <file_sep>/queue/TaskJob.php <?php namespace app\queue; use app\models\Results; use app\models\Tasks; use Yii; use yii\base\BaseObject; use yii\queue\JobInterface; class TaskJob extends BaseObject implements JobInterface { public int $task_id; public array $data; public function execute($queue) { $ch = curl_init('http://merlinface.com:12345/api/'); curl_setopt($ch, CURLOPT_POST, 1); switch ($this->data['status']) { case 'init': $file = curl_file_create($this->data['filepath'], 'image/' . pathinfo($this->data['filepath'], PATHINFO_EXTENSION)); curl_setopt($ch, CURLOPT_POSTFIELDS, ['name' => $this->data['name'], 'photo' => $file]); break; case 'retry': curl_setopt($ch, CURLOPT_POSTFIELDS, ['retry_id' => $this->data['retry_id']]); break; } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = json_decode(curl_exec($ch), true); curl_close($ch); if ($result['status'] === 'success') { $task = Tasks::findOne($this->task_id); $task->updateAttributes(['status' => 'ready']); $resultRecord = new Results(); $resultRecord->task_id = $this->task_id; $resultRecord->result = $result['result']; $resultRecord->save(); } else { Yii::$app->queue->delay(5)->push(new TaskJob(['task_id' => $this->task_id, 'data' => ['status' => 'retry', 'retry_id' => $result['retry_id']]])); } } } ?>
4f16e2c1d5b02ad6a70c4fc13b880da583334bb2
[ "SQL", "PHP" ]
9
PHP
DaniilE2000/photo_assess_service
d446e8f7f248440a9b56db8d142a1bd13907abf6
8e7d0199e31abb29446de6ca430bb907adaa5f00
refs/heads/master
<file_sep> #include "BinaryTree.hpp" #include <algorithm> #include <cstdlib> #include <ctime> #include <functional> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> using namespace std; using namespace ariel; template<typename T>//t BinaryTree<T> create_simple_tree(int adder = 0) { BinaryTree<T> tree; // create the following tree // 1 // 2 3 // 4 5 // 10 11 // 20 23 tree.add_root(1 + adder); tree.add_left(1 + adder, 2 + adder); tree.add_right(1 + adder, 3 + adder); tree.add_left(2 + adder, 4 + adder); tree.add_right(2 + adder, 5 + adder); tree.add_left(5 + adder, 10 + adder); tree.add_right(5 + adder, 11 + adder); tree.add_left(10 + adder, 20 + adder); tree.add_right(11 + adder, 23 + adder); return tree; } int main(){ cout << "[*] Creating simple tree [*]" << endl << endl; BinaryTree<int> tree = create_simple_tree<int>(); cout << "[-] Print test" << endl << endl; cout << tree << endl; cout << "[-] Changing the root to 999" << endl << endl; tree.add_root(999); cout << tree << endl; cout << "[-] Changing the '5' to '55'" << endl << endl; tree.add_right(2,55); cout << tree << endl; cout << "[-] Adding left child '223' to '3' " << endl << endl; tree.add_left(3,223); cout << tree << endl; cout << "[-] Adding right child '222' to '3' " << endl << endl; tree.add_right(3,222); cout << tree << endl; cout << "[-] Preorder iterator check and print it" << endl << endl; for (auto it = tree.begin_preorder();it != tree.end_preorder(); it++){ cout << *it << " " ; } cout << endl <<endl; cout << "[-] Inorder iterator check and print it" << endl << endl; for (auto it = tree.begin_inorder();it!= tree.end_inorder(); it++){ cout << *it << " " ; } cout << endl << endl; cout << "[-] Postorder iterator check and print it " << endl << endl; for (auto it = tree.begin_postorder();it!= tree.end_postorder(); it++){ cout << *it << " " ; } cout << endl; return 0; }<file_sep> #pragma once #include <queue> #include <queue> #include <fstream> #include <sstream> #include <iostream> #include <stack> using namespace std; namespace ariel { template <typename T> class BinaryTree { // Node class struct Node { T value; //Value Node *left_child = nullptr; //Left child Node *right_child = nullptr; //Right child Node() {} ; Node(T v) : value(v){}; // Default constructor Node(Node& other){ //Copy constructor this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; } Node& operator=(Node&& other) noexcept{ // Move operator this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; return *this; } Node& operator=(Node other) noexcept{ //Copy assignment operator this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; return *this; } Node(Node&& other) noexcept{ // Move constructor this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; } ~Node() //Destructor { //If left child isnt null so delete it if (left_child != nullptr) { delete left_child; } //If right child isnt null so delete it if (right_child != nullptr) { delete right_child; } } }; public: //Root node for the binary tree Node *root = nullptr; // Default constructor BinaryTree(){} // Default destructor ~BinaryTree(){ delete root; // Delete the root from memory } //Add root - if exist so replace the value BinaryTree &add_root(T value) { //If dont root exits - create new if(root == nullptr){ root = new Node(value); } //If root exits - replace the value else{ this->root->value = value; } return *this; }; //Add left to parent - if parent dont exist throws exception BinaryTree &add_left(T parent, T child) { auto it = begin_inorder(); // Search inorder int root_found = 0; // bool for finding the root //Searching for the parent node while (it != end_inorder()) { if (*it == parent) { root_found = 1; break; } it++; } //If parent was found if (root_found != 0) { //Adding to the left if (it.current_node->left_child != NULL) { it.current_node->left_child->value = child; } else { it.current_node->left_child = new Node(child); } } else{ //Throwing an execption - donsnt find a root throw invalid_argument("No root like this"); } return *this; }; //Add right to parent - if parent dont exist throws exception BinaryTree &add_right(T parent, T child) { auto it = begin_inorder(); // Search inorder int root_found = 0; // bool for finding the root //Searching for the parent node while (it != end_inorder()) { if (*it == parent) { root_found = 1; break; } it++; } //If parent was found if (root_found != 0) { //Adding to the right child if (it.current_node->right_child != NULL) { it.current_node->right_child->value = child; } else { it.current_node->right_child = new Node(child); } } else{ //Throwing an execption - donsnt find a root throw invalid_argument("No root like this"); } return *this; }; //Copy construtor BinaryTree(BinaryTree<T> const & t){ this->root = copyTree(t.root); } //Move construtor BinaryTree(BinaryTree<T>&& other) noexcept { this->root = other.root; other.root = nullptr; } //Operator << thats pring the tree friend std::ostream &operator<<(std::ostream &os, const BinaryTree &n) { n.printBT("", n.root, false, os); return os; } //Recursive function for printing the binary tree void printBT(const std::string& prefix, const Node* node, bool isLeft, std::ostream &os) const { if( node != nullptr ) { os << prefix; if(isLeft){ os << "├──"; } else{ os << "└──"; } // print the value of the node os << node->value << std::endl; // enter the next tree level - left and right branch printBT( prefix + (isLeft ? "│ " : " "), node->left_child, true, os); printBT( prefix + (isLeft ? "│ " : " "), node->right_child, false, os); } } //Preforming a deep copy of the tree Node* copyTree(Node* root1){ //If node is nullptr get out of the recursive if(root1 == nullptr){ return nullptr; } //Create new node Node* newRoot = new Node(root1->value); newRoot->left_child = copyTree(root1->left_child); //Copy left child newRoot->right_child = copyTree(root1->right_child); // Copy right child return newRoot; } //Operator = move BinaryTree<T>& operator=(BinaryTree&& other) noexcept{ if (root) {delete root;} root = other.root; other.ptr = nullptr; return *this; } //Operator = move BinaryTree<T>& operator=(BinaryTree<T> tree){ if(this->root){ delete root;} this->root = copyTree(tree.root); return *this; } //-----------Iterator class------------ class iterator{ public: Node *current_node = nullptr; //Initilized the queue inorder way void init_inorder_queue(queue<Node *> &queue, Node *root) { if (root == NULL) { return; } if (root->left_child != nullptr) { init_inorder_queue(queue, root->left_child); } queue.push(root); if (root->right_child != nullptr) { init_inorder_queue(queue, root->right_child); } }; //Initilized the queue postorder way void init_postorder_queue(queue<Node *> &queue, Node *root) { if (root == nullptr) { return; } if (root->left_child != nullptr) { init_postorder_queue(queue, root->left_child); } if (root->right_child != nullptr) { init_postorder_queue(queue, root->right_child); } queue.push(root); }; //Initilized the queue preorder way void init_preorder_queue(queue<Node *> &queue, Node *root) { if (root == nullptr) { return; } queue.push(root); if (root->left_child != nullptr) { init_preorder_queue(queue, root->left_child); } if (root->right_child != nullptr) { init_preorder_queue(queue, root->right_child); } }; //Queue from preforming iteration over the tree queue<Node *> queue; //Constructor that get Node what order to preforme // 0 - inorder , 1- postorder , 2- preorder iterator(Node *ptr, int order) { switch (order) { //Init Inorder queue case 0: init_inorder_queue(queue, ptr); break; //Init Postorder queue case 1: init_postorder_queue(queue, ptr); break; //Init Preorder queue case 2: init_preorder_queue(queue, ptr); break; default: break; } //If queue isnt empty after initizition, //make the current node the front of queue if(!this->queue.empty()){ current_node = this->queue.front(); } } //Operator to get the value from current node T &operator*() const { return current_node->value; } //Operator to get the value by reference T *operator->() const { return &(current_node->value); } //Get the next item in the iterator iterator &operator++() { if (queue.empty()) { current_node = nullptr; } else{ queue.pop(); current_node = queue.front(); } return *this; } //Get the next item in the iterator iterator operator++(int) { iterator tmp = *this; if (queue.empty()) { current_node = nullptr; } else { queue.pop(); //Pop from the queue current_node = queue.front(); //Repoint the curent node } return tmp; } //Operator for == bool operator==(const iterator &rhs) const { //If the queue is empty and the other one isnt or the opossite -> return false if((queue.empty() && !rhs.queue.empty()) || (queue.empty() && !rhs.queue.empty())){ return false; } if(queue.empty() && rhs.queue.empty()){ return true; } return current_node == rhs.current_node; } //Operator for != bool operator!=(const iterator &rhs) const { //If the queue is empty and the other one isnt or the opossite -> return false if((queue.empty() && !rhs.queue.empty()) || (queue.empty() && !rhs.queue.empty())){ return true; } if(queue.empty() && rhs.queue.empty()){ return false; } return current_node != rhs.current_node; } }; //Create preorder iterator iterator begin_preorder() { return iterator{root,2}; }; //Create end preorder iterator iterator end_preorder() { return iterator{nullptr,2}; }; //Create inorder iterator iterator begin_inorder() { return iterator{root,0}; }; //Create end inorder iterator iterator end_inorder() { return iterator{nullptr,0}; }; //Create postorder iterator iterator begin_postorder() { return iterator{root,1}; }; //Create end postorder iterator iterator end_postorder() { return iterator{nullptr,1}; }; //Create default begin iterator - inorder iterator iterator begin() { return iterator{root,0}; } //Creates default end iterator - inorder iterator iterator end() { return iterator{nullptr,0}; } }; };<file_sep> #pragma once #include <queue> #include <queue> #include <fstream> #include <sstream> #include <iostream> using namespace std; namespace ariel { template <typename T> class BinaryTree { // Node class struct Node { T value; Node *left_child = nullptr; Node *right_child = nullptr; Node() {} ; Node(T v) : value(v){}; Node(Node& other){ this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; } Node& operator=(Node&& other) noexcept{ this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; return *this; } Node& operator=(Node other) noexcept{ this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; return *this; } Node(Node&& other) noexcept{ this->left_child = other.left_child; this>right_child = other.right_child; this->value = other.value; } ~Node() { if (left_child != nullptr) { delete left_child; } if (right_child != nullptr) { delete right_child; } } }; public: // fields Node *root = nullptr; BinaryTree() { // root = new Node(); } ~BinaryTree(){ delete root; } BinaryTree &add_root(T value) { if(root == nullptr){ root = new Node(value); } else{ this->root->value = value; } return *this; }; BinaryTree &add_left(T prev, T child) { auto it = begin_inorder(); int root_found = 0; while (it != end_inorder()) { if (*it == prev) { root_found = 1; break; } it++; } if (root_found != 0) { if (it.current_node->left_child != NULL) { it.current_node->left_child->value = child; } else { it.current_node->left_child = new Node(child); } } else{ throw invalid_argument("No root like this"); } return *this; }; BinaryTree &add_right(T prev, T child) { auto it = begin_inorder(); int root_found = 0; while (it != end_inorder()) { if (*it == prev) { root_found = 1; break; } it++; } if (root_found != 0) { if (it.current_node->right_child != NULL) { it.current_node->right_child->value = child; } else { it.current_node->right_child = new Node(child); } } else{ throw invalid_argument("No root like this"); } return *this; }; BinaryTree(BinaryTree<T> const & t){ this->root = copyTree(t.root); } BinaryTree(BinaryTree<T>&& other) noexcept { this->root = other.root; other.root = nullptr; } friend std::ostream &operator<<(std::ostream &os, const BinaryTree &n) { return os; }; Node* copyTree(Node* root1){ if(root1 == nullptr){ return nullptr; } Node* newRoot = new Node(root1->value); newRoot->left_child = copyTree(root1->left_child); newRoot->right_child = copyTree(root1->right_child); return newRoot; } BinaryTree<T>& operator=(BinaryTree&& other) noexcept{ if (root) {delete root;} root = other.root; other.ptr = nullptr; return *this; } BinaryTree<T>& operator=(BinaryTree<T> tree){ if(this->root){ delete root;} this->root = copyTree(tree.root); return *this; } // 0 - in , 1- post , 2- pre class iterator{ public: Node *current_node = nullptr; void init_inorder_queue(std::queue<Node *> &queue, Node *root) { if (root == NULL) { return; } if (root->left_child != nullptr) { init_inorder_queue(queue, root->left_child); } queue.push(root); if (root->right_child != nullptr) { init_inorder_queue(queue, root->right_child); } }; void init_postorder_queue(std::queue<Node *> &queue, Node *root) { if (root == nullptr) { return; } if (root->left_child != nullptr) { init_postorder_queue(queue, root->left_child); } if (root->right_child != nullptr) { init_postorder_queue(queue, root->right_child); } queue.push(root); }; void init_preorder_queue(std::queue<Node *> &queue, Node *root) { if (root == nullptr) { return; } queue.push(root); if (root->left_child != nullptr) { init_preorder_queue(queue, root->left_child); } if (root->right_child != nullptr) { init_preorder_queue(queue, root->right_child); } }; std::queue<Node *> queue; iterator(Node *ptr, int order) { switch (order) { case 0: init_inorder_queue(queue, ptr); break; case 1: init_postorder_queue(queue, ptr); break; case 2: init_preorder_queue(queue, ptr); break; default: break; } if(!this->queue.empty()){ current_node = this->queue.front(); } } T &operator*() const { //return *pointer_to_current_node; return current_node->value; } T *operator->() const { return &(current_node->value); // T& temp; // return temp; } // ++i; iterator &operator++() { if (queue.empty()) { current_node = nullptr; } else{ queue.pop(); current_node = queue.front(); } return *this; } iterator operator++(int) { iterator tmp = *this; if (queue.empty()) { current_node = nullptr; } else { queue.pop(); current_node = queue.front(); } return tmp; } bool operator==(const iterator &rhs) const { if((queue.empty() && !rhs.queue.empty()) || (queue.empty() && !rhs.queue.empty())){ return false; } if(queue.empty() && rhs.queue.empty()){ return true; } return current_node == rhs.current_node; } bool operator!=(const iterator &rhs) const { if((queue.empty() && !rhs.queue.empty()) || (queue.empty() && !rhs.queue.empty())){ return true; } if(queue.empty() && rhs.queue.empty()){ return false; } return current_node != rhs.current_node; } }; iterator begin_preorder() { return iterator{root,2}; }; iterator end_preorder() { return iterator{nullptr,2}; }; iterator begin_inorder() { return iterator{root,0}; }; iterator end_inorder() { return iterator{nullptr,0}; }; iterator begin_postorder() { return iterator{root,1}; }; iterator end_postorder() { return iterator{nullptr,1}; }; iterator begin() { return iterator{root,0}; } iterator end() { return iterator{nullptr,0}; } private: }; } // namespace ariel
d61801442dc0694a1e7c18a023e4d69c9987fb8c
[ "C++" ]
3
C++
yuvalmarmer/binarytree-b
32c901c468b9b8d76774e1be4710c6a3b07d0ac9
8af7e716efaee9785e383be074f16baba9feefe0
refs/heads/main
<file_sep># Overview The included Ansible playbook will export the configured gold BIG-IP ASM policy and place it in source control with a datestamp tag. # Requirements You'll need to ensure you have Ansible install. The following instructions are for Ubuntu: ```bash apt-add-repository ppa:ansible/ansible sudo apt update apt install ansible ``` You'll need to have Python PIP and the following python modules installed: ```bash sudo apt-get install python-pip sudo pip install msrest sudo pip install msrestazure sudo pip install azure-cli sudo pip install azure-core ``` # Running Ansible Ensure that your ansible inventory is working correctly Setting the RESOURCE_GROUP_NAME programmatically below fails to work properly if there is more than one resource group with the *demo* prefix in your account. In that case run the command manually and export the appropriate resource group name. ```bash az login export RESOURCE_GROUP_NAME=`az group list --output tsv --query "[?starts_with(name, 'demo')]|[0]".name` sed -i 's/_resource_group_/'"$RESOURCE_GROUP_NAME"'/g' azure_rm.yml git update-index --assume-unchanged azure_rm.yml ansible-inventory --graph ``` if this doesn't generate a Export the required variables generated by Terraform in the IaC directory before running your playbook ```bash az login export KEYVAULT_NAME=`az keyvault list --resource-group $RESOURCE_GROUP_NAME --output tsv --query "[0].name"` export BIGIP_PASSWORD=`az keyvault secret show --name bigip-password --vault-name $KEYVAULT_NAME --query value --output tsv` export SERVICE_PRINCIPAL_ID=`az keyvault secret show --name service-principal-id --vault-name $KEYVAULT_NAME --query value --output tsv` export SERVICE_PRINCIPAL_PASSWORD=`az keyvault secret show --name service-principal-password --vault-name $KEYVAULT_NAME --query value --output tsv` export TENANT_ID=`az account show | jq ".tenantId" -r` export SUBSCRIPTION_ID=`az account show | jq ".id" -r` ansible-playbook ./main.yml ``` <file_sep>This terraform repository uses [workspaces](https://www.terraform.io/docs/state/workspaces.html) to manage multiple parallel builds. Workspace commands include, `new`, `list`, `show`, `select`, and `delete`. The details of how workspaces are used with this repository are described below. The elements of the build configuration that are controlled by the selected workspace are described at the end of this README. This terraform repository supports terraform version 0.12.x. Support of terraform 0.11.x and 0.13.x (when released) subject to further testing. (Optional) create the SSH key pair you intend to use for the INSPEC tests. it is highly recommended that you use a keypair expressly for these builds, so that if it is compromised for any reason the breadth of impact is limited to these environments. ```bash ssh-keygen -m PEM -t rsa -f ./tftest ``` Ensure you have an Azure access token before running ```terraform apply```. ```bash az login ``` and accept the F5 BIG-IP marketplace license ```bash az vm image terms accept --plan "f5-big-all-2slot-byol" --offer "f5-big-ip-byol" --publisher "f5-networks" ``` Set BASH variables for terraform and init ```bash # set the Azure Resource Group Name export RESOURCE_GROUP_NAME="demo-ab12-rg" # or export RESOURCE_GROUP_NAME=`az group list --output tsv --query "[?starts_with(name, 'demo')]".name` # Set the BIG-IQ hostname for license management export BIGIQ_HOST="bigiq.example.local" # Set remaining variables from from the Azure CLI export KEYVAULT_NAME=`az keyvault list --resource-group $RESOURCE_GROUP_NAME --output tsv --query "[0].name"` export STORAGE_ACCOUNT_NAME=`az storage account list --resource-group $RESOURCE_GROUP_NAME --output tsv --query [0].name` export HEX_LABEL=`echo $RESOURCE_GROUP_NAME | cut -d '-' -f 2` export BIGIP_PASSWORD=`az keyvault secret show --name bigip-password --vault-name $KEYVAULT_NAME --query value --output tsv` export SERVICE_PRINCIPAL_ID=`az keyvault secret show --name service-principal-id --vault-name $KEYVAULT_NAME --query value --output tsv` export SERVICE_PRINCIPAL_PASSWORD=`az keyvault secret show --name service-principal-password --vault-name $KEYVAULT_NAME --query value --output tsv` export BIGIQ_PASSWORD=`az keyvault secret show --name bigiq-password --vault-name $KEYVAULT_NAME --query value --output tsv` export MASTER_KEY=`az keyvault secret show --name master-key --vault-name $KEYVAULT_NAME --query value --output tsv` export SUBSCRIPTION_ID=`az account show | jq ".id" -r` export TENANT_ID=`az account show | jq ".tenantId" -r` # Initialize Terraform (no workspace yet) terraform init -backend-config=storage_account_name=$STORAGE_ACCOUNT_NAME -backend-config=container_name=terraform -backend-config=key=terraform.tfstate -backend-config=resource_group_name=$RESOURCE_GROUP_NAME ``` the first time you use one of the terraform workspaces you need to create it using the ```new``` action ```bash terraform workspace new [east|west|central] ``` For example, if you intend to build in both the east and central workspaces you would do the following; ```bash terraform workspace new east terraform workspace new central ``` this will create a `terraform.tfstate.d` directory that will contain subdirectories for each workspace Creating a new workspace will likely switch to that workspace automatically. You can also select the workspace you intend to use with the ```terraform workspace select action```. for example, ```bash terraform workspace select east ``` You can ```plan``` and ```apply``` the terraform repository ```bash # Initialize Terraform Workspace terraform init -backend-config=storage_account_name=$STORAGE_ACCOUNT_NAME -backend-config=container_name=terraform -backend-config=key=terraform.tfstate -backend-config=resource_group_name=$RESOURCE_GROUP_NAME # Determine what Terraform will create terraform plan -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "hex_label=$HEX_LABEL" -var "bigip_password=$<PASSWORD>" -var "service_principal_id=$SERVICE_PRINCIPAL_ID" -var "service_principal_password=$<PASSWORD>" -var "subscription_id=$SUBSCRIPTION_ID" -var "tenant_id=$TENANT_ID" -var "bigiq_license_host=$BIGIQ_HOST" -var "bigiq_license_password=$<PASSWORD>" -var "f5_master_key=$MASTER_KEY" # Build out environment terraform apply -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "hex_label=$HEX_LABEL" -var "bigip_password=$<PASSWORD>" -var "service_principal_id=$SERVICE_PRINCIPAL_ID" -var "service_principal_password=$<PASSWORD>" -var "subscription_id=$SUBSCRIPTION_ID" -var "tenant_id=$TENANT_ID" -var "bigiq_license_host=$BIGIQ_HOST" -var "bigiq_license_password=$<PASSWORD>" -var "f5_master_key=$MASTER_KEY" # Test the environment ./runtest.sh ``` You can use terraform to destroy and recreate a specific Big-IP upon terraform apply. If a license was assigned to this device, it will need to be manually revoked. ```bash # Example recreate Big-IP nodes 0 and 5: terraform taint azurerm_virtual_machine.f5bigip[0] terraform taint azurerm_virtual_machine.f5bigip[5] terraform apply -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "hex_label=$HEX_LABEL" -var "bigip_password=$<PASSWORD>" -var "service_principal_id=$SERVICE_PRINCIPAL_ID" -var "service_principal_password=$<PASSWORD>" -var "subscription_id=$SUBSCRIPTION_ID" -var "tenant_id=$TENANT_ID" -var "bigiq_license_host=$BIGIQ_HOST" -var "bigiq_license_password=$<PASSWORD>" -var "f5_master_key=$MASTER_KEY" ``` note: if you're using local state files, during an ```apply``` the state files are locked. This means you **can't** open another terminal window and select another workspace and try to run ```terraform apply```. (I may be wrong about this. An earlier version of terraform stored all the workspace state in a single tfstate file. Since they're in separate files that may allow for parallel local builds) kick the tires, and then ```bash terraform workspace select [east|west|central] terraform destroy -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "hex_label=$HEX_LABEL" -var "bigip_password=$<PASSWORD>" -var "service_principal_id=$SERVICE_PRINCIPAL_ID" -var "service_principal_password=$<PASSWORD>" -var "subscription_id=$SUBSCRIPTION_ID" -var "tenant_id=$TENANT_ID" -var "bigiq_license_host=$BIGIQ_HOST" -var "bigiq_license_password=$<PASSWORD>" -var "f5_master_key=$MASTER_KEY" ``` # Workspace Configuration In the variables.tf there is a `specification` variable that contains HCL maps named with a reference to a workspace. For example, the map below is used when the east workspace is selected using ```terraform workspace select east``` ``` east = { region = "eastus" azs = ["1"] application_count = 3 environment = "demoeast" cidr = "10.0.0.0/8" ltm_instance_count = 2 gtm_instance_count = 1 } ``` if you need to create support for another workspace duplicate an existing map, add it to the array, and adjust values as appropriate. For example, if you need to add support for `francecentral` you could do as follows; ``` east = { region = "eastus" azs = ["1"] application_count = 3 environment = "demoeast" cidr = "10.0.0.0/8" ltm_instance_count = 2 gtm_instance_count = 1 } francecentral = { region = "francecentral" azs = ["1"] application_count = 1 environment = "demofrcent" cidr = "10.0.0.0/8" ltm_instance_count = 2 gtm_instance_count = 0 } west = { region = "westus2" azs = ["1"] application_count = 3 environment = "demowest" cidr = "10.0.0.0/8" ltm_instance_count = 2 gtm_instance_count = 0 } ``` # Pipeline Configuration TODO: - document creation of service principal via ADO - allow ADO SP access to BIG-IP and Juiceshop shared images - create variable group and link it to Azure Vault created by IaC-Vault - upload ssh public and private keys into ADO Pipeline secure files - create release pipeline and link the variable group Terraform: Init - Display name: Terraform : init - Command : init - configuration directory: $(System.DefaultWorkingDirectory)/_poc-demo/IaC Terraform: Apply - Display name: Terraform : apply - Command: validate and apply - Configuration directory: $(System.DefaultWorkingDirectory)/_poc-demo/IaC - Additional command arguments: ``` -var "privatekeyfile=$(pocprivatekey.secureFilePath)" -var "publickeyfile=$(pocpublickey.secureFilePath)" -var "resource_group_name=$(resource_group_name)" -var "hex_label=$(hex_label)" -var "bigip_password=$(<PASSWORD>)" -var "service_principal_id=$(service-principal-id)" -var "service_principal_password=$(<PASSWORD>)" -var "subscription_id=$(subscription-id)" -var "tenant_id=$(tenant-id)" -var "bigiq_license_host=$(bigiq_license_host)" -var "bigiq_license_password=$(<PASSWORD>_license_password)" -var "f5_master_key=$(master_key) ```<file_sep>title "Verify BIG-IP Internal Availability" control "ASM Master Key" do impact 1.0 title "ASM Master Key is Set" desc "Ensure that the correct master key is set" only_if do file("/config/bigip.conf").exist? end describe command("f5mku -K") do its("stdout") { should match input("MASTER_KEY")} end end<file_sep># Introduction This repository is used to store ASM policies for version control and continuous integration with security <file_sep>#!/bin/bash # Get the Public IP address ALB_NAME=$(az network lb list --resource-group $RESOURCE_GROUP_NAME --query [0].name -o tsv) ALB_PUBLIC_IP_ID=$(az network lb frontend-ip show --lb-name $ALB_NAME --resource-group $RESOURCE_GROUP_NAME --name PublicIPAddress --query publicIpAddress.id -o tsv) ALB_PUBLIC_IP_ADDRESS=$(az network public-ip show --ids $ALB_PUBLIC_IP_ID --query ipAddress -o tsv) inspec exec inspec/bigip-ready --input ALB_PUBLIC_IP_ADDRESS=$ALB_PUBLIC_IP_ADDRESS<file_sep>This Terraform will build a new resource group and create the share vault inside. It will then store the BIG-IP password in the vault as well as a Service Principal for Ansible and AS3 service discovery to use. Note: you must run this from the CLI as your azure user # Requirements An Azure Resource Group and Storage Account must exist to store the Terraform state for this module before running the terraform init command. You can [create one](https://docs.microsoft.com/en-us/azure/terraform/terraform-backend) or simply use your existing infrastructure. Run the following commands to get started: ```bash # set variables used by Azure CLI and Terraform export RAND_HEX=`openssl rand -hex 2` # PREFIX must not contain special characters export PREFIX="demo-$RAND_HEX" export RESOURCE_GROUP_NAME="$PREFIX-rg" export STORAGE_ACCOUNT_NAME="`echo ${RESOURCE_GROUP_NAME//-}`sg" export LOCATION="westus2" export BIGIQ_PASSWORD="<PASSWORD>" export BIGIP_MASTER_KEY="replace with 24 character base64 encoded string to use as master key. Example: <KEY> # Login to Azure az login # Create resource group az group create --name $RESOURCE_GROUP_NAME --location eastus # Create storage account az storage account create --resource-group $RESOURCE_GROUP_NAME --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob # Get storage account key ACCOUNT_KEY=$(az storage account keys list --resource-group $RESOURCE_GROUP_NAME --account-name $STORAGE_ACCOUNT_NAME --query "[0].value" -o tsv) # Create blob container az storage container create --name terraform --account-name $STORAGE_ACCOUNT_NAME --account-key $ACCOUNT_KEY # Initialize Terraform terraform init -backend-config=storage_account_name=$STORAGE_ACCOUNT_NAME -backend-config=container_name=terraform -backend-config=key=vault-terraform.tfstate -backend-config=resource_group_name=$RESOURCE_GROUP_NAME # Determine what will be created terraform plan -var "prefix=$PREFIX" -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "region=$LOCATION" -var "bigiq_password=$<PASSWORD>" -var "bigip_master_key=$BIGIP_MASTER_KEY" # Create Azure Vault and populate the secrets terraform apply -var "prefix=$PREFIX" -var "resource_group_name=$RESOURCE_GROUP_NAME" -var "region=$LOCATION" -var "bigiq_password=$<PASSWORD>" -var "bigip_master_key=$BIGIP_MASTER_KEY" ```<file_sep>#!/bin/bash tf_output_file='inspec/bigip-ready-external/files/terraform.json' # Save the Terraform data into a JSON file for InSpec to read terraform output --json > $tf_output_file # Set the jumphost IP address jumphost=`cat $tf_output_file| jq '.jumphost_ip.value[0]' -r` # Run InSpect tests from the Jumphost inspec exec inspec/bigip-ready-external -t ssh://azureuser@$jumphost -i tftest # Set BIG-IP variables bigip_pwd=$(cat $tf_output_file| jq '.bigip_password.value' -r) master_key=$(cat $tf_output_file| jq '.f5_master_key.value' -r | base64) for bigip in $(cat $tf_output_file| jq '.bigip_mgmt_public_ips.value[]' -r) do # Run InSpect tests from the BIG-IP inspec exec inspec/bigip-ready-internal -t ssh://admin@$bigip --password $bigip_pwd --input MASTER_KEY=$master_key done<file_sep># Overview The following Ansible playbooks will configure the deployed BIG-IPs with base ASM policy and configure the desired virtual servers via AS3. # Requirements You'll need to ensure you have Ansible 2.8 or 2.9 installed. The following instructions are for Ubuntu: ```bash apt-add-repository ppa:ansible/ansible sudo apt update apt install ansible ``` Note: this may install ansible using python 2.7. Ansible using python 3.6.x is required for these playbooks. These playbooks have been tested with ansible 2.9.x using python 3.6.x You'll need to have Python PIP and the following python modules and ansible roles installed: ```bash sudo apt-get install python-pip sudo pip install msrest sudo pip install msrestazure sudo pip install azure-cli sudo pip install azure-core ansible-galaxy install f5devcentral.atc_deploy ``` # Running Ansible Ensure that your ansible inventory is working correctly ```bash export RESOURCE_GROUP_NAME=demo-rg-12ab # or export RESOURCE_GROUP_NAME=`az group list --output tsv --query "[?starts_with(name, 'demo')]".name` sed -i 's/_resource_group_/'"$RESOURCE_GROUP_NAME"'/g' azure_rm.yml git update-index --assume-unchanged azure_rm.yml ansible-inventory --graph ``` Export the required variables generated by Terraform before running your playbook ```bash az login export KEYVAULT_NAME=`az keyvault list --resource-group $RESOURCE_GROUP_NAME --output tsv --query "[0].name"` export BIGIP_PASSWORD=`az keyvault secret show --name bigip-password --vault-name $KEYVAULT_NAME --query value --output tsv` ``` You can now run all playbooks by running site.yml below, or by running the specific playbook directly. Run all playbooks ``` ansible-playbook ./site.yml ``` site.yml contains the following playbooks ``` # file: site.yml - import_playbook: import_custom_asm_signatures.yml - import_playbook: import_attack_signature_version.yml - import_playbook: import_waf_policies.yml - import_playbook: import_ltm_config.yml - import_playbook: create_declaration.yml - import_playbook: as3.yml ``` # Playbook Overview Common variables for all playbooks ```bash hosts: tag_Ansible_ltm:!tag_environment_gold # hosts is using Azure tags to select targets for the playbook. This tag combination select all ltm BIG-IPs except those in the gold environment connection: local vars: base_git_repo_path: "{{ playbook_dir }}/files/policy" #Specify local directory to store the contents of the configuration git repo git_url: "<EMAIL>" #Specify URL of the configuration git repo git_key: "{{ lookup('file','~/.ssh/id_rsa') }}" #Specify SSH key to use to authenticate to configuration git repo git_repo_path: "{{ playbook_dir }}/files/policy" #Sets git repo path git_msg: "asm policy update" #Specify commit description text if playbook pushes changes to repo (only gold-policy playbooks) git_local_only: true #Set to true to skip fetching updated files from remote repo and instead use local files only. staging_tag: "tag_purpose_test" #Specify Azure tag to indicate the Big-IP is used for testing. Playbook will use staging branch configuration for nodes with this tag. provider: server: "{{ ansible_host }}" user: admin password: "{{ lookup('env','BIGIP_PASSWORD') }}" #Use BASH variable $BIGIP_PASSWORD to populate the password variable. validate_certs: false server_port: 443 #Set the Big-IP HTTPS service port gather_facts: false any_errors_fatal: true ``` ### Playbook import_custom_asm_signatures.yml - Pulls the latest configuration from the configuration management repo. - Stores the master branch and staging branch from the repo into two local directories - Imports custom attack signatures from the master branch directory to all Big-IP targets unless they contain the staging tag. If staging tag is present the staging directory is used to look for the custom attack signatures. - Is expecting .xml file in directory {{ playbook_dir }}/files/policy/<branch>/ASM_custom_signatures/*.xml which contains the exported custom attack signatures from ASM. - If multiple .xml files are located, they will each be imported to the target Big-IPs. - The task waits for successful custom attack signature install condition before finishing the task. - The playbook task waits 180 seconds for the install task to complete. If more time is needed, this can be adjusted. ### Playbook import_attack_signature_version.yml - Pulls the latest configuration from the configuration management repo. - Stores the master branch and staging branch from the repo into two local directories - Imports the attack signature package version from the master branch directory to all Big-IP targets unless they contain the staging tag. If staging tag is present the staging directory is used to look for the attack signature package version. - Is expecting .im file in directory {{ playbook_dir }}/files/policy/<branch>/ASM_signature_version/*.im which contains the attack signatures file from downloads.f5.com. - Only a single .im file should be located in the directory. If multiple .im files are found, they will all be installed in series, which will cause undesired behavior. - The task waits for successful attack signature version install condition before finishing the task. - The playbook task waits 180 seconds for the install task to complete. If more time is needed, this can be adjusted. ### Playbook import_waf_policies.yml - Pulls the latest configuration from the configuration management repo. - Stores the master branch and staging branch from the repo into two local directories - Imports the ASM policies from the master branch directory to all Big-IP targets unless they contain the staging tag. If staging tag is present the staging directory is used to look for the ASM policies. - Is expecting .xml files in directory {{ playbook_dir }}/files/policy/<branch>/*.xml which contains all the exported ASM policies. - If multiple .xml files are found, they will all be imported. - The task waits for successful ASM policy install condition before finishing the task. - The playbook tasks also applies all imported ASM policies ### Playbook import_ltm_config.yml - This task imports LTM configuration that either AS3 does not support, or is LTM configuration preferred to load outside of AS3 (iRules, Datagroups, Bot profiles, DoS profiles). - Any configuration element an iRule references should be imported with this playbook. - Pulls the latest configuration from the configuration management repo. - Stores the master branch and staging branch from the repo into two local directories - Imports the LTM TMSH configuration from the master branch directory to all Big-IP targets unless they contain the staging tag. If staging tag is present the staging directory is used to look for the LTM TMSH configuration. - Is expecting tmsh.config files in directory {{ playbook_dir }}/files/policy/<branch>/LTM_configuration/tmsh.config which contains all the exported LTM configuration. - The task waits for successful LTM TMSH configuration install condition before finishing the task. - The playbook tasks also saves TMSH configuration ### Playbook create_declaration.yml - This task renders the AS3 JSON declaration using the F5 configuration in .yml format from {{ playbook_dir }}/files/policy/<branch>/LTM_configuration/*yml. - Jinja2 template file {{ playbook_dir }}/as3-webapp-declaration.j2 is used to create the declaration. - The F5 .yml configuration files in master and staging branch will be rendered into a master and staging declaration in their respective directories. ### Playbook as3.yml - This task imports LTM configuration via the Big-IP AS3 API endpoint. - Pulls the latest configuration from the configuration management repo. - Is expecting as3.json file in directory {{ playbook_dir }}/files/policy/<branch>/LTM_configuration/*.json which contains the configuration in JSON format. - The task waits for successful LTM AS3 configuration install condition before finishing the task. <file_sep>title "Verify BIG-IP Application is Available" alb_public_ip_address = attribute('ALB_PUBLIC_IP_ADDRESS') control "Juice Shop is Ready" do impact 1.0 title "Juice Shop is Ready" describe http("https://#{alb_public_ip_address}", method: 'GET', ssl_verify: false) do its('status') { should cmp 200 } end end <file_sep># Introduction Highly Scalable ASM solution in Azure. ALB will target a pool of stand-alone ASM instances that have their configuration synchronized via automation (Ansible + AS3). Requires TMOS 15.1.x for deployment # Getting Started To setup your environment, you'll need to follow these processes 1. Deploy shared resources: follow README doc in the IaC-vault folder 2. Deploy environment: follow README doc in the IaC folder 3. Deploy CM folder to onboard LTM + ASM configuration ![Architecture Diagram](https://github.com/megamattzilla/azure_terraform_waf/raw/main/azure_terraform_waf.png)
f5c713272550695d5478390f3cd90cf2b6d8b35a
[ "Markdown", "Ruby", "Shell" ]
10
Markdown
perbonielsen/azure_terraform_waf
50a7ee626ce9f7fa365c7eec19a97706a0eb4a5e
4181033e629dd5669b05e98a826752b03146e8c1
refs/heads/master
<repo_name>awadhesh22791/disk_usage_notifier<file_sep>/disk_usage_notifier.sh #!/bin/sh ## specify the partitions to ignore initialy set up for Filesystem|tmpfs|udev df -H | grep -vE '^Filesystem|tmpfs|udev' | awk '{print $5 " " $1}' | while read output; do echo $output usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 ) partition=$(echo $output | awk '{ print $2 }' ) ## Specify percentage initialy setup for 90 percent if [ $usep -ge 90 ]; then ## Provide email address to send to email notification echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" | mail -s "Alert: Server Almost out of disk space $usep%" <EMAIL> fi done <file_sep>/README.md # Disk usage notifier Shell script to send email notification when certain percentage of hard disk is utilized. First of all please follow the steps to setup email sender in ubuntu. Follow the link: https://linuxconfig.org/configuring-gmail-as-sendmail-email-relay Make the shell script executable. Configure shell script in crontab on daily basis.
096f0b46d85a5355f62c702567f9291c8d36449d
[ "Markdown", "Shell" ]
2
Shell
awadhesh22791/disk_usage_notifier
f3a4a77458f44f7d7623fdfcf3214304362cb5b3
903d54f7091ee11f478baae9de9f0db99cadeabc
refs/heads/master
<repo_name>PedroG386/Tienda<file_sep>/LogicaDeNegocio/Login/OperacionesLogin.cs using System; using System.Collections.Generic; using System.Text; using Entidades; using SotoredProcedures; namespace LogicaDeNegocio.Login { public class OperacionesLogin { //Get public static Entidades.Usuarios GetLogin(string Usuario,string contraseña) { return Get_Login.Get(Usuario, contraseña); } public static Entidades.Usuarios GetUsuarioById(int id_usuario) { return Get_UsuarioById.Get(id_usuario); } //Get } } <file_sep>/SotoredProcedures/Get_UsuarioById.cs using ConexionBD; using Entidades; using System.Collections.Generic; namespace SotoredProcedures { public class Get_UsuarioById { public static Usuarios Get(int id_usuario) { DBManager conexion = new DBManager(); if (id_usuario == 0) { throw new System.ArgumentNullException(nameof(id_usuario)); } else { List<DBParameter> parametros = new List<DBParameter> { new DBParameter(NombreParametro: "id_usuario", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:id_usuario), }; return conexion.ExecuteSingle<Usuarios>("Get_UsuarioById", parametros); } } } } <file_sep>/ConexionBD/ExecuteType.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConexionBD { public enum ExecuteType { ExecuteReader, ExecuteNonQuery, ExecuteScalar, DataTable }; } <file_sep>/Tienda/Account/LogIn.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using Entidades; using LogicaDeNegocio; namespace Tienda.Account { public partial class LogIn : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn_ingresa_Click(object sender, EventArgs e) { string usario = inp_usuario.Text; string contraseña = inp_contraseña.Text; var userLog = LogicaDeNegocio.Login.OperacionesLogin.GetLogin(usario,contraseña); if (userLog.id_usuario > 0&&userLog.estatus==1) { FormsAuthentication.SetAuthCookie(inp_usuario.Text, true); Response.Redirect("/inicio.aspx?id="+userLog.id_usuario, false); } } } }<file_sep>/WebApi/Controllers/Usuarios/InsertaUsuarioController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Entidades; using LogicaDeNegocio.Usuarios; namespace WebApi.Controllers.Usuarios { public class InsertaUsuarioController : ApiController { // GET: api/InsertaUsuario public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/InsertaUsuario/5 public string Get(int id) { return "value"; } // POST: api/InsertaUsuario public int Post([FromBody]Entidades.Usuarios obj) { return OperacionesUsuarios.InsertaUsuario(obj); } // PUT: api/InsertaUsuario/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/InsertaUsuario/5 public void Delete(int id) { } } } <file_sep>/Entidades/Usuarios.cs using System; using System.Collections.Generic; using System.Text; namespace Entidades { public class Usuarios { public int id_usuario { get; set; } public string Usuario { get; set; } public string contraseña { get; set; } public int id_rol { get; set; } public string Nombre { get; set; } public string Apellidos { get; set; } public string correo { get; set; } public string telefono { get; set; } public int estatus { get; set; } public string Pais { get; set; } public string Ciudad { get; set; } public DateTime fechaRegistro { get; set; } } } <file_sep>/Entidades/Productos.cs using System; using System.Collections.Generic; using System.Text; namespace Entidades { public class Productos { public int id_producto { get; set; } public string Nombre { get; set; } public string Clave { get; set; } public int id_categoriaProducto { get; set; } public float costo { get; set; } public float precio { get; set; } public int Activo { get; set; } public string strfIle { get; set; } public string descripcion { get; set; } } } <file_sep>/WebApi/Controllers/Productos/ProductosController.cs using System.Collections.Generic; using System.Web.Http; namespace WebApi.Controllers.Productos { public class ProductosController : ApiController { // GET: api/Productos public List<Entidades.Productos>Get() { return LogicaDeNegocio.Productos.OperacionesProductos.GetProductos(); } // GET: api/Productos/5 public string Get(int id) { return "value"; } // POST: api/Productos public void Post([FromBody]string value) { } // PUT: api/Productos/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Productos/5 public void Delete(int id) { } } } <file_sep>/SotoredProcedures/Get_Productos.cs using ConexionBD; using Entidades; using System.Collections.Generic; namespace SotoredProcedures { public class Get_Productos { public static List<Productos> Get() { DBManager conexion = new DBManager(); return conexion.ExecuteDataTable<Productos>("Get_Productos"); } } } <file_sep>/SotoredProcedures/Inserta_Usuario.cs using System; using System.Collections.Generic; using System.Text; using Entidades; using ConexionBD; namespace SotoredProcedures { public class Inserta_Usuario { public static int Insert(Usuarios obj) { ConexionBD.DBManager conexion = new ConexionBD.DBManager(); if (obj == null) { throw new System.ArgumentNullException(nameof(obj)); } else { List<ConexionBD.DBParameter> parametros = new List<ConexionBD.DBParameter> { new ConexionBD.DBParameter(NombreParametro: "Usuario", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.Usuario), new ConexionBD.DBParameter(NombreParametro: "contraseña", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.contraseña), new ConexionBD.DBParameter(NombreParametro: "id_rol", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.id_rol), new ConexionBD.DBParameter(NombreParametro: "Nombre", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.Nombre), new ConexionBD.DBParameter(NombreParametro: "Apellidos", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.Apellidos), new ConexionBD.DBParameter(NombreParametro: "correo", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.correo), new ConexionBD.DBParameter(NombreParametro: "telefono", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.telefono), new ConexionBD.DBParameter(NombreParametro: "estatus", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.estatus), new ConexionBD.DBParameter(NombreParametro: "Pais", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.Pais), new ConexionBD.DBParameter(NombreParametro: "Ciudad", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:obj.Ciudad), }; return conexion.ExecuteNonQuery("Inserta_Usuarios", parametros); } } } } <file_sep>/Tienda/Padre.Master.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Entidades; using LogicaDeNegocio; namespace Tienda { public partial class Padre : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["id"] ==null) { userUnLoged(); } else { userLoged(int.Parse(Request.QueryString["id"])); } } void userLoged(int idUsuario) { var usuarioLogeado = LogicaDeNegocio.Login.OperacionesLogin.GetUsuarioById(idUsuario); if (usuarioLogeado.id_usuario != 0) { string HTML = ""; HTML += "<br>Bienvenido de nuevo: "; HTML += "<p><i style=\"color:green;\" class=\"fas fa-dot-circle\"></i>" + usuarioLogeado.Usuario + "</p>"; HTML += "<p>" + usuarioLogeado.correo + "</p><br>"; //HTML += "<p>" + usuarioLogeado.Pais + "</p><br>"; lbl_info.Text = HTML; lbl_logout.Text = "<a style=\"color:white;\" href=\"/Account/LogIn\" class=\"btn btn-danger\"><i class=\"fas fa-sign-out-alt\"></i>Cerrar Sesión</a>"; } } void userUnLoged() { string BUTTONS = ""; lbl_info.Text = ""; BUTTONS += "<a class=\"btn btn-primary\" href=\"/Account/Register\"><i class=\"fas fa-user-plus\"></i>Registrate</a>"; BUTTONS += "<a class=\"btn btn-success\" href=\"/Account/LogIn\"><i style=\"color:white;\" class=\"fas fa-person-booth\"></i>Iniciar Sesión</a>"; lbl_btnsLoginRegister.Text = BUTTONS; lbl_logout.Text = ""; } } }<file_sep>/LogicaDeNegocio/Productos/OperacionesProductos.cs using SotoredProcedures; using System.Collections.Generic; namespace LogicaDeNegocio.Productos { public class OperacionesProductos { //GET public static List<Entidades.Productos> GetProductos() { return Get_Productos.Get(); } //GET } } <file_sep>/SotoredProcedures/Get_Login.cs using Entidades; using System.Collections.Generic; namespace SotoredProcedures { public class Get_Login { public static Usuarios Get(string Usuario,string contraseña ) { ConexionBD.DBManager conexion = new ConexionBD.DBManager(); if (Usuario == null) { throw new System.ArgumentNullException(nameof(Usuario)); } else { List<ConexionBD.DBParameter> parametros = new List<ConexionBD.DBParameter> { new ConexionBD.DBParameter(NombreParametro: "Usuario", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:Usuario), new ConexionBD.DBParameter(NombreParametro: "contraseña", TipoParametro: System.Data.ParameterDirection.Input, ValorParametro:contraseña), }; return conexion.ExecuteSingle<Usuarios>("Get_Login", parametros); } } } } <file_sep>/LogicaDeNegocio/Usuarios/OperacionesUsuarios.cs using System; using System.Collections.Generic; using System.Text; using Entidades; using SotoredProcedures; using LogicaDeNegocio; namespace LogicaDeNegocio.Usuarios { public class OperacionesUsuarios { //INSERT public static int InsertaUsuario(Entidades.Usuarios obj) { return Inserta_Usuario.Insert(obj); } //INSERT } }
1d422fae1b653322d0ef6aea193df18939a2a144
[ "C#" ]
14
C#
PedroG386/Tienda
85db4b8be65dc110204e006b5546c7d35d26687a
bc401849b04893754e7bbdd9f72d8314b8700a41
refs/heads/master
<file_sep># openmocap Programs related to my matura thesis. `firmware` contains Arduino programs for WiFi-enabled IMU/MARG sensors `server` contains a server to receive data from WiFi-enabled sensors `imu-mocap` contains files related to the processing of sensor data `recordings` contains three recordings made using the previously mentioned programs and sensors `camera-mocap`contains programs for a experimental camera based motion capture system <file_sep>import datatools import socket import sqlite3 # Standalone recorder # # Part of the OpenMCS project # # Visit https://www.github.com/coretool/openmcs for more information # class Server(object): def __init__(self, number_of_sensors, port, db=':memory:', db_name='sensordata', type='raw'): self.port = port self.num_of_sensors = number_of_sensors self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.bind(('0.0.0.0', port)) self.shutdown = False self.db_name = db_name self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() self.connected_sensors = [] self.sensor_ids = [] self.type = type def run(self): """ Top-level function to start the whole process. """ if self.type == 'quat': self.cursor.execute('CREATE TABLE ' + self.db_name + ''' (id integer, w real, x real, y real, z real, generation integer)''') elif self.type == 'raw': self.cursor.execute('CREATE TABLE ' + self.db_name + ''' (id integer, ax real, ay real, az real, gx real, gy real, gz real, mx real, my real, mz real, generation integer)''') else: # Create two tables for a combined recording self.cursor.execute('CREATE TABLE ' + self.db_name + '_euler' + ''' (id integer, x real, y real, z real, generation integer)''') self.cursor.execute('CREATE TABLE ' + self.db_name + '_raw' + ''' (id integer, ax real, ay real, az real, gx real, gy real, gz real, mx real, my real, mz real, generation integer)''') self.cursor.execute('CREATE TABLE ' + self.db_name + '_init' + ''' (id integer, x real, y real, z real) ''') self.wait_for_sensors() def wait_for_sensors(self): """ Method to wait for the sensors to register. Upon successful registration of all sensors, Server.ready() will be called. """ while len(self.connected_sensors) < self.num_of_sensors: data, addr = self.socket.recvfrom(100) values = datatools.unpack_init(data) self.connected_sensors.append(addr) self.cursor.execute('INSERT INTO ' + self.db_name + '_init VALUES ' + str(values)) self.conn.commit() self.sensor_ids.append(values[0]) def ready(self): """ Tell all sensors that we are ready for transmission. Upon recveiving the ready call, the sensor will wait another 5 seconds until it sends data. """ for sensor in self.connected_sensors: self.socket.sendto(b'ready', sensor) def receive(self): print('The recording has been started') while not self.shutdown: data, addr = self.socket.recvfrom(100) if self.type == 'quat': data = str(datatools.unpack_quaternion(data)) self.cursor.execute('INSERT INTO ' + self.db_name + ' VALUES ' + data) self.conn.commit() elif self.type == 'raw': data = str(datatools.unpack_raw(data)) self.cursor.execute('INSERT INTO ' + self.db_name + ' VALUES ' + data) self.conn.commit() else: data = datatools.unpack_both(data) print(data) quat = [data[0]] + list(data[10:13]) + [data[13]] quat = tuple(quat) print(quat) self.cursor.execute('INSERT INTO ' + self.db_name + '_euler VALUES ' + str(quat)) self.conn.commit() raw = [data[0]] + list(data[1:10]) + [data[13]] print(raw) raw = tuple(raw) self.cursor.execute('INSERT INTO ' + self.db_name + '_raw VALUES ' + str(raw)) self.conn.commit() def switch_off(self): """ Tell all sensors that we are done. Each sensor checks whether it has received a message after it has sent its most recent measurement. """ self.shutdown = True for sensor in self.connected_sensors: self.socket.sendto(b'end', sensor) def terminate(self): self.conn.close() <file_sep>import argparse import datatools import os.path from server import Server if __name__ == '__main__': parser = argparse.ArgumentParser(description='OpenMCS recording server. This server can be used to record data to a seperate location or to directly render it via the OpenMCS Blender Plugin.', epilog='This program is part of the OpenMCS project. For more information, visit https://github.com/coretool/openmcs') parser.add_argument('-n', type=int, help='Number of sensors to connect to', required=True) parser.add_argument('-p', '--port', type=int, help='Port to listen on', default=3000) parser.add_argument('-db', '--database', help='Database to write to', default=':memory:') parser.add_argument('-t', '--tablename', help='Table to write to', default='sensordata') parser.add_argument('--format', help='Format of the recording', default='both', choices=['quaternion', 'raw', 'both']) args = vars(parser.parse_args()) server = Server(args['n'], args['port'], args['database'], args['tablename'], args['format']) # TODO: Take other arguments into account print('Server is waiting for the sensors to connect ') server.run() input('All sensors are now connected, hit enter to continue and start the recording ') server.ready() try: print('Hit Ctrl + C to end the recording') server.receive() except KeyboardInterrupt: pass server.switch_off() server.terminate() exit(0) <file_sep>#include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> /* Constants */ const int sensor_id = 0000; // Identifier of the sensor const char* ssid = ""; // SSID of the network const char* password = ""; // Password of the network const IPAddress host = {192, 168, 1, 117}; const int remote_port = 3000; // Port for the initial connection const int local_port = 9000; // Local port for UDP communication /* Buffers */ char buffer[30]; // Message buffer char read_buffer[255]; // Buffer to read received messages int generation = 0; // Number of datapoints collected /* Global Structs */ WiFiUDP Udp; Adafruit_BNO055 bno = Adafruit_BNO055(55); /* Packet structure for data transport * * ---------------------------------------------------------------------- * | Sensor Idenitifier | Q0 | Q1 | Q2 | Q3 | Generation (packet number)| * ---------------------------------------------------------------------- * The sensor identifier is a number which is assigned to the sensor in its * firmware. During the visualiation of the data, the sensor identifier is * matched to the joint for which the sensor recorded the data. * * Q0-Q3 are the parts of the orientation quaternions supplied by the sensor * * The Generation (or packet number) is used to determine the order of datapoints * since the order of arrival might not be chronological. * */ struct sensor_packet_t { int id; float q0; float q1; float q2; float q3; int generation; }; /* Helper function to push onto the message stack */ void push(int n, char* buf, int top) { if (n < 0) { n = n * -1; buf[top] = (n >> 24) & 0xFF; buf[top + 1] = (n >> 16) & 0xFF; buf[top + 2] = (n >> 8) & 0xFF; buf[top + 3] = n & 0xFF; buf[top + 4] = 1; // the sign flag } else { buf[top] = (n >> 24) & 0xFF; buf[top + 1] = (n >> 16) & 0xFF; buf[top + 2] = (n >> 8) & 0xFF; buf[top + 3] = n & 0xFF; buf[top + 4] = 0; } } /* Helper function to turn floating point numebrs into integers * Takes a float and the precison to round to * The point is shifted by the given precision * and rounded to the next integer. This integer * is then given returned. * */ int round_to_int(float x, float prec) { x = x * pow(10, prec); x = round(x); return (int) x; } void setup(void) { // DEBUG: Serial.begin(115200); delay(100); Wire.pins(4, 5); // Setup the IO pins if(!bno.begin()) { // DEBUG: Serial.println("Could not find BNO055"); } Serial.print("Connecting to the network "); Serial.println(ssid); // Connect to the network WiFi.begin(ssid, password); while(WiFi.status() != WL_CONNECTED) { delay(500); // DEBUG: Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP Address:"); Serial.println(WiFi.localIP()); delay(1000); Udp.begin(local_port); // Tell the server this sensor is ready // by sending the current orientation imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER); int roll = round_to_int(euler.x(), 4.0); int pitch = round_to_int(euler.y(), 4.0); int yaw = round_to_int(euler.z(), 4.0); int top = 0; push(sensor_id, buffer, top); top = top + 5; push(roll, buffer, top); top = top + 5; push(pitch, buffer, top); top = top + 5; push(yaw, buffer, top); top = top + 5; Udp.beginPacket(host, remote_port); Udp.write(buffer, 100); Udp.endPacket(); // Wait for the recording to begin while(Udp.parsePacket() < 1) { delay(1000); } }; void loop(void) { imu::Quaternion quat = bno.getQuat(); // Get the absolute sensor position as a quaternion Serial.print(quat.w()); Serial.print(quat.x()); Serial.print(quat.y()); Serial.print(quat.z()); sensor_packet_t packet = {.id = sensor_id, .q0 = round_to_int(quat.w(), 4.0), .q1 = round_to_int(quat.x(), 4.0), .q2 = round_to_int(quat.y(), 4.0), .q3 = round_to_int(quat.z(), 4.0), .generation = generation}; generation = generation + 1; int top = 0; push(packet.id, buffer, top); top = top + 5; push(packet.q0, buffer, top); top = top + 5; push(packet.q1, buffer, top); top = top + 5; push(packet.q2, buffer, top); top = top + 5; push(packet.q3, buffer, top); top = top + 5; push(packet.generation, buffer, top); Serial.println(packet.q1); Udp.beginPacket(host, remote_port); Udp.write(buffer, 30); Udp.endPacket(); if(Udp.parsePacket() > 1) { // If the server sends a byte, the sensor will end the recording i.e. shutdown exit(0); } delay(100); // Set the delay to 100ms since the sensor is only capable of reading at 100Hz };<file_sep>import math def quartet_to_int(q): """ Converts the raw data back into integers """ r = 0 r += q[0] << 24 r += q[1] << 16 r += q[2] << 8 r += q[3] # reverse of the push function in the sensors firmware if q[4] == 1: return r * -1 else: return r def unpack_init(packet): id = quartet_to_int(packet[:5]) x = quartet_to_int(packet[5:10]) / (10 ** 4) y = quartet_to_int(packet[10:15]) / (10 ** 4) z = quartet_to_int(packet[15:20]) / (10 ** 4) return(id, x, y, z) def unpack_quaternion(packet): """ Unpacks the quaternion packet and returns a sqlite friendly tuple of values """ # The first four bytes form the sensor id id = quartet_to_int(packet[:5]) print(packet[5:10]) w = quartet_to_int(packet[5:10]) / (10 ** 4) x = quartet_to_int(packet[10:15]) / (10 ** 4) y = quartet_to_int(packet[15:20]) / (10 ** 4) z = quartet_to_int(packet[20:25]) / (10 ** 4) gen = quartet_to_int(packet[25:30]) return (id, w, x, y, z, gen) def unpack_raw(packet): """ Unpacks the raw packet and returns a sqlite friendly tuple of values """ # sensor id id = quartet_to_int(packet[:5]) ax = quartet_to_int(packet[5:10]) / (10 ** 4) ay = quartet_to_int(packet[10:15]) / (10 ** 4) az = quartet_to_int(packet[15:20]) / (10 ** 4) gx = quartet_to_int(packet[20:25]) / (10 ** 4) gy = quartet_to_int(packet[25:30]) / (10 ** 4) gz = quartet_to_int(packet[30:35]) / (10 ** 4) mx = quartet_to_int(packet[35:40]) / (10 ** 4) my = quartet_to_int(packet[40:45]) / (10 ** 4) mz = quartet_to_int(packet[45:50]) / (10 ** 4) gen = quartet_to_int(packet[50:55]) / (10 ** 4) return (id, ax, ay, az, gx, gy, gz, mx, my, mz, gen) def unpack_both(packet): """ Unpacks a packet w/ raw and quaternion data and returns a sqlite friendly tuple of values """ # sensor id id = quartet_to_int(packet[:5]) # sensor data ax = quartet_to_int(packet[5:10]) / (10 ** 4) ay = quartet_to_int(packet[10:15]) / (10 ** 4) az = quartet_to_int(packet[15:20]) / (10 ** 4) gx = quartet_to_int(packet[20:25]) / (10 ** 4) gy = quartet_to_int(packet[25:30]) / (10 ** 4) gz = quartet_to_int(packet[30:35]) / (10 ** 4) mx = quartet_to_int(packet[35:40]) / (10 ** 4) my = quartet_to_int(packet[40:45]) / (10 ** 4) mz = quartet_to_int(packet[45:50]) / (10 ** 4) # 9 x = quartet_to_int(packet[50:55]) / (10 ** 4) y = quartet_to_int(packet[55:60]) / (10 ** 4) z = quartet_to_int(packet[60:65]) / (10 ** 4) # 13 # packet generation gen = quartet_to_int(packet[65:70]) / (10 ** 4) return (id, ax, ay, az, gx, gy, gz, mx, my, mz, x, y, z, gen) def quaternion_to_euler_angles(w, x, y, z): """ Converts quaternions into euler angles (used for bhv output) """ x_0 = 2.0 * (w * x + y * z) x_1 = 1.0 - 2.0 * (x ** 2 + y ** 2) x = math.atan2(x_0, x_1) y = 2.0 * (w * y - z * x) if y > 1.0: y = 1.0 if y < -1.0: y = -1.0 y = math.asin(y) z_0 = 2.0 * (w * z + x * y) z_1 = 1.0 - 2.0 * (y ** 2 + z ** 2) z = math.atan2(z_0, z_1) return (x, y, z) def find_all(string, sub): start = 0 while True: start = string.find(sub, start) if start == -1: return yield start start += len(sub)<file_sep>#include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> Adafruit_BNO055 bno = Adafruit_BNO055(55); void setup(void) { Serial.begin(115200); delay(100); Wire.pins(4, 5); if(!bno.begin()) { Serial.println("Could not find BNO055"); } } void loop(void) { imu::Quaternion quat = bno.getQuat(); Serial.print(quat.w()); Serial.print(","); Serial.print(quat.x()); Serial.print(","); Serial.print(quat.y()); Serial.print(","); Serial.print(quat.z()); Serial.println(","); delay(100); }
327cacabccfe58424117f03a143d065eabe08fd3
[ "Markdown", "Python", "C++" ]
6
Markdown
Massendefekt/openmocap
8ea89e9016ce3f5fc7d952c4bdcbe212cc9e3932
86631de3c4ec2fc08686c3e96b98e61f65d71491
refs/heads/master
<repo_name>skarapedulbuk/Androi_HW_01<file_sep>/app/src/main/java/com/skarapedulbuk/HW1/MainActivity.java package com.skarapedulbuk.HW1; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.Button; import android.widget.CalendarView; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.next_button); ToggleButton calendarRotate = findViewById(R.id.rotate_calendar); CalendarView calendar1 = findViewById(R.id.calendar1); button.setOnClickListener(v -> setContentView(R.layout.activity_optional)); calendarRotate.setOnClickListener(v -> { if (calendar1.getRotation() < 360) { calendar1.setRotation(calendar1.getRotation() + 45); } else { calendar1.setRotation(0); } }); } }
8ad6bb5e53bb6fd6120d87c23f420c5bedca495f
[ "Java" ]
1
Java
skarapedulbuk/Androi_HW_01
fe50cd45a46604a6852d4aa4fcd4c746595fb085
dc59dc9e6b32e4aab8534bc06df1685b1f792ccf
refs/heads/master
<repo_name>AdamHodgson/HackerRank<file_sep>/Algorithms/Warm up/DiagonalDifference.java import java.util.*; import java.math.*; public class Solution { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] array = new int[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) array[i][j] = in.nextInt(); System.out.println(diagonalDifference(array)); } public static int diagonalDifference(int[][] numbers){ int pointerA = 0; int pointerB = numbers.length-1; int difference = 0; for(int i=0;i<numbers.length;i++){ difference -= numbers[i][pointerA]- numbers[i][pointerB]; pointerA++; pointerB--; } return Math.abs(difference); } } <file_sep>/Algorithms/Sorting/InsertionSort.java public class Selection { public static void main(String[] args){ int[] array = new int[] {2,4,1,7}; System.out.println(java.util.Arrays.toString(array)); System.out.println(java.util.Arrays.toString(insertion(array))); } private static int[] insertion(int[] a){ for(int i = 1; i < a.length; i ++ ){ int element = a[i]; int j = i; while(j > 0 && element < a[j - 1]){ a[j] = a[j - 1]; j -- ; } a[j] = element; } return a; } <file_sep>/Algorithms/Sorting/SelectionSort.java public class Selection { public static void main(String[] args){ int[] array = new int[] {1, 10, 2, 30, 15, 8}; System.out.println(java.util.Arrays.toString(array)); System.out.println(java.util.Arrays.toString(sort(array))); } private static int[] sort(int[] a){ for(int i = 0; i < a.length - 1; i++ ){ int min = i; for(int j = i + 1; j < a.length; j ++ ) if(a[j] < a[min]) min = j; // Swap variables in single line a[min] = a[min] ^ a[i] ^ (a[i] = a[min]); } return a; } }
de42af9c390e7ec1bdbdd29709ba5f1da0572c9c
[ "Java" ]
3
Java
AdamHodgson/HackerRank
e61864948007a4dbbc291dd1df04069d72d22769
d8fb394c2df40e822a626d9485f00ea36c383b87
refs/heads/master
<file_sep>#-*- coding: utf-8 -* __author__ = 'Howie' import tornado.escape import hashlib from methods.pDb import newsDb from config.n_conf import admin from handlers.base import BaseHandler class IndexHandler(BaseHandler): def get(self): self.clear_cookie("user") self.render("index.html") if admin["WEBSITE"] else self.write("<h3>网站正在维护...</h3>") def post(self): username = self.get_argument("username") password = self.get_argument("password") mSql = newsDb() result = mSql.select_table("n_admin", "*", "name", username) if result: db_pwd = result[0][2] password = hashlib.md5((admin["TOKEN"]+password).encode("utf-8")).hexdigest() if db_pwd == password: self.set_current_user(username) #将当前用户名写入cookie self.write(username) else: self.clear_cookie("user") self.write("-1") else: self.clear_cookie("user") self.write("-1") def set_current_user(self,user): if user: self.set_secure_cookie('user',tornado.escape.json_encode(user)) else: self.clear_cookie("user") <file_sep> import os class BayesOperator(object): def __init__(self,train_data_file,model_file): self.train_data_file = open(train_data_file,"r") self.model_file = open(model_file,'w') #存储每一种类型出现的次数 self.class_count = {} #存储每一种类型下各个单词出现的次数 self.class_word_count = {} #唯一单词总数 self.unique_words = {} #===========贝叶斯参数============# #每个类别的先验概率 self.class_probabilities = {} #拉普拉斯平滑,防止概率为0的情况出现 self.laplace_smooth = 0.1 #模型训练结果集 self.class_word_prob_matrix = {} #当某个单词在某类别下不存在时,默认的概率(拉普拉斯平滑后) self.class_default_prob = {} def __del__(self): self.train_data_file.close() self.model_file.close() def loadData(self): line_num = 0 line = self.train_data_file.readline().strip() while len(line)>0: words = line.split('#')[0].split() category = words[0] if category not in self.class_count: self.class_count[category] = 0 self.class_word_count[category] = {} self.class_word_prob_matrix[category] = {} self.class_count[category] += 1 for word in words[1:]: word_id = int(word) #取得唯一id描述 if word_id not in self.unique_words: self.unique_words[word_id] = 1 if word_id not in self.class_word_count[category]: self.class_word_count[category][word_id] = 1 else: self.class_word_count[category][word_id] += 1 line = self.train_data_file.readline().strip() line_num += 1 # print (line_num,'training instances loaded') print(len(self.class_count),"categories!",len(self.unique_words),"words!") def computeModel(self): #计算P(Yi) news_count = 0 for count in self.class_count.values(): news_count += count for class_id in self.class_count.keys(): self.class_probabilities[class_id] = float(self.class_count[class_id])/news_count #计算P(X|Yi)<=====>计算所有P(Xi|Yi)的积<=====>计算所有Log(P(Xi|Yi))的和 for class_id in self.class_word_count.keys(): #当前类别下所有单词的总数 sum = 0.0 for word_id in self.class_word_count[class_id].keys(): sum += self.class_word_count[class_id][word_id] count_Yi = (float)(sum + len(self.unique_words)*self.laplace_smooth) #计算单个单词在某类别下的概率,存储在结果矩阵中, # 所有当前类别没有的单词赋以默认概率(即使用拉普拉斯平滑) for word_id in self.class_word_count[class_id].keys(): self.class_word_prob_matrix[class_id][word_id] = \ (float)(self.class_word_count[class_id][word_id] + self.laplace_smooth)/count_Yi self.class_default_prob[class_id] = (float)(self.laplace_smooth)/count_Yi print(class_id,'matrix finished,length=',len(self.class_word_prob_matrix[class_id])) return def saveModel(self): #把每个分类的先验概率写入文件 for class_id in self.class_probabilities.keys(): self.model_file.write(class_id) self.model_file.write(' ') self.model_file.write(str(self.class_probabilities[class_id])) self.model_file.write(' ') self.model_file.write(str(self.class_default_prob[class_id])) self.model_file.write('#') self.model_file.write('\n') #把每个单词在当前类别的概率写入文件 for class_id in self.class_word_prob_matrix.keys(): self.model_file.write(class_id+' ') for word_id in self.class_word_prob_matrix[class_id].keys(): self.model_file.write(str(word_id)+' '\ + str(self.class_word_prob_matrix[class_id][word_id])) self.model_file.write(' ') self.model_file.write('\n') return def train(self): self.loadData() self.computeModel() self.saveModel() train_data_file = os.path.abspath(".") + "/NavieBayesInfo/train_news_Info.txt" model_file = os.path.abspath(".") + "/NavieBayesInfo/model.txt" bt = BayesOperator(train_data_file,model_file) bt.train()<file_sep>## Tornado新闻数据管理平台 ### 简述: **代码规范以及项目结构都有很大问题,不再维护,当做大学时期的回忆保存。** `git clone https://github.com/howie6879/getNews`至本地即可 ### 说明: 对采集的新闻数据进行分析,后台实现图形化操作,生成API供Android调用 ``` myNews Usage: myNews [-p] <port> Options: -h,--help 显示帮助菜单 -p 端口号 Example: myNews -p 8888 设置端口号为8888 ``` <file_sep># -*-coding:utf-8-*- __author__ = 'howie' admin = dict( WEBSITE=True, TOKEN="<PASSWORD>" ) # 本地数据库配置 localDatabase = dict( host="127.0.0.1", user="root", password="", db="howie", charset="utf8", port=3306 ) # 路径配置 #dirPath = "/home/howie/programming/python/getNews" dirPath = "/root/programming/git/getNews" <file_sep># -*-coding:utf-8-*- __author__ = 'howie' import os from config.n_conf import dirPath class NewsController(): """ 系统控制类 """ def newsFiles(self, operator, sourceName): """ :func 获取spider/sourceName/目录下爬取的各个新闻excel表 :param operator: 根据get或rm进行获取文件以及删除文件操作 sourceName:新闻网站文件夹 :return:获取文件操作返回文件名列表,删除文件,删除成功返回allFiles=False,表示目录下没有文件 """ # 获取新闻目录 path = os.path.join(os.path.join(dirPath, 'spider'), sourceName) allFiles = [] for dir in os.listdir(path): tarPath = os.path.join(path, dir) if os.path.isdir(tarPath): files = [file for file in os.listdir(tarPath) if os.path.isfile(os.path.join(tarPath, file)) and os.path.splitext(file)[1] == ".xlsx"] if files and operator == "get": for file in files: allFiles.append(os.path.join(tarPath, file)) # 删除原始数据 elif files and operator == "rm": for file in files: os.remove(os.path.join(tarPath, file)) log = os.path.join(tarPath, file) + "文件删除成功" print(log) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") if not allFiles: return False else: return allFiles def rmRepeate(self,*dirs): """ func: 删除已经去重的文件 :param *dirs:文件夹list,dirs[0]里面含有文件夹名称,默认为2个 :return: 删除成功返回True """ path = os.path.join(dirPath,'spider') #生成去重的数据目录 for dir in dirs[0]: path = os.path.join(path,str(dir)) files = [file for file in os.listdir(path) if os.path.isfile(os.path.join(path,file)) and os.path.splitext(file)[1] == ".xlsx"] for file in files: os.remove(os.path.join(path, file)) log = os.path.join(path, file) + "文件删除成功" print(log) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") return True <file_sep>/** * Created by jeezy-lyoung on 16-8-2. */ $(document).ready(function () { var net = "http://127.0.0.1:8888"; var count = 3; var page_value = 1; var alrequest = 0; var page = "xia"; var time = '1'; var tooken = '<PASSWORD>'; function get_user() { var qx = {"alrequest":alrequest,"page":page,"time":time, "tooken":tooken}; $.ajax({ type:"get", url:net + "/api/adminfeedback?count=3", data:qx, cache:false, success:function(data) { var is_success; var result = eval('(' + data + ')'); var all_data = result.data; is_success = result.message; if (is_success == "failed"){ alert("已是最后一页"); page_value = page_value - 1; } else{ var table = ""; var u_id = ""; var feed_content = ""; var get_time = "" var name = ""; var is_rep = ""; var rep_button = ""; for(i=0;i<all_data.length;i++){ name = "<div class='feedback_name'>"+ all_data[i].user_name +": </div>" feed_content = "<div class='feedback_content'>"+ all_data[i].contents +": </div>" get_time = "<div class='feedback_gettime'>"+ all_data[i].times +": </div>" is_rep = "<div class='feedback_isreply'>是否已审批: <span class='rep'>否</span>: </div>" rep_button = "<input class='rep_button' type='button' value='审批'>" table = table + "<div class='each_feedback'>" +name+feed_content+get_time+is_rep+rep_button + "</div>" } document.getElementById("not_feedback").innerHTML = table; } } }); } get_user(); $("#xia").click(function () { page = "xia"; alrequest = page_value * 3; get_user(); page_value = page_value + 1; }); $("#shang").click(function () { page = "shang"; if (page_value == 1){ alert("已是第一页") }else{ page_value = page_value - 1 ; alrequest = page_value * 3; get_user(); } }); })<file_sep># -*-coding:utf-8-*- __author__ = 'howie' import time import os import spider.toutiao.touTiaoSpider as ts import spider.sina.sinaSpider as ss import spider.mergeExcel as me import spider.wordAna.contentSpider as cs from config.n_conf import dirPath ss.cate = ["news_world", "news_sports", "news_finance", "news_society", "news_entertainment", "news_military", "news_tech"] def touTiao(category, page, num): # 爬取今日头条 for cate in category: ts.getToutiaoNews(cate, page, num) def sina(num=1000, page=1, type=ss.cate): # 爬取新浪新闻 ss.getSinaNews(num, page, type) def merge(): #新闻合并操作 mainPath = os.path.join(dirPath,'spider') secondPath = os.path.join(mainPath,'allSource') mergeExel = me.mergeExcel() mergeExel.merge(mainPath,secondPath) def wordAna(): cs.getNewsContent() def insertNews(): pass #touTiao(category=ts.category, page=2, num=20, time=time.time()) #sina() #merge() #wordAna()<file_sep>## 互联网推荐系统API分析 ### 一、目标新闻网站api分析 #### 1-1.今日头条 ​ 今日头条目录可分为如下部分: ​ domain : `http://toutiao.com` ​ directory: ​ -1.1: *hot_words* : `http://toutiao.com/hot_words/?_=1463066142015` ​ 链接功能:返回实时新闻热词 ​ 参数:?_ ​ 参数值:当前时间戳 ?_ = time.time() ​ -1.2: */api/article/recent/* : `http://toutiao.com/api/article/recent/?source=2&count=20&category=__all__&max_behot_time=1463067626.96&utm_source=toutiao&offset=0&_=1463067627001` ​ 链接功能:返回对应模块实时新闻 ​ 链接:`http://toutiao.com/api/article/recent/` `?count=20&category=__all__&max_behot_time=1463067626.96` ​ | 参数 | 参数值 | | :------------: | :------: | | count | 返回新闻数量 | | category | 新闻种类 | | max_behot_time | 热点新闻最大时间 | ​ category: | category | name | | :----------------: | :--: | | \_\_all__ | 推荐新闻 | | news_hot | 热点新闻 | | video | 视频新闻 | | gallery_detail | 图片新闻 | | news_society | 社会新闻 | | news_entertainment | 娱乐新闻 | | news_tech | 科技新闻 | | news_car | 汽车新闻 | | news_sports | 体育新闻 | | news_finance | 财经新闻 | | news_military | 军事新闻 | | news_world | 国际新闻 | | news_fashion | 时尚新闻 | | news_travel | 旅游新闻 | | news_discovery | 探索新闻 | | news_baby | 育儿新闻 | | news_regimen | 养生新闻 | | news_story | 故事新闻 | | news_essay | 美文新闻 | | news_game | 游戏新闻 | | news_history | 历史新闻 | | news_food | 美食新闻 | #### 1-2.新浪新闻 ​ 新浪新闻目录可分为如下部分: ​ domain : `http://roll.news.sina.com.cn` ​ directory: ​ 链接功能:进入新浪新闻滚动业,页面返回的是新浪当前最新新闻 ​ -2.1: *num=20&asc=&page=1* : `http://roll.news.sina.com.cn/interface/rollnews_ch_out_interface.php?col=89&spec=&type=&k=&num=20&asc=&page=1&r=0.41627189057293945` ​ 链接功能:返回滚动新闻 ​ 参数:num每页新闻条数,page页数 ​ | 参数 | 参数值 | | :--: | :----: | | num | 每页新闻条数 | | page | 页数 | ### 二、互联网推荐系统api **说明:调用api时,首选进行tooken验证,验证通过返回结果** #### 2-1.注册api 链接:`/api/register?name=huyu&passwd=<PASSWORD>&tags=x&phone=X&time=X&tooken=X` 链接功能:新用户进行注册 | 参数 | 说明 | | :----: | :---------: | | name | 注册用户昵称 | | passwd | 密码 | | phone | 电话 | | tags | 标签1,标签2.... | | time | 注册时间戳 | | token | 身份验证字符串 | **参数返回:** 注册结果:`{"data": {"user_id": ""}, "message": "success"}` 用户已存在:`{"message": "failed", "data": {"flag": -1}}` 注册失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-2.登录api 链接:`/api/login?passwd=x&phone=x&time=x&tooken=x` 链接功能:用户登录 | 参数 | 说明 | | :----: | :-----: | | passwd | 密码 | | phone | 电话 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 登录成功:`{"message": "success", "data": {"user_id": ""}}` 密码错误:`{"message": "failed", "data": {"flag": -1}}` 用户不存在:`{"message": "failed", "data": {"flag": -2}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-3.新闻列表api 链接:`/api/newstags?count=x&alrequest=x&userid=x&tag=x&time=x&tooken=x` 链接功能:返回新闻列表信息 | 参数 | 说明 | | :-------: | :----------: | | count | 请求新闻数量 | | alrequest | 已请求新闻数量 | | userid | 用户编号 | | tag | 新闻标签(默认空为全部) | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 返回参数说明: | 参数 | 说明 | | :-----------: | :---: | | time | 时间 | | abstract | 摘要 | | title | 标题 | | comment_times | 评论次数 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | news_id | 新闻编号 | | image | 图片url | | source | 来源 | 查询返回成功: `{"message": "success", "data": [{"time": "", "abstract": "", "title": "",` `"comment_times": 1, "read_times": 1, "love_times": 1, "news_id": "",` `"image": "", "source": ""}, {"time": "", "abstract": "", "title": "",` `"comment_times": 2, "read_times": 2, "love_times": 2, "news_id": "",` `"image": "", "source": ""}]}` 请求数目超出: `{"message": "failed", "data": {"flag": -1}}` 请求失败: `{"message": "failed", "data": {"flag": 0}}` #### 2-4.新闻详情api 链接:`/api/newscontent?newsid=x&userid=x&time=x&tooken=x` 链接功能:返回新闻列表信息 | 参数 | 说明 | | :----: | :-----: | | newsid | 新闻编号 | | userid | 用户编号 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 参数返回说明: | 参数 | 说明 | | :-------------: | :------------: | | content | 新闻html正文 | | comment_time | 留言时间 | | username | 留言用户昵称 | | head_url | 留言用户头像url | | comment_content | 留言内容 | | is_comment | 用户是否评论该新闻(0/1) | | is_love | 用户是否喜欢该新闻(0/1) | 查询返回成功: `{"message": "success", "data": {"content": "", "comment_list": [{"time": "",` `"username": "", "head_url": "", "comment_content": "","dianzan_num": "9"}, {"time":` `"shijian2", "username": "", "head_url": "", "comment_content": ""}],` `"is_comment": 1, "is_love": 0}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-5.用户信息查询api 链接:`/api/userinfo?userid=x&time=x&tooken=x` 链接功能:返回用户详细信息 | 参数 | 说明 | | :----: | :-----: | | userid | 用户编号 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 参数返回说明: | 参数 | 说明 | | :-----------: | :--: | | user_name | 用户昵称 | | phone | 用户电话 | | image | 头像 | | email | 用户邮箱 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | message_times | 评论次数 | 查询返回成功: `{"message": "success", "data": {"love_times": 1, "phone": "",` `"message_times": 1, "read_times": 1, "user_name": "", "email": "",` `"image": ""}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-6.用户信息修改api 链接:`/api/userinfochange?userid=x&username=x&image=x` `&email=x&time=1&tooken=x` 链接功能:返回用户详细信息 | 参数 | 说明 | | :------: | :-----: | | userid | 用户编号 | | username | 用户昵称 | | image | 头像 | | email | 用户邮箱 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 参数返回说明: | 参数 | 说明 | | :-----------: | :--: | | user_name | 用户昵称 | | phone | 用户电话 | | image | 头像 | | email | 用户邮箱 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | message_times | 评论次数 | 查询返回成功: `{"message": "success", "data": {"love_times": 1, "phone": "",` `"message_times": 1, "read_times": 1, "user_name": "", "email": "",` `"image": ""}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-7.用户一周喜欢新闻列表api 链接:`/api/lovelist?userid=000001&time=1&tooken=7<KEY>` 链接功能:返回用户详细信息 | 参数 | 说明 | | :----: | :-----: | | userid | 用户编号 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 参数返回说明: | 参数 | 说明 | | :-----------: | :--: | | news_id | 新闻编号 | | title | 新闻标题 | | abstract | 新闻摘要 | | time | 时间 | | image | 新闻图片 | | tag | 新闻标签 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | message_times | 评论次数 | 查询返回成功: `{"message": "success",data": [{"comment_times": 0, "image": "", "tag": "", "time": "", "title": "", "love_times": 3, "news_id": "", "abstract": "", "read_times": 7}]}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-8.热点新闻(每天喜欢/阅读/评论次数最多)api 链接:`/api/hotlist?hot=1&time=1&tooken=<KEY>9b2b2c` 链接功能:返回用户详细信息 | 参数 | 说明 | | :-------: | :------------: | | hot | 1为喜欢/2为阅读/3为评论 | | count | 请求数量 | | alrequest | 已请求数量 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 参数返回说明: | 参数 | 说明 | | :-----------: | :--: | | news_id | 新闻编号 | | title | 新闻标题 | | abstract | 新闻摘要 | | time | 时间 | | image | 新闻图片 | | tag | 新闻标签 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | message_times | 评论次数 | 查询返回成功: `{"message": "success",data": [{"comment_times": 0, "image": "", "tag": "", "time": "", "title": "", "love_times": 3, "news_id": "", "abstract": "", "read_times": 7}]}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-9.喜欢api 链接:`/api/lovenews?newsid=x&userid=x&islove=x&time=x&tooken=x` 链接功能:用户登录 | 参数 | 说明 | | :----: | :---------: | | newsid | 新闻编号 | | userid | 用户编号 | | islove | 1为喜欢/0为取消喜欢 | | time | 时间 | | token | 身份验证字符串 | **参数返回:** 喜欢成功:`{"message": "success", "data": {"flag": 1}}` 取消喜欢:`{"message": "success", "data": {"flag": 2}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-10.反馈api 链接:`/api/feedback?userid=x&feedback=x` `&email=x&time=1&tooken=x` 链接功能:返回用户详细信息 | 参数 | 说明 | | :------: | :-----: | | userid | 用户编号 | | feedback | 反馈内容 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 喜欢成功:`{"message": "success", "data": {"flag": 1}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` #### 2-11.关键词搜索api 链接:`/api/newstags?keyword=x&time=x&tooken=x` 链接功能:返回新闻列表信息 | 参数 | 说明 | | :-----: | :-----: | | keyword | 关键词 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 返回参数说明: | 参数 | 说明 | | :-----------: | :---: | | time | 时间 | | abstract | 摘要 | | title | 标题 | | comment_times | 评论次数 | | read_times | 阅读次数 | | love_times | 喜欢次数 | | news_id | 新闻编号 | | image | 图片url | | source | 来源 | 查询返回成功: `{"message": "success", "data": [{"time": "", "abstract": "", "title": "",` `"comment_times": 1, "read_times": 1, "love_times": 1, "news_id": "",` `"image": "", "source": ""}, {"time": "", "abstract": "", "title": "",` `"comment_times": 2, "read_times": 2, "love_times": 2, "news_id": "",` `"image": "", "source": ""}]}` 请求失败: `{"message": "failed", "data": {"flag": 0}}` #### 2-12.评论api 链接:`/api/comment?userid=x&newsid=x&content=x&time=x&tooken=x` 链接功能:返回新闻列表信息 | 参数 | 说明 | | :-----: | :-----: | | userid | 用户编号 | | newsid | 新闻编号 | | content | 评论内容 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 返回参数说明: | 参数 | 说明 | | :----------: | :----: | | user_image | 评论用户头像 | | user_id | 评论用户编号 | | user_name | 评论用户昵称 | | comment_time | 评论时间 | | content | 评论内容 | | news_id | 新闻编号 | 查询返回成功: `{"message": "success", "data": {"user_image": "", "user_id": "", "user_name": "", "comment_time": "", "content": "", "news_id": ""}}` 请求失败: `{"message": "failed", "data": {"flag": 0}}` #### 2-13.点赞评论api 链接:`/api/feedback?userid=x&feedback=x` `&email=x&time=1&tooken=x` 链接功能:返回用户详细信息 | 参数 | 说明 | | :---------: | :-----: | | userid | 用户编号 | | newsid | 新闻编号 | | comment | 该评论内容 | | commenttime | 该评论时间 | | time | 验证时间戳 | | token | 身份验证字符串 | **参数返回:** 喜欢成功:`{"message": "success", "data": {"flag": 1}}` 请求失败:`{"message": "failed", "data": {"flag": 0}}` <file_sep>"update user_tag_score set news_baby,news_entertainment,news_discovery,news_history,news_society," \ "news_game,news_sports,news_car,news_essay,news_tech,news_military,news_travel,news_fashion,news_regimen," \ "news_story,news_finance,news_food,news_world = '" +tag_list_score['news_baby']+"','"+tag_list_score['news_entertainment']+"','"+\ tag_list_score['news_discovery']+"','"+tag_list_score['news_history']+"','"+tag_list_score['news_society']+"','"+tag_list_score['news_game']+"','"+\ tag_list_score['news_sports']+"','"+tag_list_score['news_car']+"','"+tag_list_score['news_essay']+"','"+tag_list_score['news_tech']+\ "','"+tag_list_score['news_military']+"','"+tag_list_score['news_travel']+"','"+tag_list_score['news_fashion']+"','"+tag_list_score['news_regimen']\ +"','"+tag_list_score['news_story']+"','"+tag_list_score['news_finance']+"','"+tag_list_score['news_food']+"','"+tag_list_score['news_world']+"' where user_id = '" + user_id + "'"<file_sep>-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: 2016-08-11 19:45:06 -- 服务器版本: 10.1.13-MariaDB -- PHP Version: 5.6.20 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `howie` -- -- -------------------------------------------------------- -- -- 表的结构 `get_news` -- CREATE TABLE `get_news` ( `news_id` varchar(20) NOT NULL, `news_link` varchar(200) DEFAULT NULL, `source` varchar(20) DEFAULT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `title` varchar(50) NOT NULL, `abstract` varchar(500) NOT NULL, `tag` varchar(20) NOT NULL, `text_content` mediumtext NOT NULL, `html_content` mediumtext NOT NULL, `image` varchar(1000) DEFAULT NULL, `keyword` varchar(100) NOT NULL, `is_old` int(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `news_comment` -- CREATE TABLE `news_comment` ( `news_id` varchar(20) NOT NULL, `comment` varchar(20000) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `news_feedback` -- CREATE TABLE `news_feedback` ( `user_id` varchar(10) NOT NULL, `feedback` varchar(200) DEFAULT NULL, `getTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `reply` varchar(200) DEFAULT NULL, `replyTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `isReply` int(11) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `news_feedback` -- INSERT INTO `news_feedback` (`user_id`, `feedback`, `getTime`, `reply`, `replyTime`, `isReply`) VALUES ('000002', 'Good', '2016-06-14 13:19:23', NULL, '0000-00-00 00:00:00', 0), ('000002', 'Good', '2016-06-14 13:25:15', NULL, '0000-00-00 00:00:00', 0); -- -------------------------------------------------------- -- -- 替换视图以便查看 `news_hot` -- CREATE TABLE `news_hot` ( `news_id` varchar(20) ,`time` timestamp ,`image` varchar(1000) ,`abstract` varchar(500) ,`source` varchar(20) ,`title` varchar(50) ,`tag` varchar(20) ,`love_times` int(11) ,`read_times` int(11) ,`comment_times` int(11) ); -- -------------------------------------------------------- -- -- 表的结构 `news_mess` -- CREATE TABLE `news_mess` ( `news_id` varchar(20) NOT NULL, `tag` varchar(20) NOT NULL, `read_times` int(11) NOT NULL DEFAULT '0', `love_times` int(11) NOT NULL DEFAULT '0', `comment_times` int(11) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `news_nums` -- CREATE TABLE `news_nums` ( `tag` varchar(20) NOT NULL, `nums` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 替换视图以便查看 `news_nums_view` -- CREATE TABLE `news_nums_view` ( `tag` varchar(20) ,`count` bigint(21) ); -- -------------------------------------------------------- -- -- 表的结构 `news_recommend` -- CREATE TABLE `news_recommend` ( `user_id` varchar(10) NOT NULL, `news_score` mediumtext ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `news_tag_chinese` -- CREATE TABLE `news_tag_chinese` ( `news_society` varchar(20) DEFAULT NULL, `news_entertainment` varchar(20) DEFAULT NULL, `news_tech` varchar(20) DEFAULT NULL, `news_car` varchar(20) DEFAULT NULL, `news_sports` varchar(20) DEFAULT NULL, `news_finance` varchar(20) DEFAULT NULL, `news_military` varchar(20) DEFAULT NULL, `news_world` varchar(20) DEFAULT NULL, `news_fashion` varchar(20) DEFAULT NULL, `news_travel` varchar(20) DEFAULT NULL, `news_discovery` varchar(20) DEFAULT NULL, `news_baby` varchar(20) DEFAULT NULL, `news_regimen` varchar(20) DEFAULT NULL, `news_story` varchar(20) DEFAULT NULL, `news_essay` varchar(20) DEFAULT NULL, `news_game` varchar(20) DEFAULT NULL, `news_history` varchar(20) DEFAULT NULL, `news_food` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `news_tag_chinese` -- INSERT INTO `news_tag_chinese` (`news_society`, `news_entertainment`, `news_tech`, `news_car`, `news_sports`, `news_finance`, `news_military`, `news_world`, `news_fashion`, `news_travel`, `news_discovery`, `news_baby`, `news_regimen`, `news_story`, `news_essay`, `news_game`, `news_history`, `news_food`) VALUES ('社会', '娱乐', '科技', '汽车', '体育', ' 财经', '军事', '国际', '时尚', '旅游', '探索', '育儿', '养生', '故事', '美文', '游戏', '历史', '美食'); -- -------------------------------------------------------- -- -- 表的结构 `news_tag_deep` -- CREATE TABLE `news_tag_deep` ( `news_id` varchar(20) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `n_admin` -- CREATE TABLE `n_admin` ( `id` int(11) NOT NULL, `name` varchar(10) NOT NULL, `pass` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `n_admin` -- INSERT INTO `n_admin` (`id`, `name`, `pass`) VALUES (2, 'admin', '<PASSWORD>'); -- -------------------------------------------------------- -- -- 表的结构 `user` -- CREATE TABLE `user` ( `user_id` varchar(10) NOT NULL, `phone` varchar(20) NOT NULL, `name` varchar(20) NOT NULL, `passwd` varchar(40) NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `user` -- INSERT INTO `user` (`user_id`, `phone`, `name`, `passwd`, `time`) VALUES ('000001', '15767956536', '<PASSWORD>', '<PASSWORD>', '2016-08-04 07:36:33'), ('000002', '15767956890', '用户157****890', '<PASSWORD>', '2016-08-04 07:36:33'), ('000003', '15767976598', '用户157****598', '<PASSWORD>', '2016-08-04 07:36:33'), ('000004', '15767979609', '用户157****609', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000005', '15766954544', '用户157****544', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000006', '15766954533', '用户157****533', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000007', '15766954531', '用户157****531', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000008', '12345678910', '用户123****910', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000009', '12345678916', '用户123****916', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000010', '12345678912', '用户123****912', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000011', '12345678986', '用户123****986', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000012', '12345678984', '用户123****984', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000013', '12345678911', '用户123****911', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000014', '12345678942', '用户123****942', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000015', '12345678941', '用户123****941', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000016', '12345678998', '用户123****998', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000017', '12356478421', '用户123****421', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000018', '12434518000', '用户124****000', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000019', '14725836912', '用户147****912', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000020', '78945612321', '用户789****321', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000021', '14789632569', '用户147****569', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000022', '14189132569', '用户141****569', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000023', '11111111111', '用户111****111', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000024', '88888888888', '用户888****888', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000025', '88888888887', '用户888****887', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000026', '87888687888', '用户878****888', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000027', '14725883691', '用户147****691', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000028', '14714714711', '用户147****711', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000029', '14714714712', '用户147****712', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000030', '14714714713', '用户147****713', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000031', '14714714717', '用户147****717', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000032', '14714714514', '用户147****514', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000033', '14714714719', '用户147****719', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000034', '99999999999', '用户999****999', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000035', '14714712345', '用户147****345', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000036', '15815815811', '用户158****811', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000037', '15815815812', '用户158****812', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000038', '15815815813', '用户158****813', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000039', '15815815814', '用户158****814', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000040', '15815815816', '用户158****816', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000041', '15815815817', '用户158****817', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000042', '15767956539', '小孩子', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000043', '15815815866', '用户158****866', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000044', '15815815877', '用户158****877', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000045', 'null', '用户112****211', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000046', '15469874566', '用户154****566', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000047', '11225544667', '用户112****667', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000048', '25814736911', '用户258****911', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000049', '88888555552', '用户888****552', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000050', '33333666661', '用户333****661', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000051', '22222222222', '用户222****222', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000052', '15767976538', '小熊猫', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000053', '15767956534', '用户157****534', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000054', '15767956541', '用户157****541', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000055', '15767956551', '用户157****551', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000056', '15767951228', '用户157****228', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000057', '15767976596', '用户157****596', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000058', '15767976593', '用户157****593', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000059', '15767976594', '用户15', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000060', '15767976592', '用户', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000061', '15767976591', '用户157***', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000062', '12457869639956', '用户12', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000063', '15765966563', '用户157', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000064', '15767976931', '用户157****931', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000065', '15767946563', '用户157****563', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000066', '15767976535', '用户157****535', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000067', '15767956891', '用户157****891', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000068', '123456', '123456', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000069', '15767976597', '用户157****597', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-04 07:36:33'), ('000070', '15767956636', '用户15767956636', 'c3cf5482a1d16021bf316d4441ea8e72', '2016-08-08 13:30:48'), ('000071', '1576796878', '353454343', '441ecebf73c4f37ef5112c4629dd4d7c', '2016-08-09 11:40:02'), ('000072', '1576797879', '3534543', '441ecebf73c4f37ef5112c4629dd4d7c', '2016-08-09 12:40:31'), ('000073', '1576*****779', '354543', '441ecebf73c4f37ef5112c4629dd4d7c', '2016-08-09 12:44:07'); -- -------------------------------------------------------- -- -- 表的结构 `user_behavior` -- CREATE TABLE `user_behavior` ( `user_id` varchar(10) NOT NULL, `news_id` varchar(20) NOT NULL, `news_tag` varchar(20) NOT NULL, `behavior_type` int(11) NOT NULL DEFAULT '0', `weight` double DEFAULT NULL, `is_comment` int(11) NOT NULL DEFAULT '0', `address` varchar(100) DEFAULT NULL, `news_way` int(11) NOT NULL DEFAULT '0', `age` varchar(20) DEFAULT NULL, `score` double DEFAULT NULL, `times` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `user_love_tag` -- CREATE TABLE `user_love_tag` ( `user_id` varchar(10) NOT NULL, `tags` varchar(300) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `user_love_tag` -- INSERT INTO `user_love_tag` (`user_id`, `tags`) VALUES ('000001', '军事,美文,探索'), ('000002', '游戏,汽车,国际,育儿'), ('000003', '娱乐,探索,美文,故事,旅游,军事,财经'), ('000004', '游戏,娱乐,探索,养生'), ('000005', '时尚,旅游,社会,财经'), ('000006', '时尚,旅游,社会,财经'), ('000007', '时尚,旅游,社会,财经'), ('000008', '美文'), ('000009', '美文'), ('000010', '美文'), ('000011', '美文'), ('000012', '美文'), ('000013', '美文'), ('000014', '美文'), ('000015', '美文'), ('000016', '美文'), ('000017', '美食'), ('000018', '历史'), ('000019', '时尚'), ('000020', '养生'), ('000021', '社会'), ('000022', '社会,养生,历史'), ('000023', '时尚'), ('000024', '汽车'), ('000025', '科技,汽车,美文'), ('000026', '游戏,故事,汽车,娱乐,美食,社会,美文'), ('000027', '美食'), ('000028', '美食'), ('000029', '游戏'), ('000030', '游戏'), ('000031', '历史'), ('000032', '美食'), ('000033', '游戏'), ('000034', '美食,美文'), ('000035', '游戏'), ('000036', '美食'), ('000037', '游戏'), ('000038', '美食'), ('000039', '美食'), ('000040', '美食'), ('000041', '美食'), ('000042', '故事,美食,社会,历史,养生'), ('000043', '时尚,养生'), ('000044', '体育,社会'), ('000045', ''), ('000046', '历史,养生,时尚'), ('000047', '历史,养生,时尚'), ('000048', '历史,养生,时尚'), ('000049', '历史,养生,时尚'), ('000050', '养生,体育,科技'), ('000051', '探索,故事,旅游,军事,科技,财经'), ('000052', '国际,探索,故事,美食,美文,旅游,军事,科技,财经'), ('000053', '探索,故事,美食,美文,旅游,军事,科技,财经'), ('000054', ''), ('000055', '故事,探索,军事,财经,旅游,美文'), ('000056', '科技,财经,娱乐'), ('000057', '探索,美文,故事,美食,旅游,军事'), ('000058', '娱乐,探索,美文,故事,旅游,军事,科技,财经'), ('000059', '娱乐,探索,故事,旅游,军事,科技,财经'), ('000060', '社会,娱乐,探索,美文,故事,旅游,军事,科技,财经'), ('000061', '美文,探索'), ('000062', '美文,故事,旅游,军事,财经'), ('000063', '娱乐,探索,美文,故事,旅游,军事,科技,财经'), ('000064', '娱乐,探索,美文,故事,美食,旅游,军事,财经'), ('000065', '探索,美文,故事,旅游,军事,财经,科技'), ('000066', '娱乐,探索,美文,故事,美食,旅游,军事,科技,财经'), ('000067', '娱乐,国际,社会,财经'), ('000068', 'news_tech'), ('000069', '故事,探索,军事,财经,养生,旅游,美食,时尚,美文'), ('000070', '国际,体育'), ('000071', ''), ('000071', '体育,国际'), ('000072', ''), ('000073', ''); -- -------------------------------------------------------- -- -- 表的结构 `user_mess` -- CREATE TABLE `user_mess` ( `user_id` varchar(10) NOT NULL, `sex` int(11) DEFAULT NULL, `age` int(11) DEFAULT NULL, `email` varchar(20) DEFAULT NULL, `address` varchar(40) DEFAULT NULL, `image` varchar(60) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `user_mess` -- INSERT INTO `user_mess` (`user_id`, `sex`, `age`, `email`, `address`, `image`) VALUES ('000001', NULL, NULL, 'yanshanren2013@163.c', NULL, ''), ('000002', NULL, NULL, NULL, NULL, NULL), ('000003', NULL, NULL, NULL, NULL, NULL), ('000004', NULL, NULL, NULL, NULL, NULL), ('000005', NULL, NULL, NULL, NULL, NULL), ('000006', NULL, NULL, NULL, NULL, NULL), ('000007', NULL, NULL, NULL, NULL, NULL), ('000008', NULL, NULL, NULL, NULL, NULL), ('000009', NULL, NULL, NULL, NULL, NULL), ('000010', NULL, NULL, NULL, NULL, NULL), ('000011', NULL, NULL, NULL, NULL, NULL), ('000012', NULL, NULL, NULL, NULL, NULL), ('000013', NULL, NULL, NULL, NULL, NULL), ('000014', NULL, NULL, NULL, NULL, NULL), ('000015', NULL, NULL, NULL, NULL, NULL), ('000016', NULL, NULL, NULL, NULL, NULL), ('000017', NULL, NULL, NULL, NULL, NULL), ('000018', NULL, NULL, NULL, NULL, NULL), ('000019', NULL, NULL, NULL, NULL, NULL), ('000020', NULL, NULL, NULL, NULL, NULL), ('000021', NULL, NULL, NULL, NULL, NULL), ('000022', NULL, NULL, NULL, NULL, NULL), ('000023', NULL, NULL, NULL, NULL, NULL), ('000024', NULL, NULL, NULL, NULL, NULL), ('000025', NULL, NULL, NULL, NULL, NULL), ('000026', NULL, NULL, NULL, NULL, NULL), ('000027', NULL, NULL, NULL, NULL, NULL), ('000028', NULL, NULL, NULL, NULL, NULL), ('000029', NULL, NULL, NULL, NULL, NULL), ('000030', NULL, NULL, NULL, NULL, NULL), ('000031', NULL, NULL, NULL, NULL, NULL), ('000032', NULL, NULL, NULL, NULL, NULL), ('000033', NULL, NULL, NULL, NULL, NULL), ('000034', NULL, NULL, NULL, NULL, NULL), ('000035', NULL, NULL, NULL, NULL, NULL), ('000036', NULL, NULL, NULL, NULL, NULL), ('000037', NULL, NULL, NULL, NULL, NULL), ('000038', NULL, NULL, NULL, NULL, NULL), ('000039', NULL, NULL, NULL, NULL, NULL), ('000040', NULL, NULL, NULL, NULL, NULL), ('000041', NULL, NULL, NULL, NULL, NULL), ('000042', NULL, NULL, 'null', NULL, ''), ('000043', NULL, NULL, NULL, NULL, NULL), ('000044', NULL, NULL, NULL, NULL, NULL), ('000045', NULL, NULL, NULL, NULL, NULL), ('000046', NULL, NULL, NULL, NULL, NULL), ('000047', NULL, NULL, NULL, NULL, NULL), ('000048', NULL, NULL, NULL, NULL, NULL), ('000049', NULL, NULL, NULL, NULL, NULL), ('000050', NULL, NULL, NULL, NULL, NULL), ('000051', NULL, NULL, NULL, NULL, NULL), ('000052', NULL, NULL, NULL, NULL, ''), ('000053', NULL, NULL, NULL, NULL, NULL), ('000054', NULL, NULL, NULL, NULL, NULL), ('000055', NULL, NULL, NULL, NULL, NULL), ('000056', NULL, NULL, NULL, NULL, NULL), ('000057', NULL, NULL, NULL, NULL, NULL), ('000058', NULL, NULL, NULL, NULL, NULL), ('000059', NULL, NULL, NULL, NULL, ''), ('000060', NULL, NULL, NULL, NULL, ''), ('000061', NULL, NULL, NULL, NULL, ''), ('000062', NULL, NULL, NULL, NULL, ''), ('000063', NULL, NULL, NULL, NULL, ''), ('000064', NULL, NULL, NULL, NULL, ''), ('000065', NULL, NULL, NULL, NULL, NULL), ('000066', NULL, NULL, NULL, NULL, ''), ('000067', NULL, NULL, NULL, NULL, NULL), ('000068', NULL, NULL, NULL, NULL, NULL), ('000069', NULL, NULL, NULL, NULL, NULL), ('000071', NULL, NULL, NULL, NULL, NULL), ('000072', NULL, NULL, NULL, NULL, NULL), ('000073', NULL, NULL, NULL, NULL, NULL); -- -------------------------------------------------------- -- -- 表的结构 `user_operate` -- CREATE TABLE `user_operate` ( `user_id` varchar(10) NOT NULL, `news_id` varchar(20) NOT NULL, `comment` varchar(1000) DEFAULT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `is_love` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `user_tag_deep` -- CREATE TABLE `user_tag_deep` ( `user_id` varchar(10) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- 表的结构 `user_tag_score` -- CREATE TABLE `user_tag_score` ( `user_id` varchar(10) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `user_tag_score` -- INSERT INTO `user_tag_score` (`user_id`, `news_society`, `news_entertainment`, `news_tech`, `news_car`, `news_sports`, `news_finance`, `news_military`, `news_world`, `news_fashion`, `news_travel`, `news_discovery`, `news_baby`, `news_regimen`, `news_story`, `news_essay`, `news_game`, `news_history`, `news_food`) VALUES ('000001', 2.694537046614036, 2.512533923323375, 2.6750895454310064, 2.1522782579492628, 2.799692362566384, 2.250496310034508, 3.108259730537031, 3.3311367459787666, 2.2092105327698275, 2.7812033222513652, 2.2123955479525237, 2.9696680705535488, 2.176075568076781, 2.144448250281169, 2.9159446905096824, 2.0957476792748952, 3.680511261795824, 2.2907711541000144), ('000002', 5.23694051421028, 4.4558833154063775, 8.476075682968919, 13.67755177926377, 3.4937616943340575, 5.838625269616177, 5.673629955818645, 5.122406927701453, 6.310783928477896, 4.258381588785207, 5.841571127377751, 6.43179983772713, 5.874526075937517, 5.791844857872957, 7.22612400088063, 5.360897620264073, 3.753835917929619, 6.17535990542753), ('000003', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000004', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000005', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000006', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000007', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000008', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000009', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000010', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000011', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000012', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000013', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000014', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000015', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000016', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000017', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000018', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000019', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000020', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000021', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000022', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000023', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000024', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000025', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000026', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000027', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000028', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000029', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000030', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000031', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000032', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000033', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000034', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000035', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000036', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000037', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000038', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000039', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000040', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000041', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000042', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1), ('000043', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000044', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000045', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000046', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000047', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000048', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000049', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000050', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1), ('000051', 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1), ('000052', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 1), ('000053', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000054', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000055', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000056', 2, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1), ('000057', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000058', 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000059', 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1), ('000060', 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1), ('000061', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000062', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000063', 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1), ('000064', 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1), ('000065', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000066', 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1), ('000067', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1), ('000068', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000069', 1.5497209752611714, 4.684211844004147, 9.662894649793694, 3.4335737307436975, 1.362041133395879, 12.971001385730487, 2.0561922416905314, 2.3408948114293455, 1.7496557333844642, 1.5268666010248908, 1.9823199713678405, 1.7530789990901845, 1.881822511462544, 1.7671557992271185, 2.0183009422470386, 5.038980176136956, 5.287616674729766, 1.933671819280247), ('000071', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000072', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000073', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ('000070', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); -- -------------------------------------------------------- -- -- 视图结构 `news_hot` -- DROP TABLE IF EXISTS `news_hot`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `news_hot` AS select `a`.`news_id` AS `news_id`,`a`.`time` AS `time`,`a`.`image` AS `image`,`a`.`abstract` AS `abstract`,`a`.`source` AS `source`,`a`.`title` AS `title`,`b`.`tag` AS `tag`,`b`.`love_times` AS `love_times`,`b`.`read_times` AS `read_times`,`b`.`comment_times` AS `comment_times` from (`get_news` `a` join `news_mess` `b`) where (`a`.`news_id` = `b`.`news_id`) ; -- -------------------------------------------------------- -- -- 视图结构 `news_nums_view` -- DROP TABLE IF EXISTS `news_nums_view`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `news_nums_view` AS select `get_news`.`tag` AS `tag`,count(`get_news`.`tag`) AS `count` from `get_news` group by `get_news`.`tag` ; -- -- Indexes for dumped tables -- -- -- Indexes for table `get_news` -- ALTER TABLE `get_news` ADD PRIMARY KEY (`news_id`), ADD UNIQUE KEY `get_news_title_uindex` (`title`), ADD UNIQUE KEY `get_news_news_id_uindex` (`news_id`); -- -- Indexes for table `news_comment` -- ALTER TABLE `news_comment` ADD KEY `FK_get_news_news_comment` (`news_id`); -- -- Indexes for table `news_feedback` -- ALTER TABLE `news_feedback` ADD KEY `FK_user_news_feedback` (`user_id`); -- -- Indexes for table `news_mess` -- ALTER TABLE `news_mess` ADD KEY `FK_get_news_news_mess` (`news_id`); -- -- Indexes for table `news_recommend` -- ALTER TABLE `news_recommend` ADD KEY `FK_user_news_recomment` (`user_id`); -- -- Indexes for table `news_tag_deep` -- ALTER TABLE `news_tag_deep` ADD KEY `FK_get_news_news_tag_deep` (`news_id`); -- -- Indexes for table `n_admin` -- ALTER TABLE `n_admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `phone` (`phone`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `user_behavior` -- ALTER TABLE `user_behavior` ADD KEY `FK_user_user_behavior` (`user_id`), ADD KEY `FK_get_news_user_behavior` (`news_id`); -- -- Indexes for table `user_love_tag` -- ALTER TABLE `user_love_tag` ADD KEY `FK_user_user_love_tag` (`user_id`); -- -- Indexes for table `user_mess` -- ALTER TABLE `user_mess` ADD UNIQUE KEY `email` (`email`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `user_operate` -- ALTER TABLE `user_operate` ADD KEY `FK_get_news_user_operate` (`news_id`), ADD KEY `FK_user_user_operator` (`user_id`); -- -- Indexes for table `user_tag_deep` -- ALTER TABLE `user_tag_deep` ADD KEY `FK_user_user_tag_deep` (`user_id`); -- -- Indexes for table `user_tag_score` -- ALTER TABLE `user_tag_score` ADD KEY `FK_user_user_tag_score` (`user_id`); -- -- 在导出的表使用AUTO_INCREMENT -- -- -- 使用表AUTO_INCREMENT `n_admin` -- ALTER TABLE `n_admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- 限制导出的表 -- -- -- 限制表 `news_comment` -- ALTER TABLE `news_comment` ADD CONSTRAINT `FK_get_news_news_comment` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`); -- -- 限制表 `news_feedback` -- ALTER TABLE `news_feedback` ADD CONSTRAINT `FK_user_news_feedback` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `news_mess` -- ALTER TABLE `news_mess` ADD CONSTRAINT `FK_get_news_news_mess` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`); -- -- 限制表 `news_recommend` -- ALTER TABLE `news_recommend` ADD CONSTRAINT `FK_user_news_recomment` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `news_tag_deep` -- ALTER TABLE `news_tag_deep` ADD CONSTRAINT `FK_get_news_news_tag_deep` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`); -- -- 限制表 `user_behavior` -- ALTER TABLE `user_behavior` ADD CONSTRAINT `FK_get_news_user_behavior` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`), ADD CONSTRAINT `FK_user_user_behavior` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `user_love_tag` -- ALTER TABLE `user_love_tag` ADD CONSTRAINT `FK_user_user_love_tag` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `user_mess` -- ALTER TABLE `user_mess` ADD CONSTRAINT `fk_user_mess` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `user_operate` -- ALTER TABLE `user_operate` ADD CONSTRAINT `FK_get_news_user_operate` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`), ADD CONSTRAINT `FK_user_user_operator` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `user_tag_deep` -- ALTER TABLE `user_tag_deep` ADD CONSTRAINT `FK_user_user_tag_deep` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- 限制表 `user_tag_score` -- ALTER TABLE `user_tag_score` ADD CONSTRAINT `FK_user_user_tag_score` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>#-*- coding: utf-8 -* __author__ = 'Howie' import tornado.web import os from handlers.errorHandler import ErrorHandler from handlers.index import IndexHandler from handlers.admin import AdminHandler from handlers.dataAna import DataAna from handlers.spider import Spider from handlers.system import System from handlers.newsManage import NewsManage from handlers.UmFeedBack import UmFeedBack from handlers.UmMyNote import UmMyNote from handlers.userManage import UserManage from handlers.changePass import ChangePass from handlers.dataOperator import DataOperator import handlers.api.newsApi as api url = [ (r'/', IndexHandler), (r'/admin',AdminHandler), (r'/dataAna',DataAna), (r'/spider', Spider), (r'/system',System), (r'/newsManage',NewsManage), (r'/userManage',UserManage), (r'/umMyNote', UmMyNote), (r'/umFeedBack', UmFeedBack), (r'/changePass',ChangePass), (r'/dataOperator',DataOperator), (r'/api/register',api.Register), (r'/api/login', api.Login), (r'/api/newstags', api.NewsTags), (r'/api/newscontent', api.NewsContent), (r'/api/userinfo', api.UserInfo), (r'/api/userinfochange', api.UserInfoChange), (r'/api/lovenews', api.LoveNews), (r'/api/lovelist', api.LoveList), (r'/api/hotlist', api.HotList), (r'/api/feedback', api.FeedBack), (r'/api/keyword', api.KeyWord), (r'/api/comment', api.Comment), (r'/api/lovecomment', api.LoveComment), (r'/api/exitread', api.ExitRead), (r'/api/adminuser', api.AdminUser), (r'/api/adminuserinfo', api.AdminUserInfo), (r'/api/adminfeedback', api.AdminFeedback), (r'/api/returntags', api.ReturnTags), #这个页面处理语句必须放在最后 (r".*", ErrorHandler) ] setting = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static"), cookie_secret = "<KEY> #xsrf_cookies = True, debug = True, login_url = '/', ) application = tornado.web.Application( handlers = url, **setting )<file_sep># -*-coding:utf-8-*- __author__ = 'howie' from xlsxwriter import * import time import datetime import os from random import choice from spider.toutiao.touTiao import GetToutiao from config.n_conf import dirPath def getToutiaoNews(category, page, num): """ Des: 返回今日头条新闻 param: category:新闻类型,默认为__all__ page :爬取页面,默认20页 num :每页新闻数量,根据今日头条每页返回数量变化,默认参数为20 ctime :新闻时间,根据标准库time.time()获取 return: /source/下各文件夹 """ newsData = [] for page in range(0, page): # ltime = [time.time(),"1464710423","1464796865","1464753667","1464840044","1464883266"] # ctime = choice(ltime) # print(ctime) # 获取两天前的时间 twoDayAgo = (datetime.datetime.now() - datetime.timedelta(days=1)) # 转换为时间戳: timeStamp = int(time.mktime(twoDayAgo.timetuple())) ctime = choice(range(timeStamp, int(time.time()))) toutiao = GetToutiao(str(num), category, ctime) allNewsData = toutiao.getNews() for news in allNewsData: newsData.append(news) mkExcel(category, newsData) def getTimestamp(startTime): """ Des: 将时间转化为时间戳 param: startTime="2016-05-17 12:00:00"(格式) return: timeStamp """ timeArray = time.strptime(startTime, "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) return timeStamp def mkExcel(cate, data): """ 将新闻数据生成excel表 :param cate: 新闻类型 :param data: 爬取的新闻数据 :return: 返回生成的excel表 """ # 设置excel表名称 excelName = dirPath + "/spider/touTiaoSource/" + cate + "/" + str( time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())) + "&" + cate + "&" + str(len(data)) + ".xlsx" # 设置excel表名称 jr_work = Workbook(excelName) jr_sheet = jr_work.add_worksheet("toutiao") bold = jr_work.add_format({'bold': True}) # 设置一个加粗的格式对象 jr_sheet.set_column('A:H', 40) jr_sheet.set_column('C:D', 15) jr_sheet.write(0, 0, '标题', bold) jr_sheet.write(0, 1, '发表地址', bold) jr_sheet.write(0, 2, '发表时间', bold) jr_sheet.write(0, 3, '来源', bold) jr_sheet.write(0, 4, '关键词', bold) jr_sheet.write(0, 5, '摘要', bold) jr_sheet.write(0, 6, '图片地址', bold) jr_sheet.write(0, 7, '标签', bold) line = 0 for eachData in data: line += 1 jr_sheet.write(line, 0, eachData["title"]) jr_sheet.write(line, 1, eachData["display_url"]) jr_sheet.write(line, 2, eachData["display_time"]) jr_sheet.write(line, 3, eachData["source"]) jr_sheet.write(line, 4, eachData["keywords"]) jr_sheet.write(line, 5, eachData["abstract"]) jr_sheet.write(line, 6, str(eachData["images"])) jr_sheet.write(line, 7, eachData["tag"]) jr_work.close() log = "%s新闻表抓取完成,抓取数据%d条" % (excelName, line) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") print(log) # 新闻种类 category = ["news_society", "news_entertainment", "news_tech", "news_car", "news_sports", "news_finance", "news_military", "news_world", "news_fashion", "news_travel", "news_discovery", "news_baby", "news_regimen", "news_story", "news_essay", "news_game", "news_history", "news_food"] <file_sep># -*- coding: utf-8 -* __author__ = 'Howie' import tornado.options import tornado.ioloop from application import application def main(port): #tornado.options.parse_command_line() application.listen(port) print("Development server is running at http://127.0.0.1:%s" % port) print("Quit the server with Control-C") tornado.ioloop.IOLoop.instance().start() #main(8888)<file_sep># -*- coding: utf-8 -* __author__ = 'Howie,jeezy' import pymysql from config.n_conf import localDatabase class newsDb(object): """ connect mysql """ def __init__(self): self.conn = pymysql.connect(**localDatabase) self.cur = self.conn.cursor() def select_table(self, table, column, condition, value): sql = "select " + column + " from " + table + " where " + condition + "= '" + value + "'" print(sql) self.cur.execute(sql) lines = self.cur.fetchall() return lines def select_table_two(self, table, column): sql = "select " + column + " from " + table print (sql) self.cur.execute (sql) lines = self.cur.fetchall () return lines def select_table_three(self,sql): print (sql) self.cur.execute (sql) lines = self.cur.fetchall () return lines def insert_table(self, table, field, values): sql = "insert into " + table + field + " values" + values print(sql) try: self.cur.execute(sql) # 提交到数据库执行 self.conn.commit() return True except: # 出现错误则回滚 self.conn.rollback() return False def update_column(self, table, column, value_set, condition, value_find): sql = "update " + table + " set " + column + "= '" + value_set + "' where " + condition + "='" + value_find + "'" print(sql) try: self.cur.execute(sql) self.conn.commit() return True except: self.conn.rollback() return False def exeSql(self,sql): print (sql) try: self.cur.execute(sql) self.conn.commit() return True except: self.conn.rollback() return False def __del__(self): self.cur.close() self.conn.close() <file_sep># -*-coding:utf-8-*- __author__ = 'Jeezy' from xlsxwriter import * import os import xlrd import time from config.n_conf import dirPath class mergeExcel: def __init__(self): #self.mergeSuccess = False self.exelExist = False # 定义一个字典分类储存合并后的新闻 self.allNews = {} self.allNews['__all__'] = [] self.allNews['news_hot'] = [] self.allNews['video'] = [] self.allNews['gallery_detail'] = [] self.allNews['news_society'] = [] self.allNews['news_entertainment'] = [] self.allNews['news_tech'] = [] self.allNews['news_car'] = [] self.allNews['news_sports'] = [] self.allNews['news_finance'] = [] self.allNews['news_military'] = [] self.allNews['news_world'] = [] self.allNews['news_fashion'] = [] self.allNews['news_travel'] = [] self.allNews['news_discovery'] = [] self.allNews['news_baby'] = [] self.allNews['news_regimen'] = [] self.allNews['news_story'] = [] self.allNews['news_essay'] = [] self.allNews['news_game'] = [] self.allNews['news_history'] = [] self.allNews['news_food'] = [] # 定义新闻类型列表 self.category = ["__all__","news_hot","news_society", "news_entertainment", "news_tech", "news_car", "news_sports", "news_finance", "news_military", "news_world", "news_fashion", "news_travel", "news_discovery", "news_baby", "news_regimen", "news_story", "news_essay", "news_game", "news_history", "news_food", ] # 定义网站列表,如有新增网站,可在此添加用于合并 self.newsSourse = ["sinaSource", "touTiaoSource","pyspiderSource"] def merge(self,mainPath,secondPath): for typeSourse in self.newsSourse: path = os.path.join(mainPath, typeSourse) print(path) for dir in os.listdir(path): dirPath = os.path.join(path, dir) if os.path.isdir(dirPath): files = [file for file in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, file)) and os.path.splitext(file)[1] == ".xlsx"] if files: for file in files: # conserve,提取exel表数据,并合并 # 传数据,新闻类型:file.split('&')[1],该类型对应的exel名:file,该类型对应的地址:os.path.join (dirPath,file) if file: self.exelExist = True self.conserve(file.split('&')[1], file, os.path.join(dirPath, file)) # 调用mkexel写将数据循环写入exel if self.exelExist: for cate in self.category: self.mkExel(cate, self.allNews[cate],secondPath) else: print("没有原始新闻数据,合并失败!请先获取数据!") return False # conserve,提取exel表数据,并合并 def conserve(self, cate, excelData, dir): # 新闻类型:cate,该类型对应的exel名:excelData,该类型对应的地址:dir data = xlrd.open_workbook(dir) table = data.sheets()[0] nrows = table.nrows for i in range(1, nrows): value = table.row_values(i) # judgeType:判断类型,找到对应的类型,分类储存到self.allNews self.judgeType(cate, value) # print(self.allNews [cate]) def judgeType(self, cate, value): for ca in self.category: if cate == ca: self.allNews[cate].append(value) # print(self.allNews [cate]) def mkExel(self, cate, data,secondPath): """ 将新闻数据生成excel表 :param cate: 新闻类型 :param data: 爬取的新闻数据 :return: 返回生成的excel表 """ # 设置excel表名称 excelName = secondPath + "/" + cate + "/" + str( time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())) + "&" + cate + "&" + str(len(data)) + ".xlsx" # 设置excel表名称 jr_work = Workbook(excelName) jr_sheet = jr_work.add_worksheet("allNews") bold = jr_work.add_format({'bold': True}) # 设置一个加粗的格式对象 jr_sheet.set_column('A:H', 40) jr_sheet.set_column('C:D', 15) jr_sheet.write(0, 0, '标题', bold) jr_sheet.write(0, 1, '发表地址', bold) jr_sheet.write(0, 2, '发表时间', bold) jr_sheet.write(0, 3, '来源', bold) jr_sheet.write(0, 4, '关键词', bold) jr_sheet.write(0, 5, '摘要', bold) jr_sheet.write(0, 6, '图片地址', bold) jr_sheet.write(0, 7, '标签', bold) line = 0 for eachData in data: line += 1 jr_sheet.write(line, 0, eachData[0]) jr_sheet.write(line, 1, eachData[1]) jr_sheet.write(line, 2, eachData[2]) jr_sheet.write(line, 3, eachData[3]) jr_sheet.write(line, 4, eachData[4]) jr_sheet.write(line, 5, eachData[5]) jr_sheet.write(line, 6, str(eachData[6])) jr_sheet.write(line, 7, eachData[7]) jr_work.close() log = "%s新闻数据合并完成,共合并数据%d条" % (excelName, line) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") print(log) #self.mergeSuccess = True #mergeExcel = mergeExcel() #mergeExcel.merge(os.path.dirname(os.path.abspath('.')),os.path.abspath('.')) <file_sep>#-*-coding:utf-8-*- __author__ = 'howie' import base64 import uuid cookie_secret = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes) #print(cookie_secret)<file_sep>## 新闻推荐系统后台管理文档 ### 1.需求分析 ##### 目标 对数据进行界面化管理 ### 2.数据库设计 #### 2.1.用户表(admin.user) | 列名 | 数据类型 | 是否为空 | 说明 | | :--: | :---------: | :---------------------: | :--: | | id | int | not null auto_increment | PK | | name | varchar(10) | not null | 管理员 | | pass | varchar(40) | not null | 密码 | ```mysql -- Table: user CREATE TABLE `n_admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(10) NOT NULL, `pass` varchar(40) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ``` ### 3.系统搭建 <file_sep>import pymysql import os from system.classPredict.newsPredict import NewPredict from system.classPredict.predictTool import NavieBayesPredict from methods.pDb import newsDb from config.n_conf import dirPath # 存放新闻信息的集合,包括 id,文本正文 data_list = [] test_data_file = dirPath + "/system/classPredict/NavieBayesInfo/predict_new_word.txt" model_file = dirPath + "/system/classPredict/NavieBayesInfo/model.txt" result_file = dirPath + "/system/classPredict/NavieBayesInfo/predict_result.txt" def startPredict(): db = newsDb() try: datasql = "select news_id,text_content from get_news where is_old = 0" data = db.select_table_three(datasql) for d in data: new = {} new["id"] = d[0] new["textContent"] = d[1] data_list.append(new) except Exception as e: print(e) np = NewPredict(data_list) np.getNewInfo() nb = NavieBayesPredict(test_data_file, model_file, result_file) nb.predict() # startPredict() <file_sep>import jieba import jieba.analyse import os import re from spider.wordAna.contentTool import ContentOperator from spider.wordAna.excelTool import ExcelOperator from config.n_conf import dirPath def getNewsContent(): """ :return: """ # 获取总目录绝对路径 orgDir = dirPath + "/spider/wordAna/allNews" # 获取最终存放目录绝对路径 finalDir = dirPath + "/spider/wordAna/wordAnaNews/" print(orgDir) print(finalDir) # 获得excelTools.py中的excel操作工具 et = ExcelOperator() # 获得contentTools.py中的content操作工具 ct = ContentOperator() files = [x for x in os.listdir(orgDir) if os.path.splitext(x)[-1] == '.xlsx'] # 开始遍历各大新闻类别的excel文件 for file in files: # print(file) # 此处得到该excel文件夹所有信息,是一个list,list中单个元素为dict,对应 列名:值 infoList = et.getExcelInfo(os.path.join(orgDir, file)) # 用以存放完整的新闻信息元素的集合 last_list = [] for new_info in infoList: urlstr = new_info["display_url"] # 区分链接,链接来自头条或新浪,关键词,toutiao.com和sina.com htmlContent, textContent, title, abstract, keywords, source, tag = '', '', '', '', '', '', '' img_url_list = [] try: # 这里需要去除sina的滚动图片类新闻及多媒体新闻 if urlstr.find("sina.com") != -1 and urlstr.find("slide") == -1 and urlstr.find("video") == -1: print(urlstr) textContent, htmlContent, img_url_list, keyword_list, abstract = ct.getSinaContent(urlstr) new_info["keywords"] = ' '.join(keyword_list) new_info["abstract"] = ' '.join(abstract) elif urlstr.find("toutiao.com") != -1: print(urlstr) textContent, htmlContent, img_url_list, title, abstract, keywords, source, tag = ct.getToutiaoContent( urlstr) if title: new_info["title"] = title else: new_info["title"] = '' if abstract: new_info["abstract"] = abstract else: new_info["abstract"] = '' if keywords: new_info["keywords"] = keywords else: new_info["keywords"] = '' if source: new_info["source"] = source else: new_info["source"] = '' if tag: new_info["tag"] = tag else: new_info["tag"] = '' try: feature = jieba.analyse.extract_tags(textContent, 15) except: feature = new_info["keywords"] new_info["textContent"] = textContent new_info["htmlContent"] = htmlContent new_info["feature"] = feature new_info["img"] = img_url_list last_list.append(new_info) except: pass # 采用结巴中文分词提取正文最重要的十个特征词 # 相关算法 --- tf-idf算法 # print(textContent) # 信息过滤、爬取及关键词提取完毕,开始将它存到excel表中 excelName = os.path.join(finalDir, file) print("excelName:" + excelName) # 这里,第二个参数,工作表名称,需调整 et.saveToExcel(excelName, "allNews", last_list) <file_sep># -*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape from handlers.base import BaseHandler from spider import allSpider from controller.dataController import DataController, newsSource from spider.newsDb.insertNews import newsInsert from system.classPredict.main import startPredict from system.latentFactor.geneCalcul import GeneCulcal from methods.pDb import newsDb class DataOperator(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): # 新闻种类 action = self.get_argument('action') if action == "getNews": page = int(self.get_argument('page')) num = int(self.get_argument('num')) cate = ["__all__","news_hot","news_society", "news_entertainment", "news_tech", "news_car", "news_sports", "news_finance", "news_military", "news_world", "news_fashion", "news_travel", "news_discovery", "news_baby", "news_regimen", "news_story", "news_essay", "news_game", "news_history", "news_food"] allSpider.touTiao(category=cate, page=page, num=num) allSpider.sina(num=1000, page=1) print("success") elif action == "repeatedData": # 先进行合并 allSpider.merge() # 进行去重 print(DataController.repeatedData(['wordAna', 'allNews'])) print("success") elif action == "anaData": # 进行词性分析 allSpider.wordAna() elif action == "rmAllNews": DataController.rmAllNews(newsSource) print("success") elif action == "insertDB": # 清除老数据 db = newsDb() db.exeSql("delete from news_tag_deep") db.exeSql("delete from news_nums") #db.exeSql("delete from get_news where is_old=0") db.exeSql("insert into news_nums select * from news_nums_view") # 将新闻插入数据库 newsInsert.insertSql("wordAnaNews") # 删除分词文件夹里面的表 DataController.rmRepeate(['wordAna', 'wordAnaNews']) startPredict() gc = GeneCulcal() gc.getMatData() print("success") <file_sep>#-*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape from handlers.base import BaseHandler class DataAna(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): header = "数据分析" self.render("dataAna.html",header=header)<file_sep># -*- coding: utf-8 -* __author__ = 'Howie' import tornado.web import tornado.escape from methods.pDb import newsDb from handlers.base import BaseHandler class AdminHandler(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): user = self.get_argument("user") if user == "logout": self.clear_cookie("user") self.render("index.html") else: header = "新闻推荐系统后台" cateType = {"news_society":"社会", "news_entertainment":"娱乐","news_tech":"科技", "news_car":"汽车", "news_sports":"体育", "news_finance":"财经", "news_military":"军事", "news_world":"国际","news_fashion":"时尚", "news_travel":"旅游", "news_discovery":"探索", "news_baby":"育儿", "news_regimen":"养生", "news_story":"故事","news_essay":"美文", "news_game":"游戏", "news_history":"历史", "news_food":"美食"} numTag = {} for i in cateType.keys(): mSql = newsDb() result = mSql.select_table(table="get_news",column="count(*)",condition="tag",value=i) numTag[cateType[i]]=result[0][0] #排序 sortTag = list(sorted(numTag.items(), key=lambda d:d[1], reverse = True)) self.render("admin.html", header=header, numTag=numTag,sortTag=sortTag[0:7]) <file_sep>/** * Created by jeezy-lyoung on 16-7-31. */ function info_none(user_id) { document.getElementById("user_info").style.display = "none"; } function user_info(user) { var user_id = user.toString(); var net = "http://127.0.0.1:8888"; var time = '1'; var tooken = '<PASSWORD>'; for (i=0;i<6-user.toString().length;i++){ user_id = '0' + user_id; } var qx = {"time":time, "tooken":tooken}; $.ajax({ type:"get", url:net + "/api/adminuserinfo?user_id="+user_id, data:qx, cache:false, success:function(data) { var is_success; var result = eval('(' + data + ')'); var all_data = result.data; is_success = result.message; if (is_success == "failed"){ } else{ var phone = "<div class='each_info'>电话:"+ all_data.phone +"</br></div>" var age = "<div class='each_info'>年龄:"+ all_data.age +"</br></div>" var sex = "<div class='each_info'>性别:"+ all_data.sex +"</br></div>" var address = "<div class='each_info'>地址:"+ all_data.address +"</br></div>" var email = "<div class='each_info'>邮箱:"+ all_data.email +"</br></div>" document.getElementById("user_info").innerHTML = phone + age + sex + address + email; document.getElementById("user_info").style.display = "block"; } } }); } $(document).ready(function () { /*自适应高度*/ var left_show = document.getElementById('left'); var left_show_height; if (navigator.userAgent.indexOf("Firefox") > 0) { left_show_height = document.documentElement.scrollHeight; } if (window.navigator.userAgent.indexOf("Chrome") !== -1 || navigator.userAgent.indexOf("Safari") > 0) { left_show_height = document.body.scrollHeight; } if (navigator.userAgent.indexOf("MSIE") > 0) { left_show_height = (document.documentElement.scrollHeight > document.documentElement.clientHeight) ? document.documentElement.scrollHeight : document.documentElement.clientHeight; } else { left_show_height = (document.documentElement.scrollHeight > document.documentElement.clientHeight) ? document.documentElement.scrollHeight : document.documentElement.clientHeight; } //left_show.style.height = left_show_height - 50 + "px"; var second_show = document.getElementById('second'); second_show.style.height = left_show_height - 50 + "px"; var net = "http://127.0.0.1:8888"; var count = 6; var page_value = 1; var alrequest = 0; var page = "next"; var time = '1'; var tooken = '<PASSWORD>'; function get_user() { var qx = {"alrequest":alrequest,"page":page,"time":time, "tooken":tooken}; $.ajax({ type:"get", url:net + "/api/adminuser?count=6", data:qx, cache:false, success:function(data) { var is_success; var result = eval('(' + data + ')'); var all_data = result.data; is_success = result.message; if (is_success == "failed"){ alert("已是最后一页"); page_value = page_value - 1; } else{ var table = ""; for(i=0;i<all_data.length;i++){ table = table + "<tr>" + "<td>"+ all_data[i].user_id +"</td>" + "<td><a id='"+all_data[i].user_id +"' onMouseOver='user_info("+ all_data[i].user_id +")' onmouseout='info_none("+ all_data[i].user_id +")'>"+ all_data[i].user_name +"</a></td>" + "</tr>" } document.getElementById("page1").innerHTML = "<table class='table table-bordered'>" + "<caption>用户管理</caption>" +"<thead>" +"<tr>" + "<th>用户编号</th>" + "<th>昵称</th>" + "</tr>" + "</thead>" + "<tbody>" + table + "</tbody>" + "</table>"; } } }); } get_user(); $("#next").click(function () { page = "next"; alrequest = page_value * 6; get_user(); page_value = page_value + 1; }); $("#last").click(function () { page = "last"; if (page_value == 1){ alert("已是第一页") }else{ page_value = page_value - 1 ; alrequest = page_value * 6; get_user(); } }); })<file_sep># -*- coding: utf-8 -* __author__ = 'Jeezy' import os import time import hashlib from methods.pDb import newsDb import random import pandas as pd from config.n_conf import dirPath class newsInsert: def __init__(self): pass def insertSql(self, mainPath): path = dirPath + "/spider/wordAna/" + mainPath for dir in os.listdir(path): if os.path.splitext(dir)[1] == ".xlsx": file = os.path.join(path, dir) self.insert(file) def insert(self, file): try: data = pd.read_excel(file, sheetname="allNews") data = data.drop_duplicates(subset='title', keep='last') db = newsDb() cateType = {"news_society": "社会", "news_entertainment": "娱乐", "news_tech": "科技", "news_car": "汽车", "news_sports": "体育", "news_finance": "财经", "news_military": "军事", "news_world": "国际", "news_fashion": "时尚", "news_travel": "旅游", "news_discovery": "探索", "news_baby": "育儿", "news_regimen": "养生", "news_story": "故事", "news_essay": "美文", "news_game": "游戏", "news_history": "历史", "news_food": "美食"} tag = file.split('&')[1] for i in range(0, len(data)): value = data.values[i] if value[8] in cateType.keys(): tag = value[8] if value[11]: times = time.time() md5newid = hashlib.md5(str(times).encode("utf-8")).hexdigest() startNum = random.randint(0, (len(md5newid) - 20)) newsId = str(md5newid)[startNum:(startNum + 20)] try: mysqlSuccess = db.insert_table(table="get_news", field="(news_id,news_link,source,title,abstract,tag," "text_content,html_content,image,keyword)", values="('" + newsId + "','" + value[2] + "','" + value[ 4] + "','" + value[1] + "','" + value[6] + "','" + tag + "','" + value[ 10] + "','" + value[11] + "','" + value[12] + "','" + value[ 9] + "')") if mysqlSuccess: print("新闻保存sql完成!") except: print("failed") except: print("import failed") newsInsert = newsInsert() <file_sep> import os import jieba import jieba.analyse from config.n_conf import dirPath class NewPredict(object): def __init__(self,data_list): self.data_list = data_list self.ft = open(dirPath + "/system/classPredict/NavieBayesInfo/predict_new_word.txt", 'w') #存放 单词:对应唯一id 的字典 self.word_id_dict = {} #加载单词id字典,结果在word_id_dict里 self.loadWord_id_dict() #将所需预测的新闻的类别:特征词保存进文件,格式: 类别 单词1id 单词2id 单词3id....... # def getNewInfo(self): for new in self.data_list: new_id = new["id"] textContent = new["textContent"] if textContent==None: continue feature = jieba.analyse.extract_tags(textContent, 15) # print(new_id + " " + str(feature)) #代表当前新闻的特征词id集合 word_id_list = [] for word in feature: tmp = self.word_id_dict.get(word, None) if tmp==None: word_id_list.append("-1") else: word_id_list.append(str(tmp)) #将文章信息写入预测新闻信息文件 self.writeFeature(new_id, word_id_list) #关闭资源 self.ft.close() # cate为feature特征词id集合所属的类别 def writeFeature(self, new_id, word_id_list): self.ft.write(new_id + ' ') for word_id in word_id_list: self.ft.write(word_id + ' ') self.ft.write('\n') def loadWord_id_dict(self): fd = open (dirPath + "/system/classPredict/NavieBayesInfo/word_id_dict.txt", 'r') allInfo = fd.read() arr = allInfo.strip().split() for i in range(0,len(arr)): if i%2==0: self.word_id_dict[arr[i]] = arr[i+1] # np = NewPredict([]) # np.loadWord_id_dict() <file_sep># -*- coding: utf-8 -* __author__ = 'Howie' import tornado.web class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_secure_cookie("user") def write_error(self, status_code, **kwargs): self.write("错误页面,状态码{0}.\n".format( status_code)) def output(self): self.write("hi") print("hi") <file_sep>#-*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape from handlers.base import BaseHandler class UmFeedBack(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): self.render("umFeedBack.html")<file_sep>#-*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape from handlers.base import BaseHandler class UmMyNote(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): self.render("umMyNote.html")<file_sep># -*-coding:utf-8-*- from methods.pDb import newsDb '''用户-标签(类型)潜在因子矩阵计算,与新闻-标签(类型)潜在因子矩阵相乘得到推荐新闻''' '''数据表来源:用户行为信息表,存入标签喜欢程度表,计算方法是,通过用户行为信息表信息,计算各用户对各标签的喜欢程度''' class UserTagDataTool(object): def __init__(self): #存储各用户的id self.user_id_list = [] #存储各用户对各类别的喜欢比例 self.userTagMat = [] def getData(self): try: db = newsDb() data = db.select_table_two(table="user_tag_score",column="*") for item in data: # 获得用户id self.user_id_list.append(item[0]) # 当前用户对各类别的新闻的分数的集合,类别名称顺序按数据表设计来 tagsScore = [] curSum = 0 for score in item[1:len(item)]: if score == None: tmp = 1 else: tmp = float(score) curSum = curSum + tmp tagsScore.append(tmp) #当前用户对于各类别的喜欢比重,类别名称顺序按数据表设计来 tagsWeight = [] for i in range(0,len(tagsScore)): tagsWeight.append(tagsScore[i]/(float)(curSum)) self.userTagMat.append(tagsWeight) # print(self.user_id_list) # print(self.userTagMat) return self.user_id_list,self.userTagMat except Exception as e: print(e) # gut = UserTagDataTool() # x,y = gut.getData() # print(x) # print(y)<file_sep>#coding:utf-8 import math from methods.pDb import newsDb class NavieBayesPredict(object): """使用训练好的模型进行预测""" def __init__(self,test_data_file,model_data_file,result_file): self.test_data_file = open(test_data_file,'r') self.model_data_file = open(model_data_file,'r') #对预测数据集预测的结果文件 self.result_file = open(result_file,'w') #每个类别的先验概率 self.class_probabilities = {} #拉普拉斯平滑,防止概率为0的情况出现 self.laplace_smooth = 0.1 #模型训练结果集 self.class_word_prob_matrix = {} #当某个单词在某类别下不存在时,默认的概率(拉普拉斯平滑后) self.class_default_prob = {} #所有单词 self.unique_words = {} #实际的新闻分类 self.real_classes = [] #预测的新闻分类 self.predict_classes = [] def __del__(self): self.test_data_file.close() self.model_data_file.close() def loadModel(self): #从模型文件的第一行读取类别的先验概率 class_probs = self.model_data_file.readline().split('#') for cls in class_probs: arr = cls.split() if len(arr)==3: self.class_probabilities[arr[0]] = float(arr[1]) self.class_default_prob[arr[0]] = float(arr[2]) #从模型文件读取单词在每个类别的概率 line = self.model_data_file.readline().strip() while len(line)>0: arr = line.split() assert(len(arr)%2==1) assert(arr[0] in self.class_probabilities) self.class_word_prob_matrix[arr[0]] = {} i = 1 while i<len(arr): word_id = int(arr[i]) probability = float(arr[i+1]) if word_id not in self.unique_words: self.unique_words[word_id] = 1 self.class_word_prob_matrix[arr[0]][word_id] = probability i = i+2 line = self.model_data_file.readline().strip() print(len(self.class_probabilities),"classes loaded!",len(self.unique_words),"words!") def caculate(self): # 读取测试数据集 line = self.test_data_file.readline().strip() while len(line)>0: arr = line.split() new_id = arr[0] # class_id = arr[1] # print(class_id) words = arr[1:len(arr)-1] #把真实的分类保存起来 # self.real_classes.append(class_id) #预测当前行(一个新闻)属于各个分类的概率 class_score = {} for key in self.class_probabilities.keys(): class_score[key] = math.log(self.class_probabilities[key]) for word_id in words: word_id = int(word_id) for class_id in self.class_probabilities.keys(): if word_id not in self.class_word_prob_matrix[class_id]: class_score[class_id] += math.log(self.class_default_prob[class_id]) else: class_score[class_id] += math.log(self.class_word_prob_matrix[class_id][word_id]) #对于当前新闻类别值,进行正数转换,加上最低限度 needAdd = -(min(class_score.values())) + 1 #开始将所有分数转化为正数,并计算分数总和 sum = 0.0 for key in class_score.keys(): class_score[key] += needAdd sum = sum + class_score[key] #开始计算比例因子 for key in class_score.keys(): class_score[key] = class_score[key]/sum # print(key + ":" + str(class_score[key])) # 将当前新闻的比例因子数据存进数据库 self.saveToDb(new_id, class_score) line = self.test_data_file.readline().strip() #提交总体sql事务 #db.conn.commit() # def evaluation(self): # #评价当前分类器的准确性 # accuracy = 0 # i = 0 # while i<len(self.real_classes): # if self.real_classes[i] == self.predict_classes[i]: # accuracy += 1 # i += 1 # # accuracy = (float)(accuracy)/(float)(len(self.real_classes)) # print("Accuracy:",accuracy) # # # 评测精度和召回率 # # 精度是指所有预测中,正确的预测 # # 召回率是指所有对象中被正确预测的比率 # for class_id in self.class_probabilities: # correctNum = 0 # allNum = 0 # predNum = 0 # i = 0 # # while i<len(self.real_classes): # if self.real_classes[i] == class_id: # allNum += 1 # if self.predict_classes[i] == self.real_classes[i]: # correctNum += 1 # if self.predict_classes[i] == class_id: # predNum += 1 # i += 1 # precision = (float)(correctNum)/(float)(predNum) # recall = (float)(correctNum)/(float)(allNum) # print (class_id,'->precision=',precision,'recall=',recall) def saveToDb(self,new_id,class_score): db = newsDb() list = [str(class_score["society"]),str(class_score["entertainment"]),str(class_score["tech"]),str(class_score["car"]), str(class_score["sports"]),str(class_score["finance"]),str(class_score["military"]),str(class_score["world"]), str(class_score["fashion"]),str(class_score["travel"]),str(class_score["discovery"]),str(class_score["baby"]), str(class_score["regimen"]),str(class_score["story"]),str(class_score["essay"]),str(class_score["game"]), str(class_score["history"]),str(class_score["food"])] tmpstr = ','.join(list) print(tmpstr) db.insert_table(table = "news_tag_deep", field= "", values = "('" + new_id+ "'," + tmpstr + ")") print("存储" + new_id + "新闻的类别偏重比例") def predict(self): self.loadModel() self.caculate() # self.evaluation() <file_sep>import requests import re from lxml import etree from bs4 import BeautifulSoup import codecs class ContentOperator(): """ 通过excel表中的链接获取对应网页新闻的正文 """ def __init__(self): pass """ :param url为待爬取的头条网页链接 """ def getToutiaoContent(self, url): try: newstr = requests.get(url).content.decode("utf-8") # 获取对应网页html正文 soup = BeautifulSoup(newstr, "lxml") header = soup.find('div', class_="article-header") content = soup.find('div', class_="article-content") title = soup.find('h1', class_="title").get_text() abstract = re.findall(r'<meta\s*name="?description"?\s*content="(.*?)"', newstr)[0] keywords = re.findall(r'<meta\s*name="?keywords"?\s*content="(.*?)"', newstr)[0] source = soup.find('span', class_="src").get_text() tag = soup.find('a', ga_event="click_channel").get_text() cateType = {"社会": "news_society", "娱乐": "news_entertainment", "科技": "news_tech", "汽车": "news_car", "体育": "news_sports", "财经": "news_finance", "军事": "news_military", "国际": "news_world", "时尚": "news_fashion", "旅游": "news_travel", "探索": "news_discovery", "育儿": "news_baby", "养生": "news_regimen", "美文": "news_story", "故事": "news_essay", "游戏": "news_game", "历史": "news_history", "美食": "news_food"} try: tag = cateType[tag] except Exception: tag = 'news_society' htmlContent = str(header) + str(content) textContent = self.parseHtml(htmlContent) img_url_list = re.findall(r'<img.*?src="(.*?)"/?>',htmlContent) return textContent, htmlContent, img_url_list, title, abstract, keywords, source, tag except ConnectionError: exit("ConnecttionError") except Exception: return None, None, None """ :param url为待爬取的新浪网页链接 """ def getSinaContent(self, url): try: newstr = requests.get(url).content.decode("utf-8") # 获取对应网页html正文 soup = BeautifulSoup(newstr, "lxml") header = soup.find('h1', id="artibodyTitle") content = soup.find('div', id="artibody") keywordTag = soup.find('div', class_="article-keywords") quotation = soup.find('div', class_="quotation") if header == None: header = soup.find('h1', id="main_title") if keywordTag == None: keywordTag = soup.find('p', class_="art_keywords") if content == None or header == None: return htmlContent = str(header) + str(content) textContent = self.parseHtml(htmlContent) # 设置摘要 if quotation: patten = re.compile('<p.*?>(.*?)</p>', re.S) item = re.findall(patten, str(quotation)) abstract = item[0] else: abstract = str(textContent) abstract = re.sub('\s*', '', re.sub('\n*', '', abstract))[0:100] abstract = re.findall(r'<meta\s*name="?description"?\s*content="(.*?)"', newstr)[0] + abstract #print(abstract) img_url_list = [] if content: img_list = BeautifulSoup(htmlContent, "lxml").find_all("img") if img_list: for img in img_list: if 'ico' not in str(img.get("src")): img_url_list.append(img.get("src")) keyword_list = [] if keywordTag: keyword = keywordTag.find_all("a") if keyword: for word in keyword: keyword_list.append(word.get_text()) # print(textContent) # print(htmlContent) # print(','.join(img_url_list)) # print(','.join(keyword_list)) # print(abstract) return textContent, htmlContent, img_url_list, keyword_list, abstract except ConnectionError: exit("ConnecttionError") except Exception as e: print(e) return None, None, None, None, None def parseHtml(self, htmlContent): """ :param htmlContent为要解析为纯文本的html正文 """ pn = re.compile(r'<script>[\s\S]*</script>', re.S) tmpContent = pn.sub('', htmlContent) pt = re.compile(r'<[^>]+>', re.S) return pt.sub(' ', tmpContent) # c = ContentOperator() # c.getSinaContent("http://ent.sina.com.cn/tv/zy/2016-05-26/doc-ifxsqxxs7700323.shtml") <file_sep>#-*-coding:utf-8-*- __author__ = 'Jeezy' import requests import re class GetSina(): ''' 通过网易新闻API获取新闻信息,保存至exel ''' def __init__(self,num,page): self.num = str(num) self.page = str(page) self.url = "http://roll.news.sina.com.cn/interface/rollnews_ch_out_interface.php?col=89&spec=&type=&k=&num="+self.num+"&asc=&page="+self.page+"&r=0.41627189057293945" def getNews(self): #通过API爬取新浪新闻文本内容 gettext = requests.get(self.url) gettext.encoding='gbk' gettext = gettext.text allNewsData = [] patten = re.compile('channel : {title : "(.*?)",id.*?title : "(.*?)",url : "(.*?)",type.*?time : (.*?)}',re.S) items = re.findall(patten,gettext) for eachData in items: newsData = {} newsData["tag"] = eachData[0] newsData["title"] = eachData[1] newsData["display_url"] = eachData[2] newsData["display_time"] = eachData[3] newsData["source"] = "新浪新闻" allNewsData.append(newsData) return allNewsData #if allNewsData[0]['tag']== "体育": #print (allNewsData) #sina =GetSina(5,1) #sina.getNews()<file_sep># -*-coding:utf-8-*- __author__ = 'Jeezy' from xlsxwriter import * import os import time from spider.sina.sina import GetSina from config.n_conf import dirPath def getSinaNews(num, page, type): ''' num每页新闻条数,page页数,一般设置page为1,控制变量 ''' allNewsData = [] for page in range (0, page): sina = GetSina (num, page) allNewsData.append(sina.getNews ()) choice (allNewsData, type) def choice(data, type): # 分类字典,储存每一类的新闻 allNews = {} allNews['news_world'] = [] allNews['news_sports'] = [] allNews['news_finance'] = [] allNews['news_society'] = [] allNews['news_entertainment'] = [] allNews['news_military'] = [] allNews['news_tech'] = [] # 分类,将data的数据分类储存到字典里面 for eachdata in data: for number in range (0, len (eachdata)): if eachdata [number] ['tag'] == "国内": eachdata [number]["tag"]="news_world" allNews ['news_world'].append (eachdata [number]) if eachdata [number] ['tag'] == "体育": eachdata [number] ["tag"] = "news_sports" allNews ['news_sports'].append (eachdata [number]) if eachdata [number] ['tag'] == "财经": eachdata [number] ["tag"] = "news_finance" allNews ['news_finance'].append (eachdata [number]) if eachdata [number] ['tag'] == "社会": eachdata [number] ["tag"] = "news_society" allNews ['news_society'].append (eachdata [number]) if eachdata [number] ['tag'] == "国际": eachdata [number] ["tag"] = "news_world" allNews ['news_world'].append (eachdata [number]) if eachdata [number] ['tag'] == "娱乐": eachdata [number] ["tag"] = "news_entertainment" allNews ['news_entertainment'].append (eachdata [number]) if eachdata [number] ['tag'] == "军事": eachdata [number] ["tag"] = "news_military" allNews ['news_military'].append (eachdata [number]) if eachdata [number] ['tag'] == "美股": eachdata [number] ["tag"] = "news_finance" allNews ['news_finance'].append (eachdata [number]) if eachdata [number] ['tag'] == "股市": eachdata [number] ["tag"] = "news_finance" allNews ['news_finance'].append (eachdata [number]) if eachdata [number] ['tag'] == "科技": eachdata [number] ["tag"] = "news_tech" allNews ['news_tech'].append (eachdata [number]) for ty in type: mkExel (ty, allNews[ty]) # print (cate[dictNumber[i]]) def mkExel(cate, data): """ 将新闻数据生成excel表 :param cate: 新闻类型 :param data: 爬取的新闻数据 :return: 返回生成的excel表 """ # 设置excel表名称 excelName = dirPath + "/spider/sinaSource/" + cate + "/" + str ( time.strftime ('%Y-%m-%d-%H-%M-%S', time.localtime ())) + "&" + cate + "&" + str (len (data)) + ".xlsx" # 设置excel表名称 jr_work = Workbook (excelName) jr_sheet = jr_work.add_worksheet ("sina") bold = jr_work.add_format ({'bold': True}) # 设置一个加粗的格式对象 jr_sheet.write (0, 0, '标题', bold) jr_sheet.write (0, 1, '发表地址', bold) jr_sheet.write (0, 2, '发表时间', bold) jr_sheet.write (0, 3, '来源', bold) jr_sheet.write (0, 4, '关键词', bold) jr_sheet.write (0, 5, '摘要', bold) jr_sheet.write (0, 6, '图片地址', bold) jr_sheet.write (0, 7, '标签', bold) line = 0 for eachData in data: line += 1 jr_sheet.write (line, 0, eachData ["title"]) jr_sheet.write (line, 1, eachData ["display_url"]) jr_sheet.write (line, 2, eachData ["display_time"]) jr_sheet.write (line, 3, eachData ["source"]) jr_sheet.write (line, 4, '') jr_sheet.write (line, 5, '') jr_sheet.write (line, 6, '') jr_sheet.write (line, 7, eachData ["tag"]) jr_work.close () log = "%s新闻表抓取完成,抓取数据%d条" % (excelName, line) with open (dirPath+"/log.txt", 'a') as fp: fp.write (log + "\n") print (log) # getSinaNews(2000,1) # 新闻种类 cate = ["news_world", "news_sports", "news_finance", "news_society", "news_entertainment", "news_military","news_tech"]<file_sep>## 互联网内容推荐系统需求分析 ### 互联网内容推荐系统: 内容爬虫­——对若干新闻网站或论坛进行爬取和解析; 特征提取——通过文本分析技术对每一篇文章内容进行特征的提取; 用户兴趣建模——记录用户阅读行为,并进行用户兴趣画像; 推荐算法——通过特定的推荐策略,将新闻内容推荐给用户。 ### 1.目标 - [ ] **内容爬取** - [ ] **分析用户的需求和行为,帮助用户发现他们感兴趣的新闻** - [ ] **将用户行为分析结果与新闻内容进行比较,实现动态新闻推荐** ### 2.数据获取 - [ ] **首先需要获取初始数据,其目前分为两部分:** 1.*爬取的新闻数据* 2.*用户的访问数据* - [ ] **如何获取数据:** ​*以`python`语言进行新闻数据的爬取,基础教程参考[廖雪峰老师的教程](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000),在内容爬取过程中,最好使用框架进行爬取,可以参考[scarpy官方文档中文版](http://scrapy-chs.readthedocs.io/zh_CN/latest/)* ### 3.数据分析与挖掘 ​ **获得初始数据,下一步进行数据分析与挖掘:** #### 3-1:挖掘目标 ​ 1.*根据用户所处的地域、性别、年龄、访问的时间、访问的新闻类别、某个新闻点开的次数、该新闻阅读到哪里等进行分析,从而了解用户的行为* ​ 2.*根据第一步的分析结果,对不同需求的用户进行相关的新闻推荐,实现动态推荐* #### 3-2:分析方法以及过程 ##### 3-2-1:概要 ##### ![news](source/news.png) ​ 1.获得初始数据(用户的原始记录,新闻数据) ​ 2.对用户的访问内容,流失的用户,用户的分类进行分析 ​ 3.对数据进行预处理 ​ 4.对比多种推荐算法进行推荐,通过模型评价得到比较好的智能推荐模式 ##### 3-2-2:数据抽取 ​ 本项目的推荐是建立在用户行为的基础上,所以在设计推荐算法之前,分析用户行为数据必不可少,首先需要建立分析用户行为的数据表,该表包含用户对已经出现的新闻的一系列动作,news.behavior表如下(具体参照数据库设计文档): | 字段 | 说明 | | :-----------: | :------------------------: | | user_id | 唯一用户 | | news_id | 目标新闻 | | behavior_type | 对该新闻的行为类型:浏览、喜欢、跳过 | | context | 在什么时间地点产生这个行为 | | weight | 浏览时间戳前后差值作为权重 | | content | 给与评论否 | | news_way | 搜索或者推荐方式阅读新闻 | | scores | 特定用户对特定新闻的分数(下面详细说这个分数怎么算) | | age | 年龄 | ​ 目的是分析出如下表格式的数据(每个用户对新闻的标签喜欢程度): | 用户 | 科技 | 搞笑 | 娱乐 | 体育 | 历史 | | ------- | ---- | ---- | :--- | ---- | ---- | | howie-1 | 0.8 | 0.1 | 0.2 | 0.2 | 0.6 | ​ 关于对于新闻的处理,个人觉得在这部分就进行算法分析,首先将新闻分为两部分: ​ 1.*旧新闻*:对用户推荐过,获得反馈的新闻,以这些新闻为标准,得出该新闻标签的标准;对于旧新闻,又分为两种情况:被用户阅读的新闻和未被用户阅读的新闻,处理后的表大概是这个样子: | | news-1 | news-2 | news-3 | news-4 | news-5 | news-6 | | ------- | ------ | ------ | ------ | ------ | ------ | ------ | | howie-1 | 5 | 0 | 10 | 5 | 0 | 5 | | howie-2 | 0 | 0 | 10 | 5 | 0 | 0 | ​ 2.*新新闻*:刚刚经过第一步处理的新闻,尚未被推荐的新闻,以老新闻分析出来的标准为标准,进行分析,主要目的是算出该新闻的分数。 ​ 目的是分析出如下表格式的数据(各新闻的标签因子): | 新闻 | 科技 | 搞笑 | 娱乐 | 体育 | 历史 | | ------ | ---- | ---- | ---- | ---- | ---- | | news-1 | 0.2 | 0.1 | 0.1 | 0 | 0 | ​ 综合这两部分数据,就可以得出该用户对某个新闻的新欢程度,即: $$ S = \sum_{i,j=0}^\infty {f_i(i)}{f_j(j)} $$ ​ 现假使系统获取了大量数据,但这些数据并不是完全可用,所以要进行下一步对数据进行处理,得到**用户行为数据集和新闻数据集**。 ##### 3-2-3:数据探索分析 ​ 在数据探索分析的过程中,肯定会发现与分析目标无关的数据,针对这个问题的数据处理方式有:数据清洗、数据集成和数据变换。 ​ 1.*数据清洗* ​ 清除毫无意义的评论数据 ​ 2.*数据变换* ​ 有些数据可能某个字段不准确,比如无法获取位置导致这个字段为空,不给与评论也不给标签,对于这些问题: ​ 第一种情况:考虑到某些用户关闭定位功能,可以考虑结合其上次浏览的位置以及初始位置进行替换`context`内容。 ​ 第二种情况:使用默认的新闻分类标签 ​ 3.*数据去重* ​ 删除重复数据 ​ 经过上面一系列步骤之后,可以得出我们想要的数据集:**用户行为数据集和新闻数据集**,下面就要对用户行为进行分析,了解其中的的一般规律。可以考虑使用长尾分布:这可以得出`80%`用户喜欢的`20%`内容,反之亦然。 $$ f(x)=\alpha x^k (k<0) $$ ​ 或许可以不要这一步,毕竟数据量没有那么多。 ##### 3-2-4:建立模型 ​ 本项目需要根据用户的行为实现新闻推荐,可以考虑使用**协同过滤算法和潜在因子(Latent Factor)算法**. ​ 对于*协同过滤算法*,学术界提出了很多办法,比如*基于邻域的方法(neighborhood-based)*、*隐语义模型*、*基于图的随机游走算法* ​ 基于邻域的方法应用程度比较高,所以采用基于邻域的方法,此方法主要包含以下两种算法: ​ 1.基于用户的协同过滤算法:给用户推荐和其兴趣相似的其他用户喜欢的物品。 ​ 2.基于物品的协同过滤算法:给用户推荐和其之前喜欢的物品形似的物品。 ​ 不论使用那一种算法,首先需要将数据集随机分成(M)份,一份作为测试集,剩下作为训练集,随即在训练集上建立模型,测试集上对用户行为进行预测,参考代码如下: ```python import random #假设数据类型为列表 def dataGroup(data,M): practice = [] #训练集 for i in random.randint(0,int(len(data)/M)): practice.append(data[i]) del data[i] test = data #剩下的便是测试集 ``` ​ 目前暂时采用基于用户的协同过滤算法,以为一开始用户的数据量少于新闻量,基于用户的协同过滤算法主要包括以下两个步骤: ​ 1.计算用户之间的相似度 ​ 2.根据用户的相似度和用户的历史行为给用户生成推荐列表 ​ 对于步骤一:假设用户a和用户b,怎么计算这两个用户的相似度,可以通过Jaccard公式进行计算,最终是要得到用户的兴趣相似度,然后比较相似度相似的用户,进行新闻推荐。 ​ 对于*潜在因子(Latent Factor)算法* ,每个用户都有自己的感兴趣的地方,就新闻而言,可以将一个新闻分成几个兴趣点(这里兴趣点指的是上表字段content的标签),对用户而言,这些数据就表示对含有这些标签的新闻的标签喜欢程度;对新闻而言,我将这些数据称之为标签因子,用于计算该新闻能被用户喜欢到什么程度,具体看下表: | 用户 | 科技 | 搞笑 | 娱乐 | 体育 | 历史 | 当前城市 | | ------- | ---- | ---- | :--- | ---- | ---- | ---- | | howie-1 | 0.8 | 0.1 | 0.2 | 0.2 | 0.6 | 1 | | howie-2 | 0.5 | 0.4 | 0.4 | 1 | 0.5 | 0 | | 新闻 | 科技 | 搞笑 | 娱乐 | 体育 | 历史 | 当前城市 | | ------ | ---- | ---- | ---- | ---- | ---- | ---- | | news-1 | 0.2 | 0.1 | 0.1 | 0 | 0 | 1 | | news-2 | 0 | 0.2 | 0.2 | 0 | 1 | 1 | ​ 怎么计算呢?可以这样算出某个用户对某个新闻的喜欢程度: ​ howie-1和news-1: $$ result1=0.8*0.2+0.1*0.1+0.2*0.1+0.2*0+0.6*0+1*1=1.19 $$ ​ howie-1和news-2: $$ result2=0.8*0+0.1*0.2+0.2*0.2+0.2*0+0.6*1+1*1=1.66 $$ ​ howie-2和news-1: $$ result3=0.5*0.2+0.4*0.1+0.4*0.1+1*0+0.5*0+0*1=0.18 $$ ​ howie-2和news-2: $$ result4=0.5*0+0.4*0.2+0.4*0.2+1*0+0.5*1+0*1=0.66 $$ ​ 很明显,用户howie-1可以被推荐news-2,用户howie-2也可以被推荐news-2,当然,目前数据量很少,没有说明性,仅仅是举例。 | | news-1 | news-2 | | :-----: | :----: | :----: | | howie-1 | 1.19 | 1.66 | | howie-2 | 0.18 | 0.66 | ​ 所以,综上,系统推荐可以先利用协同过滤算法,分析出一些新闻数据集合 `U` ,与此同时,也通过潜在因子算法分析出一些新闻数据集合`R`,再利用公式: $$ top_i = U \cap R $$ ​ 根据计算结果,便可以得出需要推荐的前 `i` 条新闻,排序规则依据每条新闻被用户喜欢程度的数据大小。 ​ 至此,模型构建成功,下一步进行测试。 ### 4.结果分析 ​ 将计算结果与实际结果进行比较,将产生的结果反馈给模型,从而进一步优化。 ​ <file_sep># -*-coding:utf-8-*- __author__ = 'howie' import pandas as pd import os from config.n_conf import dirPath import controller.newsController as newsController from config.n_conf import dirPath class DataController(newsController.NewsController): def repeatedData(self, *dirs): """ func: 对爬取的数据进行去重操作 :param *dirs:文件夹list,dirs[0]里面含有文件夹名称,默认为2个 :return: 成功返回True,否则返回"No Data" """ self.initData = self.newsFiles("get", "allSource") if self.initData: for eachFile in self.initData: newsData = pd.read_excel(eachFile, sheetname="allNews") newsData = newsData.drop_duplicates() # 去重 # 获取主路径 path = os.path.join(dirPath, 'spider') # 获取处理后文件路径 for dir in dirs[0]: path = os.path.join(path, dir) filePath = os.path.join(path, os.path.split(eachFile)[1]) log = filePath + "文件去重成功" print(log) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") newsData.to_excel(excel_writer=filePath, sheet_name="allNews") return True else: return "No Data!" def rmAllNews(self, newsSource): for i in newsSource: self.newsFiles("rm", i) return self.rmRepeate(['wordAna', 'allNews']) newsSource = ["touTiaoSource", "sinaSource", "allSource","pyspiderSource"] DataController = DataController() # print(DataController.rmAllNews(newsSource)) #删除所有原始数据 # print(DataController.initData) # print(DataController.initData) # DataController.rmRepeate(['wordAna','allNews']) #删除去重文件夹里面的表 # DataController.rmRepeate(['wordAna','wordAnaNews']) #删除分词文件夹里面的表 # print(DataController.repeatedData(['wordAna','allNews'])) #进行去重操作 <file_sep>## 互联网内容推荐系统数据库设计 ### 1.环境要求 ​ 语言:`python3.5` ​ 数据库:`mysql5.0`以上 ​ 系统:`linux`系列皆可 ### 2.数据库需求分析 ​ 对于互联网内容推荐系统,经过分析后,设计的数据项和数据结构如下: | 名称 | 数据项 | | :--------- | :--------------------------------------- | | 用户 | 用户编号,昵称,电话,密码(<PASSWORD>),注册时间 | | 用户基本信息 | 用户编号,性别,年龄,邮箱,所在地,头像,是否被保护 | | 用户行为信息 | 用户编号,新闻编号,新闻标签,行为类型(浏览-0、喜欢-1、删除-2),权重(时间差),是否评论,地点,阅读方式(搜索-0、推荐-1),年龄段,分数,浏览次数 | | 用户操作 | 用户编号,新闻的编号,喜欢新闻的时间,评论新闻的内容(news_id{++}用户评论内容{++}时间{##}),是否喜欢 | | 用户喜欢标签 | 用户编号,标签1,标签2.. | | 新闻 | 新闻编号,发表地址,来源,时间,标题,摘要,标签,文本内容,html内容,图片,特征词,是否是老新闻—默认0表示新新闻 | | 新闻基本信息 | 新闻编号,新闻标签,阅读次数,喜欢次数,评论次数 | | 新闻评论 | 新闻编号,评论内容(user_id{++}用户评论内容{++}时间{##}) | | 用户标签因子喜欢程度 | 用户编号,各标签(分数—计算出来的概率) | | 用户标签因子分数 | 用户编号,各标签(分数--计算喜欢程度) | | 新闻标签因子 | 新闻编号,各标签(分数) | | 用户推荐新闻 | 用户编号,新新闻编号1+新闻标签1+喜欢程度值1#新新闻编号2+新闻标签2+喜欢程度值2# | | 用户反馈表 | 用户编号,反馈内容,反馈时间,回复内容,回复时间,是否回复 | | 后台管理员表 | 编号,用户名,密码 | | 新闻热点 | 新闻编号,时间,图片,简介,来源,标题,标签,喜欢次数,评论次数,阅读次数 | ### 3.数据库概念结构设计 ​ 根据上面的设计,可以得出有以下实体 `E-R图`:用户实体,用户基本信息实体,用户行为信息实体,用户操作实体,新闻实体,新闻基本信息实体,标签喜欢程度实体,老新闻分数实体,新闻标签因子实体,推荐新闻实体。 ##### 3-1.用户实体: ​ ![用户](source/用户.png) ##### 3-2.用户基本信息实体: ​ ![用户基本信息](source/用户基本信息.png) ##### 3-3.用户行为信息实体: ##### ![用户行为信息](source/用户行为信息.png) ##### 3-4.用户操作实体: ##### ![用户操作](source/用户操作.png) ##### 3-5.新闻实体: ![新闻](source/新闻.png) ##### 3-6.新闻基本信息实体: ​ ![新闻基本信息](source/新闻基本信息.png) ##### 3-7.标签喜欢程度实体: ​ ![标签喜欢程度](source/标签喜欢程度.png) ##### 3-8.新闻标签因子实体: ​ ![新闻标签因子](source/新闻标签因子.png) ##### 3-9.推荐新闻实体: ​ ![推荐新闻](source/推荐新闻.png) ##### 3-10.实体联系图: ![ERDDiagram](source/ERDDiagram.jpg) ### 4.数据库逻辑结构设计 ##### 1.用户表(news.user) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----: | :---------: | :-----------: | :------------: | | user_id | varchar(10) | not null | (PK)用户编号 | | phone | varchar(20) | not null | 用户电话 | | name | varchar(20) | not null | 用户昵称(默认为phone) | | passwd | varchar(40) | not null | 密码 | | time | timestamp | default now() | 注册时间 | ```mysql -- Table: user CREATE TABLE `user` ( `user_id` varchar(10) NOT NULL, `phone` varchar(20) NOT NULL, `name` varchar(20) NOT NULL, `passwd` varchar(40) NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`), UNIQUE KEY `phone` (`phone`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 2.用户基本信息表(news.user_mess) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----: | :---------: | :------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | sex | int | null | 用户性别 | | age | int | null | 用户年纪 | | email | varchar(20) | null | 用户邮箱 | | address | varchar(40) | null | 用户地址 | | image | varchar(60) | null | 头像 | | private | int | not null | 是否被保护 | ```mysql -- Table: user_mess CREATE TABLE `user_mess` ( `user_id` varchar(10) NOT NULL, `sex` int(11) DEFAULT NULL, `age` int(11) DEFAULT NULL, `email` varchar(20) DEFAULT NULL, `address` varchar(40) DEFAULT NULL, `image` varchar(60) DEFAULT NULL, `private` int NOT NULL DEFAULT `1`, UNIQUE KEY `email` (`email`), KEY `user_id` (`user_id`), CONSTRAINT `fk_user_mess` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 3.用户行为信息表(news.user_behavior) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----------: | :----------: | :----------------: | :-------------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | news_id | varchar(20) | not null | 新闻编号(FK),指向get_news的news_id | | news_tag | varchar(20) | not null | 新闻标签 | | behavior_type | int | not null default 0 | 行为类型(浏览-1、喜欢-2、删除-3) | | weight | double | null | 浏览时长 | | is_comment | int | default 0 | 是否评论(0 or 1) | | address | varchar(100) | null | 地点 | | news_way | int | default 0 | 推荐方式阅读新闻(0)或者搜索(1) | | age | varchar(20) | null | 年龄段 | | scores | int | not null | 特定用户对特定新闻的分数 | | times | int | not null | 阅读次数 | ```mysql -- Table: user_behavior CREATE TABLE `user_behavior` ( `user_id` varchar(10) NOT NULL, `news_id` varchar(20) NOT NULL, `news_tag` varchar(20) NOT NULL, `behavior_type` int(11) NOT NULL DEFAULT '0', `weight` double DEFAULT NULL, `is_comment` int(11) NOT NULL DEFAULT '0', `address` varchar(100) DEFAULT NULL, `news_way` int(11) NOT NULL DEFAULT '0', `age` varchar(20) DEFAULT NULL, `score` int(11) NOT NULL DEFAULT '0', `times` int(11) NOT NULL DEFAULT '0', KEY `FK_user_user_behavior` (`user_id`), KEY `FK_get_news_user_behavior` (`news_id`), CONSTRAINT `FK_get_news_user_behavior` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`), CONSTRAINT `FK_user_user_behavior` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 4.用户操作表(news.user_operate) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----: | :-----------: | :------: | :------------------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | news_id | varchar(20) | not null | 喜欢或评论新闻编号(FK),指向get_news的news_id | | time | timestamp | null | 喜欢新闻时间 | | comment | varchar(1000) | null | 评论新闻的内容(用户评论内容{++}时间{##}) | | is_love | int | null | 喜欢为1,不喜欢为0 | ```mysql -- Table: user_operate CREATE TABLE `user_operate` ( `user_id` varchar(10) NOT NULL, `news_id` varchar(20) NOT NULL, `comment` varchar(1000) DEFAULT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `is_love` int(11) DEFAULT NULL, KEY `FK_get_news_user_operate` (`news_id`), KEY `FK_user_user_operator` (`user_id`), CONSTRAINT `FK_get_news_user_operate` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`), CONSTRAINT `FK_user_user_operator` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 5.用户标签表(news.user_love_tag) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----: | :----------: | :------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | tags | varcher(300) | not null | 标签1,标签2.. | ```mysql CREATE TABLE `user_love_tag` ( `user_id` varchar(10) NOT NULL, `tags` varchar(300) NOT NULL, KEY `FK_user_user_love_tag` (`user_id`), CONSTRAINT `FK_user_user_love_tag` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ``` ##### 6.新闻表(news.get_news) | 列名 | 数据类型 | 是否为空 | 说明 | | :----------: | :------------: | :-------: | :-------------: | | news_id | varchar(20) | not null | 新闻编号(PK) | | news_link | varchar(100) | null | 发表地址 | | source | varchar(20) | null | 新闻来源 | | time | timestamp | now() | 发表时间 | | title | varchar(50) | not null | 新闻标题 | | abstract | varchar(500) | not null | 新闻摘要 | | tag | varchar(20) | not null | 新闻标签 | | text_content | varchar(50000) | not null | 新闻文本内容 | | html_content | varchar(50000) | not null | 新闻html内容 | | image | varchar(100) | null | 图片链接 | | keyword | varchar(100) | not null | 关键词 | | is_old | int | default 0 | 是否是老新闻—默认0表示新新闻 | ```mysql -- Table: get_news CREATE TABLE `get_news` ( `news_id` varchar(20) NOT NULL, `news_link` varchar(100) DEFAULT NULL, `source` varchar(20) DEFAULT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `title` varchar(50) NOT NULL, `abstract` varchar(500) NOT NULL, `tag` varchar(20) NOT NULL, `text_content` mediumtext NOT NULL, `html_content` mediumtext NOT NULL, `image` varchar(100) DEFAULT NULL, `keyword` varchar(100) NOT NULL, `is_old` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`news_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 7.新闻基本信息表(news.news_mess) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----------: | :---------: | :----------------: | :-------------------------: | | news_id | varchar(20) | not null | 新闻编号(FK),指向get_news的news_id | | tag | varchar(20) | not null | 新闻标签 | | read_times | int | not null default 0 | 阅读次数 | | love_times | int | not null default 0 | 喜欢次数 | | comment_times | int | not null default 0 | 评论次数 | ```mysql -- Table: news_mess CREATE TABLE `news_mess` ( `news_id` varchar(20) NOT NULL, `tag` varchar(20) NOT NULL, `read_times` int(11) NOT NULL DEFAULT '0', `love_times` int(11) NOT NULL DEFAULT '0', `comment_times` int(11) DEFAULT '0', KEY `FK_get_news_news_mess` (`news_id`), CONSTRAINT `FK_get_news_news_mess` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 8.新闻评论(news.comment) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----: | :------------: | :------: | :-------------------------------: | | news_id | varchar(20) | not null | 新闻编号(FK),指向get_news的new_id | | comment | varchar(20000) | null | 评论内容(user_id{++}用户评论内容{++}时间{##}) | ```mysql -- Table: news_comment CREATE TABLE `news_comment` ( `news_id` varchar(20) NOT NULL, `comment` varchar(20000) DEFAULT NULL, KEY `FK_get_news_news_comment` (`news_id`), CONSTRAINT `FK_get_news_news_comment` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 9.用户标签因子喜欢程度表(news.user_tag_deep) | 列名 | 数据类型 | 是否为空 | 说明 | | :----------------: | :---------: | :------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | news_society | double | null | 社会新闻 | | news_entertainment | double | null | 娱乐新闻 | | news_tech | double | null | 科技新闻 | | news_car | double | null | 汽车新闻 | | news_sports | double | null | 体育新闻 | | news_finance | double | null | 财经新闻 | | news_military | double | null | 军事新闻 | | news_world | double | null | 国际新闻 | | news_fashion | double | null | 时尚新闻 | | news_travel | double | null | 旅游新闻 | | news_discovery | double | null | 探索新闻 | | news_baby | double | null | 育儿新闻 | | news_regimen | double | null | 养生新闻 | | news_story | double | null | 故事新闻 | | news_essay | double | null | 美文新闻 | | news_game | double | null | 游戏新闻 | | news_history | double | null | 历史新闻 | | news_food | double | null | 美食新闻 | ```mysql -- Table: user_tag_deep CREATE TABLE `user_tag_deep` ( `user_id` varchar(10) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL, KEY `FK_user_user_tag_deep` (`user_id`), CONSTRAINT `FK_user_user_tag_deep` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 10.用户标签因子分数(news.user_tag_score) | 列名 | 数据类型 | 是否为空 | 说明 | | :----------------: | :---------: | :------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | news_society | double | null | 社会新闻 | | news_entertainment | double | null | 娱乐新闻 | | news_tech | double | null | 科技新闻 | | news_car | double | null | 汽车新闻 | | news_sports | double | null | 体育新闻 | | news_finance | double | null | 财经新闻 | | news_military | double | null | 军事新闻 | | news_world | double | null | 国际新闻 | | news_fashion | double | null | 时尚新闻 | | news_travel | double | null | 旅游新闻 | | news_discovery | double | null | 探索新闻 | | news_baby | double | null | 育儿新闻 | | news_regimen | double | null | 养生新闻 | | news_story | double | null | 故事新闻 | | news_essay | double | null | 美文新闻 | | news_game | double | null | 游戏新闻 | | news_history | double | null | 历史新闻 | | news_food | double | null | 美食新闻 | ```mysql -- Table: user_tag_deep CREATE TABLE `user_tag_score` ( `user_id` varchar(10) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL, KEY `FK_user_user_tag_score` (`user_id`), CONSTRAINT `FK_user_user_tag_score` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 11.新闻标签因子表(news.news_tag_deep) | 列名 | 数据类型 | 是否为空 | 说明 | | :----------------: | :---------: | :------: | :-------------------------: | | news_id | varchar(20) | not null | 新闻编号(FK),指向get_news的news_id | | news_society | double | null | 社会新闻 | | news_entertainment | double | null | 娱乐新闻 | | news_tech | double | null | 科技新闻 | | news_car | double | null | 汽车新闻 | | news_sports | double | null | 体育新闻 | | news_finance | double | null | 财经新闻 | | news_military | double | null | 军事新闻 | | news_world | double | null | 国际新闻 | | news_fashion | double | null | 时尚新闻 | | news_travel | double | null | 旅游新闻 | | news_discovery | double | null | 探索新闻 | | news_baby | double | null | 育儿新闻 | | news_regimen | double | null | 养生新闻 | | news_story | double | null | 故事新闻 | | news_essay | double | null | 美文新闻 | | news_game | double | null | 游戏新闻 | | news_history | double | null | 历史新闻 | | news_food | double | null | 美食新闻 | ```mysql -- Table: news_tag_deep CREATE TABLE `news_tag_deep` ( `news_id` varchar(20) NOT NULL, `news_society` double DEFAULT NULL, `news_entertainment` double DEFAULT NULL, `news_tech` double DEFAULT NULL, `news_car` double DEFAULT NULL, `news_sports` double DEFAULT NULL, `news_finance` double DEFAULT NULL, `news_military` double DEFAULT NULL, `news_world` double DEFAULT NULL, `news_fashion` double DEFAULT NULL, `news_travel` double DEFAULT NULL, `news_discovery` double DEFAULT NULL, `news_baby` double DEFAULT NULL, `news_regimen` double DEFAULT NULL, `news_story` double DEFAULT NULL, `news_essay` double DEFAULT NULL, `news_game` double DEFAULT NULL, `news_history` double DEFAULT NULL, `news_food` double DEFAULT NULL, KEY `FK_get_news_news_tag_deep` (`news_id`), CONSTRAINT `FK_get_news_news_tag_deep` FOREIGN KEY (`news_id`) REFERENCES `get_news` (`news_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 12.用户推荐新闻表(news.news_recommend) | 列名 | 数据类型 | 是否为空 | 说明 | | :--------: | :------------: | :------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | news_score | varchar(60000) | not null | 新新闻编号1+新闻标签1+喜欢程度值1# | ```mysql -- Table: news_recommend Create Table: CREATE TABLE `news_recommend` ( `user_id` varchar(10) NOT NULL, `news_score` mediumtext, KEY `FK_user_news_recomment` (`user_id`), CONSTRAINT `FK_user_news_recomment` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 13.用户反馈表(news.news_feedback) | 列名 | 数据类型 | 是否为空 | 说明 | | :-------: | :----------: | :-------: | :---------------------: | | user_id | varchar(10) | not null | 用户编号(FK),指向user的user_id | | feedback | varchar(200) | null | 反馈内容 | | getTime | timestamp | null | 反馈时间 | | reply | varchar(200) | null | 回复内容 | | replyTime | timestamp | null | 回复时间 | | isReply | int | default 0 | 是否回复 | ```mysql -- Table: news_feedback CREATE TABLE `news_feedback` ( `user_id` varchar(10) NOT NULL, `feedback` varchar(200) DEFAULT NULL, `getTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `reply` varchar(200) DEFAULT NULL, `replyTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `isReply` int(11) DEFAULT '0', KEY `FK_user_news_feedback` (`user_id`), CONSTRAINT `FK_user_news_feedback` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ##### 14.后台管理员表(news.n_admin) | 列名 | 数据类型 | 是否为空 | 说明 | | :--: | :---------: | :------: | :--: | | id | int | not null | PK | | name | varchar(10) | null | 管理员 | | pass | varchar(40) | null | 密码 | ```mysql -- Table: n_admin CREATE TABLE `n_admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(10) NOT NULL, `pass` varchar(40) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ``` ##### 15.新闻热点表(news_hot) | 列名 | 数据类型 | 是否为空 | 说明 | | :-----------: | :----------: | :------: | :--: | | news_id | varchar(20) | not null | 新闻编号 | | time | timestamp | not null | 时间 | | image | varchar(100) | null | 图片 | | abstract | varchar(500) | not null | 简介 | | source | varchar(20) | null | 来源 | | title | varchar(50) | not null | 标题 | | tag | varchar(20) | not null | 标签 | | read_times | int | not null | 阅读次数 | | love_times | int | not null | 喜欢次数 | | comment_times | int | null | 评论次数 | ```mysql create view news_hot as select a.news_id,a.time,a.image,a.abstract,a.source,a.title,b.tag,b.love_times,b.read_times,b.comment_times from get_news a join news_mess b where a.news_id = b.news_id; ``` <file_sep> from spider.wordAna.contentTool import * from newsPredict import * from predictTool import * import os ct = ContentOperator() # urlstr = "http://toutiao.com/a6292379445978808577/" # urlstr ="http://toutiao.com/a6292665412145365250/" # urlstr = "http://toutiao.com/group/6292605706580803842/" #汽车 # urlstr = "http://toutiao.com/a6291989690913620225/" #美文 # urlstr = "http://toutiao.com/a6292346062074691841/" #游戏 # urlstr = "http://toutiao.com/a6280854429832233218/" #科技 # urlstr = "http://toutiao.com/group/6291592935427604737/" #故事 # urlstr = "http://toutiao.com/a6292516516223680770/" #养生 # urlstr = "http://toutiao.com/a6292528444404973826/" #历史 # urlstr = "http://toutiao.com/a6292557068092080386/" #美食 # urlstr = "http://toutiao.com/a6292374615201153537/" #发现 # urlstr = "http://toutiao.com/a6292035179544412417/" #时尚 # urlstr = "http://toutiao.com/a6292511961298059521/" #旅游 urlstr = "http://toutiao.com/a6292830759922729218/" #育儿 textContent, htmlContent, img_url_list = ct.getToutiaoContent(urlstr) data_list = [] new = {} new["id"] = "1" new["textContent"] = textContent data_list.append(new) np = NewPredict(data_list) np.getNewInfo() test_data_file = os.path.abspath('.') + "/NavieBayesInfo/predict_new_word.txt" model_file = os.path.abspath('.') + "/NavieBayesInfo/model.txt" result_file = os.path.abspath('.') + "/NavieBayesInfo/predict_result.txt" print(test_data_file) nb = NavieBayesPredict(test_data_file,model_file,result_file) nb.predict()<file_sep>$(document).ready(function () { /*自适应高度*/ var left_show = document.getElementById('left'); var left_show_height; if (navigator.userAgent.indexOf("Firefox") > 0) { left_show_height = document.documentElement.scrollHeight; } if (window.navigator.userAgent.indexOf("Chrome") !== -1 || navigator.userAgent.indexOf("Safari") > 0) { left_show_height = document.body.scrollHeight; } if (navigator.userAgent.indexOf("MSIE") > 0) { left_show_height = (document.documentElement.scrollHeight > document.documentElement.clientHeight) ? document.documentElement.scrollHeight : document.documentElement.clientHeight; } else { left_show_height = (document.documentElement.scrollHeight > document.documentElement.clientHeight) ? document.documentElement.scrollHeight : document.documentElement.clientHeight; } left_show.style.height = left_show_height - 50 + "px"; //var second_show = document.getElementById('second'); //second_show.style.height = left_show_height - 50 + "px"; //dataAna //更改密码 $('#changePass').click(function () { var pass = $("#pass").val(); var confirm = $("#confirm").val(); if (pass == confirm) { $.get("/changePass", {pass: pass}, function (result) { alert(result) $('#close').trigger('click'); }); } else { alert("请确认您是否输入正确") } }); //home 数据处理步骤 var numOperator = $('.col-operator'); for (i = 0; i < numOperator.length; i++) { numOperator.eq(i).click(function () { numOperator.removeClass('col-operator-active'); $(this).addClass('col-operator-active') }) } //数据处理 $('#getNewsStart').click(function () { var ttSelect = $("#ttSelect").val(); var page = $("#page").val(); var num = $("#num").val(); $(".show-content").html("<p>开始进行新闻获取:</p>"); $(".show-content").append("<p>数据量较多,请耐心等待...</p>"); $.get("/dataOperator", {action: "getNews", ttSelect: ttSelect, page: page, num: num}, function (result) { $(".show-content").append("<p>新闻爬取完成,请继续下一步!</p>"); $('#close2').trigger('click'); }); }); //新闻去重 $('#repeatedData').click(function () { if (confirm("是否已经进行新闻获取?")) { $(".show-content").append("<p>正在进行数据去重...</p>"); $.get("/dataOperator", {action: "repeatedData"}, function (result) { $(".show-content").append("<p>数据去重完成,请继续下一步!</p>"); }); } }); //特征词分析 $('#anaData').click(function () { if (confirm("是否已经进行新闻去重?")) { $(".show-content").append("<p>正在进行内容分析...</p>"); $.get("/dataOperator", {action: "anaData"}, function (result) { $(".show-content").append("<p>内容分析完成,请继续下一步!</p>"); }); } }); //数据清洗 $('#rmAllNews').click(function () { if (confirm("确定清洗数据?")) { $(".show-content").append("<p>正在进行数据清洗...</p>"); $.get("/dataOperator", {action: "rmAllNews"}, function (result) { $(".show-content").append("<p>数据清洗完成,数据分析完成!</p>"); }); } }); //数据保存 $("#save").mouseover(function () { $("#save").attr("src", "/static/images/save.svg"); }); $("#save").mouseout(function () { $("#save").attr("src", "/static/images/save0.svg"); }); $('#save').click(function () { $(".show-content").html("<p>正在存储数据...</p>"); $.get("/dataOperator", {action: "insertDB"}, function (result) { $(".show-content").append("<p>数据存储完成!</p>"); $("#save").css("display", "none") $("#save1").css("display", "block") }); }); //home 底部cmd窗口效果 $('.show-nav-right-down').click(function () { $('.show-nav-right-down').css("display", "none"); $('.show-nav-right-up').css("display", "block"); $('.show-nav').css("background-color", "rgb(106, 127, 127)"); $(".showlog").animate({height: '20px'}); }); $('.show-nav-right-up').click(function () { $('.show-nav-right-down').css("display", "block"); $('.show-nav-right-up').css("display", "none"); $('.show-nav').css("background-color", "#0C0C0C"); $(".showlog").animate({height: '300px'}); }); $('#systemPage').css('height',left_show_height+"3"+"px"); })<file_sep># -*-coding:utf-8-*- __author__ = "xiao" import math from methods.pDb import newsDb class ScoreTool(object): def __init__(self): self.def_scan_time = 150.0 def scoreUpdate(self, user_id, new_id, tag, refer_time, operation): score, tagAddScoreDict = '', '' try: # 获取用户行为信息表中关于当前用户对当前类别新闻的行为数据 all_new_info_list = self.getUserNewData(user_id, tag) # 获取用户关于当前新闻的行为数据 cur_new_info_list = self.getCurNewData(new_id, all_new_info_list) # 获取当前新闻的类别比例因子字典 cur_new_tagDeep_list = self.getCurNewTagList(new_id) # 获取用户对当前类别新闻的平均浏览时间 avgTime = self.calAvgTime(all_new_info_list) # 在此行为之前用户对这条新闻的操作行为为空,或者最近一次行为的加分为0,无需考虑其他因素,主类加分可直接以当前行为进行计分 if len(cur_new_info_list) == 0 or cur_new_info_list[len(cur_new_info_list) - 1][3] == None or \ cur_new_info_list[len(cur_new_info_list) - 1][3] == 0: score = self.calFirstAddScore(refer_time, operation, avgTime) # 当用户连续两次操作为非删除操作时 # 此前已经有对于当前新闻的行为数据,代表此次行为对于用户类别之间的概括已经不能和第一次行为相比,更多的概括是在用户和此新闻涉及的话题之间 # 运用开平方的形式,保证每次加分都考虑到之前的行为,且保证加分幅度越来越小 else: score = self.calNotFirstAddScore(operation, cur_new_info_list) # print(score) # 由主类应加分数获得其他各类应加分数 tagAddScoreDict = self.calAllTagAddScore(tag, score, cur_new_tagDeep_list) # print(tagAddScoreDict) except Exception as e: print("scoreUpdate raises the error") print(e) return score, tagAddScoreDict # 计算 当前行为 对应的主类应加分数 # 此处为对当前新闻的第一次操作,不考虑是否有评论 def calFirstAddScore(self, refer_time_str, operation, avgTime): # tag 当前用户浏览类别 # refer_time 用户浏览该条新闻的时间(秒) # operation 用户对该条新闻的操作 # is_comment 是否评论 # 用户浏览此类新闻的平均浏览时间 # 用户操作为浏览 if operation == 0: refer_time = (float)(refer_time_str) if refer_time <= avgTime: return 5.0 elif refer_time > avgTime and refer_time <= 3 * avgTime: return 5.0 + (refer_time - avgTime) / 30.0 # 此范围内,每过30秒加一分 else: return 3 / 4.0 * (5.0 + 2 * avgTime / 30) # 用户操作为喜欢 elif operation == 1: return 3 / 4.0 * (5.0 + 2 * avgTime / 30) # 用户操作为删除 elif operation == 2: return -3 / 4.0 * (5.0 + 2 * avgTime / 30) def calNotFirstAddScore(self, operation, cur_new_info_list): # 距离此次行为最近的一次行为加的分数 org_score = cur_new_info_list[len(cur_new_info_list) - 1][3] if operation == 2: # 上一次操作也是删除 if org_score < 0: # 降低删除带来的影响分,开平方 score = - math.sqrt(-org_score) # 上一次的操作不是删除,#减去上一次行为带来的加成分 else: score = -org_score else: # 主类此次行为应加的分数 score = math.sqrt(org_score) return score # 根据当前新闻的比例因子计算各类别应加分数 def calAllTagAddScore(self, tag, mainTagAddScore, cur_new_tagDeep_list): tagAddScore = {} mainTagDeep = 0.0 for i in range(len(cur_new_tagDeep_list)): if i % 2 == 0: if cur_new_tagDeep_list[i] == tag: mainTagDeep = cur_new_tagDeep_list[i + 1] tagAddScore[tag] = mainTagAddScore for i in range(len(cur_new_tagDeep_list)): if i % 2 == 0: if cur_new_tagDeep_list[i] != tag: tagAddScore[cur_new_tagDeep_list[i]] = mainTagAddScore * ( cur_new_tagDeep_list[i + 1] * 1.0 / mainTagDeep) return tagAddScore # 计算用户浏览当前类别新闻的平均时间 def calAvgTime(self, data): time_sum = 0.0 # 浏览总时长 news_sum = 0.0 # 浏览新闻数 if data != None: for d in data: # 浏览时间存在时才能证明当前新闻被浏览过 if d[0] != None: if d[3] != None: time_sum += float(d[3]) news_sum += 1 if news_sum == 0.0: return self.def_scan_time avgTime = time_sum / news_sum # 如果计算出来的平均浏览时间小于30秒,则代表数据不正常,强制定性用户浏览一条当前新闻的时间为默认花费时长 if avgTime < 30: return self.def_scan_time return avgTime # 获取用户行为信息表中关于当前用户对当前类别新闻的行为数据,包括新闻id,浏览新闻的时间,是否对新闻进行评论 def getUserNewData(self, user_id, tag): db = newsDb() sql = "select news_id,weight,is_comment,score from user_behavior where news_tag='" + tag + "' and user_id='" + user_id + "'" return db.select_table_three(sql) # 获取用户对于当前此条新闻的行为数据 def getCurNewData(self, new_id, news_info_list): cur_new_info_list = [] if news_info_list != None: for info in news_info_list: if info[0] == new_id: cur_new_info_list.append(info) return cur_new_info_list # 获取当前新闻的类别比重因子 def getCurNewTagList(self, new_id): db = newsDb() list = [] sql = "select * from news_tag_deep where news_id='" + new_id + "'" data = db.select_table_three(sql) if data != None: for i in range(len(data) - 1): list.append(category[i]) list.append(float(data[i + 1])) return list return None # 新闻种类 category = ["news_society", "news_entertainment", "news_tech", "news_car", "news_sports", "news_finance", "news_military", "news_world", "news_fashion", "news_travel", "news_discovery", "news_baby", "news_regimen", "news_story", "news_essay", "news_game", "news_history", "news_food"] st = ScoreTool() # list = st.getCurNewTagList("050a797bb92b620722b6") # st.calAllTagAddScore("news_society",5,list) # x,y = st.scoreUpdate('000001','050a797bb92b620722b6',"news_travel",0,1) # print(y) <file_sep> #文件中用到了xlrd模块 import xlrd #读excel工具 import xlsxwriter #写excel工具 from config.n_conf import dirPath class ExcelOperator(): ''' excel操作工具 getInfo为读取excel表数据,返回类型为list,list中每个元素为dict,对应键值为 列名:值 参数为filePath: excel文件的绝对地址 ''' def __init__(self): #用于关键词分析后的excel数据表 self.colnames = ["index","title","display_url","display_time","source", "keywords","abstract","images","tag","feature","textContent""htmlContent","img"] def getExcelInfo(self,filePath): try: data = xlrd.open_workbook(filePath) list = [] if data: table = data.sheet_by_index(0) if table: nrows = table.nrows # 表的行数 colnames = table.row_values(0) # 表的列名(list) clen = len(colnames) # 列名个数 for rownum in range(1, nrows): row = table.row_values(rownum) if row: app = {} for i in range(1, clen): app[self.colnames[i]] = row[i] list.append(app) return list except: print ("xlrd读取" + filePath + "文件出错") exit() def saveToExcel(self,excelName,sheetName,data): """ 将数据生成excel表 :param data: 数据 :param excelName 保存的excel表名,绝对路径 :param sheetName 工作表名称 :return: 返回生成的excel表 """ # 设置excel表名称 print(excelName) open(excelName,'w') jr_work = xlsxwriter.Workbook(excelName) #避免混淆 jr_sheet = jr_work.add_worksheet(sheetName) bold = jr_work.add_format({'bold': True}) # 设置一个加粗的格式对象 jr_sheet.set_column('A:H', 40) jr_sheet.set_column('C:D', 15) jr_sheet.write(0, 0, 'index', bold) jr_sheet.write(0, 1, 'title', bold) jr_sheet.write(0, 2, 'display_url', bold) jr_sheet.write(0, 3, 'display_time', bold) jr_sheet.write(0, 4, 'source', bold) jr_sheet.write(0, 5, 'keywords', bold) jr_sheet.write(0, 6, 'abstract', bold) jr_sheet.write(0, 7, 'images', bold) jr_sheet.write(0, 8, 'tag', bold) jr_sheet.write(0, 9, 'feature', bold) jr_sheet.write(0, 10, 'textContent',bold) jr_sheet.write(0, 11, 'htmlContent',bold) jr_sheet.write(0, 12, 'img_url', bold) line = 0 for eachData in data: line += 1 jr_sheet.write(line, 0, str(line)) jr_sheet.write(line, 1, eachData["title"]) jr_sheet.write(line, 2, eachData["display_url"]) jr_sheet.write(line, 3, eachData["display_time"]) jr_sheet.write(line, 4, eachData["source"]) jr_sheet.write(line, 5, eachData["keywords"]) jr_sheet.write(line, 6, eachData["abstract"]) if eachData["display_url"].find("sina.com") != -1: if eachData["img"]: sinaImg = ','.join(eachData["img"]) jr_sheet.write(line, 7, sinaImg) else: jr_sheet.write (line, 7, str (eachData ["images"])) jr_sheet.write(line, 8, eachData["tag"]) jr_sheet.write(line, 9, ' '.join(eachData["feature"]),bold) jr_sheet.write(line, 10, eachData["textContent"]) jr_sheet.write(line, 11, eachData["htmlContent"]) jr_sheet.write(line, 12, ','.join(eachData["img"])) jr_work.close() log = "%sExcel文件保存完成" % (excelName) with open(dirPath+"/log.txt", 'a') as fp: fp.write(log + "\n") print(log) <file_sep>"""myNews Usage: myNews [-p] <port> Options: -h,--help 显示帮助菜单 -p 端口号 Example: myNews -p 8888 设置端口号为8888 """ from docopt import docopt from server import main def cli(): kwargs = docopt(__doc__) port = kwargs['<port>'] main(port) if __name__ == "__main__": cli() <file_sep>#-*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape from handlers.base import BaseHandler class NewsManage(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): header = "新闻管理" self.render("newsManage.html",header=header) <file_sep>import os import re import jieba import jieba.analyse from spider.wordAna.contentTool import ContentOperator from spider.wordAna.excelTool import ExcelOperator from config.n_conf import dirPath class DataPerpare(object): def __init__(self,dataDir): #存放训练数据的文件夹,训练数据统一为excel文件 self.dataDir = dataDir # 获得excelTools.py中的excel操作工具 self.et = ExcelOperator() # 获得contentTools.py中的content操作工具 self.ct = ContentOperator() # 使用该txt文件存储各类别新闻数等相关信息 self.fn = open(dirPath + "/system/classPredict/NavieBayesInfo/train_news_Info.txt", "a") # 要将单词与id的字典放到txt文件中,以此进行贝叶斯分类时的使用准备 self.fd = open(dirPath + "/system/classPredict/NavieBayesInfo/word_id_dict.txt", 'a') # 文件行数据格式 类别 单词1 单词2 单词3#类别 # 对于每个单词,使用一个id表示,提高检索速度=====word_ids # 一个包含所有不重复单词的集合====unique_words self.unique_words = [] self.word_ids = {} def getNewContentAndAnalyse(self): #获取所有存放训练数据的excel文件的集合 filenames = self.getDataFilenames(self.dataDir) for filename in filenames: # 得到当前新闻类别 cate = filename.split("&")[1][5:] print(filename) # 此处得到该excel文件夹所有信息,是一个list,list中单个元素为dict,对应 列名:值 infoList = self.et.getExcelInfo(os.path.join(self.dataDir, filename)) for new_info in infoList: urlstr = new_info["display_url"] # 区分链接,链接来自头条或新浪,关键词,toutiao.com和sina.com try: # 这里需要去除sina的滚动图片类新闻及多媒体新闻 if urlstr.find("sina.com") != -1 and urlstr.find("slide") == -1 and urlstr.find("video") == -1: print(urlstr) textContent, htmlContent, img_url_list, keyword_list, abstract = self.ct.getSinaContent(urlstr) elif urlstr.find("toutiao.com") != -1: print(urlstr) textContent, htmlContent, img_url_list = self.ct.getToutiaoContent(urlstr) else: continue except Exception as e: continue if textContent == None: continue # 采用结巴中文分词提取正文最重要的十个特征词 # 相关算法 --- tf-idf算法 feature = jieba.analyse.extract_tags(textContent, 15) # 将当前新闻的关键词写入贝叶斯单词信息txt self.writeFeature(cate, feature) # cate为feature特征词集合所属的类别 def writeFeature(self, cate, feature): self.fn.write(cate + ' ') for word in feature: if word not in self.word_ids: self.unique_words.append(word) # 使用unique_words当前数组长度作为单词的唯一id self.word_ids[word] = len(self.unique_words) #将单词与对应id写入单词:id字典文件 self.fd.write(word + ' ' + str(self.word_ids[word]) + ' ') self.fn.write(str(self.word_ids[word]) + ' ') self.fn.write('#' + cate + '\n') def getDataFilenames(self,dir): fileList = [] for dirpath, dirnames, filenames in os.walk(self.dataDir): break for filename in filenames: # 过滤非excel文件 m = re.search(r"xlsx", filename) if not m: continue fileList.append(filename) return fileList def loadWord_id_dict(self): fd = open(dirPath + "/system/classPredict/NavieBayesInfo/word_id_dict.txt", 'r') allInfo = fd.read() arr = allInfo.strip().split() for i in range(0, len(arr)): if i % 2 == 0: self.word_ids[arr[i]] = arr[i + 1] if arr[i] not in self.unique_words: self.unique_words.append(arr[i]) dp = DataPerpare(dirPath + "/system/classPredict/trainData") dp.loadWord_id_dict() dp.getNewContentAndAnalyse() <file_sep># -*-coding:utf-8-*- __author__ = 'howie' import sys, time, json, requests class GetToutiao(): """ 通过今日头条API获取新闻信息,保存至本地excel """ def __init__(self, count, category, time): self.count = count self.category = category self.time = time self.url = "http://toutiao.com/api/article/recent/?count=" + count + "&category=" + category + "&as=A1A5177BB0F7063&cp=57B0776066D39E1&max_create_time=1471155832&_=" + str( time) def getNews(self): print(self.url) try: header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'} root = requests.get("http://toutiao.com/", headers=header) news = requests.get(self.url, headers=header, cookies=root.cookies) allNewsData = [] try: news = str(news.text).strip("'<>() ").replace('\'', '\"') newsJson = json.loads(news) if newsJson["data"]: for eachData in newsJson["data"]: newsData = {} newsData["title"] = eachData["title"] newsData["display_url"] = eachData["display_url"] newsData["display_time"] = eachData["display_time"] newsData["source"] = eachData["source"] newsData["keywords"] = eachData["keywords"] newsData["abstract"] = eachData["abstract"] if "middle_image" in eachData.keys(): newsData["images"] = eachData["middle_image"] else: newsData["images"] = "null" newsData["tag"] = eachData["tag"] allNewsData.append(newsData) else: exit("no data!") except: print(repr(news)) print(sys.exc_info()) return allNewsData except ConnectionError: exit("ConnectionError") # for i in range(1,20): # get = GetToutiao("30", "news_society", time.time()) # allNewsData = get.getNews() # for i in allNewsData: # print(i) <file_sep>window.onload = function () { var name = document.getElementById('username'); var pass = document.getElementById('password'); var login = document.getElementById('login'); login.onclick = function () { if (name.value == "" || pass.value == "") { alert('不能有内容为空'); } } } $(document).ready(function(){ $("#login").click(function(){ var user = $("#username").val(); var pwd = $("#password").val(); var pd = {"username":user, "password":pwd}; $.ajax({ type:"post", url:"/", data:pd, cache:false, success:function(data){ window.location.href="/admin?user="+data; }, error:function(){ alert("error!"); }, }); }); //得到焦点 $("#password").focus(function () { $("#left_hand").animate({ left: "150", top: " -38" }, { step: function () { if (parseInt($("#left_hand").css("left")) > 140) { $("#left_hand").attr("class", "left_hand"); } } }, 2000); $("#right_hand").animate({ right: "-64", top: "-38px" }, { step: function () { if (parseInt($("#right_hand").css("right")) > -70) { $("#right_hand").attr("class", "right_hand"); } } }, 2000); }); //失去焦点 $("#password").blur(function () { $("#left_hand").attr("class", "initial_left_hand"); $("#left_hand").attr("style", "left:100px;top:-12px;"); $("#right_hand").attr("class", "initial_right_hand"); $("#right_hand").attr("style", "right:-112px;top:-12px"); }); }); // function keyLogin() { // if (event.keyCode == 13) //回车键 // document.getElementById('login').onclick() // } <file_sep># -*-coding:utf-8-*- __author__ = 'Jeezy' '''用户-新闻潜在因子矩阵计算,得到我们要(初始)推荐的新闻(潜在因子新闻),在geneNewsType计算得到潜在因子新闻-标签(类型)矩阵''' from numpy import * from numpy import linalg as la ''' 计算并预测用户-标签(类型)潜在因子,得到对应分值, 并返回各预测新闻评分, n由我们定义 ''' def loadExData(): # 数据库查询,获取用户编号,新闻编号及其新闻评分(如有需要,可加其他) # 测试数据 userdata = [1,2,3,4,5,0] ndata = [[5,0,3,4,0,0], [0,0,0,3,0,0], [0,0,1,0,2,0], [0,4,4,3,0,0], [0,5,0,-1,-5,0]] data = [[5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,0], [0,0,0,3,0,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,5,3,4,2,1,0,7,9,0,3,7,0,0], [1,0,1,0,0,2,1,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,1,0,7,9,0,3,0,4,1,0,1], [0,4,4,3,0,5,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,5,3,4,2,1,0,7,9,0,3,1,1,0,1,1], [4,5,0,-1,0,-5,0,0,2,1,0,5,0,3,4,1,0,5,0,3,4,1,0,5,0,3,4,1,1,0,2,5,0,7,0]] return userdata,ndata,data,mat(data) '''以下是三种计算相似度的算法,分别是欧式距离、皮尔逊相关系数和余弦相似度, 注意三种计算方式的参数inA和inB都是列向量''' def ecludSim(inA,inB): return 1.0/(1.0+la.norm(inA-inB)) #范数的计算方法linalg.norm(),这里的1/(1+距离)表示将相似度的范围放在0与1之间 def pearsSim(inA,inB): if len(inA)<3: return 1.0 return 0.5+0.5*corrcoef(inA,inB,rowvar=0)[0][1] #皮尔逊相关系数的计算方法corrcoef(),参数rowvar=0表示对列求相似度,这里的0.5+0.5*corrcoef()是为了将范围归一化放到0和1之间 def cosSim(inA,inB): num=float(inA.T*inB) denom=la.norm(inA)*la.norm(inB) return 0.5+0.5*(num/denom) #将相似度归一到0与1之间 '''按照前k个奇异值的平方和占总奇异值的平方和的百分比percentage来确定k的值, 后续计算SVD时需要将原始矩阵转换到k维空''' def sigmaPct(sigma,percentage): sigma2=sigma**2 #对sigma求平方 sumsgm2=sum(sigma2) #求所有奇异值sigma的平方和 sumsgm3=0 #sumsgm3是前k个奇异值的平方和 k=0 for i in sigma: sumsgm3+=i**2 k+=1 if sumsgm3>=sumsgm2*percentage: return k '''函数svdEst()的参数包含:数据矩阵、用户编号、物品编号和奇异值占比的阈值, 数据矩阵的行对应用户,列对应物品,函数的作用是基于item的相似性对用户未评过分的物品进行预测评分''' def svdEst(dataMat,user,simMeas,item,percentage): n=shape(dataMat)[1] simTotal=0.0;ratSimTotal=0.0 u,sigma,vt=la.svd(dataMat) k=sigmaPct(sigma,percentage) #确定了k的值 sigmaK=mat(eye(k)*sigma[:k]) #构建对角矩阵 xformedItems=dataMat.T*u[:,:k]*sigmaK.I #根据k的值将原始数据转换到k维空间(低维),xformedItems表示物品(item)在k维空间转换后的值 for j in range(n): userRating=dataMat[user,j] if userRating==0 or j==item:continue similarity=simMeas(xformedItems[item,:].T,xformedItems[j,:].T) #计算物品item与物品j之间的相似度 simTotal+=similarity #对所有相似度求和 ratSimTotal+=similarity*userRating #用"物品item和物品j的相似度"乘以"用户对物品j的评分",并求和 if simTotal==0:return 0 else:return ratSimTotal/simTotal #得到对物品item的预测评分 '''函数recommend()产生预测评分最高的N个推荐结果,默认返回5个; 参数包括:数据矩阵、用户编号、相似度衡量的方法、预测评分的方法、以及奇异值占比的阈值; 数据矩阵的行对应用户,列对应物品,函数的作用是基于item的相似性对用户未评过分的物品进行预测评分; 相似度衡量的方法默认用余弦相似度''' def recommend(dataMat,user,simMeas=cosSim,estMethod=svdEst,percentage=0.9): unratedItems=nonzero(dataMat[user,:].A==0)[1] #建立一个用户未评分item的列表 if len(unratedItems)==0:return 'you rated everything' #如果都已经评过分,则退出 itemScores=[] for item in unratedItems: #对于每个未评分的item,都计算其预测评分 estimatedScore=estMethod(dataMat,user,simMeas,item,percentage) itemScores.append((item,estimatedScore)) return itemScores #itemScores=sorted(itemScores,key=lambda x:x[1],reverse=True)#按照item的得分进行从大到小排序 #return itemScores[:N] #返回前N大评分值的item名,及其预测评分值 def gene(original,data): app = [] for i in range (0, len (original)): n = 0 if original[i] == 0: app.insert (i, data[n][1]) #print(data[n][1]) n+=1 else: app.insert (i, 0) #print(app) return app '''用户-标签(类型)返回潜在因子矩阵,0分为已评分过的矩阵''' def userGet(): geneData = [] # 用户-标签评分值表数据,第1个为列表,第2个为矩阵 userdata,ndata, data, matdata = loadExData () if matdata.shape[0]>4: for i in range(0,matdata.shape[0]): # 第一个参数:原始数据,第2个参数:第N个用户,第3个参数:奇异值占比的阈值 get = gene(data[i],recommend(matdata,i,percentage = 0.8)) geneData.append(get) print(get) #print(recommend(matdata,i,percentage = 0.8)) #return userdata,ndata,geneData #print(geneData) #userGet()<file_sep>#-*- coding: utf-8 -* __author__ = 'Howie' import tornado.web class ErrorHandler(tornado.web.RequestHandler): def write_error(self, status_code, **kwargs): self.write("错误状态码{0}.\n".format( status_code))<file_sep># -*-coding:utf-8-*- __author__ = 'howie' import tornado.web import tornado.escape import hashlib from methods.pDb import newsDb from config.n_conf import admin from handlers.base import BaseHandler class ChangePass(BaseHandler): @tornado.web.authenticated def get(self, *args, **kwargs): password = self.get_argument("pass") password = str(hashlib.md5((admin["TOKEN"] + password).encode("utf-8")).hexdigest()) sql = "update n_admin set pass='" + password + "' where name = 'admin'" # 执行SQL语句 mSql = newsDb() if mSql.exeSql(sql): self.write("密码修改成功") else: self.write("密码修改失败") <file_sep># -*-coding:utf-8-*- __author__ = 'Jeezy' '''通过geneNewsType和geneUserType计算出最终的用户-新闻矩阵,即推荐新闻表''' # from geneNewsType import NewsTagDataTool # from geneUserType import UserTagDataTool from system.latentFactor.geneNewsType import NewsTagDataTool from system.latentFactor.geneUserType import UserTagDataTool from methods.pDb import newsDb import traceback class GeneCulcal: def __init__(self): # 新闻-标签 矩阵 self.newsType = [] # 用户-标签 矩阵 self.userType = [] # 用户-新闻 矩阵 self.userNews = [] #新闻id集合 self.new_id_list = [] #用户id集合 self.user_id_list = [] #新闻id和类别的映射字典 self.news_type_dict = None #获取各矩阵的各操作类 self.ntTool = NewsTagDataTool() self.utTool = UserTagDataTool() # 每一个矩阵,及对应id集合的获取和计算 def getMatData(self): try: self.news_type_dict,self.new_id_list,self.newsType = self.ntTool.getData() self.user_id_list,self.userType = self.utTool.getData() self.finalCalcul() self.saveToDb() except Exception as e: exstr = traceback.format_exc() print(exstr) def finalCalcul(self): try: for i in range(0, len(self.userType)): append = [] for j in range(0, len(self.newsType)): sum = 0 for n in range(0, len(self.newsType[j])): sum = sum + self.newsType[j][n] * self.userType[i][n] append.insert(j, sum) self.userNews.append(append) except Exception as e: exstr = traceback.format_exc() print(exstr) # print(self.userNews) def saveToDb(self): user_id_score_dict = {} #use the user_id_list to initalize the user_id_score_dict for user_id in self.user_id_list: user_id_score_dict[user_id] = None db = newsDb() data = db.select_table_two(table="news_recommend", column = "*") for d in data: if d[1] == None: user_id_score_dict[d[0]] = None #美元符号代表两次计算结果的拼接,如果发现美元符号,则取最后一次拼接,即最后一次计算结果 elif d[1].find('$')!=-1: arr = d[1].split('$') user_id_score_dict[d[0]] = arr[len(arr)-1] else: user_id_score_dict[d[0]] = d[1] #行:用户id 列:新闻id for i in range(len(self.user_id_list)): list = [] tmp_news_tag_deep = {} for j in range(len(self.new_id_list)): tmp_news_tag_deep[self.new_id_list[j]] = self.userNews[i][j] sorted_news_tag_deep = sorted(tmp_news_tag_deep.items(),key=lambda d:d[1],reverse=True) for d in sorted_news_tag_deep: if self.news_type_dict.get(d[0],None)!=None: list.append(d[0]+ "+" + self.news_type_dict[d[0]] + "+" + str(d[1])) tmpstr = '#'.join(list) print(tmpstr) #if the table named news_recommend has not the id of this user,we should insert the data. if user_id_score_dict[self.user_id_list[i]] == None: db.insert_table(table = "news_recommend", field = "", values = "('" + self.user_id_list[i] + "','" + tmpstr + "')") else: updateStr = user_id_score_dict[self.user_id_list[i]] + "$" + tmpstr # 更新数据表news_recommend db.update_column(table= "news_recommend", column = "news_score", value_set = updateStr, condition = "user_id", value_find =self.user_id_list [i] ) #print(str(i)) # gc = GeneCulcal() # gc.getMatData() # 14715714711<file_sep># -*-coding:utf-8-*- from methods.pDb import newsDb class NewsTagDataTool(object): def __init__(self): #存新闻编号 self.new_id_list = [] self.newsTagMat = [] #存取新闻id对应的类别 self.news_type_dict = {} def getData(self): try: db = newsDb() data = db.select_table_two(table="news_tag_deep",column="*") for item in data: #获得新闻id self.new_id_list.append(item[0]) #当前新闻标签比例因子集合,标签名称顺序按数据表设计来 tagsWeight = [] for tag in item[1:len(item)]: tagsWeight.append(tag) self.newsTagMat.append(tagsWeight) datasql = "select news_id,tag from get_news where is_old = 0" data = db.select_table_three(datasql) # print(data) for item in data: #获取新闻的id及对应的类别: self.news_type_dict[item[0]] = item[1] #print(self.news_type_dict) # print(self.new_id_list) # print(self.newsTagMat) return self.news_type_dict,self.new_id_list,self.newsTagMat except Exception as e: print(e) # ntTool = NewsTagDataTool() # x,y,z=ntTool.getData() # print(x) # print(y) # <file_sep># -*-coding:utf-8-*- __author__ = 'howie,jeezy' import tornado.web import hashlib import json import datetime,time import random from config.n_conf import admin from methods.pDb import newsDb from system.classPredict.main import startPredict from system.latentFactor.geneCalcul import GeneCulcal import os from system.pointsAlo.scoreSetting import ScoreTool class Confirm(tornado.web.RequestHandler): # time=1 tooken=<PASSWORD> def tooken(self, time): tooken = "api<PASSWORD>" tooken = hashlib.md5((tooken + str(time)).encode("utf-8")).hexdigest() return tooken def write_error(self, status_code, **kwargs): self.write("错误状态码{0}.\n".format( status_code)) def errorRequest(self, num): data = {"flag": num} result = {"message": "failed", "data": data} result = json.dumps(result) self.write(result) def set_default_headers(self): self.set_header ('Access-Control-Allow-Origin', '*') self.set_header ('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') self.set_header ('Access-Control-Max-Age', 1000) self.set_header ('Access-Control-Allow-Headers', '*') class Register(Confirm): # 注册 def get(self, *args, **kwargs): all = self.request.arguments name = self.get_argument('name') passwd = self.get_argument('passwd') phone = self.get_argument('phone') tags = self.get_argument('tags') getTooken = self.get_argument('tooken') time = self.get_argument('time') tooken = self.tooken(time=time) if getTooken == tooken and len(all) == 6: passwd = hashlib.md5((admin["TOKEN"] + passwd).encode("utf-8")).hexdigest() db = newsDb() is_register = db.select_table(table = "user", column = "*", condition = "phone", value = phone) if is_register: # 用户已存在 self.errorRequest(num=-1) else: try: num = db.select_table_two(table = "user", column = "count(*)") user_id = ("%06d" % (num[0][0] + 1)) insertSql = db.insert_table(table="user", field="(user_id,phone,name,passwd,time)", values="('" + str( user_id) + "','" + phone + "','" + name + "','" + passwd + "',now())") user_messSql = db.insert_table(table="user_mess", field="(user_id)", values="('" + str(user_id) + "')") loveTageSql = db.insert_table (table="user_love_tag", field="(user_id,tags)", values="('" + str (user_id) + "','" + tags + "')") user_mess = db.select_table(table = "user", column = "user_id", condition = "phone", value = phone) #********** 分数 *************************************************************************************** db.insert_table(table = "user_tag_score",field="",values="('" + user_id + "',1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)") print("start") #gc = GeneCulcal() #gc.getMatData() print("end") print(user_mess[0][0]) if insertSql and user_messSql and loveTageSql: data = {"user_id": user_mess[0][0]} result = {"message": "success", "data": data} result = json.dumps(result) self.write(result) except: # 出现错误则回滚 print("404") else: self.errorRequest(num=0) class Login(Confirm): # 登录 def get(self, *args, **kwargs): all = self.request.arguments passwd = self.get_argument('passwd') phone = self.get_argument('phone') getTooken = self.get_argument('tooken') time = self.get_argument('time') tooken = self.tooken(time=time) if getTooken == tooken and len(all) == 4: db = newsDb () passwd = hashlib.md5((admin["TOKEN"] + passwd).encode("utf-8")).hexdigest() information = db.select_table(table = "user", column = "*", condition = "phone", value = phone) try: user_mess = db.select_table(table="user", column="user_id", condition="phone", value=phone) if information: if information[0][3] == passwd: # 登录成功 data = {"user_id": user_mess[0][0]} result = {"message": "success", "data": data} result = json.dumps(result) self.write(result) else: # 密码错误 self.errorRequest(num=-1) else: # 用户不存在 self.errorRequest(num=-2) except: # 出现错误则回滚 print("404") else: self.errorRequest(num=0) class NewsTags(Confirm): # 新闻列表请求 def get(self, *args, **kwargs): all = self.request.arguments count = self.get_argument('count') alrequest = self.get_argument('alrequest') user_id = self.get_argument('userid') tag = self.get_argument('tag') getTooken = self.get_argument('tooken') time = self.get_argument('time') tooken = self.tooken(time=time) data = [] if (getTooken == tooken and len(all) == 6) or (getTooken == tooken and len(all) == 7) : db = newsDb() # 通过用户id在推荐表中寻找要推荐的新闻id information = db.select_table(table = "news_recommend", column = "*", condition = "user_id", value =user_id ) try: if user_id !="" and user_id !=" ": if information: # 得到该用户的推荐新闻 if information[0][1].count("$"): allNews = information [0] [1].split ('$') amalen = information[0][1].count("$") news = allNews[amalen].split ('#') else: news = information [0] [1].split ('#') lenght = len (news) news_id = '' if int (alrequest) + int (count) > len (news): # 请求大于有效值 self.errorRequest (num=-1) else: if tag == '': suiji = {random.randint (int(alrequest), int(alrequest) + int(count)) for _ in range (int (count))} for i in range(int(alrequest), int(alrequest) + int(count)): news_id = news[i].split('+')[0] data.append(self.dataNews(news_id)) else: id_list = db.select_table_three("select news_id from get_news where tag = '"+tag+"' order by news_id") if len(id_list) < int(alrequest) + int(count): suiji = {random.randint (int(alrequest), len(id_list)) for _ in range ((len(id_list)-int(alrequest)))} for j in range(int(alrequest), len(id_list)): # print(self.dataNews (id_list[j][0])) data.append(self.dataNews(id_list[j][0])) else: suiji = {random.randint (int(alrequest), int(alrequest) + int(count)) for _ in range (int(count))} for j in range(int(alrequest), int(alrequest) + int(count)): # print(self.dataNews (id_list[j][0])) data.append(self.dataNews(id_list[j][0])) else: #刚注册用户 love_tags = db.select_table_three("select tags from user_love_tag where user_id = '"+user_id+"'") re_news = [] eng_tags = ('news_society','news_entertainment','news_tech','news_car','news_sports','news_finance','news_military','news_world','news_fashion','news_travel','news_discovery','news_baby','news_regimen','news_story','news_essay','news_game','news_history','news_food') chi_tags = ('社会','娱乐','科技','汽车','体育','财经','军事','国际','时尚','旅游','探索','育儿','养生','故事','美文','游戏','历史','美食') select_tag = '' if tag=='': for retag in love_tags[0]: if retag.count(","): tag_list=retag.split(',') for ta in tag_list: for i in range(0,len(eng_tags)): if chi_tags[i] == ta: select_tag = eng_tags[i] each_news = db.select_table_three("select news_id from get_news where tag = '"+select_tag+"'") if len(each_news) >=20: for d in range(0,20): re_news.append(each_news[d][0]) else: for d in range(0,len(each_news)): re_news.append(each_news[d][0]) else: for i in range(0, len(eng_tags)): if chi_tags[i] == love_tags[0][0]: select_tag = eng_tags[i] each_news = db.select_table_three("select news_id from get_news where tag = '" + select_tag + "'") if len(each_news) >= 20: for d in range(0, 20): re_news.append(each_news[d][0]) else: for d in range(0, len(each_news)): re_news.append(each_news[d][0]) if len(re_news) >=int (count): suiji = {random.randint(0,len(re_news)-1) for _ in range(int (count))} else: suiji = {random.randint (0, len (re_news) - 1) for _ in range (len (re_news) - 1)} for n in suiji: data.append(self.dataNews(re_news[n])) else: id_list = db.select_table (table="get_news", column="news_id", condition="tag", value=tag) if len (id_list) < int (alrequest) + int (count): for j in range (int (alrequest), len (id_list)): # print(self.dataNews (id_list[j][0])) data.append (self.dataNews (id_list [j] [0])) else: for j in range (int (alrequest), int (alrequest) + int (count)): # print(self.dataNews (id_list[j][0])) data.append (self.dataNews (id_list [j] [0])) else: if tag: id_list = db.select_table(table="get_news",column="news_id",condition="tag",value=tag) else: id_list = db.select_table_two(table="get_news",column="news_id") if len(id_list) < int (alrequest) + int (count): for j in range (int (alrequest),len(id_list)): # print(self.dataNews (id_list[j][0])) data.append (self.dataNews (id_list [j] [0])) else: for j in range(int (alrequest),int (alrequest)+int(count)): #print(self.dataNews (id_list[j][0])) data.append (self.dataNews (id_list[j][0])) result = {"message": "success", "data": data} result = json.dumps(result) #print(data[0]) self.write(result) except: # 出现错误则回滚 print("404") else: self.errorRequest(num=0) def dataNews(self,news_id): db = newsDb () read_times = 0 love_times = 0 comment_times = 0 image = "" news_content = db.select_table (table="get_news", column="news_id,title,time,source,image,abstract", condition="news_id ",value=news_id) opData = db.select_table (table="news_mess", column="read_times,love_times,comment_times", condition="news_id ",value=news_id) localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) startTime = (str(localtime).split(' '))[0] each = startTime.split('-') timeTwo = int(each[2]) if timeTwo > 10: times = each[0] + "-" + each[1] + "-" + str(timeTwo) else: times = each[0] + "-" + each[1] + "-" + "0" + str(timeTwo) oldTimeList = str(news_content[0][2]).split(' ') oldTimeDate = oldTimeList[0].split('-') d1 = datetime.datetime(int(oldTimeDate[0]), int(oldTimeDate[1]), int(oldTimeDate[2])) d2 = datetime.datetime(int(each[0]), int(each[1]), int(each[2])) cdate = (d2 - d1).days if cdate == 0: oldHours = oldTimeList[1].split(':')[0] eachHours = (str(localtime).split(' '))[1].split(':')[0] chineseTime = str(int(eachHours)-int(oldHours)) + "小时前" elif cdate == 1: chineseTime = "昨天" elif cdate == 2: chineseTime = "前天" else: chineseTime = str((d2 - d1).days) + "天前" #chineseTime = str(int(((d2 - d1).seconds) / 3600)) + "小时前" if opData: read_times = opData[0][0] love_times = opData[0][1] comment_times = opData[0][2] if news_content [0][4].count("http://") > 1: for i in range(0,len(news_content [0][4].split(","))): if (news_content [0][4].split(","))[i].count("icon")<1: image = (news_content [0][4].split(","))[i] break #print(image) else: if news_content [0][4].count("icon")<1: image = news_content [0][4] data={"news_id": news_content [0][0], "title": news_content [0][1], "time": chineseTime, "source": news_content [0] [3], "image": image, "abstract": news_content [0] [5], "read_times": read_times, "love_times": love_times, "comment_times": comment_times} #print(data) return data class NewsContent(Confirm): # 返回新闻内容 def get(self, *args, **kwargs): all = self.request.arguments news_id = self.get_argument('newsid') user_id = self.get_argument('userid') getTooken = self.get_argument('tooken') time = self.get_argument('time') tooken = self.tooken(time=time) message = [] relate_list = [] is_love = 0 time = '' uname = '' head_url = '' is_comment = '' comment_content = '' if getTooken == tooken and len(all) == 4: db = newsDb() news = db.select_table(table="get_news",column="html_content,news_link",condition="news_id",value=news_id) messageall = db.select_table(table="news_comment",column="*",condition="news_id",value=news_id) relate = db.select_table_three("select tag from get_news where news_id = '"+news_id+"'") tag = relate[0][0] all_relate = db.select_table_three("select news_id,title from get_news where tag ='"+tag+"'") ar = random.sample(all_relate,3) for i in range(0,len(ar)): relate_list.append({"news_id":ar[i][0],"news_title":ar[i][1]}) print(relate_list) try: news_content = news[0][0] news_url = news[0][1] #print(messageall[0][1]) if user_id: userBehavior = db.select_table (table="user_behavior", column="is_comment,behavior_type", condition="user_id", value=user_id + "' and news_id = '" + news_id) if userBehavior: if userBehavior[0][0]: is_comment = userBehavior [0] [0] else: is_comment = 0 if userBehavior[0][1] == 1: is_love = 1 else: is_love = 0 # {##}每条新闻详情 if messageall: if messageall[0][1]: allComment= messageall[0][1].split("{##}") for i in range(0,len(allComment)-1): me = allComment[i].split("{++}") times = str(me[2]) comment_content = me[1] # 通过用户编号查询用户评论的昵称和头像 com_username = db.select_table(table="user,user_mess",column="user.name,user_mess.image",condition="user.user_id", value=me[0] + "' and user_mess.user_id = '" + me[0]) if com_username[0][1]: head_url = com_username[0][1] else: head_url = "" uname = com_username[0][0] message.append({"head_url": head_url,"user_id":me[0], "username": uname, "comment_time": times,"comment_content":comment_content,"dianzan_num":me[3]}) data = {"news_id":news_id,"content":news_content ,"news_url":news_url, "is_comment": is_comment, "is_love": is_love, "comment_list": message,"relate_list":relate_list} print("data success!") result = {"message": "success", "data": data} result = json.dumps(result) self.write(result) #****阅读相关数据库更新 if user_id: timescore = db.select_table(table = "user_behavior", column = "times,score", condition = "news_id", value = news_id + "' and user_id = '" + user_id) #print("haha") #print(timescore) tag = db.select_table (table="get_news", column="tag", condition="news_id", value=news_id) if timescore: #mSql.update_column(table = "user_behavior",column = "times",value_set = times, condition = "user_id",value_find = user_id + "' and news_id = '" +news_id) db.exeSql("update user_behavior set times= times + 1 where user_id= '"+user_id+"' and news_id ='" +news_id+ "'") else: db.insert_table(table = "user_behavior", field = "(user_id,news_id,news_tag,times)", values = "('" +user_id+ "','" +news_id+ "','" +tag[0][0]+ "',1)") #设置老新闻 db.exeSql ("update get_news set is_old= 1 where news_id= '" + news_id + "'") # 设置新闻基本信息表阅读次数 read_times = db.select_table(table = "news_mess", column = "read_times", condition = "news_id", value = news_id) if read_times: db.exeSql ("update news_mess set read_times= read_times + 1 where news_id= '" + news_id + "'") else: tag = db.select_table(table="get_news", column="tag", condition="news_id", value=news_id) db.insert_table (table="news_mess", field="(news_id,tag,read_times)", values="('" +news_id + "','" + tag [0] [0] + "',1)") #************************用户标签因子历史分数**************************** all_tags = ('news_society','news_entertainment','news_tech','news_car','news_sports','news_finance','news_military','news_world','news_fashion','news_travel','news_discovery','news_baby','news_regimen','news_story','news_essay','news_game','news_history','news_food') tag = db.select_table(table="get_news", column="tag", condition="news_id", value=news_id) if_news_deep = db.select_table(table="news_tag_deep", column="*", condition="news_id", value=news_id) upda_sql = " " if if_news_deep: for i in range(0,len(all_tags)): if upda_sql==" ": upda_sql = upda_sql + all_tags[i] + " = " + all_tags[i] + " + " + str(if_news_deep[0][i+1]) else: upda_sql = upda_sql + "," + all_tags [i] + " = " + all_tags [i] + " + " + str(if_news_deep [0] [i+1]) if_tag_deep = db.select_table_three("select * from user_tag_score where user_id='"+ user_id+"'") if if_tag_deep: jiafen = db.exeSql("update user_tag_score set "+upda_sql+" where user_id ='"+user_id+"'") else: in_sql = "'" + user_id + "'" num = len (all_tags)+1 for i in range (0, len (all_tags)): in_sql = in_sql + "," + str(if_news_deep[0][i+1]) jiafen = db.exeSql("insert into user_tag_score values("+in_sql+")") if jiafen: print("阅读加分成功!") except: # 出现错误则回滚 print("404") else: self.errorRequest(num=0) class UserInfo(Confirm): # 查询返回用户信息 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument('userid') getTooken = self.get_argument('tooken') time = self.get_argument('time') tooken = self.tooken(time=time) if getTooken == tooken and len(all) == 3: db = newsDb() userSql = "select name,phone from user where user_id = '" + user_id + "'" userInfoSql = "select * from user_mess where user_id = '" + user_id + "'" love_timesSql = "select * from user_operate where user_id = '" + user_id + "'" readSql = "select times,is_comment from user_behavior where user_id = '" + user_id + "'" try: # 提交到数据库执行,得到用户电话 user = db.select_table_three(userSql) # 提交到数据库执行,得到用户详情 userInfo = db.select_table_three(userInfoSql) # 查询用户行为 love = db.select_table_three(love_timesSql) # 查询阅读 allRead = db.select_table_three(readSql) read_times = 0 message_times = 0 if allRead: for each in allRead: if each[0]: read_times = read_times + each [0] if each [1] == 1: message_times = message_times + 1 if userInfo [0] [3]: email = userInfo [0] [3] else: email="" data = {"user_name": user [0] [0], "phone": user [0] [1], "email": email, "image": userInfo [0] [5], "read_times": read_times, "love_times": len (love), "message_times": message_times} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class UserInfoChange(Confirm): # 用户更改个人信息 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') user_name = self.get_argument('username') image = self.get_argument('image') email = self.get_argument('email') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) if getTooken == tooken and len (all) == 6: db = newsDb() try: db.update_column(table = "user",column = "name",value_set = user_name, condition = "user_id",value_find = user_id) db.update_column (table="user_mess", column="email", value_set=email, condition="user_id",value_find=user_id) db.update_column (table="user_mess", column="image", value_set=image, condition="user_id",value_find=user_id) data=self.select(user_id) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) def select(self,user_id): db = newsDb() # 提交到数据库执行,得到用户电话 user = db.select_table(table="user",column="name,phone",condition="user_id",value=user_id) # 提交到数据库执行,得到用户详情 userInfo = db.select_table(table="user_mess",column="*",condition="user_id",value=user_id) # 查询用户行为 love = db.select_table(table="user_operate",column="*",condition="user_id",value=user_id) # 查询阅读 allRead = db.select_table(table="user_behavior",column="times,is_comment",condition="user_id",value=user_id) read_times = 0 message_times = 0 for each in allRead: read_times = each [0] if each [1] == 1: message_times = message_times + 1 data = {"user_name": user [0] [0], "phone": user [0] [1], "email": userInfo [0] [3], "image": userInfo [0] [5], "read_times": read_times, "love_times": len (love), "message_times": message_times} return data class LoveNews(Confirm): # 喜欢功能 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') is_love = self.get_argument('islove') news_id = self.get_argument('newsid') getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) if (getTooken == tooken and len (all) == 5) or (getTooken == tooken and len (all) == 6): db = newsDb() localtime = time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime ()) try: behavior_type = db.select_table(table = "user_behavior", column = "behavior_type", condition = "news_id", value = news_id + "' and user_id = '" +user_id) if behavior_type[0][0] == 1 and is_love == '1': self.errorRequest (num=-1) else: #用户喜欢 success = False if is_love == '1': tag = db.select_table(table = "get_news", column = "tag", condition = "news_id", value = news_id) love_times = db.select_table(table = "news_mess", column = "love_times", condition = "news_id", value = news_id) love_times = love_times[0][0] +1 tag_point = db.select_table(table = "user_tag_score", column = tag[0][0], condition = "user_id", value = user_id) #*****************用户行为表的更新****************************** timescore = db.select_table (table="user_behavior", column="times,score", condition="news_id", value=news_id + "' and user_id = '" + user_id) if timescore: # ******************************新闻分数****************************** update_love = db.update_column (table="user_behavior", column="behavior_type", value_set='1', condition="news_id ", value_find=news_id + "' and user_id = '" + user_id) else: # ******************************新闻分数****************************** db.insert_table (table="user_behavior", field="(user_id,news_id,news_tag,score,times)", values="('" + user_id + "','" + news_id + "','" + tag [0] [0] + "',3,1)") #查询user _behavior表是否有该用户和新闻 is_operate = db.select_table(table = "user_operate", column = "*", condition = "news_id ", value = news_id + "' and user_id = '" +user_id) #更新用户操作表 if is_operate: operate_islove = db.update_column (table ="user_operate" , column = "is_love",value_set = '1',condition = "news_id ", value_find = news_id + "' and user_id = '" +user_id ) operate_time = db.update_column (table="user_operate", column="time", value_set=localtime,condition="news_id ",value_find=news_id + "' and user_id = '" + user_id) else: insert_operate = db.insert_table(table = "user_operate", field = "(user_id,news_id,is_love,time)", values = "('" +user_id+ "','" +news_id+ "','1','" +localtime+ "')") #更新新闻基本信息表 update_mess = db.update_column (table ="news_mess" , column = "love_times",value_set = str(love_times),condition = "news_id ", value_find = news_id ) #********************更新用户标签因子分数(历史分数)****************************** all_tags = ( 'news_society', 'news_entertainment', 'news_tech', 'news_car', 'news_sports', 'news_finance', 'news_military', 'news_world', 'news_fashion', 'news_travel', 'news_discovery', 'news_baby', 'news_regimen', 'news_story', 'news_essay', 'news_game', 'news_history', 'news_food') tag = db.select_table (table="get_news", column="tag", condition="news_id", value=news_id) if_news_deep = db.select_table (table="news_tag_deep", column="*", condition="news_id", value=news_id) upda_sql = " " if if_news_deep: for i in range (0, len (all_tags)): if upda_sql == " ": upda_sql = upda_sql + all_tags [i] + " = " + all_tags [i] + " + " + str ( if_news_deep [0] [i + 1]*3) else: upda_sql = upda_sql + "," + all_tags [i] + " = " + all_tags [i] + " + " + str ( if_news_deep [0] [i + 1]*3) if_tag_deep = db.select_table_three ( "select * from user_tag_score where user_id='" + user_id + "'") if if_tag_deep: jiafen = db.exeSql ( "update user_tag_score set " + upda_sql + " where user_id ='" + user_id + "'") else: in_sql = "'" + user_id + "'" num = len (all_tags) + 1 for i in range (0, len (all_tags)): in_sql = in_sql + "," + str (if_news_deep [0] [i + 1]*3) jiafen = db.exeSql ("insert into user_tag_score values(" + in_sql + ")") if jiafen: print ("喜欢加分成功!") success = 1 #****************************用户取消喜欢************************************************************* elif is_love == '0': all_tags = ( 'news_society', 'news_entertainment', 'news_tech', 'news_car', 'news_sports', 'news_finance', 'news_military', 'news_world', 'news_fashion', 'news_travel', 'news_discovery', 'news_baby', 'news_regimen', 'news_story', 'news_essay', 'news_game', 'news_history', 'news_food') tag = db.select_table (table="get_news", column="tag", condition="news_id", value=news_id) if_news_deep = db.select_table (table="news_tag_deep", column="*", condition="news_id", value=news_id) upda_sql = " " if if_news_deep: for i in range (0, len (all_tags)): if upda_sql == " ": upda_sql = upda_sql + all_tags [i] + " = " + all_tags [i] + " - " + str ( if_news_deep [0] [i + 1] * 3) else: upda_sql = upda_sql + "," + all_tags [i] + " = " + all_tags [i] + " - " + str ( if_news_deep [0] [i + 1] * 3) if_tag_deep = db.select_table_three ( "select * from user_tag_score where user_id='" + user_id + "'") jiafen = db.exeSql ( "update user_tag_score set " + upda_sql + " where user_id ='" + user_id + "'") if jiafen: print ("取消喜欢减分成功!") db.update_column(table="user_behavior", column="behavior_type", value_set='0', condition="news_id ", value_find=news_id + "' and user_id = '" + user_id) tag = db.select_table (table="get_news", column="tag", condition="news_id", value=news_id) love_times = db.select_table (table="news_mess", column="love_times", condition="news_id", value=news_id) print(love_times) love_time = love_times [0] [0] + 1 print(love_time) tag_point = db.select_table (table="user_tag_score", column=tag [0] [0], condition="user_id", value=user_id) # 更新用户操作表 operate_islove = db.update_column (table="user_operate", column="is_love", value_set='0', condition="news_id ",value_find=news_id + "' and user_id = '" + user_id) operate_time = db.update_column (table="user_operate", column="time", value_set="", condition="news_id ", value_find=news_id + "' and user_id = '" + user_id) print("ga") # 更新新闻基本信息表 upNews_mess = "update news_mess set love_times = love_times - 1 where news_id = '" + news_id + "'" db.exeSql(upNews_mess) # ********************更新用户标签因子分数(历史分数)****************************** #user_tag_points = mSql.update_column (table ="user_tag_score" , column = tag[0][0],value_set = tag[0][0] +" - 1",condition = "user_id ", value_find = user_id ) success = 2 else: self.errorRequest (num=0) success = 0 if success: data = {"flag": success} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class LoveList(Confirm): # 查询返回用户历史喜欢新闻列表 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) if getTooken == tooken and len (all) == 3: #print("ha") localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) startTime = (str(localtime).split(' '))[0] each = startTime.split('-') timeTwo = int(each[2]) if timeTwo > 10: times = each [0] + "-" + each [1] + "-" + str (timeTwo) else: times = each[0] + "-" + each[1] + "-" + "0" + str(timeTwo) try: db = newsDb() love_listSql = "select news_id,time from user_operate where is_love = 1 " \ "and TIMESTAMPDIFF(DAY,time,'" +times+ "') < 60 and user_id = '" +user_id+ "' order by time desc" # 提交到数据库执行 love_list = db.select_table_three(love_listSql) data = [] for item in love_list: getNews = db.select_table(table = "get_news", column = "title,abstract,time", condition = "news_id", value = item[0]) each_get_news = getNews[0] oldTimeList = str (each_get_news [2]).split(' ') oldTimeDate = oldTimeList[0].split('-') d1 = datetime.datetime (int(oldTimeDate[0]), int(oldTimeDate[1]), int(oldTimeDate[2])) d2 = datetime.datetime (int(each[0]), int(each[1]), int(each[2])) cdate = (d2-d1).days if cdate == 0: chineseTime = "今天" elif cdate == 1 : chineseTime = "今天" elif cdate == 2 : chineseTime = "昨天" elif cdate == 2: chineseTime = "前天" else: chineseTime = oldTimeDate[1] + "."+ oldTimeDate[2] news_mess = db.select_table(table = "news_mess", column = "*", condition = "news_id", value = item[0]) image = db.select_table(table = "get_news", column = "image", condition = "news_id", value = item[0]) tag = db.select_table(table = "news_tag_chinese", column = news_mess[0][1], condition = "'1'", value = "1") #print(image) if image[0][0]: if image[0][0].count("http://") >1: images = (image[0][0].split(","))[0] #print(image) else: images = image[0][0] else: images = '' #print("haha") if news_mess: data.append({"news_id":news_mess[0][0],"tag":tag[0][0],"image":images,"read_times":news_mess[0][2],"love_times":news_mess[0][3], "comment_times":news_mess[0][4],"title":each_get_news[0],"abstract":each_get_news[1],"time":chineseTime}) print(data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class HotList(Confirm): # 查询返回热点新闻 def get(self, *args, **kwargs): all = self.request.arguments hot_type = self.get_argument ('hot') count = self.get_argument('count') alrequest = self.get_argument('alrequest') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) if getTooken == tooken and len (all) == 5: db = newsDb() sqlcount = db.select_table(table = "news_hot", column = "news_id", condition = "'1'", value = "1") if int (alrequest) == len (sqlcount): self.errorRequest (num=-1) else: if int (alrequest) + int (count) > len(sqlcount): self.loveList (hot_type, str(len(sqlcount)-int(alrequest)), alrequest) else: self.loveList(hot_type,count,alrequest) else: self.errorRequest (num=0) def loveList(self,hot_type,count,alrequest): try: localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) startTime = (str(localtime).split(' '))[0] each = startTime.split('-') timeTwo = int(each[2]) if timeTwo > 10: start = each [0] + "-" + each [1] + "-" + str (timeTwo) else: start = each[0] + "-" + each[1] + "-" + "0" +str(timeTwo) if hot_type == "1": self.love(start,count,alrequest) elif hot_type =="2": self.read(start,count,alrequest) elif hot_type == "3": self.comment(start,count,alrequest) else: self.errorRequest (num=0) except: # 出现错误则回滚 print("404") def love(self,times,count,alrequest): db = newsDb() data = [] #print("love") try: #allLove = mSql.select_table(table = "hot", column = "news_id,tag,love_times,read_times,comment_times", condition = "1", value = "1 order by love_times desc") listSql = "select news_id,tag,image,love_times,read_times,comment_times,abstract," \ "source,title,time from news_hot where TIMESTAMPDIFF(DAY,time,'" +times+ "') < 2 order by love_times desc" #print(listSql) # 提交到数据库执行 allLove = db.select_table_three(listSql) for j in range (int (alrequest), int (alrequest) + int (count)): # print(self.dataNews (id_list[j][0])) love = allLove[j] tag = db.select_table (table="news_tag_chinese", column=love [1], condition="'1'", value="1") print(love[2]) if love[2]: if love[2].count ("http://") > 1: image = (love[2].split (",")) [0] # print(image) else: image = love[2] else: image = '' chinese = self.chinese_time(love[0]) print(chinese) data.append({"news_id":love[0],"tag":tag[0][0],"image":image,"love_times":love[3],"read_times":love[4],"comment_times":love[5],"abstract":love[6],"source":love[7],"title":love[8],"time":chinese}) print(data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: self.errorRequest (num=0) def read(self,time,count,alrequest): db = newsDb() data = [] #print("read") try: # allLove = mSql.select_table(table = "hot", column = "news_id,tag,love_times,read_times,comment_times", condition = "1", value = "1 order by love_times desc") listSql = "select news_id,tag,image,love_times,read_times,comment_times,abstract," \ "source,title from news_hot where TIMESTAMPDIFF(DAY,time,'" + time + "') < 2 order by read_times desc" # print(listSql) # 提交到数据库执行 allLove = db.select_table_three(listSql) for j in range (int (alrequest), int (alrequest) + int (count)): # print(self.dataNews (id_list[j][0])) love = allLove [j] tag = db.select_table(table = "news_tag_chinese", column = love [1], condition = "'1'", value = "1") if love [2]: if love [2].count ("http://") > 1: image = (love [2].split (",")) [0] # print(image) else: image = love [2] else: image = '' chinese = self.chinese_time(love[0]) data.append ({"news_id": love [0], "tag": tag [0][0],"image":image,"love_times":love[3],"read_times":love[4], "comment_times":love[5],"abstract":love[6],"source":love[7],"title":love[8],"time":chinese}) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: self.errorRequest (num=0) def comment(self,time,count,alrequest): db = newsDb() data = [] #print("commnet") try: # allLove = mSql.select_table(table = "hot", column = "news_id,tag,love_times,read_times,comment_times", condition = "1", value = "1 order by love_times desc") listSql = "select news_id,tag,image,love_times,read_times,comment_times,abstract," \ "source,title from news_hot where TIMESTAMPDIFF(DAY,time,'" + time + "') < 2 order by comment_times desc" # print(listSql) # 提交到数据库执行 allLove = db.select_table_three(listSql) for j in range (int (alrequest), int (alrequest) + int (count)): # print(self.dataNews (id_list[j][0])) love = allLove [j] tag = db.select_table (table="news_tag_chinese", column=love [1], condition="'1'", value="1") if love [2]: if love [2].count ("http://") > 1: image = (love [2].split (",")) [0] # print(image) else: image = love [2] else: image = '' chinese = self.chinese_time(love[0]) data.append ({"news_id": love [0], "tag": tag[0][0],"image":image,"love_times":love[3],"read_times":love[4],"comment_times":love[5],"abstract":love[6],"source":love[7],"title":love[8],"time":chinese}) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: self.errorRequest (num=0) def chinese_time(self,news_id): db = newsDb() sql = "select time from news_hot where news_id = '" +news_id+ "'" da = db.select_table_three(sql) localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) startTime = (str(localtime).split(' '))[0] each = startTime.split('-') oldTimeList = str(da[0][0]).split(' ') oldTimeDate = oldTimeList[0].split('-') d1 = datetime.datetime(int(oldTimeDate[0]), int(oldTimeDate[1]), int(oldTimeDate[2])) d2 = datetime.datetime(int(each[0]), int(each[1]), int(each[2])) cdate = (d2 - d1).days if cdate == 0: oldHours = oldTimeList[1].split(':')[0] eachHours = (str(localtime).split(' '))[1].split(':')[0] chineseTime = str(int(eachHours) - int(oldHours)) + "小时前" elif cdate == 1: chineseTime = "今天" elif cdate == 2: chineseTime = "昨天" elif cdate == 2: chineseTime = "前天" else: chineseTime = str((d2 - d1).days) + "天前" return chineseTime class FeedBack(Confirm): # 反馈 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') feedBack = self.get_argument ('feedback') getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) if getTooken == tooken and len (all) == 4: db = newsDb() times = time.time() print(str(times)) localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) try: db.insert_table(table = "news_feedback ", field = "(user_id,feedback,getTime)", values = "('" + user_id + "','" +feedBack+ "','"+ localtime +"')") data = {"flag": 1} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class KeyWord(Confirm): # 关键词搜索 def get(self, *args, **kwargs): all = self.request.arguments keyWord = self.get_argument ('keyword') getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) data = [] read_times = 0 love_times = 0 comment_times = 0 if getTooken == tooken and len (all) == 3: db = newsDb() try: keySql = "select news_id from get_news where title like '%" +keyWord+ "%'" # 提交到数据库执行 news_id_list = db.select_table_three(keySql) if len(news_id_list)>=20: counts = 20 else: counts = len(news_id_list) for m in range(0,counts): news_content = db.select_table (table="get_news", column="news_id,title,time,source,image,abstract", condition="news_id ", value=news_id_list[m][0]) opData = db.select_table (table="news_mess", column="read_times,love_times,comment_times", condition="news_id ", value=news_id_list[m][0]) if opData: read_times = opData [0] [0] love_times = opData [0] [1] comment_times = opData [0] [2] if news_content [0] [4].count ("http://") > 1: image = (news_content [0] [4].split (",")) [0] # print(image) else: image = news_content [0] [4] localtime = time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime ()) startTime = (str (localtime).split (' ')) [0] each = startTime.split ('-') oldTimeList = str (news_content[0][2]).split (' ') oldTimeDate = oldTimeList [0].split ('-') d1 = datetime.datetime (int (oldTimeDate [0]), int (oldTimeDate [1]), int (oldTimeDate [2])) d2 = datetime.datetime (int (each [0]), int (each [1]), int (each [2])) cdate = (d2 - d1).days if cdate == 0: oldHours = oldTimeList [1].split (':') [0] eachHours = (str (localtime).split (' ')) [1].split (':') [0] chineseTime = str (int (eachHours) - int (oldHours)) + "小时前" elif cdate == 1: chineseTime = "今天" elif cdate == 2: chineseTime = "昨天" elif cdate == 2: chineseTime = "前天" else: chineseTime = str ((d2 - d1).days) + "天前" data.append({"news_id": news_content [0][0], "title": news_content [0][1], "time": chineseTime, "source": news_content [0] [3],"image": image, "abstract": news_content [0] [5], "read_times": read_times, "love_times": love_times, "comment_times": comment_times}) #print(data) result = {"message": "success", "data": data} result = json.dumps (result) # print(data[0]) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class Comment(Confirm): # 评论 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') news_id = self.get_argument ('newsid') content = self.get_argument("content") getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) localtime = time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime ()) comment = user_id + "{++}" + content + "{++}" + localtime + "{++}" + '0' + "{##}" news_comment = news_id + "{++}" + content + "{++}" + localtime + "{##}" if (getTooken == tooken and len (all) == 5) or (getTooken == tooken and len (all) == 6): db = newsDb() try: tags = db.select_table(table = "get_news", column = "tag", condition = "news_id", value = news_id) tag = tags[0][0] is_comment = db.select_table(table = "news_comment", column = "comment", condition = "news_id", value = news_id) #print(is_comment) #如果该新闻已有评论 if is_comment: commentNew = is_comment[0][0] + comment db.update_column(table = "news_comment",column = "comment",value_set = commentNew, condition = "news_id",value_find = news_id) #如果还没有评论 else: comment = user_id + "{++}" + content + "{++}" + localtime + "{++}" +'0' + "{##}" db.insert_table(table = "news_comment", field = "(news_id,comment)", values = "('" + news_id + "','" + comment + "')") #****************************设置用户对应分数******************************************* upBehaviorSql = "update user_behavior set is_comment = 1,score = score + 2 " \ "where user_id = '" +user_id+ "' and news_id = '" +news_id+ "'" db.exeSql(upBehaviorSql) print ("评论成功,用户对此条新闻 分数 加1") #设置新闻基本信息表 upNews_mess = "update news_mess set comment_times = comment_times + 1 where news_id = '" + news_id + "'" db.exeSql(upNews_mess) print ("评论成功,用户对此条新闻 评论次数 加1") #设置用户操作表 is_comment = db.select_table(table = "user_operate", column = "comment", condition = "user_id", value = user_id +"' and news_id = '" +news_id) if is_comment: if is_comment[0][0]: db.update_column (table="user_operate", column="comment", value_set= is_comment[0][0] + news_comment, condition="user_id", value_find=user_id + "' and news_id = '" + news_id) else: print("ha") db.update_column(table = "user_operate",column = "comment",value_set = news_comment, condition = "user_id",value_find = user_id + "' and news_id = '" + news_id) else: db.insert_table(table = "user_operate", field = "(user_id,news_id,comment,is_love,time)", values = "('" +user_id+ "','" +news_id+ "','" +news_comment+ "',0,'" +localtime +"')") print("评论成功,用户操作表更新") #*******************用户标签因子分数表对应该标签历史分数*************************** all_tags = ( 'news_society', 'news_entertainment', 'news_tech', 'news_car', 'news_sports', 'news_finance', 'news_military', 'news_world', 'news_fashion', 'news_travel', 'news_discovery', 'news_baby', 'news_regimen', 'news_story', 'news_essay', 'news_game', 'news_history', 'news_food') tag = db.select_table (table="get_news", column="tag", condition="news_id", value=news_id) if_news_deep = db.select_table (table="news_tag_deep", column="*", condition="news_id", value=news_id) upda_sql = " " if if_news_deep: for i in range (0, len (all_tags)): if upda_sql == " ": upda_sql = upda_sql + all_tags [i] + " = " + all_tags [i] + " + " + str ( if_news_deep [0] [i + 1]*2) else: upda_sql = upda_sql + "," + all_tags [i] + " = " + all_tags [i] + " + " + str ( if_news_deep [0] [i + 1]*2) if_tag_deep = db.select_table_three ("select * from user_tag_score where user_id='" + user_id + "'") if if_tag_deep: jiafen = db.exeSql ( "update user_tag_score set " + upda_sql + " where user_id ='" + user_id + "'") else: in_sql = "'" + user_id + "'" num = len (all_tags) + 1 for i in range (0, len (all_tags)): in_sql = in_sql + "," + str (if_news_deep [0] [i + 1]*2) jiafen = db.exeSql ("insert into user_tag_score values(" + in_sql + ")") if jiafen: print ("评论加分成功!") #查询评论的用户的个人信息返回 image = db.select_table(table = "user_mess", column = "image", condition = "user_id", value = user_id) name = db.select_table (table="user", column="name", condition="user_id", value=user_id) data = {"user_id": user_id,"user_name":name[0][0],"user_image":image[0][0],"news_id":news_id, "content":content,"comment_time":localtime} #print(data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) print("success") except: # 出现错误则回滚 print('404') else: self.errorRequest (num=0) class LoveComment(Confirm): # 赞评论 def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') news_id = self.get_argument ('newsid') comment = self.get_argument("comment") comment_time = self.get_argument("commenttime") getTooken = self.get_argument ('tooken') retime = self.get_argument ('time') tooken = self.tooken (time=retime) #print(tooken) news_comment = '' new_love = '' if getTooken == tooken and len (all) == 6: db = newsDb() try: commentAllList = db.select_table(table = "news_comment", column = "*", condition = "news_id", value = news_id) commentAll = commentAllList[0][1].split("{##}") #print(commentAllList[0][1]) for i in range(0,len(commentAll)-1): each = commentAll[i].split("{++}") if comment_time == each [2] and comment == each [1] and user_id == each[0]: #print (each [3]) new_love = str(int (each [3])+ 1) break for n in range (0, len (commentAll) - 1): each = commentAll [n].split ("{++}") if comment_time == each [2] and comment == each [1] and user_id == each[0]: news_comment = news_comment + each[0] + "{++}" + each[1] + "{++}" + each[2] + "{++}" + new_love + "{##}" #continue else: news_comment = news_comment + commentAll[n] + "{##}" #continue db.update_column(table = "news_comment",column = "comment",value_set = news_comment, condition = "news_id",value_find = news_id) data = {"flag": 1} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print("404") else: self.errorRequest (num=0) class ExitRead(Confirm): def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('userid') news_id = self.get_argument ('newsid') time_diff = self.get_argument('timediff') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) if getTooken == tooken and len (all) == 5: db = newsDb() try: db.update_column(table = "user_behavior",column = "weight",value_set = time_diff, condition = "user_id",value_find = user_id +"' and news_id = '"+ news_id) data = {"flag": 1} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print ("404") else: self.errorRequest (num=0) class ReturnTags(Confirm): def get(self, *args, **kwargs): all = self.request.arguments getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) if getTooken == tooken and len (all) == 2: try: data = [{"key":"news_society","name":"社会"},{"key":"news_entertainment","name":"娱乐"},{"key":"news_tech","name":"科技"},{"key":"news_car","name":"汽车"},{"key":"news_sports","name":"体育"}, {"key":"news_finance","name":"财经"},{"key":"news_military","name":"军事"},{"key":"news_world","name":"国际"}, {"key":"news_fashion","name":"时尚"},{"key":"news_travel","name":"旅游"}, {"key":"news_discovery","name":"探索"},{"key":"news_baby","name":"育儿"},{"key":"news_regimen","name":"养生"},{"key":"news_story","name":"故事"}, {"key":"news_essay","name":"美文"},{"key":"news_game","name":"游戏"},{"key":"news_history","name":"历史"},{"key":"news_food","name":"美食"}] result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print ("404") else: self.errorRequest (num=0) class AdminUser(Confirm): def get(self, *args, **kwargs): all = self.request.arguments count = self.get_argument('count') alrequest = self.get_argument ('alrequest') page = self.get_argument('page') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) data = [] if (getTooken == tooken and len (all) == 5) or (getTooken == tooken and len (all) == 6): try: db = newsDb() user = db.select_table_three ("select user_id,name from user order by user_id") if page == "next": if int(alrequest) >= len(user): self.errorRequest (num=-1) else: if int(alrequest) + int(count) > len(user): for i in range (int (alrequest), len(user)): each_user = user [i] info = {"user_id": each_user [0], "user_name": each_user [1]} data.append (info) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: for i in range(int(alrequest),int(count) + int(alrequest)): each_user = user[i] info = {"user_id":each_user[0],"user_name":each_user[1]} data.append(info) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: for i in range (int (alrequest)-int(count),int (alrequest)): each_user = user [i] info = {"user_id": each_user [0], "user_name": each_user [1]} data.append (info) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) except: # 出现错误则回滚 print ("404") else: self.errorRequest (num=0) class AdminUserInfo(Confirm): def get(self, *args, **kwargs): all = self.request.arguments user_id = self.get_argument ('user_id') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) if (getTooken == tooken and len (all) == 3) or (getTooken == tooken and len (all) == 4): db = newsDb () info_1 = db.select_table_three("select phone from user where user_id='" +user_id+"'") info_2 = db.select_table_three("select sex,age,email,address from user_mess where user_id='" +user_id+"'") data={"phone":info_1[0][0],"sex":info_2[0][0],"age":info_2[0][1],"email":info_2[0][0],"address":info_2[0][0]} result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: self.errorRequest (num=0) class AdminFeedback(Confirm): def get(self, *args, **kwargs): all = self.request.arguments count = self.get_argument ('count') alrequest = self.get_argument ('alrequest') page = self.get_argument ('page') getTooken = self.get_argument ('tooken') time = self.get_argument ('time') tooken = self.tooken (time=time) data=[] if (getTooken == tooken and len (all) == 5) or (getTooken == tooken and len (all) == 6): db = newsDb() feedback = db.select_table_three("select user_id,feedback,getTime from news_feedback where isReply = 0") user_name = db.select_table_three("select name from user where user_id = '"+ feedback[0][0] +"'") if page == "xia": if int (alrequest) >= len (feedback): self.errorRequest (num=-1) else: if int (alrequest) + int (count) > len (feedback): for i in range (int (alrequest), len (feedback)): each_user = feedback [i] user_name = db.select_table_three ("select name from user where user_id = '" + each_user[0] + "'") info = {"user_id":each_user[0],"user_name":user_name[0][0],"contents":each_user[1],"times":"2016-07-11 15:11:21"} data.append (info) print (data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: for i in range (int (alrequest), int (count) + int (alrequest)): each_user = feedback [i] user_name = db.select_table_three ( "select name from user where user_id = '" + each_user [0] + "'") info = {"user_id":each_user[0],"user_name":user_name[0][0],"contents":each_user[1],"times":"2016-07-11 15:11:21"} data.append (info) print (data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: for i in range (int (alrequest) - int (count), int (alrequest)): each_user = feedback [i] user_name = db.select_table_three ("select name from user where user_id = '" + each_user [0] + "'") info = {"user_id":each_user[0],"user_name":user_name[0][0],"contents":each_user[1],"times":"2016-07-11 15:11:21"} data.append (info) print (data) result = {"message": "success", "data": data} result = json.dumps (result) self.write (result) else: self.errorRequest (num=0)
74b6523512f17f4c18096b956e4c3c074b53cf4c
[ "Markdown", "SQL", "Python", "JavaScript" ]
51
Python
howie6879/getNews
ab5ad56c8520e60d5f568deed0081dfc127b7cd9
f7fdbd310c0e48a8a2c74504aa27893d25354ba1
refs/heads/master
<file_sep>require("regenerator-runtime/runtime"); import { checkForName } from '../client/js/nameChecker' describe('Test, the function "checkForName()" should exist' , () => { test('It should return true', async () => { expect(checkForName).toBeDefined(); }); }); describe('Test "checkForName()" should be a function' , () => { test('It should be a function', async () => { expect(typeof checkForName).toBe("function"); }); });
244af8e72333f998d1994816634ddad0826fc69d
[ "JavaScript" ]
1
JavaScript
luisguerra44/fend-webpack-content
deda50c27a898316596c577a207c004e2b369a73
f16c5097153a57404e822f06ab92a9b70413ee26
refs/heads/master
<repo_name>SherJlok15/cook_book_v3.0<file_sep>/client/src/components/Main.js import React, { Component } from 'react'; import { Switch, Route, Redirect} from 'react-router-dom'; import NavBarContainer from './NavBarContainer'; import RecipesListContainer from './RecipesListContainer'; import CreateNewRecipe from './CreateNewRecipe'; import Recipe from './Recipe'; import EditRecipe from './EditRecipe'; import Footer from './Footer'; export default class Main extends Component { componentDidMount() { this.props.loadData() } render(props) { return ( <div className="wrapper"> <div className="content header-img"> <NavBarContainer /> <main> <Switch> <Route exact path='/recipes/'> <RecipesListContainer /> </Route> <Route path='/recipes/add/'> <CreateNewRecipe getUsernameValue={this.props.getUsernameValue} username={this.props.username} getTitleValue={this.props.getTitleValue} title={this.props.title} getTextValue={this.props.getTextValue} text={this.props.text} getDateValue={this.props.getDateValue} date={this.props.date} subitNewRecipeForm={this.props.subitNewRecipeForm} navbarSearchValue={this.props.navbarSearchValue} /> </Route> <Route exact path='/recipes/:id' render={(props) => <Recipe{...props} data={this.props.data} deleteRecipe={this.props.deleteRecipe} getRecipeId={this.props.getRecipeId} toggleClassLastVersion={this.props.toggleClassLastVersion} show_last_version={this.props.show_last_version} navbarSearchValue={this.props.navbarSearchValue} toggleElectValue={this.props.toggleElectValue} getElectValue={this.props.getElectValue} getElectFromRecipe={this.props.getElectFromRecipe} loadRecipeData={this.props.loadRecipeData} recipe_data={this.props.recipe_data} /> }/> <Route exact path='/recipes/update/:id' render={(props) => <EditRecipe{...props} edit_mode_recipe_data={this.props.edit_mode_recipe_data} editModeGetUsernameValue={this.props.editModeGetUsernameValue} edit_mode_username={this.props.edit_mode_username} editModeGetTitleValue={this.props.editModeGetTitleValue} edit_mode_title={this.props.edit_mode_title} editModeGetTextValue={this.props.editModeGetTextValue} edit_mode_text={this.props.edit_mode_text} editModeGetDateValue={this.props.editModeGetDateValue} edit_mode_date={this.props.edit_mode_date} editModeLoadRecipeData={this.props.editModeLoadRecipeData} editModeSubmitForm={this.props.editModeSubmitForm} navbarSearchValue={this.props.navbarSearchValue} /> }/> <Redirect to="/recipes/"/> </Switch> </main> </div> <footer className="footer"> <Footer/> </footer> </div> ) } } <file_sep>/client/src/components/MainContainer.js import { connect } from 'react-redux'; import Main from './Main'; import { loadData, toggleClassLastVersion, getElectValue, getElectFromRecipe, loadRecipeData, } from '../redux/actions/mainActions'; import { getUsernameValue, getTitleValue, getTextValue, getDateValue, subitNewRecipeForm, deleteRecipe, getRecipeId } from '../redux/actions/createRecipeActions'; import { editModeGetUsernameValue, editModeGetTitleValue, editModeGetTextValue, editModeGetDateValue, editModeLoadRecipeData, editModeSubmitForm, } from '../redux/actions/editRecipeActions'; function mapStateToProps(state) { return { data: state.main.data, username: state.createRecipe.username, title: state.createRecipe.title, text: state.createRecipe.text, date: state.createRecipe.date, edit_mode_username: state.editRecipe.username, edit_mode_title: state.editRecipe.title, edit_mode_text: state.editRecipe.text, edit_mode_date: state.editRecipe.date, edit_mode_recipe_data: state.editRecipe.edit_mode_recipe_data, show_last_version: state.main.show_last_version, navbarSearchValue: state.main.navbarSearchValue, elect_value: state.main.elect_value, recipe_data: state.main.recipe_data } } function mapDispatchToProps(dispatch) { return { loadData: () => dispatch(loadData()), getUsernameValue: (value) => dispatch(getUsernameValue(value)), getTitleValue: (value) => dispatch(getTitleValue(value)), getTextValue: (value) => dispatch(getTextValue(value)), getDateValue: (date) => dispatch(getDateValue(date)), subitNewRecipeForm: (event) => dispatch(subitNewRecipeForm(event)), deleteRecipe: (value) => dispatch(deleteRecipe(value)), getRecipeId: (value) => dispatch(getRecipeId(value)), editModeGetUsernameValue: (value) => dispatch(editModeGetUsernameValue(value)), editModeGetTitleValue: (value) => dispatch(editModeGetTitleValue(value)), editModeGetTextValue: (value) => dispatch(editModeGetTextValue(value)), editModeGetDateValue: (date) => dispatch(editModeGetDateValue(date)), editModeLoadRecipeData: (value) => dispatch(editModeLoadRecipeData(value)), editModeSubmitForm: (event) => dispatch(editModeSubmitForm(event)), toggleClassLastVersion: () => dispatch(toggleClassLastVersion()), getElectValue: (value, id) => dispatch(getElectValue(value, id)), getElectFromRecipe: (value) => dispatch(getElectFromRecipe(value)), loadRecipeData: (value) => dispatch(loadRecipeData(value)), } } const MainContainer = connect(mapStateToProps, mapDispatchToProps)(Main); export default MainContainer; <file_sep>/client/src/redux/actions/editRecipeActions.js import axios from 'axios'; export const EDIT_MODE_GET_USERNAME_VALUE = 'edit_mode_get_username_value'; export const EDIT_MODE_GET_TITLE_VALUE = 'edit_mode_get_title_value'; export const EDIT_MODE_GET_TEXT_VALUE = 'edit_mode_get_text_value'; export const EDIT_MODE_GET_DATE_VALUE = 'edit_mode_get_date_value'; export const EDIT_MODE_SUBMIT_FORM = 'edit_mode_submit_form'; export const EDIT_MODE_LOAD_RECIPE_DATA ='edit_mode_load_recipe_data'; export const EDIT_MODE_SAVE_RECIPE_DATA ='edit_mode_save_recipe_data'; export function editModeGetUsernameValue(value) { return { type: EDIT_MODE_GET_USERNAME_VALUE, value } } export function editModeGetTitleValue(value) { return { type: EDIT_MODE_GET_TITLE_VALUE, value } } export function editModeGetTextValue(value) { return { type: EDIT_MODE_GET_TEXT_VALUE, value } } export function editModeGetDateValue(date) { return { type: EDIT_MODE_GET_DATE_VALUE, date } } export function editModeSubmitForm(event) { return { type: EDIT_MODE_SUBMIT_FORM, event } } export function editModeLoadRecipeData(value) { return(dispatch) => { axios.get('/recipes/'+value) .then(res => { dispatch(editModeSaveRecipeData(res.data)) }) } } export function editModeSaveRecipeData(value) { return { type: EDIT_MODE_SAVE_RECIPE_DATA, value } } <file_sep>/client/src/redux/reducers/MainReducer.js import { SAVE_DATA, TOGGLE_CLASS_LAST_VERSION, NAVBAR_GET_SEARCH_INPUT_VALUE, NAVBAR_SEARCH_INPUT_RESET_VALUE, NAVBAR_GET_SORT_VALUE, CHANGE_ELECT_VALUE, GET_ELECT_FROM_RECIPE, SAVE_RECIPE_DATA, } from '../actions/mainActions'; const initialState = { data: '', show_last_version: false, navbarSearchValue: '', navbarSortValue: 'date', elect_value: 0, recipe_data: '', } export default function MainReducer(state = initialState, action) { switch (action.type) { case SAVE_DATA: return { ...state, data: action.value } case TOGGLE_CLASS_LAST_VERSION: const lastVersionBool = state.show_last_version === true ? false : true; return { ...state, show_last_version: lastVersionBool } case NAVBAR_GET_SEARCH_INPUT_VALUE: return { ...state, navbarSearchValue:action.value } case NAVBAR_SEARCH_INPUT_RESET_VALUE: return { ...state, navbarSearchValue: '' } case NAVBAR_GET_SORT_VALUE: return { ...state, navbarSortValue: action.value } case CHANGE_ELECT_VALUE: return { ...state, elect_value: action.value } case GET_ELECT_FROM_RECIPE: return { ...state, elect_value: action.value } case SAVE_RECIPE_DATA: return { ...state, recipe_data: [action.value] } default: return state } } <file_sep>/client/src/redux/actions/createRecipeActions.js export const GET_USERNAME_VALUE = 'get_username_value'; export const GET_TITLE_VALUE = 'get_title_value'; export const GET_TEXT_VALUE = 'get_text_value'; export const GET_DATE_VALUE = 'get_date_value'; export const SUBMIT_NEW_RECIPE_FORM = 'submit_new_recipe_form'; export const DELETE_RECIPE = 'delete_recipe'; export const GET_RECIPE_ID = 'get_recipe_id'; export function getUsernameValue(value) { return { type: GET_USERNAME_VALUE, value } } export function getTitleValue(value) { return { type: GET_TITLE_VALUE, value } } export function getTextValue(value) { return { type: GET_TEXT_VALUE, value } } export function getDateValue(date) { return { type: GET_DATE_VALUE, date } } export function subitNewRecipeForm(event) { return { type: SUBMIT_NEW_RECIPE_FORM, event } } export function deleteRecipe() { return { type: DELETE_RECIPE } } export function getRecipeId(value) { return { type: GET_RECIPE_ID, value } } <file_sep>/client/src/components/CreateNewRecipe.js import React, { Component } from 'react'; import DatePicker from 'react-datepicker'; import "react-datepicker/dist/react-datepicker.css"; export default class CreateNewRecipe extends Component { componentDidUpdate() { if (this.props.navbarSearchValue.length > 0 ) { window.location = '/recipes/'; } } render (props) { return ( <div className="bg-light container vh-100 padding-top-10"> <h3 className="text-center text-info">Create new recipe</h3> <form onSubmit={(event) => this.props.subitNewRecipeForm(event)} className="container d-flex flex-column justify-content-center max-width-90 min-width-90"> <div className="form-group container"> <label className="text-primary">Author name: </label> <input name="username" type='text' required value={this.props.username} onChange={(event)=> this.props.getUsernameValue(event.target.value)} placeholder="author name" title="minlength 3 characters" className="form-control" /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container"> <label className="text-primary">Recipe title: </label> <input name="title" type='text' required value={this.props.title} onChange={(event)=> this.props.getTitleValue(event.target.value)} placeholder="recipe title" title="minlength 3 characters" className="form-control" /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container"> <label className="text-primary">Recipe text: </label> <textarea name="text" required value={this.props.text} onChange={(event)=> this.props.getTextValue(event.target.value)} placeholder="recipe text" title="minlength 3 characters" className="form-control" minLength="3" wrap="soft" col="10" rows="10" /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container d-flex align-items-center"> <label className="control-label text-primary margin-right-10"> I want to cook this dish at: </label> <DatePicker selected={this.props.date} onChange={this.props.getDateValue} showTimeSelect timeIntervals={5} timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" placeholder="date" title="back in time" required className="form-control" /> </div> <div className="form-group d-flex justify-content-center container"> <input type="submit" value="Create new Recipe" className="btn btn-primary block"/> </div> </form> </div> ) } } <file_sep>/client/src/components/EditRecipe.js import React, { Component } from 'react'; import DatePicker from 'react-datepicker'; import "react-datepicker/dist/react-datepicker.css"; export default class EditRecipe extends Component { componentDidMount() { this.props.editModeLoadRecipeData(this.props.match.params.id); } componentDidUpdate() { if (this.props.navbarSearchValue.length > 0 ) { window.location = '/recipes/'; } } render(props) { return( <div className="bg-light container vh-100 padding-top-10"> {this.props.edit_mode_recipe_data === '' ? <div className="text-center text-success">Loading...</div> : this.props.edit_mode_recipe_data.map(item => <div key={item._id}> <h3 className="text-center text-info">Edit recipe</h3> <form onSubmit={(event) => this.props.editModeSubmitForm(event)} className="container d-flex flex-column justify-content-center max-width-90 min-width-90"> <div className="form-group container"> <label className="text-primary">Username: </label> <input type="text" required value={this.props.edit_mode_username} onChange={(event) => this.props.editModeGetUsernameValue(event.target.value)} className="form-control" /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container"> <label className="text-primary">Title: </label> <input type="text" required value={this.props.edit_mode_title} onChange={(event) => this.props.editModeGetTitleValue(event.target.value)} className="form-control" /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container"> <label className="text-primary">Text: </label> <textarea className="form-control" minLength="3" wrap="soft" col="10" rows="10" type="text" required value={this.props.edit_mode_text} onChange={(event) => this.props.editModeGetTextValue(event.target.value)} /> <small className="form-text text-muted">minlength 3 characters</small> </div> <div className="form-group container d-flex align-items-center"> <label className="control-label text-primary margin-right-10"> I want to cook this dish at: </label> <DatePicker selected={this.props.edit_mode_date} onChange={this.props.editModeGetDateValue} showTimeSelect timeIntervals={5} timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" placeholder="date" title="back in time" required className="form-control" /> </div> <div className="form-group d-flex justify-content-center container"> <input type="submit" value="Edit Recipe" className="btn btn-primary block"/> </div> </form> </div> ) } </div> ) } } <file_sep>/client/src/components/Footer.js import React from 'react'; export default function Footer() { return( <div className="bg-dark padding-10 text-center text-light"> <div> © 2019 Copyright: <a href="#"><NAME></a> </div> </div> ) } <file_sep>/README.md # cook_book_v3.0 -clone repositori -npm install (in cookbook folder) -npm install (in client folder) -npm run start (in cookbook folder) https://cookbookreciope.herokuapp.com <file_sep>/client/src/components/RecipesListRecipeSchema.js import React from 'react'; import { Link } from 'react-router-dom'; export default function RecipesListRecipeSchema(props) { return ( <div key={props.item._id} className="border-radius min-width-90 d-flex flex-column margin-top-20 padding-10 bg-light container"> <div className="d-flex flex-column"> <h3 className="text-success text-center align-self-center"> {props.item.title} </h3> </div> <div className="margin-10"> <div> <div className="text-success"> created at: </div> <div className="text-muted"> {new Date(props.item.updatedAt).toString().split("GMT")[0]} </div> </div> <div> <div className="text-success"> Author: </div> <div className="text-muted"> {props.item.username} </div> </div> <div> <div className="text-success"> I want to cook this dish at: </div> <div className="text-muted"> {new Date(props.item.date).toString().split("GMT")[0]} </div> </div> <div className="pre-wrap margin-top-20"> {props.item.text.length > 180 ? props.item.text.substring(0, 180 - 3) + "..." : props.item.text} </div> </div> <Link to={"/recipes/"+props.item._id} className="btn btn-success align-self-end mt-auto p-2 bd-highlight margin-10"> Read more </Link> </div> ) } <file_sep>/client/src/redux/actions/mainActions.js import axios from 'axios'; export const SAVE_DATA = 'save_data'; export const TOGGLE_CLASS_LAST_VERSION = 'toggele_class_last_version'; export const NAVBAR_GET_SEARCH_INPUT_VALUE = 'navbar_get_search_input_value'; export const NAVBAR_SEARCH_INPUT_RESET_VALUE = 'navbar_search_input_reset_value'; export const NAVBAR_GET_SORT_VALUE = 'navbar_get_sort_value'; export const CHANGE_ELECT_VALUE = 'change_elect_value'; export const GET_ELECT_FROM_RECIPE = 'get_elect_from_recipe'; export const SAVE_RECIPE_DATA = 'save_recipe_data'; export function loadData() { return(dispatch) => { axios.get('http://localhost:5000/recipes') .then(res => { dispatch(saveData(res.data)) }) .catch(err => { console.log(err) }) } }; export function saveData(value){ return { type: SAVE_DATA, value } }; export function toggleClassLastVersion(){ return { type: TOGGLE_CLASS_LAST_VERSION, } }; export function navbarGetSearchInputValue(value){ return { type: NAVBAR_GET_SEARCH_INPUT_VALUE, value } }; export function navbarSearchInputResetValue(){ return { type: NAVBAR_SEARCH_INPUT_RESET_VALUE, } }; export function navbarGetSortValue(value){ return { type: NAVBAR_GET_SORT_VALUE, value } }; export function changeElectValue(value){ return { type: CHANGE_ELECT_VALUE, value } }; export function getElectValue(value, id) { return(dispatch) => { const elect_value = { elect: value === 1 ? 0 : 1 } axios.post('http://localhost:5000/recipes/updateelect/'+id, elect_value) .then(res => { dispatch(changeElectValue(elect_value.elect)) }) .catch(err => { console.log(err) }) } }; export function getElectFromRecipe(value){ return { type: GET_ELECT_FROM_RECIPE, value } }; export function saveRecipeData(value){ return { type: SAVE_RECIPE_DATA, value } }; export function loadRecipeData(id) { return(dispatch) => { axios.get('http://localhost:5000/recipes/'+id) .then(res => { dispatch(saveRecipeData(res.data)) }) .catch(err => { console.log(err) }) } }; <file_sep>/client/src/redux/redux-store.js import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import MainReducer from './reducers/MainReducer'; import CreateRecipeReducer from './reducers/CreateRecipeReducer'; import EditRecipeReducer from './reducers/EditRecipeReducer'; const reducers = combineReducers({ main: MainReducer, createRecipe: CreateRecipeReducer, editRecipe: EditRecipeReducer }); const store = createStore(reducers, applyMiddleware(thunk)); export default store; <file_sep>/client/src/components/FilterPanel.js import React from 'react'; export default function FilterPanel(props) { return ( <div className="bg-whith-opacity text-white"> <div className="container d-flex justify-content-center"> <div className="margin-10 opacity-1">Sort by: </div> <label className="margin-10 cursor-pointer"> <input type="radio" name="filter" value="author" onChange={(event) => props.navbarGetSortValue(event.target.value)} checked={props.navbarSortValue === 'author'}className="margin-right-5 hide"/> <span className={props.navbarSortValue === 'author'? 'border-botom padding-10' : 'padding-10'}>Author name</span> </label> <label className="margin-10 cursor-pointer"> <input type="radio" name="filter" value="date" onChange={(event) => props.navbarGetSortValue(event.target.value)} checked={props.navbarSortValue === 'date'} className="margin-right-5 hide"/> <span className={props.navbarSortValue === 'date'? 'border-botom padding-10' : 'padding-10'}>Creation date</span> </label> <label className="margin-10 cursor-pointer"> <input type="radio" name="filter" value="title" onChange={(event) => props.navbarGetSortValue(event.target.value)} checked={props.navbarSortValue === 'title'} className="margin-right-5 hide"/> <span className={props.navbarSortValue === 'title'? 'border-botom padding-10' : 'padding-10'}>Recipe title</span> </label> <label className="margin-10 cursor-pointer"> <input type="radio" name="filter" value="date_of_cooking" onChange={(event) => props.navbarGetSortValue(event.target.value)} checked={props.navbarSortValue === 'date_of_cooking'} className="margin-right-5 hide" /> <span className={props.navbarSortValue === 'date_of_cooking'? 'border-botom padding-10' : 'padding-10'}>Date of cooking</span> </label> </div> </div> ); }
fb741dd03a4ceccf0ceeddb7bda27716f58f16bc
[ "JavaScript", "Markdown" ]
13
JavaScript
SherJlok15/cook_book_v3.0
f84dc708e07c1c0e23e1644549b6a2f8b17c1916
30986e3b090a87ba8d5eb42fd1d1a385c3db3fdb
refs/heads/master
<file_sep>/** * This software was developed at the National Institute of Standards and Technology by employees of * the Federal Government in the course of their official duties. Pursuant to title 17 Section 105 * of the United States Code this software is not subject to copyright protection and is in the * public domain. This is an experimental system. NIST assumes no responsibility whatsoever for its * use by other parties, and makes no guarantees, expressed or implied, about its quality, * reliability, or any other characteristic. We would appreciate acknowledgement if the software is * used. This software can be redistributed and/or modified freely provided that any derivative * works bear some notice that they are derived from it, and any modified versions bear some notice * that they have been modified. */ package gov.nist.hit.erx.core.service; import com.fasterxml.jackson.databind.JsonNode; import gov.nist.hit.core.domain.*; import gov.nist.hit.core.service.edi.EDIResourceLoader; import gov.nist.hit.core.service.exception.ProfileParserException; import gov.nist.hit.core.service.util.FileUtil; import gov.nist.hit.core.service.xml.XMLResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Service public class ERXResourceLoaderImpl extends ERXResourceLoader { static final Logger logger = LoggerFactory.getLogger(ERXResourceLoaderImpl.class); @Autowired EDIResourceLoader edirb; @Autowired XMLResourceLoader xmlrb; public static final String DOMAIN = "erx"; public ERXResourceLoaderImpl() {} @PostConstruct public void load() throws Exception { logger.info("loading ERXResourcebundle"); super.load(); } @Override public List<ResourceUploadStatus> addOrReplaceValueSet(String rootPath, String domain, TestScope scope, String username, boolean preloaded) throws IOException { System.out.println("AddOrReplace VS"); List<Resource> resources; try { resources = this.getApiResources("*.xml",rootPath); if (resources == null || resources.isEmpty()) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.VALUESETLIBRARY); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("No resource found"); return Arrays.asList(result); } } catch (IOException e1) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.VALUESETLIBRARY); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("Error while parsing resources"); return Arrays.asList(result); } List<ResourceUploadStatus> results = new ArrayList<ResourceUploadStatus>(); for (Resource resource : resources) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.VALUESETLIBRARY); String content = FileUtil.getContent(resource); try { VocabularyLibrary vocabLibrary = vocabLibrary(content, domain, scope, username, preloaded); result.setId(vocabLibrary.getSourceId()); VocabularyLibrary exist = this.getVocabularyLibrary(vocabLibrary.getSourceId()); if (exist != null) { System.out.println("Replace"); result.setAction(ResourceUploadAction.UPDATE); vocabLibrary.setId(exist.getId()); vocabLibrary.setSourceId(exist.getSourceId()); } else { result.setAction(ResourceUploadAction.ADD); } this.vocabularyLibraryRepository.save(vocabLibrary); result.setStatus(ResourceUploadResult.SUCCESS); } catch (Exception e) { result.setStatus(ResourceUploadResult.FAILURE); result.setMessage(e.getMessage()); } results.add(result); } return results; } @Override public List<ResourceUploadStatus> addOrReplaceConstraints(String rootPath, String domain, TestScope scope, String username, boolean preloaded) throws IOException { System.out.println("AddOrReplace Constraints"); List<Resource> resources; try { resources = this.getApiResources("*.xml",rootPath); if (resources == null || resources.isEmpty()) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.CONSTRAINTS); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("No resource found"); return Arrays.asList(result); } } catch (IOException e1) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.CONSTRAINTS); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("Error while parsing resources"); return Arrays.asList(result); } List<ResourceUploadStatus> results = new ArrayList<ResourceUploadStatus>(); for (Resource resource : resources) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.CONSTRAINTS); String content = FileUtil.getContent(resource); try { Constraints constraint = constraint(content, domain, scope, username, preloaded); result.setId(constraint.getSourceId()); Constraints exist = this.getConstraints(constraint.getSourceId()); if (exist != null) { System.out.println("Replace"); result.setAction(ResourceUploadAction.UPDATE); constraint.setId(exist.getId()); constraint.setSourceId(exist.getSourceId()); } else { result.setAction(ResourceUploadAction.ADD); System.out.println("Add"); } this.constraintsRepository.save(constraint); result.setStatus(ResourceUploadResult.SUCCESS); } catch (Exception e) { result.setStatus(ResourceUploadResult.FAILURE); result.setMessage(e.getMessage()); } results.add(result); } return results; } @Override public List<ResourceUploadStatus> addOrReplaceIntegrationProfile(String rootPath, String domain, TestScope scope, String username, boolean preloaded) throws IOException { System.out.println("AddOrReplace integration profile"); List<Resource> resources; try { resources = this.getApiResources("*.xml",rootPath); if (resources == null || resources.isEmpty()) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.PROFILE); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("No resource found"); return Arrays.asList(result); } } catch (IOException e1) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.PROFILE); result.setStatus(ResourceUploadResult.FAILURE); result.setMessage("Error while parsing resources"); return Arrays.asList(result); } List<ResourceUploadStatus> results = new ArrayList<ResourceUploadStatus>(); for (Resource resource : resources) { ResourceUploadStatus result = new ResourceUploadStatus(); result.setType(ResourceType.PROFILE); String content = FileUtil.getContent(resource); try { IntegrationProfile integrationP = integrationProfile(content, domain, scope, username, preloaded); result.setId(integrationP.getSourceId()); IntegrationProfile exist = this.integrationProfileRepository .findBySourceId(integrationP.getSourceId()); if (exist != null) { System.out.println("Replace"); result.setAction(ResourceUploadAction.UPDATE); integrationP.setId(exist.getId()); integrationP.setSourceId(exist.getSourceId()); } else { result.setAction(ResourceUploadAction.ADD); System.out.println("Add"); } this.integrationProfileRepository.save(integrationP); result.setStatus(ResourceUploadResult.SUCCESS); } catch (Exception e) { result.setStatus(ResourceUploadResult.FAILURE); result.setMessage(e.getMessage()); } results.add(result); } return results; } @Override public TestCaseDocument generateTestCaseDocument(TestContext c) throws IOException { if (c == null) return new TestCaseDocument(); else { if ("edi".equals(c.getFormat())){ return edirb.generateTestCaseDocument(c); } if ("xml".equals(c.getFormat())){ return xmlrb.generateTestCaseDocument(c); } return new TestCaseDocument(); } } @Override public TestContext testContext(String location, JsonNode parentOb, TestingStage stage, String rootPath, String domain, TestScope scope, String authorUsername, boolean preloaded) throws Exception { TestContext res = edirb.testContext(location, parentOb, stage, rootPath, domain, scope, authorUsername, preloaded); if (res != null) return res; res = xmlrb.testContext(location, parentOb, stage, rootPath, domain, scope, authorUsername, preloaded); return res; } // Methods not meant to be public exposed @Override public ProfileModel parseProfile(String integrationProfileXml, String conformanceProfileId, String constraintsXml, String additionalConstraintsXml) throws ProfileParserException { return edirb.parseProfile(integrationProfileXml, conformanceProfileId, constraintsXml, additionalConstraintsXml); } @Override public VocabularyLibrary vocabLibrary(String content, String domain, TestScope scope, String authorUsername, boolean preloaded) throws IOException, UnsupportedOperationException { return edirb.vocabLibrary(content, domain, scope, authorUsername, preloaded); } @Override protected IntegrationProfile getIntegrationProfile(String sourceId) throws IOException { //Only for EDI throw new UnsupportedOperationException(); } }
70e2e017408853f8034d17011e48c5a5ee42edc3
[ "Java" ]
1
Java
davidcozsmith/hit-erx-tool-config
32110e5483871c0194429693bb7cc7b3980dc6d7
c9a404223a987aa46366f5a2c0dd1c2a6e5524a8
refs/heads/master
<file_sep>import matplotlib # isort:skip matplotlib.use('TkAgg') # isort:skip import matplotlib.pyplot as pl # isort:skip from dotenv import load_dotenv from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.declarative import declarative_base import json import logging import numpy as np import os import pandas as pd import seaborn as sns import sys import threading import traceback # with open('data/essentials/weightage.json') as f: # weightage_data = json.load(f) load_dotenv(dotenv_path='.env') app = Flask(__name__, root_path=os.getcwd()) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URL') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ''' To create our database based off our model, run the following commands $ python >>> from app import db >>> db.create_all() >>> exit()''' Base = declarative_base() # keywords used to check real_world_presence hyperlinks_attributes = ['contact', 'email', 'help', 'sitemap'] apiList = { 'lastmod': ['getDate', '', '', 'Integer'], 'domain': ['getDomain', '', '', 'String(120)'], 'inlinks': [ 'getInlinks', '', '', 'Integer', ], 'outlinks': [ 'getOutlinks', '', '', 'Integer', ], 'hyperlinks': [ 'getHyperlinks', hyperlinks_attributes, '', 'JSON', ], 'imgratio': ['getImgratio', '', '', 'FLOAT'], 'brokenlinks': ['getBrokenlinks', '', '', 'Integer'], 'cookie': ['getCookie', '', '', 'Boolean'], 'langcount': ['getLangcount', '', '', 'Integer'], 'misspelled': ['getMisspelled', '', '', 'Integer'], # 'wot': ['getWot', '', 'JSON'], 'responsive': ['getResponsive', '', '', 'Boolean'], 'ads': ['getAds', '', 'Integer'], 'pageloadtime': ['getPageloadtime', '', '', 'Integer'], 'site': [ '', '', '', 'String(120)', ], } # A class to catch error and exceptions class WebcredError(Exception): """An error happened during assessment of site. """ def __init__(self, message): self.message = message def __str__(self): return repr(self.message) class MyThread(threading.Thread): # def __init__( # self, Module='api', Method=None, Name=None, Url=None, Args=None # ): # pass def __init__(self, func, Name, Url, Args=None): threading.Thread.__init__(self) self.func = func self.name = Name self.url = Url self.args = Args self.result = None if Args and Args != '': self.args = Args def run(self): try: if self.args: self.result = self.func(self.url, self.args) else: self.result = self.func(self.url) except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) try: if not ex_value.message == 'Response 202': logger.info('{}:{}'.format(ex_type.__name__, ex_value)) logger.info(stack_trace) except: pass self.result = None def getResult(self): return self.result # clear url if Urlattributes object def freemem(self): self.url.freemem() class Database(object): def __init__(self, database): engine = db.engine # check existence of table in database if not engine.dialect.has_table(engine, database.__tablename__): # db.create_all() Base.metadata.create_all(engine, checkfirst=True) logger.info('Created table {}'.format(database.__tablename__)) self.db = db self.database = database def filter(self, name, value): # print ("---------------------------------------in filter---------------------------------------") # print ("name ",name," database ",self.database) # print () return self.db.session.query( self.database ).filter(getattr(self.database, name) == value) def exist(self, name, value): if self.filter(name, value).count(): return True return False def getdb(self): return self.db def getsession(self): return self.db.session def add(self, data): logger.debug('creating entry') reg = self.database(data) self.db.session.add(reg) self.commit() def update(self, name, value, data): # TODO pull out only items of available columns of table if not self.filter(name, value).count(): self.add(data) else: logger.debug('updating entry') # we want assess_time only at the time of creation if data.get('assess_time'): del data['assess_time'] try: self.filter(name, value).update(data) # TODO come back and fix the bug # ConnectionError can't be adapted by sqlalchemy except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info(ex_value) logger.debug(stack_trace) self.commit() def commit(self): try: self.db.session.commit() except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.debug(ex_value) logger.debug(stack_trace) logger.debug('Rolling back db commit') self.getsession().rollback() def getdata(self, name=None, value=None): # print ("********************************************************************************************") a=self.filter(name, value).all()[0].__dict__ # print (a["url"]) # print ("********************************************************************************************") # return self.filter(name, value).all()[0].__dict__ return a def getcolumns(self): return self.database.metadata.tables[self.database.__tablename__ ].columns.keys() def gettablename(self): return self.database.__tablename__ def getcolumndata(self, column): return self.getsession().query(getattr(self.database, column)) def getdbdata(self): data = [] for i in self.getcolumndata('url'): if not self.getdata('url', i).get('error'): data.append(self.getdata('url', i)) # for d in data: # print (d['url']) return data class Correlation(object): def __init__(self): pass def getcorr(self, data, features_name): # supply data to np.coorcoef dataframe = pd.DataFrame( data=np.asarray(data)[0:, 0:], index=np.asarray(data)[0:, 0], columns=features_name ) corr = dataframe.corr() return corr def getheatmap(self, data, features_name): corr = self.getcorr(data, features_name) # get correlation heatmap sns.heatmap( corr, xticklabels=features_name, yticklabels=features_name, cmap=sns.diverging_palette(220, 10, as_cmap=True) ) # show graph plot of correlation pl.show() <file_sep><!doctype html> <head> <title>WEBCred</title> <link rel=stylesheet type=text/css href="static/style.css"> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <div class=header> <div class="left"> <a href="https://www.iiit.ac.in/"><img src="static/iiit-new.png" alt="iiit-logo" /></a> <a href="https://serc.iiit.ac.in/"><img src="static/SERClogo.png" alt="iiit-logo" /></a> </div> <div class=page> <center> <h1>WEBCred</h1> <sub>(A tool to assess Relevence Based Web Page Credibility Score)</sub> </center> {% for message in get_flashed_messages() %} <div class=flash>{{ message }}</div> {% endfor %} {% block body %}{% endblock %} </div> <div class="right"> </div> </div> </body> <footer> <center> <p> <a href="https://docs.google.com/document/d/1e_FLu-IyrTOBbyf1Z7QHEOJGHR3VsPWQ_okYjPnH-zc/edit?usp=sharing">Documentation</a> of WEBCred</p> <p>For any query, contact at: <a href="mailto:<EMAIL>"> <EMAIL></a>.</p> <p><a href="https://github.com/Shriyanshagro/WEBCred">Source Code</a></p> </center> </footer> <file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: import gzip import gensim import logging from gensim.test.utils import get_tmpfile from gensim.models import KeyedVectors import numpy as np from scipy import spatial import re import requests import urllib.request import time from bs4 import BeautifulSoup import pronto from nltk.corpus import wordnet import queue import math logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # In[2]: bfs_queue = queue.Queue(maxsize=1000) find_words = [] def show_file_contents(input_file): with gzip.open(input_file, 'rb') as f: for i, line in enumerate(f): print(line) break # In[3]: def read_input(input_file): """This method reads the input file which is in gzip format""" logging.info("reading file {0}...this may take a while".format(input_file)) with gzip.open(input_file, 'rb') as f: for i, line in enumerate(f): if (i % 10000 == 0): logging.info("read {0} reviews".format(i)) # do some pre-processing and return list of words for each review text yield gensim.utils.simple_preprocess(line) # In[7]: def avg_feature_vector(sentence, model, num_features, index2word_set): words = sentence.split() feature_vec = np.zeros((num_features, ), dtype='float32') n_words = 0 for word in words: if word in index2word_set: n_words += 1 feature_vec = np.add(feature_vec, model[word]) # print (n_words) if (n_words > 0): feature_vec = np.divide(feature_vec, n_words) return feature_vec # In[4]: def own_phrase_simi(list1,list2): keys = [] lines = [] stop = ["what","why","how","is","am","was","were","that","which","a","an","the"] #remove stop words for word in list1: if not(word in stop): keys.append(word) for word in list2: if not(word in stop): lines.append(word) sm = 0 cnt = 0 while(keys!=[] and lines!=[]): w = keys.pop() simi = 0 ind = 0 for i,word in enumerate(lines): try: sv = model.wv.similarity(w,word) except: sv = 0 pass if w == word: sv = 1 if sv > simi: simi = sv ind = i sm += simi # Weighted similarity # if simi > 0.7: # w2 = lines.pop(ind) # cnt += 1 # elif simi > 0.4: # w2 = lines.pop(ind) # cnt += 0.5 # elif simi >0.05: # w2 = lines.pop(ind) # cnt += 0.1 # else: # sm -= simi w2 = lines.pop(ind) cnt += 1 # print (sm) if cnt: sm /= cnt # print (sm) return sm # In[15]: # DFS def dfs(node_id): global find_words global model global index2word_set global ms global visited global wa,wb global mini_simi term = ms[node_id] visited[term.__hash__()] = 1 term_name = term.name.lower() term_name = "" if term_name == "": term_repr = term.__repr__() for ind,c in enumerate(term_repr): if term_repr[ind] == ':': break if ind-1 and c.isupper() and (term_repr[ind+1].islower() or term_repr[ind+1]==':'): term_name += " " if c != '<': term_name += c if term_name == "": return term_name = term_name.lower() # global cnt # cnt += 1 w1 = avg_feature_vector(term_name, model=model, num_features=150, index2word_set=index2word_set) minisimi_local = min(spatial.distance.cosine(w1, wa),spatial.distance.cosine(w1, wb)) if minisimi_local < mini_simi: find_words.append(term_name) children = [] if term.children: raw_children = [] sim_children = [] for child in term.children: if visited[child.__hash__()]: continue child_name = (child.name).lower() child_name = "" if child_name == "": child_repr = child.__repr__() for ind,c in enumerate(child_repr): if child_repr[ind] == ':': break if ind-1 and c.isupper() and (child_repr[ind+1].islower() or child_repr[ind+1]==':'): child_name += " " if c != '<': child_name += c if child_name == "": continue w2 = avg_feature_vector(child_name, model=model, num_features=150, index2word_set=index2word_set) neg_sim = spatial.distance.cosine(w1, w2) if math.isnan(neg_sim): neg_sim = 0 if neg_sim < mini_simi: sim_children.append(neg_sim) raw_children.append(child.id) # sim_children.append(neg_sim) # raw_children.append(child.id) children = [raw_children for _,raw_children in sorted(zip(sim_children,raw_children))] # print (term_name) # print (children) for child_id in children: if not visited[ms[child_id].__hash__()]: dfs(child_id) # In[16]: # BFS def bfs(): global find_words global model global index2word_set global ms global visited global wa,wb global mini_simi if bfs_queue.empty(): return node_id = bfs_queue.get() term = ms[node_id] visited[term.__hash__()] = 1 term_name = term.name.lower() term_name = "" if term_name == "": term_repr = term.__repr__() for ind,c in enumerate(term_repr): if term_repr[ind] == ':': break if ind-1 and c.isupper() and (term_repr[ind+1].islower() or term_repr[ind+1]==':'): term_name += " " if c != '<': term_name += c if term_name == "": return term_name = term_name.lower() # print (term_name) # global cnt # cnt += 1 w1 = avg_feature_vector(term_name, model=model, num_features=150, index2word_set=index2word_set) minisimi_local = min(spatial.distance.cosine(w1, wa),spatial.distance.cosine(w1, wb)) if minisimi_local < mini_simi: find_words.append(term_name) children = [] if term.children: raw_children = [] sim_children = [] for child in term.children: if visited[child.__hash__()]: continue child_name = (child.name).lower() child_name = "" if child_name == "": child_repr = child.__repr__() for ind,c in enumerate(child_repr): if child_repr[ind] == ':': break if ind-1 and c.isupper() and (child_repr[ind+1].islower() or child_repr[ind+1]==':'): child_name += " " if c != '<': child_name += c if child_name == "": continue w2 = avg_feature_vector(child_name, model=model, num_features=150, index2word_set=index2word_set) neg_sim = spatial.distance.cosine(w1, w2) if math.isnan(neg_sim): neg_sim = 0 if neg_sim < mini_simi: sim_children.append(neg_sim) raw_children.append(child.id) # sim_children.append(neg_sim) # raw_children.append(child.id) children = [raw_children for _,raw_children in sorted(zip(sim_children,raw_children))] # print (term_name) # print (children) for child_id in children: if not visited[ms[child_id].__hash__()]: bfs_queue.put(child_id) bfs() def initmain(): global model global index2word_set input_file = '../dataset.gz' # read first line of the dataset # show_file_contents(input_file) # documents is a list of lists documents = list(read_input(input_file)) logging.info("Done reading dataset") # build vocabulary and train model model = gensim.models.Word2Vec( documents, size=150, window=10, min_count=2, workers=10) # In[5]: model.train(documents, total_examples=len(documents), epochs=10) # In[6]: index2word_set = set(model.wv.index2word) # own_phrase_simi("abhishek mathur is great".split(),"mathur is awesome".split()) # s1_afv = avg_feature_vector('firewall', model=model, num_features=150, index2word_set=index2word_set) # s2_afv = avg_feature_vector('complex firewall', model=model, num_features=150, index2word_set=index2word_set) # sim = 1 - spatial.distance.cosine(s1_afv, s2_afv) # print(sim) url = 'https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460?gi=79ec9ea38660' response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") body = soup.findAll('body') content = str(body[0]) without_tags = "" # print (content) cnt = 0 flag = 0 for c in content: if c == '<': cnt = 1 if cnt == 0: without_tags += c flag = 0 if c == '>': cnt = 0 if not flag: without_tags += " " flag = 1 # words = re.split('=|(|)|-',without_tags) words = re.split('\.|,| ',without_tags) # content = " " # for word in words: # content += word # print (without_tags) # for word in words: # print (word) # In[12]: # In[13]: def findrelevantwords(word): global find_words global model global index2word_set global ms global visited global wa,wb global mini_simi ms = pronto.Ontology("pizza.owl") find_words = [] visited = {} cnt = 0 word = word.lower() find_words.append(word) list_word = word.split() word_with_spaces = list_word[0] word = word_with_spaces for ind,w in enumerate(list_word): if ind > 0: word += "_" word += w word_with_spaces += " " word_with_spaces += w print (word) syn = wordnet.synsets(word) # In[14]: if syn == []: tmp_keyword = word else: w = syn[0] tmp_keyword = w.hypernyms()[0].lemmas()[0].name() # print(tmp_keyword) keyword = "" for ind,c in enumerate(tmp_keyword): if c == '_': keyword += " " else: keyword += c keyword = keyword.lower() find_words.append(keyword) print (keyword) print (word_with_spaces) wa = avg_feature_vector(keyword, model=model, num_features=150, index2word_set=index2word_set) wb = avg_feature_vector(word_with_spaces, model=model, num_features=150, index2word_set=index2word_set) mini_simi = 0.5 # In[18]: for term in ms: visited[term.__hash__()] = 0 children = [] raw_children = [] sim_children = [] w1 = avg_feature_vector(keyword, model=model, num_features=150, index2word_set=index2word_set) w11 = avg_feature_vector(word_with_spaces, model=model, num_features=150, index2word_set=index2word_set) for child in ms: # print (child) if visited[child.__hash__()]: continue child_name = (child.name).lower() child_name = "" if child_name == "": child_repr = child.__repr__() for ind,c in enumerate(child_repr): if child_repr[ind] == ':': break if ind-1 and c.isupper() and (child_repr[ind+1].islower() or child_repr[ind+1]==':'): child_name += " " if c != '<': child_name += c if child_name == "": continue child_name = child_name.lower() w2 = avg_feature_vector(child_name, model=model, num_features=150, index2word_set=index2word_set) neg_sim1 = spatial.distance.cosine(w1, w2) if math.isnan(neg_sim1): neg_sim1 = 1 neg_sim11 = spatial.distance.cosine(w11, w2) if math.isnan(neg_sim11): neg_sim11 = 1 # print ("...........") # print (child_name,child.id,1-min(neg_sim1,neg_sim11)) if min(neg_sim1,neg_sim11) < mini_simi: sim_children.append(min(neg_sim1,neg_sim11)) raw_children.append(child.id) # sim_children.append(min(neg_sim1,neg_sim11)) # raw_children.append(child.id) children = [raw_children for _,raw_children in sorted(zip(sim_children,raw_children))] find_words = [] # All terms sorted with decreasing similarity in children[] # print (term_name) # print (children) # DFS for child_id in children: if not visited[ms[child_id].__hash__()]: dfs(child_id) # print (cnt) print (find_words) print () print () for term in ms: visited[term.__hash__()] = 0 find_words_dfs = find_words find_words = [] # BFS for child_id in children: # print(ms[child_id].__repr__()) if not visited[ms[child_id].__hash__()]: bfs_queue.put(child_id) bfs() find_words.insert(0,word_with_spaces) find_words.insert(0,keyword) print (find_words) return find_words # for a,b in enumerate(find_words): # try: # if b!=find_words_dfs[a]: # print (b,find_words_dfs[a]) # except: # pass # In[19]: # Sorted directly w.r.t. similarity # w1 = avg_feature_vector(keyword, model=model, num_features=150, index2word_set=index2word_set) # w11 = avg_feature_vector(word_with_spaces, model=model, num_features=150, index2word_set=index2word_set) # raw_children = [] # sim_children = [] # children = [] # simi_sort = [] # for term in ms: # term_name = term.name.lower() # term_name = "" # if term_name == "": # term_repr = term.__repr__() # for ind,c in enumerate(term_repr): # if term_repr[ind] == ':': # break # if ind-1 and c.isupper() and (term_repr[ind+1].islower() or term_repr[ind+1]==':'): # term_name += " " # if c != '<': # term_name += c # term_name = term_name.lower() # if term_name == "": # # print (term.__repr__()) # continue # w2 = avg_feature_vector(term_name, model=model, num_features=150, index2word_set=index2word_set) # neg_sim1 = spatial.distance.cosine(w1, w2) # if math.isnan(neg_sim1): # neg_sim1 = 1 # neg_sim11 = spatial.distance.cosine(w11, w2) # if math.isnan(neg_sim11): # neg_sim11 = 1 # # print (word_with_spaces,term_name,term.name,1-min(neg_sim1,neg_sim11)) # # if term_name == "firewall a": # # print (term.__repr__(),min(neg_sim1,neg_sim11)) # sim_children.append(min(neg_sim1,neg_sim11)) # raw_children.append(term_name) # children = [raw_children for _,raw_children in sorted(zip(sim_children,raw_children))] # sim_children.sort() # # print (children) # for i,child in enumerate(children): # print (child,1-sim_children[i]) <file_sep>from datetime import datetime from features import surface from utils.essentials import apiList from utils.essentials import MyThread from utils.essentials import WebcredError from utils.urls import normalizeCategory from utils.urls import normalizedData from utils.urls import Urlattributes import logging import os import re import sys import traceback # logger = logging.getLogger('WEBCred.webcred') # logging.basicConfig( # filename='log/logging.log', # filemode='a', # format='[%(asctime)s] {%(name)s:%(lineno)d} %(levelname)s - %(message)s', # datefmt='%m/%d/%Y %I:%M:%S %p', # level=logging.INFO # ) # map feature to function name # these keys() are also used to define db columns class Webcred(object): def __init__(self, db, request): self.db = db self.request = request def assess(self): now = datetime.now() if not isinstance(self.request, dict): self.request = dict(self.request.args) data = {} req = {} req['args'] = {} percentage = {} site = None dump = True try: # get percentage of each feature # and copy self.request to req['args'] # TODO come back and do this properly for keys in apiList.keys(): if self.request.get(keys, None): # because self.request.args is of ImmutableMultiDict form if isinstance(self.request.get(keys, None), list): req['args'][keys] = str(self.request.get(keys)[0]) perc = keys + "Perc" if self.request.get(perc): percentage[keys] = self.request.get(perc)[0] else: req['args'][keys] = self.request.get(keys) perc = keys + "Perc" if self.request.get(perc): percentage[keys] = self.request.get(perc) # to show wot ranking # req['args']['wot'] = "true" data['url'] = req['args']['site'] site = Urlattributes(url=req['args'].get('site', None)) # get genre # WARNING there can be some issue with it data['genre'] = self.request.get('genre', None) if data['url'] != site.geturl(): data['redirected'] = site.geturl() data['lastmod'] = site.getlastmod() # site is not a WEBCred parameter del req['args']['site'] # check database, # if url is already present? if self.db.filter('url', data['url']).count(): ''' if lastmod not changed update only the columns with None value else update every column ''' if self.db.filter( 'lastmod', data['lastmod']).count() or not data['lastmod']: # get all existing data in dict format data = self.db.getdata('url', data['url']) # check the ones from columns which have non None value ''' None value indicates that feature has not successfully extracted yet ''' for k, v in data.items(): if v or str(v) == '0': # always assess loadtime if k != 'pageloadtime': req['args'][k] = 'false' dump = False else: data = self.db.getdata('url', data['url']) data = self.extractValue(req, apiList, data, site) # HACK 13 is calculated number, refer to index.html, where new # dimensions are dynamically added # create percentage dictionary number = 13 # TODO come back and do this properly print () print () print () print("no error 1") print () print () print () while True: dim = "dimension" + str(number) API = "api" + str(number) if dim in self.request.keys(): try: data[self.request.get(dim)[0]] = surface.dimapi( site.geturl(), self.request.get(API)[0] ) perc = API + "Perc" percentage[dim] = self.request.get(perc)[0] except WebcredError as e: data[self.request.get(dim)[0]] = e.message except: data[self.request.get(dim)[0]] = "Fatal ERROR" else: break number += 1 print () print () print () print("no error 2") print () print () print () data = webcredScore(data, percentage) data['error'] = None print ("data1error ",data['error']) except WebcredError as e: data['error'] = e.message print ('python error') print() dump = False except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info(ex_value) logger.debug(stack_trace) # HACK if it's not webcred error, # then probably it's python error data['error'] = 'Fatal Error' dump = False logger.debug(data['url']) finally: now = str((datetime.now() - now).total_seconds()) data['assess_time'] = now # store it in data self.db.update('url', data['url'], data) # dump text and html of html if dump: self.dumpRaw(site) data = self.db.getdata('url', data['url']) # prevent users to know of dump location del data['html'] del data['text'] logger.debug(data['url']) logger.debug('Time = {}'.format(now)) print ("data2error ",data['error']) return data # dump text and html of html def dumpRaw(self, site): if not site: return # location where this data will be dumped loct = 'data/dump/' dump = { 'html': { 'function': 'gethtml' }, 'text': { 'function': 'gettext' }, } data = {} filename = re.sub('^http*://', '', site.getoriginalurl()) for i in dump.keys(): location = (os.sep).join([ loct, i, (os.sep).join(filename.split('/')[:-1]) ]) if not os.path.exists(location): os.makedirs(location) location = (os.sep).join([location, filename.split('/')[-1]]) fi = open(location, 'w') func = getattr(site, dump[i]['function']) data[i] = location raw = func() try: fi.write(raw) except UnicodeEncodeError: fi.write(raw.encode('utf-8')) fi.close() # update db with locations of their dump self.db.update('url', site.getoriginalurl(), data) # to differentiate it with DB null value def extractValue(self, req, apiList, data, site): # assess requested features threads = [] for keys in req['args'].keys(): if str(req['args'].get(keys, None)) == "true": Method = apiList[keys][0] Name = keys Url = site Args = apiList[keys][1] func = getattr(surface, Method) thread = MyThread(func, Name, Url, Args) thread.start() threads.append(thread) # wait to join all threads in order to get all results maxTime = 300 for t in threads: t.join(maxTime) data[t.getName()] = t.getResult() logger.debug('{} = {}'.format(t.getName(), data[t.getName()])) return data # esp. are we removing any outliers? def webcredScore(data, percentage): # percentage is dict # score varies from -1 to 1 score = 0 # take all keys of data into account for k, v in data.items(): try: if k in normalizeCategory['3'].keys() and k in percentage.keys(): name = k + "norm" data[name] = normalizedData[k].getnormalizedScore(v) score += data[name] * float(percentage[k]) if k in normalizeCategory['2'].keys() and k in percentage.keys(): name = k + "norm" data[name] = normalizedData[k].getfactoise(v) score += data[name] * float(percentage[k]) if k in normalizeCategory['misc' ].keys() and k in percentage.keys(): sum_hyperlinks_attributes = 0 try: for key, value in v.items(): sum_hyperlinks_attributes += value name = k + "norm" data[name] = normalizedData[k].getnormalizedScore( sum_hyperlinks_attributes ) score += data[name] * float(percentage[k]) except: logger.info('Issue with misc normalizing categories') except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info(ex_value) logger.debug(stack_trace) print (score) data["webcred_score"] = score / 100 # TODO add Weightage score for new dimensions return data <file_sep>import dotenv from flask import render_template from flask import request from flask import Flask from utils.databases import Features from utils.essentials import Database import word2vec1 import json import queue import threading import logging import os import re import requests import urllib.request from bs4 import BeautifulSoup import time app = Flask(__name__) dotenv.load_dotenv(dotenv_path='.env') urls = queue.Queue(maxsize=40) ans = {} cnt = 0 rel = [] final_url = [] final_score = [] class mythread (threading.Thread): def __init__(self,thread_id): threading.Thread.__init__(self) self.thread_id = thread_id # self.thread_url = thread_url def run(self): print ("Starting thread",self.thread_id) while not urls.empty(): threadLock.acquire() self.thread_url=urls.get() threadLock.release() print (self.thread_id,urls.qsize()) find_simi(self.thread_id,self.thread_url) print ("Finished thread",self.thread_id) def find_simi(thread_id,thread_url): # find count of words print ("Running thread ",thread_id) ans[thread_url] = 1 try: domain = thread_url.split(':') domain.pop(0) thread_url = "https:" for i in domain: thread_url += i response = requests.get(thread_url,timeout=3) soup = BeautifulSoup(response.text, "html.parser") body = soup.findAll('body') content = str(body[0]) without_tags = "" content_string = "" # print (content) cnt = 0 flag = 0 for c in content: if c == '<': cnt = 1 if cnt == 0: without_tags += c flag = 0 if c == '>': cnt = 0 if not flag: without_tags += " " flag = 1 words = re.split('\.|,| ',without_tags) for word in words: content_string += word content_string += " " global rel fac = 1 sm1 = 0 print (content_string) j = 0 for word in rel: cnt1 = content_string.count(word) print (word,cnt1) sm1 += cnt1*fac if j > 1: fac /= 2 global final_url global final_score final_url.append(thread_url) final_score.append(sm1) except Exception as e: # print (e) pass # content = str(body[0]) # content = content.split('>') # print ("Data sample from ",thread_id) print ("a") database = Database(Features) data = database.getdbdata() data_urls = [] for d in data: data_urls.append(d['url']) print ("b") @app.route("/sendurl", methods=['GET']) def start(): print ("assess credibility") j=0 global data_urls global final_url global final_score final_url = [] final_score = [] for d in data_urls: if j == 40: break urls.put(d) j+=1 keyword=request.args['keyword'] global rel rel = word2vec1.findrelevantwords(keyword) print ("rel ",rel) j=0 threads = [] while not urls.empty() and j<20: thread1 = mythread(j) threads.append(thread1) j+=1 for t in threads: t.start() for t in threads: t.join() print ("final score ",final_score) print ("final url ",final_url) urls1 = [final_url for _,final_url in sorted(zip(final_score,final_url))] urls1.reverse() final_score.sort(reverse=True) print ("final score ",final_score) print ("final url ",urls1) # print (len(ans)) # data = {"xewd":"dwee"} # json_data = json.dumps(data, default=lambda o: '<not serializable>') # print ("json_data ",json_data) data = {} for i,url in enumerate(urls1): data[url] = final_score[i] json_data = json.dumps(data, default=lambda o: '<not serializable>') return json_data @app.route("/") def index(): print ("render source.html") return render_template("index.html") @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 def appinfo(url=None): pid = os.getpid() # print pid cmd = ['ps', '-p', str(pid), '-o', "%cpu,%mem,cmd"] # print while True: info = subprocess.check_output(cmd) print (info) time.sleep(3) print ('exiting appinfo') return None if __name__ == "__main__": word2vec1.initmain() print ("assess") threadLock = threading.Lock() app.run( threaded=True, host='0.0.0.0', debug=False, port=5050, ) <file_sep>import dotenv from flask import render_template from flask import request from flask import Flask from utils.databases import Features from utils.essentials import Database import json import queue import threading # import logging # import os # import requests # import subprocess # import time app = Flask(__name__) dotenv.load_dotenv(dotenv_path='.env') urls = queue.Queue(maxsize=40) ans = {} cnt = 0 class mythread (threading.Thread): def __init__(self,thread_id): threading.Thread.__init__(self) self.thread_id = thread_id # self.thread_url = thread_url def run(self): # print ("Starting thread",self.thread_id) while not urls.empty(): threadLock.acquire() self.thread_url=urls.get() print (self.thread_id,urls.qsize()) threadLock.release() find_simi(self.thread_id,self.thread_url) # print ("Finished thread",self.thread_id) def find_simi(thread_id,thread_url): print ("Running thread ",thread_id) ans[thread_url] = 1 try: domain = thread_url.split(':') domain.pop(0) thread_url = "https:" for i in domain: thread_url += i try: response = requests.get(thread_url, timeout=3) except: # print ("aaaaaaaaaaaaaaa") pass soup = BeautifulSoup(response.text, "html.parser") body = soup.findAll('body') except: print (thread_url) pass # content = str(body[0]) # content = content.split('>') # print ("Data sample from ",thread_id) database = Database(Features) data = database.getdbdata() data_urls = [] for d in data: data_urls.append(d['url']) @app.route("/sendurl", methods=['POST','GET']) def start(): print ("assess credibility") # j=0 # for d in data: # if j == 10: # break # urls.put(d['url']) # j+=1 # threadLock = threading.Lock() # j=0 # threads = [] # while not urls.empty() and j<7: # thread1 = mythread(j) # threads.append(thread1) # j+=1 # thread1.start() # for t in threads: # t.join() # print (len(ans)) # print (request.args['keyword']) # data = {"xewd":"dwee"} # json_data = json.dumps(data, default=lambda o: '<not serializable>') # print ("json_data ",json_data) global data_urls data = {} for url in data_urls: data[url] = 0 json_data = json.dumps(data, default=lambda o: '<not serializable>') return json_data @app.route("/") def index(): print ("render source.html") return render_template("index.html") @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 def appinfo(url=None): pid = os.getpid() # print pid cmd = ['ps', '-p', str(pid), '-o', "%cpu,%mem,cmd"] # print while True: info = subprocess.check_output(cmd) print (info) time.sleep(3) print ('exiting appinfo') return None if __name__ == "__main__": print ("assess") app.run( threaded=True, host='0.0.0.0', debug=False, port=5050, ) <file_sep>from ast import literal_eval from dotenv import load_dotenv from nltk.corpus import wordnet from nltk.tag import pos_tag from nltk.tokenize import word_tokenize from urllib.parse import urlparse from utils.essentials import MyThread from utils.essentials import WebcredError from utils.urls import Urlattributes import logging import os import re import requests import sys import traceback import validators logger = logging.getLogger('WEBCred.surface') logging.basicConfig( filename='log/logging.log', filemode='a', format='[%(asctime)s] {%(name)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO ) load_dotenv() def funcBrokenllinks(url): result = False if url: try: Urlattributes(url) except WebcredError: result = True return result def funcImgratio(url): size = 0 size = url.getsize() return size # if rank not available, 999999999 wil be returned def getAlexarank(url): if not isinstance(url, Urlattributes): url = Urlattributes(url) uri = "http://data.alexa.com/data?cli=10&dat=s&url=" + url.geturl() uri = Urlattributes(uri) soup = uri.getsoup() try: rank = soup.find("reach")['rank'] except: rank = None return rank def getWot(url): if not isinstance(url, Urlattributes): url = Urlattributes(url) result = ( "http://api.mywot.com/0.4/public_link_json2?hosts=" + url.geturl() + "/&callback=&key=<KEY>" ) uri = Urlattributes(result) raw = uri.gettext() result = literal_eval(raw[1:-4]) result = str(result).split(']')[0].split('[')[-1].split(',') data = None if isinstance(result, list) and len(result) == 2: data = {} data['reputation'] = int(result[0]) data['confidence'] = int(result[1]) return data def getResponsive(url): # should output boolean value api_url = 'https://searchconsole.googleapis.com/v1/urlTestingTools/' \ 'mobileFriendlyTest:run' response = requests.post( api_url, json={'url': url.geturl()}, params={ 'fields': 'mobileFriendliness', 'key': os.environ['Google_API_KEY'] } ) if response.status_code / 100 >= 4: return None response = response.json() state = 0 try: if response['mobileFriendliness'] == 'MOBILE_FRIENDLY': state = 1 else: pass # NOT_MOBILE_FRIENDLY # logger.debug(response['mobileFriendliness']) except KeyError: logger.warning(response['error']['message']) state = None return state def getHyperlinks(url, attributes): soup = url.getsoup() data = {} for element in attributes: data[element] = 0 ''' Using wn.synset('dog.n.1').lemma_names is the correct way to access the synonyms of a sense. It's because a word has many senses and it's more appropriate to list synonyms of a particular meaning/sense ''' syn = wordnet.synsets(element) if syn: syn = wordnet.synsets(element)[0].lemma_names() lookup = {'header': 0, 'footer': 0} percentage = 10 # looking for element in lookup for tags in lookup.keys(): if soup.find_all(tags, None) and not data[element]: lookup[tags] = 1 text = soup.find_all(tags, None) text = text[0].find_all('a', href=True) for ss in syn: for index in text: if data[element]: break try: pattern = url.getPatternObj().regexCompile([ss]) match, matched = url.getPatternObj().regexMatch( pattern=pattern, data=str(index) ) except: logger.debug('Error with patternmatching') return None if match: data[element] = 1 break '''if lookup tags are not found, then we check in upper and lower percentage of text''' for tags in lookup.keys(): if not data[element] and not lookup[tags]: text = soup.find_all('a', href=True) if tags == 'header': text = text[:(len(text) * (percentage / 100))] elif tags == 'footer': text = text[(len(text) * ((100 - percentage) / 100)):] for ss in syn: for index in text: if data[element]: break try: pattern = url.getPatternObj().regexCompile([ss]) match, matched = url.getPatternObj().regexMatch( pattern=pattern, data=str(index) ) except: logger.debug('Error with patternmatching') return None if match: data[element] = 1 break # such cases where syn is [] # wordnet has no synonyms for sitemap if not data[element]: for index in text: if data[element]: break try: pattern = url.getPatternObj().regexCompile([ element ]) match, matched = url.getPatternObj().regexMatch( pattern=pattern, data=str(index) ) except: logger.debug('Error with patternmatching') return None if match: data[element] = 1 break return data def getLangcount(url): ''' idea is to find pattern 'lang' in tags and then iso_lang code in those tags there are 2 possible patterns, to match iso_lang - ="en" =en ''' soup = url.getsoup() count = 0 matched = [] tags = soup.find_all(href=True) for tag in tags: tag = str(tag) match = re.search("lang", tag, re.I) if match: pattern = url.patternMatching.getIsoPattern() match, pattern = url.getPatternObj().regexMatch(pattern, tag) if match: # iso_pattern = ="iso"|=iso pattern = pattern.split('=')[-1] if pattern.startswith('"'): pattern = pattern.split('"')[1] if pattern not in matched: matched.append(pattern) count += 1 # some uni-lang websites didn't mention lang tags if count == 0: count = 1 return count # TODO: think about this def getImgratio(url): total_img_size = 0 threads = [] text_size = url.getsize() soup = url.getsoup() # total_img_size of images for link in soup.find_all('img', src=True): uri = link.get('src', None) if not uri.startswith('http://') and not uri.startswith('https://'): uri = url.geturl() + uri if validators.url(uri): try: uri = Urlattributes(uri) Method = funcImgratio Name = 'Imgratio' Url = uri func = Method t = MyThread(func, Name, Url) t.start() threads.append(t) except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) if ex_value.message != 'Response 202': logger.warning(ex_value) logger.debug(stack_trace) for t in threads: t.join() size = t.getResult() t.freemem() if isinstance(size, int): total_img_size += size # print total_img_size total_size = total_img_size + text_size ratio = float(text_size) / total_size return ratio def getAds(url): soup = url.getsoup() count = 0 for link in soup.find_all('a', href=True): try: href = str(link.get('href')) if href.startswith('http://') or href.startswith('https://'): pattern = url.getPatternObj().getAdsPattern() match, pattern = url.getPatternObj().regexMatch(pattern, href) if match: count += 1 except UnicodeEncodeError: pass return count def getCookie(url): header = url.getheader() pattern = url.getPatternObj().regexCompile(['cookie']) for key in header.keys(): match, matched = url.getPatternObj().regexMatch( pattern=pattern, data=key ) if match: # print key return 1 return 0 def getMisspelled(url): text = url.gettext() excluded_tags = [ 'NNP', 'NNPS', 'SYM', 'CD', 'IN', 'TO', 'CC', 'LS', 'POS', '(', ')', ':', 'EX', 'FW', 'RP' ] try: text = word_tokenize(text) except UnicodeDecodeError: text = unicode(text, 'utf-8') text = word_tokenize(text) tags = [] # print text for texts in text: i = pos_tag(texts.split()) i = i[0] if i[1] not in excluded_tags and i[0] != i[1]: tags.append(i[0]) # count of undefined words count = 0 for tag in tags: try: syns = wordnet.synsets(str(tag)) if syns: # [0] is in the closest sense syns[0].definition() except Exception: count += 1 return count def getDate(url): return url.getlastmod() def getDomain(url): # a fascinating use of .format() syntax domain = url.getdomain() return domain def getBrokenlinks(url): broken_links = 0 threads = [] soup = url.getsoup() for link in soup.find_all('a', href=True): uri = link.get('href') # to include inner links as well if not uri.startswith('http://') and not uri.startswith('https://'): uri = url.geturl() + uri if validators.url(uri): Method = funcBrokenllinks Name = 'brokenlinks' Url = uri func = Method t = MyThread(func, Name, Url) t.start() threads.append(t) for t in threads: t.join() if t.getResult(): broken_links += 1 logger.debug('broken_links {}'.format(broken_links)) return broken_links def getOutlinks(url): outlinks = 0 soup = url.getsoup() for link in soup.find_all('a', href=True): uri = link.get('href') if uri.startswith('https://') or uri.startswith('http://'): parsed_uri = urlparse(uri) netloc = '{uri.netloc}'.format(uri=parsed_uri) if url.getnetloc() != netloc: outlinks += 1 logger.debug('outlinks = {}'.format(outlinks)) return outlinks def googleinlink(url): API_KEY = os.environ.get('Google_API_KEY') inlinks = None try: # keyword link is used in search query to search only hyperlinks uri = ( 'https://www.googleapis.com/customsearch/v1?key=' + API_KEY + '&cx=017576662512468239146:omuauf_lfve&q=link:' + url.getoriginalurl() ) uri = Urlattributes(uri) txt = uri.gettext() for line in txt.splitlines(): if "totalResults" in line: break inlinks = int(re.sub("[^0-9]", "", line)) except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info('Inlinks error {}'.format(ex_value)) logger.debug(stack_trace) return inlinks # TODO def yahooinlink(url): pass # TODO def binginlink(url): pass # total web-pages which points url def getInlinks(url): inlinks = None # request google, yahoo, bing for inlinks # take average of there results queries = { 'google': googleinlink, # 'yahoo': yahooinlink, # 'bing': binginlink, } threads = [] for keys in queries.keys(): Method = queries[keys] Name = keys func = Method Url = url thread = MyThread(func, Name, Url) thread.start() threads.append(thread) score = 0 length = 0 for t in threads: try: t.join() if t.getResult(): # HACK to incorporate 0 values score = str(int(t.getResult()) + int(score)) length += 1 except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info(ex_value) logger.debug(stack_trace) if score: inlinks = (int(score) / length) logger.debug('inlinks {}'.format(inlinks)) if inlinks == 0: # HACK because database and python take 0 as None inlinks = -1 return inlinks '''install phantomjs and have yslow.js in the path to execute''' def getPageloadtime(url): return url.getloadtime() # try: # response = os.popen('phantomjs yslow.js --info basic ' + # url.geturl()).read() # response = json.loads(response.split('\n')[1]) # return (int)(response['lt']) / ((int)(response['r'])) # except ValueError: # raise WebcredError('FAIL to load') # except: # raise WebcredError('Fatal error') def dimapi(url, api): # REVIEW try: uri = Urlattributes(api) raw = uri.gettext() # result = literal_eval(raw[1:-2]) return raw except WebcredError: raise WebcredError("Give valid API") except: return 'NA' <file_sep>import dotenv from flask import render_template from flask import request # from flask import jsonify from utils.databases import Features # from utils.essentials import app from utils.essentials import Database # from utils.essentials import WebcredError # from utils.webcred import Webcred import json import logging import os import requests import subprocess import time import threading import re import urllib.request from bs4 import BeautifulSoup import queue urls = queue.Queue(maxsize=40) ans = {} cnt = 0 class mythread (threading.Thread): def __init__(self,thread_id): threading.Thread.__init__(self) self.thread_id = thread_id # self.thread_url = thread_url def run(self): print ("Starting thread",self.thread_id) while not urls.empty(): threadLock.acquire() self.thread_url=urls.get() print (self.thread_id,urls.qsize()) threadLock.release() find_simi(self.thread_id,self.thread_url) print ("Finished thread",self.thread_id) def find_simi(thread_id,thread_url): print ("Running thread ",thread_id) ans[thread_url] = 1 try: domain = thread_url.split(':') domain.pop(0) thread_url = "https:" for i in domain: thread_url += i try: response = requests.get(thread_url, timeout=3) except: print ("aaaaaaaaaaaaaaa") pass soup = BeautifulSoup(response.text, "html.parser") body = soup.findAll('body') except: print (thread_url) pass # content = str(body[0]) # content = content.split('>') print ("Data sample from ",thread_id) dotenv.load_dotenv(dotenv_path='.env') logger = logging.getLogger('WEBCred.app') logging.basicConfig( filename='log/logging.log', filemode='a', format='[%(asctime)s] {%(name)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO ) if __name__ == "__main__": print ("assess") database = Database(Features) data = database.getdbdata() print (len(data)) j=0 for d in data: if j == 40: break urls.put(d['url']) j+=1 threadLock = threading.Lock() j=0 threads = [] while not urls.empty() and j<20: thread1 = mythread(j) threads.append(thread1) j+=1 thread1.start() for t in threads: t.join() print (len(ans))<file_sep>import threading from scipy import spatial import re import requests import urllib.request import time from bs4 import BeautifulSoup class mythread (threading.Thread): def __init__(self,thread_id,thread_url): threading.Thread.__init__(self) self.thread_id = thread_id self.thread_url = thread_url def run(self): print ("Starting thread",self.thread_id) find_simi(self.thread_id,self.thread_url) print ("Finished thread",self.thread_id) def find_simi(thread_id,thread_url): print ("Running thread ",thread_id) response = requests.get(thread_url) soup = BeautifulSoup(response.text, "html.parser") body = soup.findAll('body') content = str(body[0]) content = content.split('>') print ("Data sample from",thread_id,content[1]) urls = [] urls.append("https://radimrehurek.com/gensim/models/keyedvectors.html") urls.append("https://pypi.org/project/pronto/") urls.append("https://www.google.com/search?client=ubuntu&channel=fs&q=options+request+instead+of+post+request&ie=utf-8&oe=utf-8") urls.append("https://github.com/axios/axios/issues/475") urls.append("https://stackoverflow.com/questions/14908864/how-can-i-use-data-posted-from-ajax-in-flask") # print (urls) for i,url in enumerate(urls): thread1 = mythread(i,url) thread1.start() <file_sep>from bs4 import BeautifulSoup from datetime import datetime from html2text import html2text from urllib.parse import urlparse from utils.databases import Features from utils.essentials import Database from utils.essentials import WebcredError import arrow import copy import json import logging import re import requests import statistics import sys import threading import traceback import types import validators # logger = logging.getLogger('WEBCred.urls') # logging.basicConfig( # filename='log/logging.log', # filemode='a', # format='[%(asctime)s] {%(name)s:%(lineno)d} %(levelname)s - %(message)s', # datefmt='%m/%d/%Y %I:%M:%S %p', # level=logging.DEBUG # ) global patternMatching patternMatching = None # represents the normalized class of each dimension """ normalizedData[dimension_name].getscore(dimension_value) gives normalized_value """ global normalizedData normalizedData = None global lastmodMaxMonths # 3 months lastmodMaxMonths = 93 # define rules to normalize data global normalizeCategory normalizeCategory = { '3': { 'outlinks': 'reverse', 'inlinks': 'linear', 'ads': 'reverse', 'brokenlinks': 'reverse', # TODO relook at it's normalization 'pageloadtime': 'reverse', 'imgratio': 'linear' }, '2': { 'misspelled': { 0: 1, 'else': 0 }, 'responsive': { 'true': 1, 'false': 0, '0': 0, '1': 1, }, 'langcount': { 1: 0, 'else': 1 }, 'domain': { 'gov': 1, 'org': 0, 'edu': 1, 'com': 0, 'net': 0, 'else': -1 }, "lastmod": { lastmodMaxMonths: 1, 'else': 0, }, }, 'misc': { 'hyperlinks': "linear" }, } # A class for pattern matching using re lib class PatternMatching(object): def __init__(self, lang_iso=None, ads_list=None): if lang_iso: try: iso = open(lang_iso, "r") self.isoList = iso.read().split() isoList = [] for code in self.isoList: # isoList.pop(iso) isoList.append(str('=' + code)) isoList.append(str('="' + code + '"')) self.isoList = isoList self.isoPattern = self.regexCompile(self.isoList) iso.close() except WebcredError as e: raise WebcredError(e.message) except: raise WebcredError('Unable to open {} file'.format(lang_iso)) else: logger.debug('Provide Language iso file') if ads_list: try: ads = open(ads_list, "r") self.adsList = ads.read().split() self.adsPattern = self.regexCompile(self.adsList) ads.close() print ('successfull with ads compilation') except WebcredError as e: raise WebcredError(e.message) except: raise WebcredError('Unable to open {} file'.format(ads_list)) else: logger.debug('Provide a good ads list') def getIsoList(self): return self.isoList def getAdsList(self): return self.adsList def getAdsPattern(self): return self.adsPattern def getIsoPattern(self): return self.isoPattern def regexCompile(self, data=None): if not data: raise WebcredError('Provide data to compile') pattern = [] for element in data: temp = re.compile(re.escape(element), re.X) pattern.append(temp) return pattern def regexMatch(self, pattern=None, data=None): if not pattern: raise WebcredError('Provide regex pattern') if not data: raise WebcredError('Provide data to match with pattern') for element in pattern: match = element.search(data) if match: break if match: return True, element.pattern else: return False, None # A class to get normalized score for given value based on collectData class Normalize(object): # data = json_List # name =parameter to score def __init__(self, data=None, name=None): if not data or not name: raise WebcredError('Need 3 args, 2 pass') self.reverse = self.dataList = self.mean = self.deviation = None self.factorise = None self.data = data self.name = name[0] if isinstance(name[1], str): if name[1] == 'reverse': self.reverse = True elif isinstance(name[1], dict): self.factorise = name[1] def getdatalist(self): if not self.dataList: dataList = [] NumberTypes = ( # types.IntType, types.LongType, types.FloatType, types.ComplexType #python 2 int, float, complex #python 3 ) for element in self.data: if element.get(self.name) and isinstance(element[self.name], NumberTypes): # # done for decimal values like 0.23 # if isinstance(element[self.name], float): # element[self.name] = int(element[self.name]*1000000) dataList.append(element[self.name]) self.dataList = dataList # print self.dataList return self.dataList def normalize(self): NumberTypes = ( # types.IntType, types.LongType, types.FloatType, types.ComplexType #python 2 int, float, complex #python 3 ) for index in range(len(self.data)): if isinstance(self.data[index].get(self.name), NumberTypes): self.data[index][self.name] = self.getscore( self.data[index][self.name] ) return self.data def getnormalizedScore(self, value): NumberTypes = ( # types.IntType, types.LongType, types.FloatType, types.ComplexType #python 2 int, float, complex #python 3 ) if isinstance(value, NumberTypes): return self.getscore(value) # case when dimension value throws error # 0 because it neither add nor reduces credibility return 0 def getdata(self): return self.data def getmean(self): if not self.mean: self.mean = statistics.mean(self.getdatalist()) print ("mean=", self.mean, self.name) return self.mean def getdeviation(self): if not self.deviation: self.deviation = statistics.pstdev(self.getdatalist()) print ("deviation=", self.deviation, self.name) return self.deviation def getscore(self, value): mean = self.getmean() deviation = self.getdeviation() """ sometimes mean<deviation and surpass good results, as no value is less than 0 """ netmd = mean - deviation if netmd < 0: netmd = 0 if value <= (netmd): if self.reverse: return 1 return -1 else: if value >= (mean + deviation): if self.reverse: return -1 return 1 return 0 def getfactoise(self, value): global lastmodMaxMonths # condition for lastmod if self.name == "lastmod": value = self.getDateDifference(value) if value < lastmodMaxMonths: return self.factorise.get(lastmodMaxMonths) # condition for everthing else else: for k, v in self.factorise.items(): if str(value) == str(k): return v if 'else' in self.factorise.keys(): return self.factorise.get('else') # return dayDiffernce form now and value def getDateDifference(self, value): try: # strptime = string parse time # strftime = string format time try: lastmod = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S').date() except: lastmod = arrow.get(value).datetime.date() dayDiffernce = (datetime.now().date() - lastmod).days return dayDiffernce except: # in case of ValueError, lastmod will sum to WEBcred Score return 100000 def factoise(self): if not self.factorise: raise WebcredError('Provide attr to factorise') global lastmodMaxMonths for index in range(len(self.data)): if self.data[index].get(self.name): modified = 0 # condition for lastmod if self.name == "lastmod": value = self.data[index][self.name] value = self.getDateDifference(value) if value < lastmodMaxMonths: self.data[index][ self.name ] = self.factorise.get(lastmodMaxMonths) modified = 1 # condition for everything else else: value = self.data[index][self.name] for k, v in self.factorise.items(): if str(value) == str(k): self.data[index][self.name] = v modified = 1 if not modified: if 'else' in self.factorise.keys(): self.data[index][self.name ] = self.factorise.get('else') return self.data # A class to use extract url attributes class Urlattributes(object): # HACK come back and do this properly try: # TODO fetch ads list dynamically from org if not patternMatching: patternMatching = PatternMatching( lang_iso='data/essentials/lang_iso.txt', ads_list='data/essentials/easylist.txt' ) print ('end patternMatching') global normalizedData global normalizeCategory if not normalizedData: normalizedData = {} # read existing data old_data = 'data/json/data2.json' old_data = open(old_data, 'r').read() old_data = old_data.split('\n') new_data = 'data/json/new_data.json' new_data = open(new_data, 'r').read() new_data = new_data.split('\n') re_data = 'data/json/re_data.json' re_data = open(re_data, 'r').read() re_data = re_data.split('\n') # list with string/buffer as values file_ = list(set(new_data + old_data + re_data)) # final json_List of data data = [] for element in file_[:-1]: try: metadata = json.loads(str(element)) # if metadata.get('redirected'): # url = metadata['redirected'] # else: # url = metadata['Url'] # obj = utils.Domain(url) # url = obj.getnetloc() # metadata['domain_similarity'] = scorefile_data.get(url) except: continue if metadata.get('Error'): continue data.append(metadata) # get data from postgres db = Database(Features) data = db.getdbdata() it = normalizeCategory['3'].items() for k in it: normalizedData[k[0]] = Normalize(data, k) data = normalizedData[k[0]].normalize() it = normalizeCategory['misc'].items() for k in it: tmp_it = k[0] it = tmp_it # summation of hyperlinks_attribute values for index in range(len(data)): if data[index].get(it[0]): sum_hyperlinks_attributes = 0 tempData = data[index].get(it[0]) try: for k, v in tempData.items(): sum_hyperlinks_attributes += v except: # TimeOut error clause pass finally: data[index][it[0]] = sum_hyperlinks_attributes normalizedData[it[0]] = Normalize(data, it) data = normalizedData[it[0]].normalize() for k in normalizeCategory['2'].items(): print ("normalizing", k) normalizedData[k[0]] = Normalize(data, k) data = normalizedData[k[0]].factoise() # csv_filename = 'analysis/WebcredNormalized.csv' # # pipe = Pipeline() # csv = pipe.convertjson(data) # f = open(csv_filename,'w') # f.write(csv) # f.close() except WebcredError as e: # raise WebcredError(e.message) pass def __init__(self, url=None): # print 'here' if patternMatching: self.patternMatching = patternMatching self.hdr = {'User-Agent': 'Mozilla/5.0'} self.requests = self.urllibreq = self.soup = self.text = None self.netloc = self.header = self.lastmod = self.size = \ self.html = self.domain = self.loadTime = None self.lock = threading.Lock() if url: if not validators.url(url): raise WebcredError('Provide a valid url') self.url = url self.originalUrl = copy.deepcopy(url) # case of redirections resp = self.getrequests() if resp.status_code / 100 >= 4: raise WebcredError('Response 202') self.url = resp.url else: raise WebcredError('Provide a url') def getloadtime(self): return self.loadTime def getoriginalurl(self): return self.originalUrl def getjson(self): return self.getrequests().json() def geturl(self): return self.url def gethdr(self): return self.hdr def getheader(self): if not self.header: self.header = self.geturllibreq().headers return self.header def getrequests(self): if not self.requests: self.requests = self.geturllibreq() return self.requests def geturllibreq(self): # with self.lock: if not self.urllibreq: try: now = datetime.now() self.urllibreq = requests.get(url=self.url, headers=self.hdr) self.loadTime = int((datetime.now() - now).total_seconds()) except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) raise WebcredError(ex_value) # logger.info(stack_trace) # HACK if it's not webcred error, # then probably it's python error # print self.urllibreq.geturl() return self.urllibreq def clean_html(self, html): """ Copied from NLTK package. Remove HTML markup from the given string. :param html: the HTML string to be cleaned :type html: str :rtype: str """ # First we remove inline JavaScript/CSS: cleaned = re.sub( r"(?is)<(script|style).*?>.*?(</\1>)", "", html.strip() ) # Then we remove html comments. # This has to be done before removing regular # tags since comments can contain '>' characters. cleaned = re.sub(r"(?s)<!--(.*?)-->[\n]?", "", cleaned) # Next we can remove the remaining tags: cleaned = re.sub(r"(?s)<.*?>", " ", cleaned) # Finally, we deal with whitespace cleaned = re.sub(r"&nbsp;", " ", cleaned) cleaned = re.sub(r" ", " ", cleaned) cleaned = re.sub(r" ", " ", cleaned) return cleaned.strip() def gettext(self): if not self.text: text = self.gethtml() text = self.clean_html(text) self.text = html2text(text) return self.text def gethtml(self): if not self.html: self.html = self.getrequests().text return self.html def getsoup(self, parser='html.parser'): data = self.getrequests().text try: self.soup = BeautifulSoup(data, parser) except: raise WebcredError('Error while parsing using bs4') return self.soup def getnetloc(self): if not self.netloc: try: parsed_uri = urlparse(self.geturl()) self.netloc = '{uri.netloc}'.format(uri=parsed_uri) except: logger.debug('Error while fetching attributes from parsed_uri') return self.netloc def getdomain(self): if not self.domain: try: netloc = self.getnetloc() self.domain = netloc.split('.')[-1] except: raise WebcredError('provided {} not valid'.format(netloc)) return self.domain def getPatternObj(self): try: return self.patternMatching except: raise WebcredError('Pattern Obj is NA') # self.isoList = def getsize(self): if not self.size: t = self.gettext() try: self.size = len(t) except: raise WebcredError('error in retrieving length') return self.size def getlastmod(self): if self.lastmod: return self.lastmod try: data = None # fetching data form archive for i in range(15): uri = "http://archive.org/wayback/available?url=" + \ self.geturl() uri = Urlattributes(uri) resp = uri.geturllibreq() if resp.status_code / 100 < 4: resp = resp.json() try: data = arrow.get( resp['archived_snapshots']['closest']['timestamp'], 'YYYYMMDDHHmmss' ).timestamp except: data = str(0) if data: self.lastmod = int(data) break # if not data: # resp = self.geturllibreq() # lastmod = str(resp.headers.getdate('Date')) # 'Mon, 09 Jul 2018 07:29:16 GMT' # Error z directive is bad format # lastmod = datetime.strptime( # str(lastmod), '(%a, %d %b %Y %H:%M:%S %z)' # ) # lastmod = datetime.strptime( # we.headers.get('Date'), '(%a, %d %b %Y %H:%M:%S %z)' # ) # str(lastmod), '(%Y, %m, %d, %H, %M, %S, %f, %W, %U)' # ) # self.lastmod = lastmod.isoformat() except Exception: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]) ) # print("Exception type : %s " % ex_type.__name__) logger.info(ex_value) logger.debug(stack_trace) self.lastmod = None return self.lastmod def freemem(self): del self
6ce52c7d9ec42712445b763bf3e8751929b5b926
[ "Python", "HTML" ]
10
Python
abhishek8899/Relevance-Credibility-NLP
900571d51fc4b6902fd9945e94a53d25493754df
c5bcfeff9f341b96ee4789f4791c1e6c53172c62
refs/heads/main
<repo_name>besiobu/cryptocollector<file_sep>/cryptocollector/cfg/config.py # Logger settings LOG_FORMAT = '%(asctime)s.%(msecs)03d | %(levelname)10s | %(module)25s | %(funcName)25s | %(message)s' DATE_FORMAT = '%Y-%m-%d %H:%M:%S' # Coinbase settings COINBASE_CFG = { 'url': 'wss://ws-feed.pro.coinbase.com', 'channels': {'trades': 'matches', 'heartbeat': 'heartbeat'}, 'symbols': ['BTC-USD', 'BTC-EUR', 'BTC-GBP', 'LTC-USD', 'LTC-EUR', 'LTC-GBP', 'ETH-USD', 'ETH-EUR', 'ETH-GBP', 'ETH-BTC', 'LTC-BTC'], 'storage': 'sqlserver', 'table': '[staging].[coinbase]' } # Bitmex settings BITMEX_CFG = { 'url': 'wss://www.bitmex.com/realtime', 'channels': {'trades': 'trade'}, 'symbols': ['XBTUSD', 'LTCUSD', 'ETHUSD'], 'storage': 'sqlserver', 'table': '[staging].[bitmex]' } # SQL Server settings SQL_CFG = { 'driver': 'SQL Server', 'server': r'DESKTOP-62E4RH1', 'database': 'crypto_dev', 'user': 'PythonScript', 'password': r'<PASSWORD>', 'table': None, 'data_dir': r"C:/Users/Programista/Desktop/crypto_dwh/data" }<file_sep>/setup.py from pathlib import Path Path('data').mkdir(parents=True, exist_ok=True)<file_sep>/cryptocollector/persistance/persistor.py class Persistor(object): """ Base class for persistance objects. """ def __init__(self): self.name = None def write(self, msg): pass<file_sep>/cryptocollector/websocket/websocket_monitor.py import time import logging from threading import Thread from cryptocollector.utils.utils import setup_logger logger = setup_logger(name=__name__) class WebsocketMonitor(Thread): """ A class to monitor the websocket class. """ def __init__(self, ws, time_recv, stop, timeout=15, wait=15): super().__init__() self.ws = ws self.time_recv = time_recv self.stop = stop self.timeout = timeout self.wait = wait self._count_chk = 0 def run(self): """ Monitor thread to keep connection alive. Notes ----- If there is no new message from the websocket send ping every `timeout` seconds and wait `wait` seconds between checking if new messages were received. """ logger.info(f'Monitor is starting.') try: while not self.stop.is_set(): if self.time_recv is not None: if time.time() - self.time_recv >= self.timeout: logger.warn(f'Monitor sending ping.') self.ws.ping('ping') logger.info('Monitor waiting.') time.sleep(self.wait) else: logger.warn(f'Monitor is stopping.') pass except KeyboardInterrupt: self.stop.set() return <file_sep>/cryptocollector/utils/utils.py import logging from cryptocollector.cfg.config import DATE_FORMAT, LOG_FORMAT def setup_logger(name, level=logging.INFO): """ Setup logging. Parameters ---------- name : str Name of module. level : int Level of logging. """ logger = logging.getLogger(name) logger.setLevel(level) formatter = logging.Formatter( fmt=LOG_FORMAT, datefmt=DATE_FORMAT) sh = logging.StreamHandler() sh.setLevel(level) sh.setFormatter(formatter) logger.addHandler(sh) return logger<file_sep>/cryptocollector/exchange/bitmex.py import json from cryptocollector.exchange.exchange_feed import ExchangeFeed from cryptocollector.utils.utils import setup_logger logger = setup_logger(name=__name__) class Bitmex(ExchangeFeed): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = type(self).__name__ + '_feed' def on_open(self): symbols = list(map(lambda x: 'trade:' + str(x), self.symbols)) sub_msg = {'op': 'subscribe', 'args': symbols} self.ws.send(json.dumps(sub_msg)) def on_message(self, msg): if 'table' in msg and 'action' in msg: if msg['table'] == 'trade' and msg['action'] == 'insert': self.__handler_trade_insert(msg) else: pass elif 'subscribe' in msg: if msg['success'] == True: logger.info(f'Subscribed to {msg["subscribe"]}.') else: logger.info(f'Subscription failed.') elif 'error' in msg: for k,v in msg.items(): logger.info(f'{k}: {v}') else: for k,v in msg.items(): logger.info(f'{k}: {v}') def __handler_trade_insert(self, msg): """ Handle trade insert messages. Notes ----- This is an example message from the exchanges documentation. {'table': 'trade', 'action': 'insert', 'data': [{'timestamp': '2019-11-05T08:09:26.587Z', 'symbol': 'XBTZ19', 'side': 'Sell', 'size': 2000, 'price': 9386.5, 'tickDirection': 'ZeroPlusTick', 'trdMatchID': '48405459-36fc-6eea-87a6-8139753927aa', 'grossValue': 21308000, 'homeNotional': 0.21308, 'foreignNotional': 2000}]} """ for trade in msg['data']: self.persistance.write(msg=trade) <file_sep>/cryptocollector/exchange/feeds.py from cryptocollector.exchange.coinbase import Coinbase from cryptocollector.exchange.bitmex import Bitmex from cryptocollector.cfg.config import COINBASE_CFG, BITMEX_CFG class Feeds(object): def __init__(self): pass @staticmethod def coinbase(): return Coinbase(**COINBASE_CFG) @staticmethod def bitmex(): return Bitmex(**BITMEX_CFG) <file_sep>/cryptocollector/persistance/sqlserver.py import time import urllib import datetime from json import dump from random import randint from sqlalchemy import create_engine from cryptocollector.persistance.persistor import Persistor from cryptocollector.utils.utils import setup_logger logger = setup_logger(name=__name__) class SqlServer(Persistor): """ A class to persist messages to SQL Server database. """ def __init__(self, driver, server, database, user, password, table, data_dir): """ Parameters ---------- database : str Name of SQL Server database. driver : str Microsoft driver. user : str SQL Server user with data writer permissions. password : str SQL Server user password. server : str _name of SQL Server server. data_dir : str Path to use if write to database fails. Notes ------ Inputs must make a valid connection string. """ super().__init__() self.driver = driver self.server = server self.database = database self.user = user self.password = <PASSWORD> self.table = table self.data_dir = data_dir self.engine = self.__make_engine() def __del__(self): if self.engine is not None: logger.warn('Disposing of connection pool.') try: self.engine.dispose() except KeyError as e: logger.warn(e) def __make_engine(self): """ Create SQL Server engine. """ conn_string = self.__create_conn_string() # logger.info(f'connection string: {conn_string}.') logger.info(f'Will write to database: {self.database}.') logger.info(f'Will write to table: {self.table}.') engine = create_engine(conn_string) return engine def __create_conn_string(self): """ Create connection string to sql server. """ conn_params = 'DRIVER={' + self.driver +'};' conn_params += 'SERVER=' + self.server + ';' conn_params += 'DATABASE=' + self.database + ';' conn_params += 'UID=' + self.user + ';' conn_params += 'PWD=' + self.password conn_params = urllib.parse.quote_plus(conn_params) conn_string = f'mssql+pyodbc:///?odbc_connect={conn_params}' return conn_string def write(self, msg): """ Persist message from websocket. Parameters ---------- msg : dict Message from exchange. table : str name of table in database. Notes ----- 1. Try to write to sql database. 2. In case of error write to json on disk. """ try: self._write_msg_to_db(msg=msg) except Exception as e: logger.critical(e) try: self._write_msg_to_json(msg=msg) except Exception as e: logger.critical(e) def _write_msg_to_db(self, msg): """ Write message from websocket to database. Parameters ---------- msg : dict Message from exchange. table : str name of table in database. Notes ----- The messages from the websocket a received as dictionaries and are converted into a `INSERT INTO (cols) VALUES (values)` transact sql query. """ msg['timestamp_script'] = str(datetime.datetime.now()) columns = list() values = list() for k,v in msg.items(): columns.append(str(k)) values.append("'" + str(v) + "'") columns = ', '.join(columns) values = ', '.join(values) query = f""" INSERT INTO {self.table} ({columns}) VALUES ({values}) """ self.engine.execute(query) def _write_msg_to_json(self, msg): """ Write message from websocket to json. Parameters ---------- msg : dict Message from exchange. """ path = self.__make_path_file() with open(path, 'w') as f: dump(msg, f) def __make_path_file(self): """ Create path to file. Notes ----- The file name is constructed in 3 steps: 1. The name of the table. 2. A unix timestamp with milisecond precision. 3. A random integer to minimize collisions. """ table = self.table.replace('.', '') path = f'{self.data_dir}/{table}_' path += f'{str(int(time.time() * 1000))}_' path += f'{str(randint(1, 10 ** 6))}.txt' return path <file_sep>/cryptocollector/websocket/websocket_client.py import json import time from threading import Event, Thread from cryptocollector.utils.utils import setup_logger from cryptocollector.websocket.websocket_monitor import WebsocketMonitor from websocket import create_connection logger = setup_logger(name=__name__) class WebsocketClient(Thread): """ A websocket class. """ def __init__(self, url, timeout=60): """ Inputs: ------ url : str The url of the websocket. timeout : int The websocket connection timeout in seconds. """ super().__init__() self.url = url self.timeout = timeout self.stop = Event() self.name = None self._count_msg = 0 self._time_recv = None self.monitor = None self.ws = None def run(self): while not self.stop.is_set(): self.__go() else: return def __go(self): try: self.connect() self.listen() except Exception as e: self.stop.set() logger.critical(repr(e)) try: self.disconnect() except Exception as e: logger.critical(repr(e)) def __stop(self): """ Disconnect from websocket and stop monitor thread. """ try: self.disconnect() except Exception as e: logger.critical(repr(e)) try: self.monitor.join() except Exception as e: logger.critical(repr(e)) def connect(self): """ Connect to websocket. """ logger.info(f'{self.name} is connecting to: {self.url}') self.ws = create_connection(self.url, timeout=self.timeout) self.on_open() def listen(self): """ Receive new messages from websocket. """ self.monitor = WebsocketMonitor(ws=self.ws, time_recv=self._time_recv, stop=self.stop) self.monitor.daemon = True self.monitor.start() while not self.stop.is_set(): try: data = self.ws.recv() self._time_recv = time.time() msg = json.loads(data) self.on_message(msg) self._count_msg += 1 if self._count_msg % 100 == 0: logger.info(f'Received {self._count_msg} messages.') except Exception as e: self.stop.set() self.on_error(e) logger.critical(repr(e)) self.monitor.join() def disconnect(self): """ Disconnect from websocket. """ if self.ws: self.ws.close() logger.warn('Disconnected.') def on_open(self): """ Called upon initialization of connection. Notes ----- In the derived class this method should send a subscription message to the exchange. """ pass def on_message(self, msg): """ Called upon receipt of message Inputs ------ msg : dict The message from the exchange. Notes ----- In the derived class this method should parse the message and save it to storage. """ pass def on_error(self, error): """ Called when error occurs. Notes ----- After error disconnect from websocket. """ self.disconnect() def on_close(self): """ Called when the websocket connection closes. """ logger.warn('Websocket closed.')<file_sep>/README.md # cryptocollector ![image](https://github.com/besiobu/cryptocollector/blob/main/img/xbt_report.PNG) A simple python module to collect trades from cryptocurrency exchanges. ## Features * Persistance: Messages are written directly to staging area in database. * Exception handling: if a write fails the message from exchange is saved to `json`. * Timestamping: Each message is timestamped by the script before persisting to database. * Run forever: Script to automatically reconnect to exchange websocket. * Logging: Handled by Python's logging module. ## Supported exchanges * Coinbase * Bitmex * `more coming` ## Prerequisites This module is requires SQL Server to be setup with the database solution available [here](https://github.com/besiobu/cryptocollector_db). ## Getting Started Clone this repository and run: ``` python3 setup.py ``` ## Installing Install requirements: ``` pip3 install -r requirements.txt ``` ## Usage To connect to a websocket run: ``` python3 run_forever.py <name of exchange> ``` The script will run in an endless loop and will reconnect in case of any trouble. ## Authors * **<NAME>** - *Initial work* - [besiobu](https://github.com/besiobu) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details<file_sep>/cryptocollector/exchange/exchange_feed.py from cryptocollector.cfg.config import SQL_CFG from cryptocollector.persistance.sqlserver import SqlServer from cryptocollector.websocket.websocket_client import WebsocketClient class ExchangeFeed(WebsocketClient): """ A class to create exchange feeds. """ def __init__(self, url, storage, channels, symbols, *args, **kwargs): """ Parameters ---------- url : str The url of the websocket. storage : str The type of storage to use. channels : dict The channels the websocket will subscribe to. symbols : list of str Symbols the weboscket will subscribe to. """ super().__init__(url=url) self.channels = channels self.symbols = symbols self.storage = storage self.table = None if storage == 'sqlserver': self.storage = storage if 'table' in kwargs: self.table = kwargs['table'] SQL_CFG['table'] = self.table else: raise RuntimeError(f'Table not specified.') self.persistance = SqlServer(**SQL_CFG) else: raise ValueError(f'{storage} is not supported.') <file_sep>/requirements.txt astroid==2.4.2 colorama==0.4.3 isort==5.6.1 lazy-object-proxy==1.4.3 mccabe==0.6.1 pylint==2.6.0 pyodbc==4.0.30 six==1.15.0 SQLAlchemy==1.3.19 toml==0.10.1 websocket-client==0.57.0 wrapt==1.12.1 <file_sep>/run_forever.py import sys import time from cryptocollector.exchange.feeds import Feeds from cryptocollector.utils.utils import setup_logger logger = setup_logger(name=__name__) def run_forever(exchange_name, delay=2): """ Keep connecting to exchange websocket. """ def run_once(): """ Connect to exchange websocket. """ feed = Feeds() try: # Get exchange feed. exchange = getattr(feed, exchange_name)() except Exception: print(f'{sys.argv[1]} is not supported.') return exchange.daemon = True exchange.start() try: # Run until exchange feed stops. while not exchange.stop.is_set(): time.sleep(delay) else: if exchange.monitor is not None: exchange.monitor.join() exchange.join() except KeyboardInterrupt as e: logger.critical(repr(e)) # Stop threads and close db connection exchange.stop.set() if exchange.monitor is not None: exchange.monitor.join() exchange.join() return True stop = False while not stop: try: logger.info('Started.') stop = run_once() except KeyboardInterrupt as e: logger.critical(repr(e)) stop = True time.sleep(delay) logger.info('Stopped.') if __name__ == '__main__': run_forever(sys.argv[1])<file_sep>/cryptocollector/exchange/coinbase.py import json from cryptocollector.exchange.exchange_feed import ExchangeFeed from cryptocollector.utils.utils import setup_logger logger = setup_logger(name=__name__) class Coinbase(ExchangeFeed): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = type(self).__name__ + '_feed' self.sequences = {} def on_open(self): sub_msg = {'type': 'subscribe', 'product_ids': self.symbols, 'channels': ['matches']} self.ws.send(json.dumps(sub_msg)) def on_message(self, msg): msg_type = msg["type"] if msg_type == "match": self.__handler_match(msg) elif msg_type == "last_match": logger.info(f"Ignoring {msg_type} message.") elif msg_type == "error": logger.info(f'Received error message {msg["message"]}.') elif msg_type == "subscriptions": self.__handler_subscriptions(msg) elif msg_type == "heartbeat": self.__heartbeat_handler(msg) else: logger.info(f'Received unsupported message {msg_type}.') def __handler_subscriptions(self, msg): """ Hanlde subscription messages. Notes ----- This is an example message from the exchanges documentation. { "type": "subscriptions", "channels": [ { "name": "level2", "product_ids": [ "ETH-USD", "ETH-EUR" ], }, { "name": "heartbeat", "product_ids": [ "ETH-USD", "ETH-EUR" ], }, { "name": "ticker", "product_ids": [ "ETH-USD", "ETH-EUR", "ETH-BTC" ] } ] } """ for ch in msg['channels']: for product in ch['product_ids']: channel = ch['name'] logger.info(f'subscribed to {channel} for {product}') def __heartbeat_handler(self, msg): """ Handle heartbeat messages. Notes ----- This is an example message from the exchanges documentation. { "type": "heartbeat", "sequence": 90, "last_trade_id": 20, "product_id": "BTC-USD", "time": "2014-11-07T08:19:28.464459Z" } """ self.sequences[msg['product_id']] = {"seq": int(msg['sequence']), "tid": int(msg['last_trade_id'])} def __handler_match(self, msg): """ Handle match (trade) messages. Notes ----- This is an example message from the exchanges documentation. { "type": "match", "trade_id": 10, "sequence": 50, "maker_order_id": "ac928c66-ca53-498f-9c13-a110027a60e8", "taker_order_id": "132fb6ae-456b-4654-b4e0-d681ac05cea1", "time": "2014-11-07T08:19:27.028459Z", "product_id": "BTC-USD", "size": "5.23512", "price": "400.23", "side": "sell" } """ self.persistance.write(msg=msg)
77425fabb59523684b53e899dee0765a0077ee89
[ "Markdown", "Python", "Text" ]
14
Python
besiobu/cryptocollector
7886ff5d4a6e9961f65a3dad121e7496e0b74d47
60ed5972330cdb33611ba849241a96f523fd1e69
refs/heads/main
<repo_name>nsantos16/bcu-cloudflare-worker<file_sep>/src/handler.ts interface BcuResponseCotizaciones { ArbAct: number CodigoISO: string Emisor: string Fecha: string FormaArbitrar: number Moneda: number Nombre: string TCC: number TCV: number } interface BcuResponseStatus { status: number codigoError: number mensaje: string } interface BcuResponseList { Moneda: null | string RespuestaStatus: BcuResponseStatus Cotizaciones: BcuResponseCotizaciones[] } interface BcuResponse { operation: string cotizacionesoutlist: BcuResponseList } const BCU_ENDPOINT = 'https://www.bcu.gub.uy/_layouts/15/BCU.Cotizaciones/handler/CotizacionesHandler.ashx?op=getcotizaciones' export async function handleRequest(request: Request): Promise<Response> { const data = await request.json(); const res = await fetch(BCU_ENDPOINT, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ KeyValuePairs: { Monedas: [{ Val: '2225', Text: 'DLS. USA BILLETE' }], FechaDesde: data.date, FechaHasta: data.date, Grupo: '2', }, }), }) const response: BcuResponse = await res.json(); return new Response(JSON.stringify(response.cotizacionesoutlist.Cotizaciones[0]["TCV"]), { headers: { 'Content-Type': 'application/json' }, }) } <file_sep>/wrangler.toml name = "bcu-exchange" type = "javascript" zone_id = "" account_id = "<KEY>" route = "" workers_dev = true compatibility_date = "2021-09-19" [build] command = "npm install && npm run build" [build.upload] format = "service-worker" [env.production] route="/bcu"
9c439e460a3e5db27d3b8f67e6b673712a237bb6
[ "TOML", "TypeScript" ]
2
TypeScript
nsantos16/bcu-cloudflare-worker
6b06fa7f253118915fddc62339170dbbbacc98d7
7018ad0bdea4f808305f90be6ce6080ffd64528c
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: caoych * Date: 2017/2/12 * Time: 15:30 */ namespace CAO\TvSeriesBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Tv Series * * @author <NAME> <EMAIL> * * @package TvSeriesBundle\Entity * * @ORM\Entity * */ class TvSeries { /** * @var string * @ORM\Id() * @ORM\Column(type="guid", nullable=false) * @ORM\GeneratedValue(strategy="UUID") */ private $id; /** * @var string * @ORM\Column(type="string", nullable=false) */ private $name; /** * @var string * @ORM\Column(nullable=true) */ private $author; /** * @var \DateTimeInterface * @ORM\Column(type="datetime", nullable=true) */ private $releaseAt; /** * @var string * @ORM\Column(type="string", nullable=true) */ private $description; /** * @var string * @ORM\Column(type="string", nullable=true) * @Assert\File(mimeTypes={"image/*"}) */ private $image; /** * @return string */ public function getId() { return $this->id; } /** * @param string $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getAuthor() { return $this->author; } /** * @param string $author */ public function setAuthor($author) { $this->author = $author; } /** * @return \DateTimeInterface */ public function getReleaseAt() { return $this->releaseAt; } /** * @param \DateTimeInterface $releaseAt */ public function setReleaseAt($releaseAt) { $this->releaseAt = $releaseAt; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * @return string */ public function getImage() { return $this->image; } /** * @param string $image */ public function setImage($image) { $this->image = $image; } } <file_sep><?php /** * Created by PhpStorm. * User: caoych * Date: 2017/2/28 * Time: 14:09 */ namespace CAO\TvSeriesBundle\Form; use CAO\TvSeriesBundle\Entity\Episode; use CAO\TvSeriesBundle\Entity\User; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class UserEpisodeType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('current', IntegerType::class) ->add('watechedAt', DateType::class) ->add('episode', EntityType::class, array( 'class' => Episode::class, 'choice_label' => 'id' )) ->add('user', EntityType::class, array( 'class' => User::class, 'choice_label' => 'id' )) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'CAO\TvSeriesBundle\Entity\UserEpisode' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'cao_tvseriesbundle_userepisode'; } }<file_sep><?php namespace CAO\TvSeriesBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class TvSeriesType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', TextType::class) ->add('author', TextType::class) ->add('releaseAt', DateType::class) ->add('description', TextType::class) ->add('image', FileType::class, array( 'label' => 'Image (optional)', 'required' => false )) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'CAO\TvSeriesBundle\Entity\TvSeries' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'cao_tvseriesbundle_tvseries'; } } <file_sep><?php namespace CAO\TvSeriesBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Episode * * @author <NAME> <EMAIL> * * @package TvSeriesBundle\Entity * * @ORM\Entity * */ class Episode { /** * @var string * * @ORM\Id() * @ORM\Column(type="guid", nullable=false) * @ORM\GeneratedValue(strategy="UUID") */ private $id; /** * @var string * @ORM\Column(type="string", nullable=true) * */ private $name; /** * @var int * @ORM\Column(type="integer", nullable=true) * */ private $episodeNumber; /** @var \DateTimeInterface * * @ORM\Column(type="datetime", nullable=true) */ private $datePublished; /** @var string * * @ORM\Column(type="string", nullable=true) */ private $description; /** * @var string * @ORM\Column(type="string", nullable=true) * @Assert\File(mimeTypes={"image/*"}) */ private $image; /** * @return string */ public function getId() { return $this->id; } /** * @param string $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return int */ public function getEpisodeNumber() { return $this->episodeNumber; } /** * @param int $episodeNumber */ public function setEpisodeNumber($episodeNumber) { $this->episodeNumber = $episodeNumber; } /** * @return \DateTimeInterface */ public function getDatePublished() { return $this->datePublished; } /** * @param \DateTimeInterface $datePublished */ public function setDatePublished($datePublished) { $this->datePublished = $datePublished; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * @return string */ public function getImage() { return $this->image; } /** * @param string $image */ public function setImage($image) { $this->image = $image; } /** * @return mixed */ public function getTvSeries() { return $this->tvSeries; } /** * @param mixed $tvSeries */ public function setTvSeries($tvSeries) { $this->tvSeries = $tvSeries; } /** * Many Episodes have one TvSeries. * @ORM\ManyToOne(targetEntity="CAO\TvSeriesBundle\Entity\TvSeries") * @ORM\JoinColumn(name="tvSeriesId",referencedColumnName="id") */ private $tvSeries; } <file_sep><?php namespace CAO\TvSeriesBundle\Controller; use CAO\TvSeriesBundle\Entity\Episode; use CAO\TvSeriesBundle\Entity\UserEpisode; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request; use Doctrine\ORM\Tools\Pagination\Paginator; /** * Episode controller. * * @Route("/episode") */ class EpisodeController extends Controller { /** * Lists all episode entities. * @Route("/", name="admin_episode_index") * @Route("/{page}", name="episode_with_paginator", requirements={"page": "\d+"}) * @Method("GET") */ public function indexAction($page=1) { $em = $this->getDoctrine()->getManager(); // $episodes = $em->getRepository('CAOTvSeriesBundle:Episode')->findAll(); $limit = 5; $offset = ($page-1) * $limit; $dql ="SELECT e FROM CAOTvSeriesBundle:Episode e ORDER BY e.name ASC"; $query = $em->createQuery($dql) ->setFirstResult($offset) ->setMaxResults($limit) ; $paginator = new Paginator($query); return $this->render('CAOTvSeriesBundle:episode:index.html.twig', array( // 'episodes' => $episodes, 'totalPages' => (int) ceil($paginator->count() / $limit), 'currentPage' => $page, 'paginator' => $paginator, )); } /** * Creates a new episode entity. * * @Route("/new", name="admin_episode_new") * @Method({"GET", "POST"}) * @Security("has_role('ROLE_ADMIN')") */ public function newAction(Request $request) { $episode = new Episode(); $form = $this->createForm('CAO\TvSeriesBundle\Form\EpisodeType', $episode); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // deal with the image. $image = $episode->getImage(); if ($image != NULL) { $imageName = md5(uniqid()).'.'.$image->guessExtension(); $image->move( $this->getParameter('image_directory'), $imageName ); $episode->setImage($imageName); } $em = $this->getDoctrine()->getManager(); $em->persist($episode); $em->flush($episode); return $this->redirectToRoute('admin_episode_show', array('id' => $episode->getId())); } return $this->render('CAOTvSeriesBundle:episode:new.html.twig', array( 'episode' => $episode, 'form' => $form->createView(), )); } /** * Finds and displays a episode entity. * * @Route("/{id}", name="admin_episode_show") * @Method("GET") */ public function showAction(Episode $episode) { $deleteForm = $this->createDeleteForm($episode); $userEpisode = array(); if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) { $userEpisode = $this->getDoctrine() ->getManager() ->getRepository("CAOTvSeriesBundle:UserEpisode") ->findBy(array( 'user' => $this->get('security.token_storage')->getToken()->getUser(), 'episode' => $episode )) ; } return $this->render('CAOTvSeriesBundle:episode:show.html.twig', array( 'episode' => $episode, 'userEpisode' => $userEpisode, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing episode entity. * * @Route("/{id}/edit", name="admin_episode_edit") * @Method({"GET", "POST"}) * @Security("has_role('ROLE_ADMIN')") */ public function editAction(Request $request, Episode $episode) { $deleteForm = $this->createDeleteForm($episode); $editForm = $this->createForm('CAO\TvSeriesBundle\Form\EpisodeType', $episode); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('admin_episode_edit', array('id' => $episode->getId())); } return $this->render('@CAOTvSeries/episode/edit.html.twig', array( 'episode' => $episode, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a episode entity. * * @Route("/{id}", name="admin_episode_delete") * @Method("DELETE") * @Security("has_role('ROLE_ADMIN')") */ public function deleteAction(Request $request, Episode $episode) { $form = $this->createDeleteForm($episode); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->remove($episode); $em->flush($episode); } return $this->redirectToRoute('admin_episode_index'); } /** * Creates a form to delete a episode entity. * * @param Episode $episode The episode entity * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm(Episode $episode) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_episode_delete', array('id' => $episode->getId()))) ->setMethod('DELETE') ->getForm() ; } /** * @param $name * @return \Symfony\Component\HttpFoundation\Response * @Route("/watch/{id}", name="user_watch_episode") */ public function watchAction(Episode $episode) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $userEpisodeTable = $em->getRepository('CAOTvSeriesBundle:UserEpisode'); $episodeArr = $userEpisodeTable ->findBy(array( 'user' => $user, 'episode' => $episode )) ; $userEpisode = new UserEpisode(); $userEpisode->setUser($user); $userEpisode->setEpisode($episode); $userEpisode->setCurrent($episode->getEpisodeNumber()); $userEpisode->setWatechedAt(new \DateTime('now')); // if null add new if (empty($episodeArr)) { $em->persist($userEpisode); } else // if not update this term with new data { $em->merge($userEpisode); } $em->flush(); return $this->redirectToRoute("admin_episode_index"); // // $form = $this->createForm('CAO\TvSeriesBundle\Form\UserEpisodeType', $userEpisode); // // if ($form->isSubmitted() && $form->isValid()) // { // // } // return $this->render('', array( // 'user' => $user, // 'episode' => $episode // )); } } <file_sep><?php /** * Created by PhpStorm. * User: caoych * Date: 2017/2/24 * Time: 23:20 */ namespace CAO\TvSeriesBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * UserEpisode * * @author <NAME> <EMAIL> * * @package TvSeriesBundle\Entity * * @ORM\Entity * */ class UserEpisode { /** * Many Episodes -- One User * @ORM\ManyToOne(targetEntity="CAO\TvSeriesBundle\Entity\User") * @ORM\JoinColumn(name="userId", referencedColumnName="id") * @ORM\Id() */ private $user; /** * Many Users -- One Episodes * @ORM\ManyToOne(targetEntity="CAO\TvSeriesBundle\Entity\Episode") * @ORM\JoinColumn(name="episodeId", referencedColumnName="id") * @ORM\Id() */ private $episode; /** * @var int * @ORM\Column(type="integer", nullable=true) * */ private $current; /** * @var \DateTimeInterface * @ORM\Column(type="datetime", nullable=true) */ private $watechedAt; /** * @return mixed */ public function getUser() { return $this->user; } /** * @param mixed $user */ public function setUser($user) { $this->user = $user; } /** * @return mixed */ public function getEpisode() { return $this->episode; } /** * @param mixed $episode */ public function setEpisode($episode) { $this->episode = $episode; } /** * @return int */ public function getCurrent() { return $this->current; } /** * @param int $current */ public function setCurrent($current) { $this->current = $current; } /** * @return \DateTimeInterface */ public function getWatechedAt() { return $this->watechedAt; } /** * @param \DateTimeInterface $watechedAt */ public function setWatechedAt($watechedAt) { $this->watechedAt = $watechedAt; } } <file_sep><?php namespace CAO\TvSeriesBundle\Form; use CAO\TvSeriesBundle\Entity\TvSeries; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class EpisodeType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name') ->add('episodeNumber') ->add('datePublished', DateType::class) ->add('description') ->add('image', FileType::class, array( 'label' => 'Image (optional)', 'required' => false )) ->add('tvSeries', EntityType::class, array( 'class' => TvSeries::class, 'choice_label' => 'name' )) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'CAO\TvSeriesBundle\Entity\Episode' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'cao_tvseriesbundle_episode'; } } <file_sep><?php namespace CAO\TvSeriesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class CAOTvSeriesBundle extends Bundle { } <file_sep><?php namespace CAO\TvSeriesBundle\Controller; use CAO\TvSeriesBundle\Entity\TvSeries; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request; /** * Tvseries controller. * * @Route("tvseries") */ class TvSeriesController extends Controller { /** * Lists all tvSeries entities. * * @Route("/", name="tvseries_index") * @Method("GET") */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $tvSeries = $em->getRepository('CAOTvSeriesBundle:TvSeries')->findAll(); return $this->render('CAOTvSeriesBundle:tvseries:index.html.twig', array( 'tvSeries' => $tvSeries, )); } /** * Creates a new tvSeries entity. * * @Route("/new", name="admin_tvseries_new") * @Method({"GET", "POST"}) * @Security("has_role('ROLE_ADMIN')") */ public function newAction(Request $request) { $tvSeries = new Tvseries(); $form = $this->createForm('CAO\TvSeriesBundle\Form\TvSeriesType', $tvSeries); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // deal with the image. $image = $tvSeries->getImage(); if ($image != NULL) { $imageName = md5(uniqid()).'.'.$image->guessExtension(); $image->move( $this->getParameter('image_directory'), $imageName ); $tvSeries->setImage($imageName); } $em = $this->getDoctrine()->getManager(); $em->persist($tvSeries); $em->flush($tvSeries); return $this->redirectToRoute('admin_tvseries_show', array('id' => $tvSeries->getId())); } return $this->render('CAOTvSeriesBundle:tvseries:new.html.twig', array( 'tvSeries' => $tvSeries, 'form' => $form->createView(), )); } /** * Finds and displays a tvSeries entity. * * @Route("/{id}", name="admin_tvseries_show") * @Method("GET") */ public function showAction(TvSeries $tvSeries) { $deleteForm = $this->createDeleteForm($tvSeries); return $this->render('CAOTvSeriesBundle:tvseries:show.html.twig', array( 'tvSeries' => $tvSeries, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing tvSeries entity. * * @Route("/{id}/edit", name="admin_tvseries_edit") * @Method({"GET", "POST"}) * @Security("has_role('ROLE_ADMIN')") */ public function editAction(Request $request, TvSeries $tvSeries) { $deleteForm = $this->createDeleteForm($tvSeries); $editForm = $this->createForm('CAO\TvSeriesBundle\Form\TvSeriesType', $tvSeries); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('admin_tvseries_edit', array('id' => $tvSeries->getId())); } return $this->render('CAOTvSeriesBundle:tvseries:edit.html.twig', array( 'tvSeries' => $tvSeries, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a tvSeries entity. * * @Route("/{id}", name="admin_tvseries_delete") * @Method("DELETE") * @Security("has_role('ROLE_ADMIN')") */ public function deleteAction(Request $request, TvSeries $tvSeries) { $form = $this->createDeleteForm($tvSeries); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->remove($tvSeries); $em->flush($tvSeries); } return $this->redirectToRoute('admin_tvseries_index'); } /** * Creates a form to delete a tvSeries entity. * * @param TvSeries $tvSeries The tvSeries entity * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm(TvSeries $tvSeries) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_tvseries_delete', array('id' => $tvSeries->getId()))) ->setMethod('DELETE') ->getForm() ; } } <file_sep>Rendu Application Web ======================== Implementé -------------- * Créer un bundle TvSeries * Images enregistrés sous dossier 'upload' selon la boone pratique. * CRUD de TvSeries et Episode * CRUD de l'utilisateur pour admin. * Accès admin va utiliser directement l'URL. <file_sep><?php //namespace CAO\TvSeriesBundle\Repository; // //use Doctrine\ORM\EntityRepository; //use Doctrine\ORM\Tools\Pagination\Paginator; ///** // * Created by PhpStorm. // * User: caoych // * Date: 2017/3/2 // * Time: 17:48 // */ //class EpisodeRepository extends EntityRepository //{ // /** // * @param int $currentPage // * @return \Doctrine\ORM\Tools\Pagination\Paginator // */ // public function getAllEpisodes($currentPage = 1) // { // $query = $this->createQueryBuilder('p') // ->orderBy('p.name', 'DESC') // ->getQuery(); // // $paginator = $this->paginate($query, $currentPage); // // return $paginator; // } // // /** // * @param $dql // * @param int $page // * @param int $limit // * @return Paginator // */ // public function paginate($dql, $page=1, $limit=5) // { // $paginator = new Paginator($dql); // // $paginator->getQuery() // ->setFirstResult($limit * ($page - 1)) // ->setMaxResults($limit); // // return $paginator; // } //}
315f8fb6b39321a6c2b28bb3609ea7c1fea92d6c
[ "Markdown", "PHP" ]
11
PHP
Jostar1024/tvseries
5f78563eb61741672a4a6e1504c44b643718ad86
de1259ce7a64b72f08485589892bd06b5a19dd83
refs/heads/master
<file_sep># ConwayGameOfLife Game Overview: Launch the app to begin the game. Use the mouse to select one of two options; play or generation selector. The generation selector will allow you to select the number of generations you wish to simulate. Enter this value in the provided space and click done once you have typed your response. If you choose the play option instead, the program will directly proceed to the simulator. The simulator will operate for a randomly selected number of generations, unless otherwise indicated. Select the seed cells with a left mouse click. Once you are done, click the right side of your mouse to begin simulating the evolution of the cells. After the desired number of generations is reached, the program will automatically close on its own. Rules of Evolution: Every cell has 8 neighbours and interacts with the cells that are horizontally, vertically, or diagonally adjacent to it. The initial pattern is the first generation. Future generations evolve by applying the following rules iteratively: 1. Any live cell with fewer than two live neighbours dies due to underpopulation 2. Any live cell with two or three live neighbours lives on to the next generation 3. Any live cell with more than three live neighbours dies due to overpopulation 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction <file_sep>/* <NAME> January.19.2018 Mr. Radulovic - ICS3U1 Culminating Project Purpose: This project applies course concepts to generate a cellular automaton that evolves the set of selected cells Class: This class loads all the design elements */ package Culminating; // Imports import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.scene.paint.Color; import javafx.scene.control.Label; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class DesignElements { // Initializes menu buttons and labels private Button play = new Button(); private Button genSelector= new Button(); private Button done = new Button(); private TextField genInput = new TextField(); private Label selectorLabel; private Text genCounter=new Text(); // Sets font styles private String style1="-fx-font-size: 20pt;"; private String style2="-fx-font-size: 15pt;"; // Initializes screen dimensions private final double width = 800; private final double height = 800; // Returns the play button public Button playButton() { play.setMinWidth(0.25*width); play.setText("Play"); play.setLayoutY((height/2)+(height/4)); play.setLayoutX((width-play.getMinWidth())/2); play.setStyle(style1); return play; } // Returns the selector button public Button selectorButton() { genSelector.setText("Selector"); genSelector.setMinWidth(0.25*width); genSelector.setLayoutY((height/2)+(height/4)+(height/10)); genSelector.setLayoutX((width-play.getMinWidth())/2); genSelector.setStyle(style1); return genSelector; } // Returns the done button public Button doneButton() { done.setText("Done"); done.setLayoutX(0.48*width); done.setLayoutY(height/2); done.setMinWidth(width/25); done.setStyle(style2); return done; } // Returns the generation selector's label public Label selectorLabel() { selectorLabel = new Label("Enter the desired number of generations below:"); selectorLabel.setStyle(style2); selectorLabel.setLayoutX(width/4); selectorLabel.setLayoutY(0.375*800); return selectorLabel; } // Returns the generation counter text public Text genCounter() { genCounter.setX(0.01875*width); genCounter.setY(0.05625*height); genCounter.setFont(Font.font("Century Gothic", FontWeight.BOLD, 36)); genCounter.setFill(Color.PURPLE); return genCounter; } // Returns generation selector's input bar public TextField inputBar() { genInput.setPrefWidth(width/3); genInput.setLayoutX(0.3625*width); genInput.setLayoutY(0.45*height); return genInput; } // Returns the width of the window public double getWidth() { return width; } // Returns the height of the window public double getHeight() { return height; } } <file_sep>/* <NAME> January.19.2018 Mr. Radulovic - ICS3U1 Culminating Project Purpose: This project applies course concepts to generate a cellular automaton that evolves the set of selected cells Class: This class draws the grid, implements the design templates, and updates the cell as per the rules */ package Culminating; // Imports import java.util.Random; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.image.*; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.event.ActionEvent; import javafx.scene.text.Text; import javafx.scene.control.Label; public class GameOfLife extends Application { // Accesses other Classes private CellState state = new CellState(); // Determines if cell is alive or dead private DesignElements design = new DesignElements(); // Loads GUI elements private PageThemes pageTheme= new PageThemes(); // Loads page designs // Window Dimensions (pixels) private final double width = design.getWidth(); private final double height = design.getHeight(); // Animation Timer private long oldTime; // Next generation is updated every 10 counts private int updateCounter = 0; // Sets dimension of the maze private final int numRows = state.getRows(); private final int numColumns = state.getColumns(); // Calculates the spacing to accurately position each tile private double xSpace; private double ySpace; // Initializes graphics,pane, and scene private GraphicsContext gc; private Pane root=new Pane(); private Scene scene; private Stage primarystage = new Stage(); // Stores mouse coordinates private int mouseX; private int mouseY; // Stores coordinates of the selected tile private int tile_x; private int tile_y; // Initializes GUI elements // Buttons private Button playBtn; // Automatically begins when selected private Button selectorBtn; // User inputs the number of generations when selected private Button doneBtn; // Proceeds to the simulator when selected // Page themes private ImageView titleImageView; // Title image private ImageView selectorImageView; // Generation selector image // Labels private Label genSelector; // Text fields private TextField genInput; // Determines if the user is in the menu (changes to false when the menu selections are complete) private boolean menuState = true; // Keeps track of generations private int genMax; // Determined by the user ( if user does not choose a value, it is randomly calculated) private int genCount = 1; // Counts the generations private Text counterText; // Provides instruction // Random integer generator private Random rand = new Random(); // Identifies if the user is done selecting the seed cells (deactivated with right click) private boolean userSelecting = true; public static void main(String[] args) { // Sets up the app and launches it launch(args); } @Override public void start(Stage primarystage1) throws Exception { // Updates primarystage primarystage = primarystage1; // Initializes graphics and canvas Canvas canvas = new Canvas(width, height); gc = canvas.getGraphicsContext2D(); // Loads menu Buttons playBtn = design.playButton(); selectorBtn = design.selectorButton(); // Loads generation selector GUI elements/buttons genInput = design.inputBar(); doneBtn = design.doneButton(); genSelector=design.selectorLabel(); counterText=design.genCounter(); // Loads page themes titleImageView = pageTheme.getTitleImageView(); selectorImageView = pageTheme.getSelectorImageView(); // Adds GUI elements to pane root.getChildren().addAll(titleImageView, canvas); // Adds title page in background root.getChildren().addAll(playBtn, selectorBtn); // Adds buttons on top // Sets the scene style root.setStyle("-fx-background: #C8FFF4"); scene = new Scene(root, width, height, Color.WHITE); // Activates mouse handler to receive mouse input scene.setOnMouseClicked(mouseHandler); // Mouse only receives input to set seed cells when the user has exited the main menu if (menuState == false) { scene.setOnMouseClicked(mouseHandler); } // Sets title primarystage.setTitle("Conway's Game of Life"); // Sets the scene for this stage primarystage.setScene(scene); // Shows the primary stage primarystage.show(); // Sets up a timer to repeatedly redraw the scene oldTime = System.nanoTime(); AnimationTimer timer = new AnimationTimer() { public void handle(long now) { double deltaT = (now - oldTime) / 1000000000.0; // in nanoseconds onUpdate(deltaT); oldTime = now; } }; // When selected, the simulator appears playBtn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { root.getChildren().removeAll(playBtn, selectorBtn, titleImageView); // Removes all the old buttons genMax = rand.nextInt(500) + 20; // Randomly generates a maximum generation value between 20 and 500 drawScene(gc); // Draws the grid timer.start(); // Starts the timer } }); // When selected, the user inputs the desired maximum generation value selectorBtn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { root.getChildren().removeAll(playBtn, selectorBtn, titleImageView); // Removes old buttons root.getChildren().addAll(selectorImageView,genSelector); // Adds new page themes root.getChildren().addAll(genInput, doneBtn); // Adds new GUI elements doneBtn.setOnAction(new EventHandler<ActionEvent>() // When selected, the input is stored { public void handle(ActionEvent event) { genMax = Integer.parseInt((genInput.getText())); // Converts string input to integer root.getChildren().removeAll(genInput, doneBtn, selectorImageView,genSelector); // Removes the buttons drawScene(gc); // Draws the grid primarystage.show(); timer.start(); } }); } }); } private void drawScene(GraphicsContext gc) // Draws the grid for the simulator { // Calculates the Width of the column xSpace = width / numColumns; // Calculates the height of the row ySpace = height / numRows; // Sets the line colour and width gc.setStroke(Color.BLACK); gc.setLineWidth(1); // Sets background to white again root.setStyle("-fx-background: #FFFFFF"); // Draws the rows of the grid for (int i = 0; i <= numRows; i += 1) { gc.strokeLine(0, i * ySpace, width, i * ySpace); } // Draws the columns of the grid for (int i = 0; i <= numColumns; i += 1) { gc.strokeLine(i * xSpace, 0, i * xSpace, height); } } // Receives mouse input to select seed cells EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() { public void handle(MouseEvent mouseEvent) { MouseButton button = mouseEvent.getButton(); // Allows user to selected seed cells only if they have passed the main menu if (menuState == false) { // Selects seed cells with a left mouse click if ((button == MouseButton.PRIMARY) && userSelecting == true) { // Identifies mouse coordinates mouseX = (int) mouseEvent.getX(); mouseY = (int) mouseEvent.getY(); // Converts mouse coordinates to actual tile positions tile_x = (int) (mouseX / xSpace); tile_y = (int) (mouseY / ySpace); // Colours selected cells black gc.setFill(Color.BLACK); gc.fillRect(tile_x * xSpace, tile_y * ySpace, xSpace, ySpace); // Sets selected cells to alive state.setAlive(tile_x, tile_y); // Print generation counter on screen root.getChildren().remove(counterText); counterText.setText(Integer.toString(genCount)); root.getChildren().add(counterText); } // Disables selection with right mouse click else if (button == MouseButton.SECONDARY) { userSelecting = false; } } } }; // Updates grid from one generation to the next private void onUpdate(double deltaT) { // Menu state is now set to false as the user has passed it menuState = false; // Updates counter only if the user is done selecting seed cells if (userSelecting == false) updateCounter += 1; // Updates the grid with new cells every 10 counts // Repopulates next generation accordingly if (userSelecting == false && updateCounter == 10 && genCount < genMax) { for (int a = 0; a < numColumns; a += 1) { for (int b = 0; b < numRows; b += 1) { if (state.cellState(a, b) == "alive") { // Colours cell black if alive gc.setFill(Color.BLACK); } else if (state.cellState(a, b) == "dead") { // Colours cell white if dead gc.setFill(Color.WHITE); } gc.fillRect(a * xSpace, b * ySpace, xSpace, ySpace); } } // Draws the rows of the grid for (int i = 0; i <= numRows; i += 1) { gc.strokeLine(0, i * ySpace, width, i * ySpace); } // Draws the columns of the grid for (int i = 0; i <= numColumns; i += 1) { gc.strokeLine(i * xSpace, 0, i * xSpace, height); } // Increases generation counts genCount += 1; // Prints the generation count on the screen root.getChildren().remove(counterText); counterText.setText(Integer.toString(genCount)); root.getChildren().add(counterText); // Updates the current generation grid to account for the changes made to the cells state.updateGrid(); // Resets animation counter updateCounter = 0; } // If the generation count exceeds the maximum value, the application is exited after 120 counts if (genCount == genMax && updateCounter==120) { primarystage.close(); } } } <file_sep>/* <NAME> January.19.2018 Mr. Radulovic - ICS3U1 Culminating Project Purpose: This project applies course concepts to generate a cellular automaton that evolves the set of selected cells Class: This class loads the themes and designs of the menu pages */ package Culminating; // Imports import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class PageThemes { // Loads screen dimensions private DesignElements designElement = new DesignElements(); private final double width = designElement.getWidth(); private final double height = designElement.getHeight(); // Loads the necessary images/templates private final Image titleImage; private final ImageView titleImageView; private final Image selectorImage; private final ImageView selectorImageView; //Loads files private final String titleFilename = "file:resources//images//TitlePage.png"; private final String selectorFilename = "file:resources//images//SelectorPage.png"; public PageThemes() { // Loads the title page and sets the width to correspond with the window dimensions titleImage = new Image(titleFilename); titleImageView = new ImageView(); titleImageView.setImage(titleImage); titleImageView.setFitWidth(width); titleImageView.setPreserveRatio(true); // Loads the generation selector page and sets the width to correspond with the window dimensions selectorImage = new Image(selectorFilename); selectorImageView = new ImageView(); selectorImageView.setImage(selectorImage); selectorImageView.setFitHeight(height); selectorImageView.setPreserveRatio(true); selectorImageView.setX(width / 8); } // Returns title page public ImageView getTitleImageView() { return titleImageView; } // Retuns generation selector page public ImageView getSelectorImageView() { return selectorImageView; } }
efb9832eed7c3d3657741ab481115cf75059912a
[ "Markdown", "Java" ]
4
Markdown
AnjanaSomar/ConwayGameOfLife
40e9c983c11abd3359ddbec86cbdb60b251e3ca7
e5df3dd3e18d852287ff1feb3987dffbf5148ad8
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Attackable : MonoBehaviour { const int LMB = 0; const int RMB = 1; const int MMB = 2; bool isMouseDown = false; PlayerControl player; private void Start() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerControl>(); } private void Update() { isMouseDown = Input.GetMouseButton(LMB); } private void OnMouseDown() { NotifyPlayer(); } private void OnMouseUp() { //NotifyPlayer(); } private void OnMouseOver() { //if (isMouseDown) // NotifyPlayer(); } void NotifyPlayer() { player.MoveAndAttack(this); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; public class GenerateDetails : MonoBehaviourPunCallbacks { private Visualizer visualizer; private int[] mapData; //public GameObject details; //public GameObject visualizers; public GameObject[] rooms; private int width; private int height; private int randomNumber; private int[] location; private List<GameObject> objects; Vector3 position; Vector3 finalPosition; private bool firstTime; public GameObject player; public GameObject boss; Quaternion rotation; bool doneGenerating = false; ExitGames.Client.Photon.Hashtable positionTable = new ExitGames.Client.Photon.Hashtable(); public GameStart start; public void Details() { positionTable.Add("Dungeon Generated", false); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); visualizer = GetComponent<Visualizer>(); width = visualizer.width; height = visualizer.height; location = new int[2]; objects = new List<GameObject>(); //if (firstTime != true) //{ // for(int i = 0; i < objects.Count; i++) // { // Destroy(objects[i]); // } // objects.Clear(); //} //else if (firstTime == true) //{ // firstTime = false; //} if (visualizer.firstTime == false) { int heighMultiplier = 1; int widthMultiplier = 0; //details.SetActive(true); //visualizers.SetActive(false); mapData = visualizer.mapData; for (int i = 0; i < mapData.Length; i++) { if (i > width * heighMultiplier) { heighMultiplier++; widthMultiplier = 0; } location[0] = widthMultiplier * 49; location[1] = heighMultiplier * 49; position = new Vector3(location[1], 0, location[0] - 200); if (mapData[i] == 2 || mapData[i] == 3 || mapData[i] == 4) { //Top if (mapData[i - width] == 2 || mapData[i - width] == 3 || mapData[i - width] == 4) { //Top, Bottom if (mapData[i + width] == 2 || mapData[i + width] == 3 || mapData[i + width] == 4) { //Top, Bottom, Forward if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Top, Bottom, Forward, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 3 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[3].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 4 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[4].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 5 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[5].name, position, rotation)); } } //Top, Bottom, Forward else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[6].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); //objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[7].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[8].name, position, rotation)); } } } //Top, Bottom else { //Top, Bottom, back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[6].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[7].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[8].name, position, rotation)); } } //Top, Bottom else { randomNumber = Random.Range(1, 3); rotation = Quaternion.Euler(0, 0, 0); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 12 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[12].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 10 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[10].name, position, rotation)); } } } } //Top else { //Top, Front if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Top, Front, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[6].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[7].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[8].name, position, rotation)); } } //Top, Front else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[9].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[11].name, position, rotation)); } } } else //Top { //Top, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[9].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); // photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[11].name, position, rotation)); } } //Top else { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[0].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[1].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[2].name, position, rotation)); } } } } } else { //Bottom if (mapData[i + width] == 2 || mapData[i + width] == 3 || mapData[i + width] == 4) { //Bottom, Forward if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Bottom, Forward, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[6].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[7].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[8].name, position, rotation)); } } //Bottom, Forward else { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[9].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[11].name, position, rotation)); } } } //Bottom else { //Bottom, back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[9].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[11].name, position, rotation)); } } //Bottom else { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[0].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[1].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[2].name, position, rotation)); } } } } //None else { //Front if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Front, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { randomNumber = Random.Range(1, 3); rotation = Quaternion.Euler(0, 90, 0); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 12 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[12].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 10 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[10].name, position, rotation)); } } //Front else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[0].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[1].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[2].name, position, rotation)); } } } else //None { //Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[0].name, position, rotation)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { finalPosition = position; positionTable.Add("Players", finalPosition); PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); //photonView.RPC("PositionSetUp", RpcTarget.AllBufferedViaServer); } else if (mapData[i] == 4) { //objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[1].name, position, rotation)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(PhotonNetwork.Instantiate(rooms[2].name, position, rotation)); } } //None, Final else { } } } } } widthMultiplier++; } } positionTable["Dungeon Generated"] = true; PhotonNetwork.CurrentRoom.SetCustomProperties(positionTable); } //[PunRPC] //public void PositionSetUp() //{ // if (PhotonNetwork.CurrentRoom.CustomProperties["Players"] != null) // { // finalPosition = (Vector3)PhotonNetwork.CurrentRoom.CustomProperties["Players"]; // start.SetUp(finalPosition); // } // else // { // wait(); // } //} //IEnumerator wait() //{ // while (true) // { // yield return new WaitForEndOfFrame(); // if ((Vector3)PhotonNetwork.CurrentRoom.CustomProperties["Players"] != null) // { // break; // } // } // PositionSetUp(); //} } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dungeon_Check : MonoBehaviour { //This entire Script might need to be changed later, to take out the test code #region Variables //variable to decide what to do, open or close the dungeon private bool dungeonOpen = false; public GameObject details; public GameObject visualizers; //Object that holds the dungeon Screen [SerializeField] private GameObject dungeonScreen; //Variable that holds the player Input component private Character_Controller playerInput; #endregion #region Set up private void Awake() { //Find the PlayerInput component playerInput = GameObject.Find("Main Camera").GetComponent<Character_Controller>(); //Subscription here //playerInput.OnGPress += DungeonCheck; } private void Start() { //dungeonOpen = playerInput.inventoryOpen; //Disables the inventoryScreen if dungeonOpen is false if (dungeonOpen == false) { dungeonScreen.SetActive(false); } //Else it makes sure that it's open else { dungeonScreen.SetActive(true); } } #endregion #region Inventory Check //Open or Close Dungeon public void DungeonCheck() { //Opens the Dungeon Screen if (dungeonOpen == false) { dungeonScreen.SetActive(true); dungeonOpen = true; } //Closes the Dungeon Screen else { details.SetActive(false); visualizers.SetActive(false); dungeonScreen.SetActive(false); dungeonOpen = false; } } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EquipClick : MonoBehaviour { public bool equipSelected = false; private AudioSource cameraAudio; public AudioClip selectSound; private void Awake() { cameraAudio = this.gameObject.GetComponent<AudioSource>(); } public void _SelectEquippedItem(Image button) { if (equipSelected == false) { button.color = Color.red; cameraAudio.clip = selectSound; cameraAudio.Play(); equipSelected = true; } else { if (button.color == Color.red) { equipSelected = false; button.color = Color.white; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using UnityEngine.UI; using Photon.Realtime; public class Chicken_Controller : MonoBehaviourPunCallbacks, IPunObservable { Animator animator; [SerializeField] float moveSpeed = 8; int score = 0; [SerializeField] float timeToScore = 2; float currentScoreTimer = 0; float oneHalf = 1 / 2; float scoreUpdate = 0; bool isEating = false; bool isWalking = false; ScoreReport scoreReport; //bool doTest = false; private void Start() { scoreReport = GameObject.Find("UIManager").GetComponent<ScoreReport>(); if (photonView.IsMine) { animator = GetComponent<Animator>(); scoreReport.Register("local"); } else { scoreReport.Register(photonView.Owner.NickName); } } private void Update() { if (!photonView.IsMine) { scoreReport.ScoreUpdate(photonView.Owner.NickName, score); return; } scoreReport.ScoreUpdate("local", score); Vector3 movement = new Vector3(-Input.GetAxis("Vertical"), 0, Input.GetAxis("Horizontal")); if (movement.sqrMagnitude == 0) { isWalking = false; animator.SetBool("Walk", false); if(Input.GetKey(KeyCode.Space)) { isEating = true; animator.SetBool("Eat", true); DoScoring(); } else { isEating = false; animator.SetBool("Eat", false); } } else { isWalking = true; isEating = false; animator.SetBool("Walk", true); animator.SetBool("Eat", false); transform.position += movement.normalized * (moveSpeed * Time.deltaTime); transform.rotation = Quaternion.Euler(0, Mathf.Atan2(movement.x, movement.z) * Mathf.Rad2Deg, 0); } //scoreBoxes["Mine"].text = string.Format("My Score: {0}", score); } void DoScoring() { if (Input.GetKeyDown(KeyCode.Space)) { currentScoreTimer = timeToScore; } else { currentScoreTimer -= Time.deltaTime; if (currentScoreTimer <= 0) { score++; currentScoreTimer += timeToScore; } } } private void OnTriggerEnter(Collider other) { if (!photonView.IsMine) { return; } Chicken_Controller ckOther = other.gameObject.GetComponent<Chicken_Controller>(); if (ckOther != null && isWalking) { if (ckOther.isEating) { PhotonView otherView = other.gameObject.GetComponent<PhotonView>(); otherView.RPC("ReduceScore", RpcTarget.Others, otherView.ViewID); // Debug.Log("Sending an RPC Call"); } } } //private void OnTriggerStay(Collider other) //{ // if (doTest && other.gameObject.tag == "Player") // { // PhotonView otherView = other.gameObject.GetComponent<PhotonView>(); // otherView.RPC("ReduceScore", RpcTarget.Others, otherView.ViewID); // } //} [PunRPC] public void ReduceScore(int ID) { if (ID == this.photonView.ViewID) { //Debug.Log("Getting a Call"); scoreUpdate = score * oneHalf; score = (int)scoreUpdate; } } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if(stream.IsWriting) { stream.SendNext(isEating); stream.SendNext(score); } else { this.isEating = (bool)stream.ReceiveNext(); this.score = (int)stream.ReceiveNext(); } } public override void OnPlayerLeftRoom(Player otherPlayer) { scoreReport.UnRegister(otherPlayer.NickName); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Raycast : MonoBehaviour { const int LMB = 0; const int RMB = 1; const int MMB = 2; public Transform targetPoint; private void Update() { if (Input.GetMouseButton(LMB)) { Ray mouseCast = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; int layerMask = ~LayerMask.GetMask("Pong"); if (Physics.Raycast(mouseCast, out hit, float.PositiveInfinity, layerMask)) { targetPoint.position = hit.point; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MakeParent : MonoBehaviour { private void Awake() { StartCoroutine(Parenting()); } IEnumerator Parenting() { yield return new WaitForEndOfFrame(); this.gameObject.transform.SetParent(GameObject.FindGameObjectWithTag("Ground").transform); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseHighlight : MonoBehaviour { public Renderer myRenderer; private void OnMouseEnter() { myRenderer.material.SetFloat("_HighlightOn", 1); } private void OnMouseExit() { myRenderer.material.SetFloat("_HighlightOn", 0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateDetails : MonoBehaviour { private Visualizer visualizer; private int[] mapData; public GameObject details; public GameObject visualizers; public GameObject[] rooms; private int width; private int height; private int randomNumber; private int[] location; private List<GameObject> objects; Vector3 position; private bool firstTime; public GameObject player; public GameObject boss; Quaternion rotation; private void Awake() { visualizer = GetComponent<Visualizer>(); width = visualizer.width; height = visualizer.height; location = new int[2]; objects = new List<GameObject>(); } public void Details() { if (firstTime != true) { for(int i = 0; i < objects.Count; i++) { Destroy(objects[i]); } objects.Clear(); } else if (firstTime == true) { firstTime = false; } if (visualizer.firstTime == false) { int heighMultiplier = 1; int widthMultiplier = 0; details.SetActive(true); visualizers.SetActive(false); mapData = visualizer.mapData; for (int i = 0; i < mapData.Length; i++) { if (i > width * heighMultiplier) { heighMultiplier++; widthMultiplier = 0; } location[0] = widthMultiplier * 49; location[1] = heighMultiplier * 49; position = new Vector3(location[1], 0, location[0] - 200); if (mapData[i] == 2 || mapData[i] == 3 || mapData[i] == 4) { //Top if (mapData[i - width] == 2 || mapData[i - width] == 3 || mapData[i - width] == 4) { //Top, Bottom if (mapData[i + width] == 2 || mapData[i + width] == 3 || mapData[i + width] == 4) { //Top, Bottom, Forward if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Top, Bottom, Forward, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 3 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[3], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 4 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[4], position, rotation, details.transform)); } else if (randomNumber == 3) { //Load from array at index 5 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[5], position, rotation, details.transform)); } } //Top, Bottom, Forward else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[6], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it Instantiate(rooms[7], position, rotation, details.transform); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[8], position, rotation, details.transform)); } } } //Top, Bottom else { //Top, Bottom, back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[6], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it Instantiate(rooms[7], position, rotation, details.transform); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[8], position, rotation, details.transform)); } } //Top, Bottom else { randomNumber = Random.Range(1, 3); rotation = Quaternion.Euler(0, 0, 0); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 12 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[12], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 10 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[10], position, rotation, details.transform)); } } } } //Top else { //Top, Front if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Top, Front, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[6], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it Instantiate(rooms[7], position, rotation, details.transform); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[8], position, rotation, details.transform)); } } //Top, Front else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[9], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[11], position, rotation, details.transform)); } } } else //Top { //Top, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[9], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[11], position, rotation, details.transform)); } } //Top else { rotation = Quaternion.Euler(0, 270, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[0], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[1], position, rotation, details.transform)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[2], position, rotation, details.transform)); } } } } } else { //Bottom if (mapData[i + width] == 2 || mapData[i + width] == 3 || mapData[i + width] == 4) { //Bottom, Forward if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Bottom, Forward, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 6 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[6], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 7 instantiating it at this spot, and maybe rotating it Instantiate(rooms[7], position, rotation, details.transform); } else if (randomNumber == 3) { //Load from array at index 8 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[8], position, rotation, details.transform)); } } //Bottom, Forward else { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[9], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[11], position, rotation, details.transform)); } } } //Bottom else { //Bottom, back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 3); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 9 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[9], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 11 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[11], position, rotation, details.transform)); } } //Bottom else { rotation = Quaternion.Euler(0, 90, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[0], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[1], position, rotation, details.transform)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[2], position, rotation, details.transform)); } } } } //None else { //Front if (mapData[i - 1] == 2 || mapData[i - 1] == 3 || mapData[i - 1] == 4) { //Front, Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { randomNumber = Random.Range(1, 3); rotation = Quaternion.Euler(0, 90, 0); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 12 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[12], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 10 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[10], position, rotation, details.transform)); } } //Front else { rotation = Quaternion.Euler(0, 180, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[0], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[1], position, rotation, details.transform)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[2], position, rotation, details.transform)); } } } else //None { //Back if (mapData[i + 1] == 2 || mapData[i + 1] == 3 || mapData[i + 1] == 4) { rotation = Quaternion.Euler(0, 0, 0); randomNumber = Random.Range(1, 4); if (randomNumber == 1 || mapData[i] == 3 || mapData[i] == 4) { //Load from array at index 0 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[0], position, rotation, details.transform)); position = new Vector3(location[1], 2, location[0] - 200); if (mapData[i] == 3) { objects.Add(Instantiate(player, position, Quaternion.identity)); } else if (mapData[i] == 4) { objects.Add(Instantiate(boss, position, Quaternion.identity)); } } else if (randomNumber == 2) { //Load from array at index 1 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[1], position, rotation, details.transform)); } else if (randomNumber == 3) { //Load from array at index 2 instantiating it at this spot, and maybe rotating it objects.Add(Instantiate(rooms[2], position, rotation, details.transform)); } } //None, Final else { } } } } } widthMultiplier++; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class PlayerControl : MonoBehaviour { const int LMB = 0; const int RMB = 1; const int MMB = 2; const int MOVING = 1; const int ATTACKING = 2; const int IDLE = 0; int currentMode = 0; public float allowedDelta = 0.1f; public float moveSpeed = 8f; public float forwardOffset; public Vector3 bottomOffset; public Vector3 heightOffset; public float overlapRadius = 0.2f; Vector3 lastValidMoveTarget; Vector3 targetCorner; int currentCornerIndex; Collider[] overlapResults; RaycastHit[] rayHits; NavMeshAgent agent; NavMeshPath path; public NavMeshSurface navSurface; Attackable attackTarget; bool isMouseDown = false; private void Start() { overlapResults = new Collider[16]; rayHits = new RaycastHit[16]; agent = GetComponent<NavMeshAgent>(); path = new NavMeshPath(); lastValidMoveTarget = transform.position; //NavMeshSurface pong; //pong.BuildNavMesh(); } private void Update() { isMouseDown = false; HandleMouseDown(); HandleMouseUp(); MovePlayer(); } private void MovePlayer() { if (Vector3.Distance(this.transform.position, lastValidMoveTarget) > allowedDelta && isMouseDown) { //Old Solution //Vector3 offset = transform.forward * (Time.deltaTime * moveSpeed); //transform.position += offset; Vector3 desiredPosition = this.transform.position + this.transform.forward * (Time.deltaTime * moveSpeed); Vector3 bottomSphere = desiredPosition + transform.forward * forwardOffset + bottomOffset; Vector3 topSphere = desiredPosition + transform.forward * forwardOffset + heightOffset; int count = Physics.OverlapCapsuleNonAlloc(bottomSphere, topSphere, overlapRadius, overlapResults); bool canMove = true; for (int i = 0; i < count; i++) { //Debug.Log(overlapResults[i].name); if (overlapResults[i].gameObject.tag == "NoPass") { //This shouldn't break anything but is just expensive. You can use it, if you feel like the code's broken //currentCornerIndex += 1; //if (currentCornerIndex < path.corners.Length) //{ // targetCorner = path.corners[currentCornerIndex]; // Vector3 lookPoint = targetCorner; // lookPoint.y = transform.position.y; // transform.LookAt(lookPoint); //} //canMove = false; //This line just sucks } } if (canMove) { transform.position = desiredPosition; } } else if (Vector3.Distance(this.transform.position, lastValidMoveTarget) > allowedDelta && !isMouseDown) { if (Vector3.Distance(transform.position, targetCorner) > allowedDelta) { Vector3 offset = transform.forward * (Time.deltaTime * moveSpeed); transform.position += offset; } else { currentCornerIndex += 1; if (currentCornerIndex < path.corners.Length) { targetCorner = path.corners[currentCornerIndex]; Vector3 lookPoint = targetCorner; lookPoint.y = transform.position.y; transform.LookAt(lookPoint); } else if (attackTarget != null) { //Additional Attack code needed!!!!!! Vector3 lookPoint = attackTarget.transform.position; lookPoint.y = this.transform.position.y; this.transform.LookAt(lookPoint); //HAAAAACK attackTarget = null; currentMode = IDLE; } } } } private void HandleMouseUp() { if (Input.GetMouseButtonUp(LMB)) { isMouseDown = false; //agent.SetDestination(lastValidMoveTarget); NavMesh.CalculatePath(transform.position, lastValidMoveTarget, NavMesh.AllAreas, path); if (path.corners.Length == 0 && attackTarget == null) { lastValidMoveTarget = transform.position; print("Invalid Path"); } else if (path.corners.Length == 0 && attackTarget != null) { Physics.RaycastNonAlloc(new Ray(transform.position, transform.forward), rayHits); foreach(RaycastHit hit in rayHits) { if (hit.transform == null) { attackTarget = null; } else if(hit.transform.gameObject == attackTarget.gameObject) { NavMeshHit navHit; NavMesh.SamplePosition(hit.transform.position, out navHit, 3f, NavMesh.AllAreas); NavMesh.CalculatePath(transform.position, navHit.position, NavMesh.AllAreas, path); targetCorner = path.corners[0]; currentCornerIndex = 0; break; } } } else { targetCorner = path.corners[0]; currentCornerIndex = 0; } } } private void HandleMouseDown() { if (Input.GetMouseButton(LMB)) { isMouseDown = true; Ray mouseCast = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; int layerMask = ~LayerMask.GetMask("Pong") & ~LayerMask.GetMask("Ignore Raycast"); if (currentMode != ATTACKING && Physics.Raycast(mouseCast, out hit, float.PositiveInfinity, layerMask)) { if (hit.transform.gameObject.tag != "NoPass") { agent.ResetPath(); attackTarget = null; Vector3 lookPoint = hit.point; lookPoint.y = transform.position.y; transform.LookAt(lookPoint); lastValidMoveTarget = hit.point; } else if (attackTarget != null) { agent.ResetPath(); Vector3 lookPoint = attackTarget.gameObject.transform.position; lookPoint.y = transform.position.y; transform.LookAt(lookPoint); lastValidMoveTarget = attackTarget.gameObject.transform.position; } } } //end of checking left mouse button } private void OnDrawGizmos() { //if (Vector3.Distance(this.transform.position, lastValidMoveTarget) > allowedDelta) //{ // Vector3 desiredPosition = this.transform.position + this.transform.forward * (Time.deltaTime * moveSpeed); // Vector3 bottomSphere = desiredPosition + transform.forward * forwardOffset + bottomOffset; // Vector3 topSphere = desiredPosition + transform.forward * forwardOffset + heightOffset; // Gizmos.color = Color.green; // Gizmos.DrawWireSphere(bottomSphere, overlapRadius); // Gizmos.DrawWireSphere(topSphere, overlapRadius); //} Gizmos.color = Color.red; Gizmos.DrawSphere(lastValidMoveTarget, .2f); } private void OnDrawGizmosSelected() { Vector3 bottomSphere = transform.position + transform.forward * forwardOffset + bottomOffset; Vector3 topSphere = transform.position + transform.forward * forwardOffset + heightOffset; Gizmos.color = Color.green; Gizmos.DrawWireSphere(bottomSphere, overlapRadius); Gizmos.DrawWireSphere(topSphere, overlapRadius); } public void MoveAndAttack(Attackable target) { if (target != attackTarget) { attackTarget = target; lastValidMoveTarget = attackTarget.gameObject.transform.position; currentMode = ATTACKING; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using UnityEngine.AI; public class Attackable : MonoBehaviourPun { const int LMB = 0; const int RMB = 1; const int MMB = 2; bool ready = false; bool isMouseDown = false; Character_Controller player; private void Start() { StartCoroutine(Check()); } private void LateUpdate() { //if (firstTime == true) //{ // player = GameObject.FindGameObjectWithTag("Player").GetComponent<Character_Controller>(); // firstTime = false; // //Debug.Log("Finding Player"); //} } private void Update() { isMouseDown = Input.GetMouseButton(LMB); } public void Attacked() { photonView.RPC("Die", RpcTarget.AllBufferedViaServer); } private void OnMouseDown() { NotifyPlayer(); } void NotifyPlayer() { player.MoveAndAttack(this); //player.Tag(this.gameObject.tag); } [PunRPC] public void Die() { Destroy(this.gameObject); //Debug.Log("Destroyed"); } public void OnDestroy() { GameObject ground = GameObject.FindGameObjectWithTag("Ground"); if (ground != null) { NavMeshSurface surface = ground.GetComponent<NavMeshSurface>(); if (surface != null) { surface.UpdateNavMesh(surface.navMeshData); } } } private void SetUp() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<Character_Controller>(); } IEnumerator Check() { while (!ready) { yield return new WaitForEndOfFrame(); ready = GameObject.Find("GameMaster").GetComponent<GameStart>().ready; } SetUp(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; using UnityEngine.UI; public class PunLauncher : MonoBehaviourPunCallbacks { public string gameVersion = "1"; public byte maxPlayers = 3; Text status; string roomName = "default"; RoomOptions roomOps; private void Start() { status = GameObject.Find("TxtConnection").GetComponent<Text>(); roomOps = new RoomOptions(); roomOps.MaxPlayers = maxPlayers; //Connect(); if (PlayerPrefs.HasKey("PlayerName")) { PhotonNetwork.NickName = PlayerPrefs.GetString("PlayerName"); InputField playerInput = GameObject.Find("InputPlayerName").GetComponent<InputField>(); playerInput.text = PlayerPrefs.GetString("PlayerName"); } } public override void OnRoomListUpdate(List<RoomInfo> roomList) { Dropdown dropRoomList = GameObject.Find("DropRoomList").GetComponent<Dropdown>(); dropRoomList.ClearOptions(); List<Dropdown.OptionData> opData = new List<Dropdown.OptionData>(); if (roomList.Count == 0) { opData.Add(new Dropdown.OptionData("NO ROOMS")); } else { foreach (RoomInfo ri in roomList) { opData.Add(new Dropdown.OptionData(ri.Name)); } } dropRoomList.AddOptions(opData); dropRoomList.value = 0; } public void SetPlayerName() { InputField playerInput = GameObject.Find("InputPlayerName").GetComponent<InputField>(); string tempPlayerName = playerInput.text; if (string.IsNullOrEmpty(tempPlayerName)) { //status.text += ("Player name is empty"); tempPlayerName = "Zeroclipse"; PhotonNetwork.NickName = tempPlayerName; PlayerPrefs.SetString("PlayerName", tempPlayerName); } else { PhotonNetwork.NickName = tempPlayerName; PlayerPrefs.SetString("PlayerName", tempPlayerName); } } public void SetRoomName() { InputField playerInput = GameObject.Find("InputRoomName").GetComponent<InputField>(); string tempRoomName = playerInput.text; if (string.IsNullOrEmpty(tempRoomName)) { status.text += ("Room name is empty"); } else { roomName = tempRoomName; PhotonNetwork.JoinOrCreateRoom(roomName, roomOps, null); } } public void Connect() { if (PhotonNetwork.IsConnected) { status.text += ("\nAlready Connected"); //PhotonNetwork.JoinRandomRoom(); //PhotonNetwork.JoinOrCreateRoom(roomName, roomOps, null); if (!PhotonNetwork.InLobby) { PhotonNetwork.JoinLobby(); } } else { PhotonNetwork.GameVersion = gameVersion; PhotonNetwork.ConnectUsingSettings(); } } public override void OnConnectedToMaster() { status.text += ("\n<color=green>Connected to server</color>"); //PhotonNetwork.JoinRandomRoom(); //PhotonNetwork.JoinOrCreateRoom(roomName, roomOps, null); PhotonNetwork.JoinLobby(); } public override void OnDisconnected(DisconnectCause cause) { status.text += ("\n<color=red>Disconnected from server </color> : " + cause.ToString()); } //public override void OnJoinRandomFailed(short returnCode, string message) //{ // status.text += ("\n<color=red>Failed to join</color>: " + message); // //print(message); // //RoomOptions roomsOps = new RoomOptions(); // //roomsOps.MaxPlayers = maxPlayers; // //roomsOps.PlayerTtl = 10; // //roomsOps.EmptyRoomTtl = 10; // //PhotonNetwork.CreateRoom(null, roomOps); //} public override void OnJoinRoomFailed(short returnCode, string message) { status.text += ("\n<color=red>Failed to join</color>: " + message); } public override void OnJoinedRoom() { status.text += ("\n<color=green>Joined Room</color>"); PhotonNetwork.LoadLevel("Level One"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageOverTime : MonoBehaviour { public Material material; public float dps; public float damage = 0; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { damage += dps * Time.deltaTime; material.SetFloat("Vector1_50FD39D0", damage); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; public class ChickenGame : MonoBehaviour { [SerializeField] GameObject playerPrefab; private void Start() { GameObject temp = PhotonNetwork.Instantiate(playerPrefab.name, Vector3.zero, Quaternion.identity); temp.name = "ChickenPlayer"; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Close_Game : MonoBehaviour { #region Test Closer //This is temporary and just for making sure the game closes early on private void Awake() { GetComponent<Player_Input>().OnEscPress += Close; } #endregion #region Close The Game //Closes the game when called public void Close() { Application.Quit(); } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Map_Randomization { public int width; public int height; public int[] mapData; public void GenerateLevel() { mapData = new int[width * height]; for (int i = 0; i < mapData.Length; i++) { mapData[i] = UnityEngine.Random.Range(1, 101) % 2; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; using UnityEngine.UI; public class NetworkManager : MonoBehaviourPunCallbacks { public string gameVersion = "1"; public byte maxPlayers; string roomName = "default"; RoomOptions roomOps; Text status; List<RoomInfo> list; bool host = false; bool joinable = false; private void Awake() { status = GameObject.Find("ErrorT").GetComponent<Text>(); roomOps = new RoomOptions(); GameObject.Find("SoloQ").GetComponent<Text>().text = "Solo Play"; GameObject.Find("TSolo").GetComponent<Toggle>().isOn = false; GameObject.Find("ConnectText").GetComponent<Text>().text = "Connect"; GameObject.Find("NameS").GetComponent<Text>().text = "Name"; } private void Start() { if (PhotonNetwork.IsConnected == false) { PhotonNetwork.GameVersion = gameVersion; PhotonNetwork.ConnectUsingSettings(); } } public override void OnConnectedToMaster() { status.text += ("\n<color=green>Connected to Server</color>"); PhotonNetwork.JoinLobby(); } public override void OnJoinedLobby() { status.text += ("\n<color=green>Joined Lobby</color>"); if (PlayerPrefs.HasKey("PlayerName")) { status.text += ("\n<color=green>Your name is currently: " + PlayerPrefs.GetString("PlayerName") + "</color>"); PhotonNetwork.NickName = PlayerPrefs.GetString("PlayerName"); InputField playerInput = GameObject.Find("Nickname").GetComponent<InputField>(); playerInput.text = PlayerPrefs.GetString("PlayerName"); } } public override void OnRoomListUpdate(List<RoomInfo> roomList) { list = roomList; Dropdown rooms = GameObject.Find("RoomListDrop").GetComponent<Dropdown>(); rooms.ClearOptions(); List<Dropdown.OptionData> data = new List<Dropdown.OptionData>(); if (roomList.Count == 0) { data.Add(new Dropdown.OptionData("No Rooms Found.")); } else { foreach (RoomInfo room in roomList) { data.Add(new Dropdown.OptionData(room.Name)); } } rooms.AddOptions(data); rooms.value = 0; } public void SelectNickname() { InputField playerInput = GameObject.Find("Nickname").GetComponent<InputField>(); string tempPlayerName = playerInput.text; if (string.IsNullOrEmpty(tempPlayerName)) { status.text += ("\n<color=red>No Nickname entered!</color>"); } else { PhotonNetwork.NickName = tempPlayerName; PlayerPrefs.SetString("PlayerName", tempPlayerName); status.text += ("\n<color=green>Your name is now: " + PlayerPrefs.GetString("PlayerName") + "</color>"); } } public void Connect() { roomName = GameObject.Find("RoomName").GetComponent<InputField>().text; string soloName = "Solo Room "; Toggle solo = GameObject.Find("TSolo").GetComponent<Toggle>(); if (PlayerPrefs.HasKey("PlayerName")) { if (solo.isOn == true) { bool taken = false; maxPlayers = 1; foreach (RoomInfo data in list) { if (data.Name == roomName) { taken = true; } } if (taken == true || roomName == null) { taken = false; int i = 1; bool naming = true; while (naming) { roomName = soloName + i; foreach (RoomInfo data in list) { if (data.Name == roomName) { taken = true; } } if (taken == false) { naming = false; } } } else { } } else { maxPlayers = 4; } roomOps.MaxPlayers = maxPlayers; PhotonNetwork.JoinOrCreateRoom(roomName, roomOps, null); } else { status.text += ("\n<color=red>Sorry, You need to set a Name first</color>"); } } public override void OnJoinedRoom() { //if (host == true) //{ status.text += ("\n<color=green>You have Joined the room named " + roomName + "</color>"); PhotonNetwork.LoadLevel("Level One"); //} //else if (host == false && joinable == true) //{ //status.text += ("\n<color=green>You have Joined the room named " + roomName + "</color>"); //PhotonNetwork.LoadLevel("Test Room"); //} //else //{ //} } public override void OnJoinRoomFailed(short returnCode, string message) { status.text += ("\n<color=red>Sorry, " + roomName + " is full</color>"); } public override void OnCreatedRoom() { //status.text += ("\n<color=green>You have created the room named " + roomName + "</color>"); //PhotonNetwork.LoadLevel("Level One"); //host = true; //StartCoroutine(Timer()); } //IEnumerator Timer() //{ // yield return new WaitForSeconds(3f); // joinable = true; //} } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Simple_Follow : MonoBehaviour { Transform followTarget; Vector3 cameraOffset; private void Start() { //cameraOffset = followTarget.position - this.transform.position; } private void Update() { if (followTarget == null) { GameObject temp = GameObject.Find("ChickenPlayer"); if (temp != null) { followTarget = temp.transform; cameraOffset = followTarget.position - this.transform.position; } } } private void LateUpdate() { if (followTarget != null) { this.gameObject.transform.position = followTarget.position - cameraOffset; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; using UnityEngine.AI; public class GameStart : MonoBehaviourPunCallbacks, IPunObservable { [SerializeField] GameObject playerPrefab; public Vector3 playerPosition; NavMeshSurface surface; public bool ready = false; private void Awake() { surface = GameObject.FindGameObjectWithTag("Ground").GetComponent<NavMeshSurface>(); GameObject.Find("Main Camera").GetComponent<LoadingScreen>().Load(); if (PhotonNetwork.IsMasterClient) { GetComponent<Visualizer>().GenerateNewMap(); GetComponent<GenerateDetails>().Details(); } } private void Start() { GameObject.Find("Main Camera").GetComponent<LoadingScreen>().Stop(); StartCoroutine(Ready()); //Debug.Log("Making Player"); //Debug.Log(temp.name); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { PhotonNetwork.LeaveRoom(); PhotonNetwork.JoinLobby(); PhotonNetwork.LoadLevel("Lobby"); } } public void SetUp() { surface.BuildNavMesh(); Debug.Log(surface.name); Debug.Log("Where's the NavMesh?"); playerPosition = (Vector3)PhotonNetwork.CurrentRoom.CustomProperties["Players"]; GameObject temp = PhotonNetwork.Instantiate(playerPrefab.name, playerPosition, Quaternion.identity); temp.name = "Player"; ready = true; } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { } public IEnumerator Ready() { while (PhotonNetwork.CurrentRoom.CustomProperties["Dungeon Generated"] == null) { yield return null; } while ((bool)PhotonNetwork.CurrentRoom.CustomProperties["Dungeon Generated"] == false) { yield return null; } yield return new WaitForSeconds(3f); SetUp(); } } <file_sep>using System.Collections; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEditor; public class InventoryClick : MonoBehaviour { #region Variables private SetupInventory steal; //Holds the SetupInventory Script private EquipClick equip; //Holds the EquipClick Script private List<Items> itemList; //Holds the entire itemList private Image[] Inventory; //Holds an array of the items in the Inventory private Image[] Equipment; //Holds an array of the equipment in the inventory private int itemNumber; //The number of the item when it's picked private int nameint; //The name of the button when it's picked private int tint; //The tint of the item when it's picked public Sprite tempSprite; public Color tempColor; private AudioSource cameraAudio; //Audio Source Component for the camera private AudioClip failSound; //Audioclip for failure private AudioClip correctSound; //Audioclip for success #endregion #region Setup private void Awake() { //Initializes variables to their respective components steal = GetComponent<SetupInventory>(); equip = GetComponent<EquipClick>(); cameraAudio = GameObject.Find("Main Camera").GetComponent<AudioSource>(); failSound = Resources.Load<AudioClip>("Sounds/Inventory/Hit_Hurt"); correctSound = Resources.Load<AudioClip>("Sounds/Inventory/Blip_Select"); } private void Start() { //Initializes arrays and List to the created list from the SetupInventory Script itemList = steal.itemList; Inventory = steal.Inventory; Equipment = steal.Equipment; } #endregion #region Select Inventory Item public void _SelectEquippedItem(Image button) { if (equip.equipSelected == true) { if (!Input.GetKey(KeyCode.LeftShift)) { for (int i = 0; i < Equipment.Length; i++) { if (Equipment[i].transform.parent.GetComponent<Image>().color == Color.red) { nameint = Convert.ToInt32(button.gameObject.name); for (int j = 0; j < Inventory.Length; j++) { if (steal.itemList[j] == steal.itemList[nameint]) { if (steal.itemList[j].item == steal.itemList[i + 9].item) { tempSprite = button.sprite; tempColor = button.color; button.sprite = Equipment[i].sprite; button.color = Equipment[i].color; Equipment[i].sprite = tempSprite; Equipment[i].color = tempColor; tint = steal.itemList[j].tint; steal.itemList[j].tint = steal.itemList[i + 9].tint; steal.itemList[i + 9].tint = tint; cameraAudio.clip = correctSound; cameraAudio.Play(); } else if (steal.itemList[j].item != steal.itemList[i + 9].item) { Debug.Log(steal.itemList[j].item + " " + steal.itemList[i + 9].item); cameraAudio.clip = failSound; cameraAudio.Play(); } } } equip.equipSelected = false; Equipment[i].transform.parent.GetComponent<Image>().color = Color.white; } } } } } #endregion #region Destroy Inventory Item public void _DestroyInventory(Image button) { //If nothing is selected from the equipment side if (equip.equipSelected == false) { //If left shift is being held down if (Input.GetKey(KeyCode.LeftShift)) { //Gets the name of the button which is a number, er the image that's a number under the button int nameint = Convert.ToInt32(button.gameObject.name); //Uses that int to Load the black sprite Inventory[nameint].sprite = Resources.Load<Sprite>("Assets/Images/annexation.png"); //Changes the color to black Inventory[nameint].color = Color.black; //Changes the tint to 0 steal.itemList[nameint].tint = 0; //Changes the item to 0 steal.itemList[nameint].item = 0; //Calls the Compress method steal.Compress(); } } } #endregion }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ClearEquip : MonoBehaviour { private EquipClick equip; public Image[] buttons; private void Awake() { equip = GameObject.Find("Main Camera").GetComponent<EquipClick>(); } private void OnDisable() { foreach (Image button in buttons) { button.color = Color.white; } equip.equipSelected = false; } } <file_sep>Attribution: Attribution goes to Andymeneely, Carl-olsen, and Delapouite, for the inventory items. Nothing for the Dungeon Randomization Link: https://zeroclipse.itch.io/torchlight-clone Password: <PASSWORD><file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Player_Input : MonoBehaviour { #region Variables and Delegates #region delete later //Temporary camera things [Tooltip("The Mouse Sensitivity for rotating Right and Left")] public float sensitivityX; [Tooltip("The Mouse Sensitivity for rotating Up and Down")] public float sensitivityY; [Tooltip("The farthest You can look down.")] public float minY = -60; [Tooltip("The farthest you can look up.")] public float maxY = 60; float rotationY = 0f; private Vector3 cameraStartPosition; private Vector3 cameraStartRotation; [SerializeField] private GameObject testInfoScreen; #endregion //This is just to check if the inventory is open or closed public bool inventoryOpen; //This is permanent //This is just to check if the Dungeon Randomization Menu is open or closed public bool dungeonOpen; //This all may be just temporary and is probably temporary, if so delete any instances of this or stuff that requires this //Delete this, this is just for setting up the inventory public SetupInventory setup; //Sends when you click the inventory button, which is i public event Action OnInventoryPress = delegate { }; //Needed //sends when you press escape public event Action OnEscPress = delegate { }; //Needed //Sends when you press G, opens dungeon management things public event Action OnGPress = delegate { }; //Delete later #endregion private void Start() { if (inventoryOpen == false && dungeonOpen == false) { testInfoScreen.SetActive(true); } else { testInfoScreen.SetActive(false); } cameraStartPosition = Camera.main.transform.position; cameraStartRotation = Camera.main.transform.localEulerAngles; } void Update() { #region Dungeon Randomization Test //Test Code for the Dungeon Management things if (Input.GetKeyDown(KeyCode.G) && inventoryOpen == false || inventoryOpen == false && Input.GetButtonDown("Escape") && dungeonOpen == true) { //Calls the delegate that has the method to open or close the Dungeon Menu OnGPress(); //Switches Dungeon open to true or false if (dungeonOpen == false) { dungeonOpen = true; testInfoScreen.SetActive(false); } else { testInfoScreen.SetActive(true); dungeonOpen = false; Camera.main.transform.position = cameraStartPosition; Camera.main.transform.localEulerAngles = cameraStartRotation; } } #endregion #region Open and Close Inventory //Check if you want to close the inventory if (Input.GetButtonDown("InventoryButton") && dungeonOpen == false || inventoryOpen == true && Input.GetButtonDown("Escape") && dungeonOpen == false) { //Calls the delegate that has the method to open or close the inventory OnInventoryPress(); //Switches inventory open to true or false if (inventoryOpen == false) { inventoryOpen = true; testInfoScreen.SetActive(false); } else { testInfoScreen.SetActive(true); inventoryOpen = false; } } #endregion #region Escape if (inventoryOpen == false && dungeonOpen == false && Input.GetButtonDown("Escape")) { OnEscPress(); } #endregion if (inventoryOpen == true && dungeonOpen == false) { #region Temporary Test Things for Inventory if (Input.GetKeyDown(KeyCode.Alpha1)) { setup.Place1(); } if (Input.GetKeyDown(KeyCode.Alpha2)) { setup.Place2(); } if (Input.GetKeyDown(KeyCode.Alpha3)) { setup.Place3(); } if (Input.GetKeyDown(KeyCode.Alpha4)) { setup.Place4(); } if (Input.GetKeyDown(KeyCode.Alpha5)) { setup.Place5(); } #endregion } #region Test things for dungeon else if (dungeonOpen == true && inventoryOpen == false) { //Use this for the camera moving scripts, maybe make a method that this calls and can be commented out CameraMove(); } #endregion } #region CameraMove //Moves, rotates and changes height of the camera. private void CameraMove() { //If tester pressed w or s buttons, camera moves forward and backwards if (Input.GetButton("Vertical Movement")) { Camera.main.transform.position += transform.forward * Input.GetAxis("Vertical Movement") * .5f; } //If tester pressed a or d buttons, camera moves left and right if (Input.GetButton("Horizontal Movement")) { Camera.main.transform.position += transform.right * Input.GetAxis("Horizontal Movement") * .5f; } //If tester moves mouse, it rotates the camera if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0) { float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; rotationY -= Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp(rotationY, minY, maxY); Camera.main.transform.localEulerAngles = new Vector3(rotationY, rotationX, 0); } //If tester presses space or left alt, camera moves up or down if (Input.GetButton("Raise/Lower Camera")) { Camera.main.transform.position += transform.up * Input.GetAxis("Raise/Lower Camera"); } } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; public class ThreadTest : MonoBehaviour { Thread ping; float workTime = 10; float startTime; float currentTime; public UnityEngine.UI.Text textBox; System.Diagnostics.Stopwatch timer; private void Start() { timer = new System.Diagnostics.Stopwatch(); } private void Update() { if(ping == null) { textBox.text = "Thread is not created...PONG"; } else if (ping.ThreadState == ThreadState.Unstarted) { textBox.text = "Thread is not started...PONG"; } else if (ping.ThreadState == ThreadState.Running) { textBox.text = "Thread is doing something...PONG"; } else if (ping.ThreadState == ThreadState.WaitSleepJoin) { textBox.text = "Thread is sleeping...PONG"; } else if (ping.ThreadState == ThreadState.Stopped) { textBox.text = "Thread is stopped...PONG"; } } void DoStuff() { timer.Start(); System.Random random = new System.Random(); int z = 0; while ((timer.Elapsed.TotalSeconds) < workTime) { for(long i=0;i<10000;i++) { int x = random.Next(1, 21); if (x == 20) { z++; Debug.Log("Ping"); } } Thread.Sleep(500); } timer.Stop(); timer.Reset(); Debug.Log("Ping: " + z); } public void CreateThread() { if ((ping != null && ping.ThreadState == ThreadState.Stopped) || ping == null) { ping = new Thread(DoStuff); ping.Start(); } else { Debug.Log("Did not start thread...PONG"); } } public void StartThread() { //ping.Start(); } } <file_sep>using System; using System.Threading; namespace Threading { class Program { static Object obj = new object(); static void Main(string[] args) { #region OldMain //while (true) //{ // //Console.WriteLine("Main thread starting"); // //Thread t = new Thread(new ThreadStart(ThreadTest.DoStuff)); // //t.Start(); // //// Thread.Sleep(0); // //// for (int i = 0; i < 5; i++) // //// { // //// Console.WriteLine("This is the main thread! + " + i); // //// Thread.Sleep(0); // //// } // //ThreadTest.counter = 0; // //for (int i = 0; i < 50; i++) // //{ // // ThreadTest.counter += 1; // // Console.WriteLine("Main thread: counter is " + ThreadTest.counter); // // Thread.Sleep(1); // //} // //Console.WriteLine("Waiting for the other thread"); // //t.Join(); // //Console.WriteLine("All threads done."); //} #endregion Console.WriteLine("Main thread start"); Thread t = new Thread(ShowThreadInfo); t.Start(); t = new Thread(ShowThreadInfo); t.IsBackground = true; t.Start(); t = new Thread(ShowThreadInfo); t.Start(); Thread.Sleep(50); ShowThreadInfo(); //Console.WriteLine("Waiting for other thread"); //t.Join(); Console.WriteLine("All Done"); } static void ShowThreadInfo() { Thread currentThread = Thread.CurrentThread; lock (obj) { Console.WriteLine("Thread ID: {0}", currentThread.ManagedThreadId); Console.WriteLine("Background: {0}", currentThread.IsBackground); Console.WriteLine("Is Threadpool: {0}", currentThread.IsThreadPoolThread); Console.WriteLine("Priority: {0}", currentThread.Priority); Console.WriteLine("Culture Name: {0}", currentThread.CurrentCulture.Name); Console.WriteLine("Done"); } } } public class ThreadTest { public static int counter; /// <summary> /// This is a tool tip /// </summary> /// <param name="data">How many times to say hi</param> public static void DoStuff(Object data) { #region OldDostuff // for(int i = 0; i < 10; i++) // { // Console.WriteLine("Hello from the other thread + " + i); // Thread.Sleep(0); // } //while (true) //{ // if (ThreadTest.counter >= 25) // { // break; // } // ThreadTest.counter += 1; // Console.WriteLine("Other thread: counter is " + ThreadTest.counter); //} #endregion int counter = (int)data; for (int i = 0; i < counter; i++) { Console.WriteLine("Hello There Carter #" + (i+1)); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Visualizer : MonoBehaviour { public bool firstTime = true; public int width = 20; public int height = 10; [SerializeField] GameObject floorTile; //[SerializeField] GameObject wallTile; [SerializeField] Color floorColor; [SerializeField] Color wallColor; public GameObject details; public GameObject visualizer; public int[] mapData; private GameObject[] tileData; public void GenerateNewMap() { details.SetActive(false); visualizer.SetActive(true); if (firstTime) { mapData = new int[width * height]; tileData = new GameObject[mapData.Length]; for (int i = 0; i < mapData.Length; i++) { mapData[i] = i % 2; tileData[i] = Instantiate(floorTile, visualizer.transform); if (mapData[i] == 0) { tileData[i].GetComponent<SpriteRenderer>().color = wallColor; } Vector3 newPos = tileData[i].transform.position; newPos.y = (height / 2) - (i / width - .5f); newPos.x = (width / 2) - (i % width); tileData[i].transform.position = newPos; } firstTime = false; } Map_Randomization random = new Map_Randomization(); random.width = this.width; random.height = this.height; random.GenerateLevel(); this.mapData = random.mapData; DisplayMapData(); } public void DisplayMapData() { for(int i = 0; i < mapData.Length; i++) { if (mapData[i] == 1) { tileData[i].GetComponent<SpriteRenderer>().color = wallColor; } else if (mapData[i] == 2) { tileData[i].GetComponent<SpriteRenderer>().color = floorColor; } else if (mapData[i] == 3) { tileData[i].GetComponent<SpriteRenderer>().color = Color.green; } else if (mapData[i] == 4) { tileData[i].GetComponent<SpriteRenderer>().color = Color.red; } else if (mapData[i] == 0) { tileData[i].GetComponent<SpriteRenderer>().color = Color.yellow; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Visualizer : MonoBehaviour { [SerializeField] int width = 20; [SerializeField] int height = 10; [SerializeField] GameObject floorTile; //[SerializeField] GameObject wallTile; [SerializeField] Color floorColor; [SerializeField] Color wallColor; public int[] mapData; private GameObject[] tileData; private void Start() { mapData = new int[width * height]; tileData = new GameObject[mapData.Length]; for (int i = 0; i < mapData.Length; i++) { mapData[i] = i % 2; tileData[i] = Instantiate(floorTile); if (mapData[i] == 0) { tileData[i].GetComponent<SpriteRenderer>().color = wallColor; } Vector3 newPos = tileData[i].transform.position; newPos.y = (height/2) - (i / width - .5f); newPos.x = (width / 2) - (i % width); tileData[i].transform.position = newPos; } } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Map_Randomization random = new Map_Randomization(); random.width = this.width; random.height = this.height; random.GenerateLevel(); this.mapData = random.mapData; DisplayMapData(); } } public void DisplayMapData() { for(int i = 0; i < mapData.Length; i++) { if (mapData[i] == 0) { tileData[i].GetComponent<SpriteRenderer>().color = wallColor; } else tileData[i].GetComponent<SpriteRenderer>().color = floorColor; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEditor; public class SetupInventory : MonoBehaviour { public List<Items> itemList; public int randomNumber; public Image[] Inventory; public Image[] Equipment; public Sprite tempSprite; public Color tempColor; public int tint; public int itemNumber; //Think about using this delegate when other methods want to call compressItems, maybe delete it public event System.Action compressItems = delegate { }; private void Awake() { itemList = new List<Items>(); //Temporary foreach (Image item in Inventory) { Items newItem = new Items(); itemList.Add(newItem); } tint = Random.Range(1, 5); //Finish itemList[0].EnterItems(1, tint); itemList[1].EnterItems(2, tint); itemList[2].EnterItems(3, tint); itemList[3].EnterItems(4, tint); itemList[4].EnterItems(5, tint); randomNumber = Random.Range(1, 5); if (randomNumber == 1) { //Use Asset Database Inventory[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/brutal-helm"); } if (randomNumber == 2) { //Use Asset Database Inventory[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/spartan-helmet"); } if (randomNumber == 3) { //Use Asset Database Inventory[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/turban"); } if (randomNumber == 4) { //Use Asset Database Inventory[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/viking-helmet"); } randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database Inventory[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/pirate-coat"); } if (randomNumber == 2) { //Use Asset Database Inventory[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/polo-shirt"); } if (randomNumber == 3) { //Use Asset Database Inventory[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/sleeveless-jacket"); } randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database Inventory[2].sprite = Resources.Load<Sprite>("Images/Inventory/Pants/shorts"); } if (randomNumber == 2) { //Use Asset Database Inventory[2].sprite = Resources.Load<Sprite>("Images/Inventory/Pants/wooden-pegleg"); } randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database Inventory[3].sprite = Resources.Load<Sprite>("Images/Inventory/Shields/police-badge"); } if (randomNumber == 2) { //Use Asset Database Inventory[3].sprite = Resources.Load<Sprite>("Images/Inventory/Shields/templar-shield"); } randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database Inventory[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/baseball-bat"); } if (randomNumber == 2) { //Use Asset Database Inventory[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/crossbow"); } if (randomNumber == 3) { //Use Asset Database Inventory[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/two-handed-sword"); } Inventory[0].color = Color.red; Inventory[1].color = Color.blue; Inventory[2].color = Color.green; Inventory[3].color = Color.yellow; Inventory[4].color = Color.magenta; foreach (Image item in Equipment) { Items newItem = new Items(); itemList.Add(newItem); } tint = Random.Range(1, 5); itemList[9].EnterItems(1, tint); randomNumber = Random.Range(1, 5); if (randomNumber == 1) { //Use Asset Database Equipment[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/brutal-helm"); } if (randomNumber == 2) { //Use Asset Database Equipment[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/spartan-helmet"); } if (randomNumber == 3) { //Use Asset Database Equipment[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/turban"); } if (randomNumber == 4) { //Use Asset Database Equipment[0].sprite = Resources.Load<Sprite>("Images/Inventory/Helmets/viking-helmet"); } if (itemList[9].tint == 0) { Equipment[0].color = Color.red; } if (itemList[9].tint == 1) { Equipment[0].color = Color.blue; } if (itemList[9].tint == 2) { Equipment[0].color = Color.green; } if (itemList[9].tint == 3) { Equipment[0].color = Color.yellow; } if (itemList[9].tint == 4) { Equipment[0].color = Color.magenta; } tint = Random.Range(1, 5); itemList[10].EnterItems(2, tint); randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database Equipment[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/pirate-coat"); } if (randomNumber == 2) { //Use Asset Database Equipment[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/polo-shirt"); } if (randomNumber == 3) { //Use Asset Database Equipment[1].sprite = Resources.Load<Sprite>("Images/Inventory/Chest/sleeveless-jacket"); } if (itemList[10].tint == 0) { Equipment[1].color = Color.red; } if (itemList[10].tint == 1) { Equipment[1].color = Color.blue; } if (itemList[10].tint == 2) { Equipment[1].color = Color.green; } if (itemList[10].tint == 3) { Equipment[1].color = Color.yellow; } if (itemList[10].tint == 4) { Equipment[1].color = Color.magenta; } tint = Random.Range(1, 5); itemList[11].EnterItems(3, tint); randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database Equipment[2].sprite = Resources.Load<Sprite>("Images/Inventory/Pants/shorts"); } if (randomNumber == 2) { //Use Asset Database Equipment[2].sprite = Resources.Load<Sprite>("Images/Inventory/Pants/wooden-pegleg"); } if (itemList[11].tint == 0) { Equipment[2].color = Color.red; } if (itemList[11].tint == 1) { Equipment[2].color = Color.blue; } if (itemList[11].tint == 2) { Equipment[2].color = Color.green; } if (itemList[11].tint == 3) { Equipment[2].color = Color.yellow; } if (itemList[11].tint == 4) { Equipment[2].color = Color.magenta; } tint = Random.Range(1, 5); itemList[12].EnterItems(4, tint); randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database Equipment[3].sprite = Resources.Load<Sprite>("Images/Inventory/Shields/police-badge"); } if (randomNumber == 2) { //Use Asset Database Equipment[3].sprite = Resources.Load<Sprite>("Images/Inventory/Shields/templar-shield"); } if (itemList[12].tint == 0) { Equipment[3].color = Color.red; } if (itemList[12].tint == 1) { Equipment[3].color = Color.blue; } if (itemList[12].tint == 2) { Equipment[3].color = Color.green; } if (itemList[12].tint == 3) { Equipment[3].color = Color.yellow; } if (itemList[12].tint == 4) { Equipment[3].color = Color.magenta; } tint = Random.Range(1, 5); itemList[13].EnterItems(5, tint); randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database Equipment[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/baseball-bat"); } if (randomNumber == 2) { //Use Asset Database Equipment[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/crossbow"); } if (randomNumber == 3) { //Use Asset Database Equipment[4].sprite = Resources.Load<Sprite>("Images/Inventory/Weapons/two-handed-sword"); } if (itemList[13].tint == 0) { Equipment[4].color = Color.red; } if (itemList[13].tint == 1) { Equipment[4].color = Color.blue; } if (itemList[13].tint == 2) { Equipment[4].color = Color.green; } if (itemList[13].tint == 3) { Equipment[4].color = Color.yellow; } if (itemList[13].tint == 4) { Equipment[4].color = Color.magenta; } } public void Compress() { for (int i = 0; i < Inventory.Length - 1; i++) { if (itemList[i].item == 0) { tempSprite = Inventory[i].sprite; tempColor = Inventory[i].color; Inventory[i].sprite = Inventory[i + 1].sprite; Inventory[i].color = Inventory[i + 1].color; Inventory[i + 1].sprite = tempSprite; Inventory[i + 1].color = tempColor; tint = itemList[i].tint; itemList[i].tint = itemList[i + 1].tint; itemList[i + 1].tint = tint; itemNumber = itemList[i].item; itemList[i].item = itemList[i + 1].item; itemList[i + 1].item = itemNumber; } } } #region Temporary Testing things //takes in, item, number, and tint, replacing first empty spot with that item, using the loop, once it finds an empty spot, call compress and finally break out. public void PlaceItem(Sprite item, int number, int tint) { for (int i = 0; i < Inventory.Length; i++) { if (itemList[i].item == 0) { Inventory[i].sprite = item; itemList[i].EnterItems(number, tint); if (itemList[i].tint == 1) { Inventory[i].color = Color.blue; } if (itemList[i].tint == 2) { Inventory[i].color = Color.green; } if (itemList[i].tint == 3) { Inventory[i].color = Color.yellow; } if (itemList[i].tint == 4) { Inventory[i].color = Color.magenta; } Compress(); break; } } } public void Place1() { randomNumber = Random.Range(1, 5); if (randomNumber == 1) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Helmets/brutal-helm"); } if (randomNumber == 2) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Helmets/spartan-helmet"); } if (randomNumber == 3) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Helmets/turban"); } if (randomNumber == 4) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Helmets/viking-helmet"); } itemNumber = Random.Range(1, 5); tint = Random.Range(1, 5); PlaceItem(tempSprite, itemNumber, tint); } public void Place2() { randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Chest/pirate-coat"); } if (randomNumber == 2) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Chest/polo-shirt"); } if (randomNumber == 3) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Chest/sleeveless-jacket"); } itemNumber = Random.Range(1, 5); tint = Random.Range(1, 5); PlaceItem(tempSprite, itemNumber, tint); } public void Place3() { randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Pants/shorts"); } if (randomNumber == 2) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Pants/wooden-pegleg"); } itemNumber = Random.Range(1, 5); tint = Random.Range(1, 5); PlaceItem(tempSprite, itemNumber, tint); } public void Place4() { randomNumber = Random.Range(1, 3); if (randomNumber == 1) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Shields/police-badge"); } if (randomNumber == 2) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Shields/templar-shield"); } itemNumber = Random.Range(1, 5); tint = Random.Range(1, 5); PlaceItem(tempSprite, itemNumber, tint); } public void Place5() { randomNumber = Random.Range(1, 4); if (randomNumber == 1) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Weapons/baseball-bat"); } if (randomNumber == 2) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Weapons/crossbow"); } if (randomNumber == 3) { //Use Asset Database tempSprite = Resources.Load<Sprite>("Images/Inventory/Weapons/two-handed-sword"); } itemNumber = Random.Range(1, 5); tint = Random.Range(1, 5); PlaceItem(tempSprite, itemNumber, tint); } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LoadingScreen : MonoBehaviour { public float totalTime = 4; public bool doingThings; public string words = "Connecting"; public Text connectingText; public GameObject connectingCanvas; public void Load() { connectingCanvas.SetActive(true); doingThings = true; StartCoroutine(Loading()); } IEnumerator Loading() { float elapsedTime = 0; float timer = totalTime / 4f; float timer2 = timer + timer; float timer3 = timer + timer2; float timer4 = timer + timer3; while (doingThings) { elapsedTime += timer; yield return new WaitForSeconds(timer); if (elapsedTime % timer4 == 0) { connectingText.text = words + "..."; } else if (elapsedTime % timer3 == 0) { connectingText.text = words + ".."; } else if (elapsedTime % timer2 == 0) { connectingText.text = words + "."; } else if (elapsedTime % timer == 0) { connectingText.text = words; } } } public void Stop() { StartCoroutine(Stopping()); } IEnumerator Stopping() { yield return new WaitForSeconds(5); doingThings = false; connectingCanvas.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScoreReport : MonoBehaviour { Dictionary<string, Text> scoreBoxes; private string firstPerson; private string secondPerson; private string thirdPerson; [SerializeField] List<GameObject> textRefs; private void Start() { scoreBoxes = new Dictionary<string, Text>(); //if (photonView.IsMine) //{ // //animator = GetComponent<Animator>(); //} //scoreBoxes.Add("local", GameObject.Find("My Panel").GetComponentInChildren<Text>()); foreach (GameObject item in textRefs) { item.SetActive(false); } } public void ScoreUpdate(string ID, int score) { scoreBoxes[ID].text = ID + ": " + score; } public void Register(string ID) { if (ID == "local") { scoreBoxes.Add("local", textRefs[0].GetComponentInChildren<Text>()); textRefs[0].SetActive(true); } else { scoreBoxes.Add(ID, textRefs[scoreBoxes.Count].GetComponentInChildren<Text>()); textRefs[scoreBoxes.Count].SetActive(true); if (firstPerson == null) { firstPerson = ID; } else if (secondPerson == null) { secondPerson = ID; } else if (thirdPerson == null) { thirdPerson = ID; } } } public void UnRegister(string ID) { if (ID == "local") { } else { scoreBoxes.Remove(ID); if (firstPerson != null && firstPerson == ID) { textRefs[1].SetActive(false); } else if (secondPerson != null && secondPerson == ID) { textRefs[2].SetActive(false); } else if (thirdPerson != null && thirdPerson == ID) { textRefs[3].SetActive(false); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Items { public int item; public int tint; public Items() { item = 0; tint = 0; } public void EnterItems(int itement, int tintent) { item = itement; tint = tintent; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Check_Inventory : MonoBehaviour { #region Variables //variable to decide what to do, open or close the inventory private bool inventoryOpen = false; //Object that holds the inventory Screen [SerializeField]private GameObject inventoryScreen; //Variable that holds the player Input component private Player_Input playerInput; #endregion #region Set up private void Awake() { //Find the PlayerInput component playerInput = GameObject.Find("Main Camera").GetComponent<Player_Input>(); //Subscription here playerInput.OnInventoryPress += InventoryCheck; } private void Start() { inventoryOpen = playerInput.inventoryOpen; //Disables the inventoryScreen if inventoryOpen is false if (inventoryOpen == false) { inventoryScreen.SetActive(false); } //Else it makes sure that it's open else { inventoryScreen.SetActive(true); } } #endregion #region Inventory Check //Open or Close Inventory public void InventoryCheck() { //Opens the inventory Screen if (inventoryOpen == false) { inventoryScreen.SetActive(true); inventoryOpen = true; } //Closes the inventory Screen else { inventoryScreen.SetActive(false); inventoryOpen = false; } } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Follow : MonoBehaviour { Transform followTarget; public Vector3 cameraOffset; // Start is called before the first frame update void Start() { if (followTarget == null) { StartCoroutine(FollowDelay()); } } private void LateUpdate() { if (followTarget != null) { this.gameObject.transform.position = followTarget.position - cameraOffset; } } IEnumerator FollowDelay() { yield return new WaitForSeconds(1f); GameObject temp = GameObject.Find("Player"); if (temp != null) { this.gameObject.GetComponent<Transform>().Rotate(new Vector3(40, 180, 0)); followTarget = temp.transform; } } }
620db74553cb42e4d734c311f13d46bd006c9681
[ "C#", "Text" ]
33
C#
Zeroclipse/Torchlight-Clone
f97bae390ef2f9f11a282e78d90d37e00b32586e
3c4dcd4e3981452a665283c4443f47852b3360d0
refs/heads/master
<repo_name>33priya/LearnCamel<file_sep>/learncamel-transform/src/test/java/com/learncamel/routes/defaulterrorhandler/DefaultErrorHandlerRouteTest.java package com.learncamel.routes.defaulterrorhandler; import org.apache.camel.RoutesBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class DefaultErrorHandlerRouteTest extends CamelTestSupport { @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new DefaultErrorHandlerRoute(); } @Test(expected = RuntimeException.class) public void checkException() { String expectedValue = "123*Priya*15OCT2018"; String input = null; String output = template.requestBody("direct:exception", input, String.class); assertEquals(expectedValue, output); } } <file_sep>/learncamel-transform/src/main/java/com/learncamel/aggregate/CompletionPredicateAggregatorStrategy.java package com.learncamel.aggregate; import org.apache.camel.Exchange; import org.apache.camel.processor.aggregate.AggregationStrategy; public class CompletionPredicateAggregatorStrategy implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange != null) { String oldExchangeValue = (String) oldExchange.getIn().getBody(); String newExchangeValue = (String) newExchange.getIn().getBody(); newExchangeValue = oldExchangeValue.concat(":").concat(newExchangeValue); newExchange.getIn().setBody(newExchangeValue); } return newExchange; } } <file_sep>/learncamel-transform/src/main/java/com/learncamel/bean/DataModifier.java package com.learncamel.bean; import java.util.logging.Logger; public class DataModifier { Logger logger = Logger.getLogger(DataModifier.class.getName()); public String map(String input) throws Exception { String newBody; try { newBody = input.replace(",", "*"); } catch (RuntimeException e) { logger.severe("RuntimeException: " + e); throw e; } catch (Exception e) { logger.severe("Exception: " + e); throw e; } return newBody; } public String mapOnException(String input) throws Exception { String newBody; try { newBody = input.replace(",", "*"); } catch (RuntimeException e) { logger.severe("RuntimeException: " + e); throw e; } catch (Exception e) { logger.severe("Exception: " + e); throw e; } return newBody; } } <file_sep>/learncamel-transform/src/main/java/com/learncamel/bean/CamelBean.java package com.learncamel.bean; public class CamelBean { public String map(String input) { return input.replace(",", "*"); } public String map1(String input) { return input.replace(",", "*"); } } <file_sep>/learncamel-transform/src/test/java/com/learncamel/routes/transform/CamelModifyDirectTransformRouteTest.java package com.learncamel.routes.transform; import org.apache.camel.RoutesBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class CamelModifyDirectTransformRouteTest extends CamelTestSupport { @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new CamelModifyDirectTransformRoute(); } @Test public void testDirectTransform() { String expectedOutput = "123*Line1*Test*Apache*Camel*Transform\n" + "456*Line2*Test*Apache*Camel*Transform"; String input = "123,Line1,Test,Apache,Camel,Transform\n" + "456,Line2,Test,Apache,Camel,Transform"; String actual = (String) template.requestBody("direct:transformInput", input); assertEquals(expectedOutput, actual); } @Test public void testDirectTransformUsingMock() throws InterruptedException { String expectedOutput = "123*Line1*Test*Apache*Camel*Transform\n" + "456*Line2*Test*Apache*Camel*Transform"; MockEndpoint mock = getMockEndpoint("mock:output"); mock.expectedBodiesReceived(expectedOutput); String input = "123,Line1,Test,Apache,Camel,Transform\n" + "456,Line2,Test,Apache,Camel,Transform"; template.sendBody("direct:transformInput", input); assertMockEndpointsSatisfied(); } } <file_sep>/learncamel-transform/src/main/java/com/learncamel/routes/onexceptionhandler/OnExceptionHandlerRoute.java package com.learncamel.routes.onexceptionhandler; import com.learncamel.bean.DataModifier; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; public class OnExceptionHandlerRoute extends RouteBuilder { @Override public void configure() throws Exception { /*onException(RuntimeException.class, Exception.class).maximumRedeliveries(2).redeliveryDelay(5000) .backOffMultiplier(2).log(LoggingLevel.INFO, "Exception caught in Bean");*/ /*onException(RuntimeException.class).handled(true).maximumRedeliveries(2).delay(5000) .process(new GenerateErrorReponseProcessor()).log(LoggingLevel.INFO, "Exception caught in Bean");*/ onException(RuntimeException.class).continued(true).log(LoggingLevel.INFO, "Exception caught in Bean"); from("direct:exception") .bean(new DataModifier(), "mapOnException") .to("log:?level=INFO&showBody=true"); } } <file_sep>/learncamel-transform/src/test/java/com/learncamel/eips/aggregator/AggregatorRouteTest.java package com.learncamel.eips.aggregator; import org.apache.camel.RoutesBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class AggregatorRouteTest extends CamelTestSupport { @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new AggregatorRoute(); } @Test public void aggregateRouteTest() throws InterruptedException { MockEndpoint endpoint = getMockEndpoint("mock:output"); endpoint.expectedBodiesReceived("123"); template.sendBodyAndHeader("direct:simpleAggregator", "1", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "2", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "4", "aggregatorId", 2); template.sendBodyAndHeader("direct:simpleAggregator", "3", "aggregatorId", 1); assertMockEndpointsSatisfied(); } @Test public void aggregateMultipleMessages() throws InterruptedException { MockEndpoint endpoint = getMockEndpoint("mock:output"); List<String> expectedValueList = new ArrayList<>(); expectedValueList.add("123"); expectedValueList.add("567"); endpoint.expectedBodiesReceived(expectedValueList); template.sendBodyAndHeader("direct:simpleAggregator", "1", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "2", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "4", "aggregatorId", 2); template.sendBodyAndHeader("direct:simpleAggregator", "3", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "5", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "6", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "7", "aggregatorId", 1); assertMockEndpointsSatisfied(); } @Test public void aggregateMultipleMessagesWithDiffAggregateId() throws InterruptedException { MockEndpoint endpoint = getMockEndpoint("mock:output"); List<String> expectedValueList = new ArrayList<>(); expectedValueList.add("123"); expectedValueList.add("456"); endpoint.expectedBodiesReceived(expectedValueList); template.sendBodyAndHeader("direct:simpleAggregator", "1", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "4", "aggregatorId", 2); template.sendBodyAndHeader("direct:simpleAggregator", "2", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "5", "aggregatorId", 2); template.sendBodyAndHeader("direct:simpleAggregator", "3", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "6", "aggregatorId", 2); assertMockEndpointsSatisfied(); } @Test public void aggregateMessageTimeout() throws InterruptedException { MockEndpoint endpoint = getMockEndpoint("mock:output"); endpoint.expectedBodiesReceived("12"); template.sendBodyAndHeader("direct:simpleAggregator", "1", "aggregatorId", 1); template.sendBodyAndHeader("direct:simpleAggregator", "2", "aggregatorId", 1); Thread.sleep(5000); template.sendBodyAndHeader("direct:simpleAggregator", "4", "aggregatorId", 2); template.sendBodyAndHeader("direct:simpleAggregator", "3", "aggregatorId", 1); assertMockEndpointsSatisfied(); } }
a0831cad6135d11701495f84b1d4eee617009d5a
[ "Java" ]
7
Java
33priya/LearnCamel
0de023b6812018940592ed40bdceef32b13184ca
72826b2b248748f976948b2a09a70909b61d75b9
refs/heads/master
<file_sep>/* Set up imports */ import { register } from "./config/config.js" import ActiveTimelinesApp from "./apps/ActiveTimelinesApp.js"; import { timelineFolderId, constants } from "./utils.js" import { preloadTemplates, renderTimelineBodyTmpl, strEqual } from "./hbs-templates.js" import * as logger from "./logger.js" Hooks.once('setup', () => { console.debug("Timeline | seting up") }) Hooks.once('init', () => { console.debug("Timeline | initializing...") register(); preloadTemplates(); Handlebars.registerHelper("renderTimelineBody", renderTimelineBodyTmpl); Handlebars.registerHelper("strEqual", strEqual); }) /** * Setting up the main timeline, adding triggers, etc. */ Hooks.once('ready', () => { console.debug("Timeline | ready...") if (timelineFolderId()) { logger.log(logger.DEBUG, "loaded timeline folder") } }); /** * Setting up the button so it is rendered and setting the click events for the button */ Hooks.on("renderJournalDirectory", (app, html, data) => { logger.log(logger.DEBUG, "Adding button to journal sidebar"); const button = $("<button class='timeline-button'><i class='fas fa-code-branch'></i>Manage Timelines</button>"); let footer = html.find(".directory-footer"); if (footer.length === 0) { footer = $(`<footer class="directory-footer"></footer>`); html.append(footer); } footer.append(button); button.click(ev => { logger.log(logger.DEBUG, "Bringing up timeline management window ") new ActiveTimelinesApp().render(true); }); // removing the folder from the display so accidents can't happen if (!constants.DEBUG_MODE || !game.user.isGM) { let folderId = timelineFolderId() let folder = html.find(`.folder[data-folder-id="${folderId}"]`) folder.remove(); logger.log(logger.DEBUG, "game folder id: ", folderId); } });<file_sep>import { constants } from "../utils.js"; export default class TimelineEntry { constructor(data = {}) { this.year = Number(data[constants.TIMELINE_ENTRY_YEAR_KEY] || 0); this.month = Number(data[constants.TIMELINE_ENTRY_MONTH_KEY] || 0); this.day = Number(data[constants.TIMELINE_ENTRY_DAY_KEY] || 0); this.hours = Number(data[constants.TIMELINE_ENTRY_HOUR_KEY] || 0); this.minutes = Number(data[constants.TIMELINE_ENTRY_MINUTES_KEY] || 0); this.eventClass = data[constants.TIMELINE_ENTRY_EVENT_CLASS_KEY]; this.eventType = data[constants.TIMELINE_ENTRY_EVENT_TYPE_KEY]; this.eventTitle = data[constants.TIMELINE_ENTRY_EVENT_TITLE_KEY]; this.htmlDescription = data[constants.TIMELINE_ENTRY_DESCRIPTION_KEY]; } /** * A comparator for * @param {Timeline} entry1 * @param {Timeline} entry2 * @returns */ static comparator(entry1, entry2) { let years = entry1.year - entry2.year; let months = entry1.month - entry2.month; let days = entry1.day - entry2.day; let hours = entry1.hours - entry2.hours; let minutes = entry1.minutes - entry2.minutes; return (years != 0 ? years : months != 0 ? months : days != 0 ? days : hours != 0 ? hours : minutes); } }<file_sep> import * as logger from "../logger.js" import { timelineFolderId, constants, isNullOrUndefined } from "../utils.js" /** * */ export default class ImportTimelineForm extends FormApplication { constructor(data, parent, folderId) { super(data) this.parent = parent this.folderId = folderId } static get defaultOptions() { return mergeObject(super.defaultOptions, { id: 'new-timeline-form', template: 'modules/foundry-timeline/templates/import-timeline-form.html', title: "Import Timeline", width: 200, height: 140, closeOnSubmit: false }); } async _onEditorSave(target, element, content) { this[target] = content; } async _updateObject(event, formData) { let entryList = JSON.parse(formData['import-entries'].trim()) let promiseList = []; for (let i = 0; i < entryList.length; i++) { promiseList.push(JournalEntry.create({ name: entryList[i]['eventTitle'], content: JSON.stringify(entryList[i]), folder: this.folderId, permission: { default: constants.PERMISSION_OBSERVER } })); } Promise.all(promiseList).then(x => { this.close(); }); } }<file_sep>import Timeline from "../entities/timeline.js" import * as logger from "../logger.js" import AddTimelineForm from "./AddTimelineForm.js"; import ImportTimelineForm from "./ImportTimelineForm.js"; import AddEventForm from "./AddEventForm.js"; import { constants, isNullOrUndefined, timelineFolder } from "../utils.js" let TITLE = "Active Timelines" export default class ActiveTimelinesApp extends Application { allTimelines = []; constructor(data) { super(data); this.refreshData() } /** * TODO could be a performance issue to access all these different files at the same time. Maybe refactor here */ refreshData() { this.allTimelines = timelineFolder().children.map(entry => { logger.log(logger.DEBUG, "Reading timeline data for ", entry.data.name); // get _metadata journal entry let metadataJournal = entry.content.find(e => { return e.name === constants.TIMELINE_METADATA_JOURNAL_ENTRY_NAME }) // read the content let data = JSON.parse(metadataJournal.data.content) // use it to instantiate the Timeline return new Timeline(mergeObject(data, { title: entry.data.name, htmlDescription: data.htmlDescription, era: data.era, era_short: data.era_short, folder: entry })) }) } static get defaultOptions() { return mergeObject(super.defaultOptions, { id: "timeline-management", classes: ['forien-quest-log'], template: "modules/foundry-timeline/templates/all-timelines.html", width: 750, height: 580, minimizable: true, resizable: true, title: TITLE, popOut: true, tabs: [{ navSelector: ".log-tabs", contentSelector: ".log-body", initial: "management" }] }); } _getHeaderButtons() { const buttons = super._getHeaderButtons(); if (game.user.isGM) { buttons.unshift({ label: "Delete Timeline", class: "delete-timeline", parent: this, icon: "fas fa-calendar-times", onclick: function() { let timelineName = this.parent._tabs[0].active; let folder = game.journal.directory.folders.find(f => f.name === timelineName) let folderId = folder._id; new Dialog({ title: "Are you sure?", content: "<h3>Deleting the timeline will also delete all entries in the timeline, are you sure?</h3>", buttons: { yes: { icon: `<i class="far fa-trash-alt"></i>`, label: "Yes, delete", callback: () => { let folder = game.journal.directory.folders.find(f => f._id === folderId); logger.log(logger.DEBUG, "Deleting folder id", folderId); let rootDelete = folder.delete(); folder.content.reduce((prev, next) => { return prev.then(() => { return next.delete(); }) }, rootDelete); rootDelete.then(() => { this.parent.render(true) }); } }, no: { icon: `<i class="fas fa-undo"></i>`, label: "Wait!" } } }).render(true) this.parent.render(true) } }); buttons.unshift({ label: "New Timeline", class: "add-timeline", parent: this, icon: "fas fa-calendar-plus", onclick: function() { new AddTimelineForm({}, this.parent).render(true); } }); buttons.unshift({ label: "Event", class: "add-event", parent: this, icon: "fas fa-plus", onclick: function() { let timelineName = this.parent._tabs[0].active; let folder = game.journal.directory.folders.find(f => f.name === timelineName) if (!isNullOrUndefined(folder)) { new AddEventForm({ parentTimelineFolder: folder }, this.parent).render(true) } else { logger.log(logger.ERR, "Could not find timeline folder? Something bad has happened in " + constants.TIMELINE_FOLDER_NAME); } } }); if ( game.settings.get(constants.MODULE_NAME, constants.CONFIG_ALLOW_IMPORTS)) { buttons.unshift({ label: "Import Timeline", class: "import-timeline", parent: this, icon: "fas fa-file-import", onclick: function() { let timelineName = this.parent._tabs[0].active; let folder = game.journal.directory.folders.find(f => f.name === timelineName) let folderId = folder._id; new ImportTimelineForm({}, parent, folderId).render(true) } }); } } return buttons; } getData(options = {}) { // Return promise object containing info used during rendering a template return mergeObject(super.getData(), { options: options, isGm: game.user.isGM, timelines: this.allTimelines.reduce((prev, e) => { return prev.concat(e.asJson()) }, []) }); } render(force, options) { this.refreshData() super.render(force, options) } }<file_sep>/** * Preloads templates for partials */ export let preloadTemplates = function() { let templates = [ "templates/partials/timeline.html", "templates/partials/management.html", "templates/partials/timelineEntry.html" ]; templates = templates.map(t => `modules/foundry-timeline/${t}`); loadTemplates(templates); }; export let renderTimelineBodyTmpl = function(entries, era_short) { let template_function = Handlebars.partials['modules/foundry-timeline/templates/partials/timelineEntry.html'] return entries.map(function(context, index) { let invert = index % 2 == 0 ? "timeline-entry-inverted" : ""; context['invert'] = invert context['era_short'] = era_short return template_function(context) }).join('\n'); }; export let strEqual = function(arg1, arg2, options) { if (arg1 === arg2) { return options.fn(this); } else { return options.inverse(this); } };<file_sep>import * as logger from "../logger.js" import { timelineFolderId, constants, isNullOrUndefined } from "../utils.js" /** * */ export default class AddTimelineForm extends FormApplication { constructor(data, parent) { super(data) this.parent = parent } static get defaultOptions() { return mergeObject(super.defaultOptions, { id: 'new-timeline-form', template: 'modules/foundry-timeline/templates/new-timeline-form.html', title: "New Timeline", width: 600, height: 640, closeOnSubmit: false }); } async _onEditorSave(target, element, content) { this[target] = content; } async _updateObject(event, formData) { if (event.type == "mcesave") { // skip this event... We'll pick it up when the event is added return } let title = formData.title let playerVisible = formData.playerVisible; let era = isNullOrUndefined(formData.era) ? "" : formData.era let era_initials = isNullOrUndefined(formData.era_initials) ? "" : formData.era_initials; let htmlDescription = isNullOrUndefined(formData.description) ? constants.HTML_NO_DESCRIPTION : formData.description; logger.log(logger.DEBUG, "Creating new timeline titled ", title.toString()); if (title === undefined) { logger.log(logger.ERR, "Timeline must be given a title") return; } let timelineExists = game.journal.directory.folders.find(f => f.name === title); if (timelineExists) { logger.log(logger.WARN, "Timeline '", title, "' already exists"); return; } let data = {} data[constants.TIMEILNE_METADATA_PLAYER_VISIBLE] = playerVisible data[constants.TIMELINE_METADATA_ERA] = era; data[constants.TIMELINE_METADATA_ERA_INITIALS] = era_initials; data[constants.TIMELINE_METADATA_DESCRIPTION] = htmlDescription; // comes from _onEditorSave() return Folder.create({ name: title, type: "JournalEntry", parent: timelineFolderId() }).then((entry) => { ui.notifications.info("New timeline '" + title + "' created"); JournalEntry.create({ name: constants.TIMELINE_METADATA_JOURNAL_ENTRY_NAME, content: JSON.stringify(data), folder: entry._id, permission: { default: constants.PERMISSION_OBSERVER } }).then(() => { logger.log(logger.INFO, "Metadata for ", title, " timeline created") this.parent.render(true); }, () => { logger.log(logger.WARN, "Metadata for ", title, " timeline could not be created! This could lead to undesireable affects") }) this.close(); }); } }<file_sep>export const DEBUG = "debug" export const INFO = "info" export const WARN = "warn" export const ERR = "err" export let log = (level, ...message) => { let output = message.reduce((prev, curr) => { return prev + " " + curr.toString() }, "") switch (level) { case ERR: { ui.notifications.error(output); console.error("Timeline | " + output); break; } case WARN: { ui.notifications.warn(output); console.warn("Timeline | " + output); break; } case INFO: { ui.notifications.info(output); console.info("Timeline | " + output); break; } case DEBUG: default: { console.debug("Timeline | " + output); } } };<file_sep>FROM ubuntu:20.04 # ** [Optional] Uncomment this section to install additional packages. ** # RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive \ apt-get -y install node-typescript node-typescript-types build-essential npm git python3 python3-pip RUN npm install --save-dev gitlab:foundry-projects/foundry-pc/foundry-pc-types RUN git config --global user.name "<NAME>" RUN git config --global user.email "<EMAIL>" RUN npm install -g sass<file_sep>from html.parser import HTMLParser import json TIMELINE_FILE = './wa-timeline-copy.html' OUT_FILE = './wa-timeline-entry-data.json' EVENT_CLASS_ENUMERATION = set(['trivial', 'minor', 'important', 'major', 'milestone']) class WaParser(HTMLParser): path = [] parse_mode = "none" all_entries = [] current_entry = { "year" : 0, "month" : -1, "day" : -1, "hours" : 0, "minutes" : 0, "eventClass" : "", "eventType" : "", "eventTitle" : "", "htmlDescription" : "" } passthrough = False content_builder = "" data_handler = id cannot_be_empty = True def handle_starttag(self, tag, attr): if len(self.path) > 0: self.path.append(tag) self.content_builder += f'<{tag} ' self.content_builder += ' '.join([ f'{x}="{y}"' for (x,y) in attr]) self.content_builder += ">" return attr = dict(attr) for key in attr: attr[key] = set(attr[key].split(' ')) if tag == 'div': self.handle_div(tag, attr) elif tag == 'li': self.handle_li(tag, attr) elif tag == 'h4': self.handle_h4(tag, attr) elif tag == 'small': self.handle_small(tag, attr) def handle_endtag(self, tag): if len(self.path) > 0: self.path.pop() if len(self.path) == 0: self.current_entry['htmlDescription'] = self.content_builder.strip() self.content_builder = "" else: self.content_builder += f' </{tag}> ' return if tag == 'li': self.all_entries.append(self.current_entry) self.reset_entry() def handle_data(self, data): if len(self.path) > 0: self.content_builder += ' '.join(map(lambda x: x.strip(), data.split('\n'))) return if len(data.strip()) == 0 and self.cannot_be_empty: return self.data_handler(data) self.data_handler = id def handle_div(self, tag, attr): if 'class' in attr and 'history-content' in attr['class']: self.path.append(tag) elif 'class' in attr and 'history-year' in attr['class']: def handler(x): year = x.strip().split(' ')[0] self.current_entry['year'] = int(year) self.data_handler = handler elif 'class' in attr and 'history-day' in attr['class'] and self.current_entry['day'] == -1: def handler(x): day = int(x.strip()) self.current_entry['day'] = day self.data_handler = handler elif 'class' in attr and 'history-month' in attr['class'] and self.current_entry['month'] == -1: def handler(x): month = int(x.strip().split('/')[1]) self.current_entry['month'] = month self.data_handler = handler elif 'class' in attr and 'history-hour' in attr['class']: def handler(x): time_string = x.strip().split('-')[0] if time_string != '': time_string_ls = time_string.split(':') self.current_entry['hours'] = int(time_string_ls[0]) if len(time_string_ls) > 1: self.current_entry['minutes'] = int(time_string_ls[1]) self.cannot_be_empty = True self.cannot_be_empty = False self.data_handler = handler def handle_li(self, tag, attr): if 'timeline-entry' in attr['class']: entry_class = EVENT_CLASS_ENUMERATION & attr['class'] self.current_entry['eventClass'] = entry_class.pop() if len(entry_class) > 0 else "trivial" def handle_h4(self, tag, attr): def handler(x): self.current_entry['eventTitle'] = x.strip() self.data_handler = handler def handle_small(self, tag, attr): def handler(x): if len(x.strip()) == 0: return else: print(x) self.current_entry['eventType'] = x.strip() self.data_handler = handler def reset_entry(self): self.current_entry = { "year" : 0, "month" : -1, "day" : -1, "hours" : 0, "minutes" : 0, "eventClass" : "", "eventType" : "", "eventTitle" : "", "htmlDescription" : "" } if __name__ == '__main__': parser = WaParser() with open(TIMELINE_FILE, 'r') as f: parser.feed(f.read()) entry_len = len(parser.all_entries) print(f'Number of entries parsed: {entry_len}') print(parser.all_entries[0]) with open(OUT_FILE, 'w') as f: json.dump(parser.all_entries, f, indent=2) with open(OUT_FILE.replace(".json", ".min.json"), 'w') as f: json.dump(parser.all_entries, f)<file_sep>{ "compilerOptions": { "allowJs" : true, "experimentalDecorators": true, "target": "ES2020", "types": [ "/node_modules/foundry-pc-types" ], "outDir": "./out-js" } }<file_sep>export let constants = { DEBUG_MODE: false, PERMISSION_NONE: 0, PERMISSION_OBSERVER: 2, MODULE_NAME: "foundry-timeline", CONFIG_DEBUG_MODE: "timeline-debug-mode", CONFIG_USE_ABOUT_TIME_OPTION: "timeline-use-about-time", CONFIG_ALLOW_IMPORTS: "timeline-allow-json-imports", TIMELINE_FOLDER_NAME: "_all_timelines", MAX_TAB_TITLE_LENGTH: 14, HTML_NO_DESCRIPTION: "<p>No Description given...</p>", TIMELINE_METADATA_JOURNAL_ENTRY_NAME: "_metadata", TIMEILNE_METADATA_PLAYER_VISIBLE: "playerVisible", TIMELINE_METADATA_ERA: "era", TIMELINE_METADATA_ERA_INITIALS: "era_short", TIMELINE_METADATA_DESCRIPTION: "htmlDescription", TIMELINE_ENTRY_EVENT_TYPES: ["trivial", "minor", "important", "major", "milestone"], TIMELINE_ENTRY_YEAR_KEY: "year", TIMELINE_ENTRY_MONTH_KEY: "month", TIMELINE_ENTRY_DAY_KEY: "day", TIMELINE_ENTRY_HOUR_KEY: "hours", TIMELINE_ENTRY_MINUTES_KEY: "minutes", TIMELINE_ENTRY_EVENT_CLASS_KEY: "eventClass", TIMELINE_ENTRY_EVENT_TYPE_KEY: "eventType", TIMELINE_ENTRY_EVENT_TITLE_KEY: "eventTitle", TIMELINE_ENTRY_DESCRIPTION_KEY: "htmlDescription" }; export let isNullOrUndefined = (obj) => { return obj === null || obj === undefined } export let timelineFolder = () => { if (!(isNullOrUndefined(game) || isNullOrUndefined(game.journal) || isNullOrUndefined(game.journal.directory) || isNullOrUndefined(game.journal.directory.folders))) { let gameFolder = game.journal.directory.folders.find(f => f.name === constants.TIMELINE_FOLDER_NAME); if (gameFolder === undefined) { Folder.create({ name: constants.TIMELINE_FOLDER_NAME, type: "JournalEntry", parent: null }); } return game.journal.directory.folders.find(f => f.name === constants.TIMELINE_FOLDER_NAME); } else { return null } } export let timelineFolderId = () => { let folder = timelineFolder(); return folder === null ? null : folder._id; };<file_sep>import * as logger from "../logger.js" import { constants as c, isNullOrUndefined } from "../utils.js" export default class AddEventForm extends FormApplication { constructor(data = {}, parentUi) { super(data) this.activeTimelineApp = parentUi; this.parentTimelineFolder = data.parentTimelineFolder this.useAboutTime = game.settings.get(c.MODULE_NAME, c.CONFIG_USE_ABOUT_TIME_OPTION); this.eventClass = c.TIMELINE_ENTRY_EVENT_TYPES[0] this.data = {} } static get defaultOptions() { return mergeObject(super.defaultOptions, { id: "new-event-form", template: "modules/foundry-timeline/templates/new-event-form.html", title: "New Event", width: 600, height: 700, closeOnSubmit: false }); } async _updateObject(event, formData, x) { logger.log(logger.DEBUG, "Adding journal entry to '", this.parentTimelineFolder.data.name, "'") if (event.type == "mcesave") { // no need to close right now on MCE save. We'll close once the user hits create this.description = formData.description; return } else { let playerVisible = formData.playerVisible || false; let time = isNullOrUndefined(formData.timeString) ? event.target.elements.timeString.getAttribute('defaultValue') : formData.timeString; this.data[c.TIMELINE_ENTRY_YEAR_KEY] = Number(isNullOrUndefined(formData.year) ? event.target.elements.year.getAttribute('defaultValue') : formData.year); this.data[c.TIMELINE_ENTRY_DAY_KEY] = Number(isNullOrUndefined(formData.day) ? event.target.elements.day.getAttribute('defaultValue') : formData.day); this.data[c.TIMELINE_ENTRY_MONTH_KEY] = Number(isNullOrUndefined(formData.month) ? event.target.elements.month.getAttribute('defaultValue') : formData.month); this.data[c.TIMELINE_ENTRY_HOUR_KEY] = Number(time.split(':')[0]); this.data[c.TIMELINE_ENTRY_MINUTES_KEY] = Number(time.split(':')[1]); this.data[c.TIMELINE_ENTRY_EVENT_CLASS_KEY] = this.eventClass; this.data[c.TIMELINE_ENTRY_EVENT_TITLE_KEY] = formData.eventTitle; this.data[c.TIMELINE_ENTRY_DESCRIPTION_KEY] = (formData.description !== undefined && formData.description.length) ? formData.description : this.description; return JournalEntry.create({ name: this.data.eventTitle, content: JSON.stringify(this.data), folder: this.parentTimelineFolder._id, permission: { default: playerVisible ? c.PERMISSION_OBSERVER : c.PERMISSION_NONE } }).then(() => { logger.log(logger.INFO, "Event created") this.activeTimelineApp.render(true) this.close() }); } } async _onEditorSave(target, element, content) { this[target] = content; } activateListeners(html) { super.activateListeners(html); html.on("click", ".use-about-time-checkbox", () => { logger.log(logger.DEBUG, "Checkbox clicked, re-render") this.useAboutTime = !this.useAboutTime; this.render(true) }); html.on('click', '.eventClass', (e) => { this.eventClass = e.target.value logger.log(logger.DEBUG, "clicky clicked", e.target.value) }); } getData(options) { let datetime = this.useAboutTime ? game.Gametime.DTNow() : null; let years = datetime ? datetime.years : ""; let months = datetime ? datetime.months + 1 : ""; // Damn, 0 based crap. let days = datetime ? datetime.days + 1 : ""; // Damn, 0 based crap let timeString = datetime ? ("00" + datetime.hours).slice(-2) + ":" + ("00" + datetime.minutes).slice(-2) : "00:00" return mergeObject(options, { aboutTimeEnabled: game.settings.get(c.MODULE_NAME, c.CONFIG_USE_ABOUT_TIME_OPTION), useAboutTime: this.useAboutTime, years: years, months: months, days: days, timeString: timeString, eventTypes: c.TIMELINE_ENTRY_EVENT_TYPES }); } }<file_sep>import TimelineEntry from "./TimelineEntry.js" import { constants } from "../utils.js" export default class Timeline { constructor(data = {}, entry = null) { this.folder = data.folder; this.htmlDescription = data.htmlDescription || constants.HTML_NO_DESCRIPTION; this.title = data.title || "New Timeline"; this.shortName = this.title.length > constants.MAX_TAB_TITLE_LENGTH ? this.title.substring(0, constants.MAX_TAB_TITLE_LENGTH - 3) + "..." : this.title; this.entries = data.entries || []; // TODO read from this.folderId this.playerVisible = data.playerVisible || false; this.era = data.era || ""; this.era_short = data.era_short || ""; this.reload(); } reload() { this.folder.content.map(entry => { if (entry.name !== constants.TIMELINE_METADATA_JOURNAL_ENTRY_NAME) { this.entries.push(new TimelineEntry(JSON.parse(entry.data.content))); } }); } /** * @returns an objects such that each entry has the following fields: * name: the name of the timeline, used to populate the side bar of the TimelineManger window * description: an html description of of the timeline, used for displaying at the top of the div * playerVisible: boolean flag that determines whether the player can see the tab * entries: an array of TimelineEntry objects */ asJson() { //resort to make sure we are displaying the most recent this.entries.sort(function(e1, e2) { return -TimelineEntry.comparator(e1, e2) }); return { name: this.title, shortName: this.shortName, era: this.era, era_short: this.era_short, description: TextEditor.enrichHTML(this.htmlDescription), playerVisible: this.playerVisible, entries: this.entries }; } }
234014df1dde56c0f9b19090557d27e706ecb63b
[ "JavaScript", "Python", "JSON with Comments", "Dockerfile" ]
13
JavaScript
teberger/foundry-vtt-timeline
e6d84bc6bc203330d2177734d3f4bfec24b74429
54bc01197a9a73d15bc62b4fd8472d6c56392bcf
refs/heads/master
<repo_name>matheus0608/date-php<file_sep>/week.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Week</title> </head> <body> <?php $month = date('n'); $month_in_br = array( '1' => 'Janeiro', '2' => 'Fevereiro', '3' => 'Março', '4' => 'Abril', '5' => 'Maio', '6' => 'Junho', '7' => 'Julho', '8' => 'Agosto', '9' => 'Setembro', '10' => 'Outubro', '11' => 'Novembro', '12' => 'Dezembro', ); $day_week_in_br = array( '7' => "Dom", '1' => "Seg", '2' => "Ter", '3' => "Qua", '4' => "Qui", '5' => "Sex", '6' => "Sáb" ); $get_date = 'now'; // now or set date in format '2019/07/20' $set_timezone = new DateTimeZone('America/Sao_Paulo'); // or Brazil/East $date = new DateTime( $get_date, $set_timezone ); $get_key_day_week = $date->format( 'N' ); ?> <table> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <?php // list before today $countweewk1 = 1; for ($g = $date->format( 'N' ) - 1; $g > 0; $g--) : $date = new DateTime( $get_date, $set_timezone ); $date->modify( '-' . ( $g ) . ' days' ); ?> <td> <b><?php echo $day_week_in_br[ $date->format( 'N' ) ]; ?></b> <h4><?php echo $date->format( 'd' ); ?></h4> </td> <?php endfor; // list today $date = new DateTime( $get_date, $set_timezone ); ?> <td> <b><?php echo $day_week_in_br[$get_key_day_week]; ?></b> <h4><?php echo $date->format( 'd' ); ?></h4> </td> <?php // list after today for ($i = $date->format( 'N' ); $i <= 6; $i++) : $date = new DateTime( $get_date, $set_timezone ); $date->modify( '+' . ( $countweewk1 ) . ' days' ); ?> <td> <?php echo $day_week_in_br[ $date->format( 'N' ) ]; ?> <h4><?php echo $date->format( 'd' ); ?></h4> </td> <?php $countweewk1++; endfor; ?> </tr> </tbody> </table> </body> </html>
11ec53ebf87b447ddb80bfd157ca41f59578425a
[ "PHP" ]
1
PHP
matheus0608/date-php
b9cae250e2ffd646a64ada420a6830707b23ee80
c98a7fb169e7394e03f4eaca911d687c00953762
refs/heads/main
<file_sep># XLS-TO-SQL-PYTHON<file_sep> import pandas as pd import mysql.connector import os from datetime import datetime xls = pd.ExcelFile("listado.xls") error=False; indice=0; contenido = "" columnas = [] columnas.append("test") columnas.append("test") columnas.append("test") columnas.append("test") columnas.append("test") sheetX = xls.parse(0) texto="" contador=0 cnx = mysql.connector.connect(user='test', password='<PASSWORD>',host='test',database='test') mycursor = cnx.cursor() sql="INSERT INTO test (test,test,test,test,test) VALUES " def replace_last(string, find, replace): reversed = string[::-1] replaced = reversed.replace(find[::-1], replace[::-1], 1) return replaced[::-1] while not error: try: for i in range(5): fila = sheetX[columnas[i]] valor =str(fila[indice]); if len(valor)==7: valor='1970-01-01 00:00:00' if i== 0 or i==1 or i==3: if i==1: mycursor.execute("SELECT test FROM test WHERE test='"+valor+"'") myresult = mycursor.fetchone() valor=str(myresult) if valor != "None": valor=valor.replace("(","") valor=valor.replace(",","") valor=valor.replace(")","") else: valor="" texto="" if i==0: mycursor.execute("SELECT id FROM producto WHERE raiz='"+valor+"'") myresult = mycursor.fetchone() valor=str(myresult) if valor != "None": valor=valor.replace("(","") valor=valor.replace(",","") valor=valor.replace(")","") else: valor="" texto="" if contador==1 and valor!="": texto=texto+valor+"," contador=1 else: if valor!="" and texto!="" and contador==1: texto=texto+"'"+valor if i<4: if i==2 and valor=="nan": texto=texto.replace("nan","") if valor!="" and texto!="" and contador==1: texto=texto+"'," contador=1 else: contador=0 if valor!="" and texto!="": contador=1 else: contador=0 if contador>0 and i==4: contador=1 sql=sql+"("+texto+"')," texto="" contador=1 indice+=1; except: error=True; sql=replace_last(sql, ",", ";") print(sql) #mycursor.execute(sql) #cnx.commit() cnx.close()
bd16e3d3af61d14046dd77661947ec9ff3898c46
[ "Markdown", "Python" ]
2
Markdown
ComandPromt/XLS-TO-SQL-PYTHON
0adbf2c5002706e95ca3edb83a2a97afc2c1c3e9
dcd91835c74f42e418576cf91a6510940bcbc9fa
refs/heads/main
<repo_name>rolysoft/landing<file_sep>/src/app/shared/plans/data.ts const pricingData = [ { title: 'Economy', price: 19, bandwidth: '1GB', onlinespace: '50MB', support: 'No' }, { title: 'Premium', price: 29, bandwidth: '2GB', onlinespace: '1GB', support: 'No' }, { title: 'Developer', price: 39, bandwidth: '3GB', onlinespace: '2GB', support: 'Yes' }, { title: '<NAME>', price: 39, bandwidth: '3GB', onlinespace: '2GB', support: 'Yes' }, { title: '<NAME>', price: 39, bandwidth: '3GB', onlinespace: '2GB', support: 'Yes' }, ]; export { pricingData }; <file_sep>/src/app/shared/plans/plans.model.ts export interface Pricing { title: string; price: number; bandwidth: string; onlinespace: string; support: string; } <file_sep>/src/app/shared/clients/data.ts const testimonialData = [ { // tslint:disable-next-line: max-line-length message: '" To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages of the resulting language "', username: '<NAME>' }, { // tslint:disable-next-line: max-line-length message: '" To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is languages are members "', username: 'James Brown' }, { // tslint:disable-next-line: max-line-length message: '" To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is languages are members "', username: 'James Brown' }, { // tslint:disable-next-line: max-line-length message: '" Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this it would be necessary "', username: '<NAME>' }, { // tslint:disable-next-line: max-line-length message: '" Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their most common words. "', username: '<NAME>' }, { // tslint:disable-next-line: max-line-length message: '" For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. "', username: '<NAME>' }, ]; export { testimonialData }; <file_sep>/src/app/shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ScrollspyDirective } from './scrollspy.directive'; import { FeatherModule } from 'angular-feather'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { CountToModule } from 'angular-count-to'; import { Grid, Edit, Headphones, Layers, Code, Tablet, BarChart2, Check, PieChart, ArrowRight, Bookmark, Coffee, Award, UserPlus, MapPin, Mail, Phone } from 'angular-feather/icons'; const icons = { Grid, Edit, Headphones, Layers, Code, Tablet, BarChart2, Check, PieChart, ArrowRight, Bookmark, UserPlus, Coffee, Award, MapPin, Mail, Phone }; import { ServicesComponent } from './services/services.component'; import { FeaturesComponent } from './features/features.component'; import { ClientsComponent } from './clients/clients.component'; import { PlansComponent } from './plans/plans.component'; import { FooterComponent } from './footer/footer.component'; import { ModeloComponent } from './modelo/modelo.component'; @NgModule({ declarations: [ServicesComponent, FeaturesComponent, ClientsComponent, PlansComponent, FooterComponent, ScrollspyDirective, ModeloComponent], imports: [ CommonModule, FeatherModule.pick(icons), CarouselModule, CountToModule ], exports: [ServicesComponent, FeaturesComponent, ClientsComponent, PlansComponent, FooterComponent, ScrollspyDirective, FeatherModule, ModeloComponent], }) export class SharedModule { } <file_sep>/src/app/shared/modelo/data.ts const pricingData = [ { title: 'Economy', price: 19, bandwidth: '1GB', onlinespace: '50MB', genero: 'F', support: 'No', desc: 'Camiseta larga con aberturas laterales', foto: 'https://m.media-amazon.com/images/I/710yMs4BjqL._AC_UX385_.jpg' }, { title: 'Vestido', price: 29, bandwidth: '2GB', onlinespace: '1GB', genero: 'F', support: 'No', desc: 'Camiseta larga con aberturas laterales', foto: 'https://dyaboo.com/ropa-de-mujer/blusa-dyaboo.jpg' }, { title: 'Camisa', price: 39, bandwidth: '3GB', onlinespace: '2GB', genero: 'M', support: 'Yes', desc: 'Camiseta larga con aberturas laterales', foto: 'https://i.pinimg.com/550x/9e/f1/d8/9ef1d83080f0fc5691a44e11a333c000.jpg' }, { title: '<NAME>', price: 39, bandwidth: '3GB', onlinespace: '2GB', genero: 'F', support: 'Yes', desc: 'Camiseta larga con aberturas laterales', foto: 'https://tiendakalendar.vteximg.com.br/arquivos/ids/263665-307-470/BLUSA-ASTROBOY-BLSF568-11365-NEGRO_2.jpg' }, { title: '<NAME>', price: 39, bandwidth: '3GB', onlinespace: '2GB', genero: 'F', support: 'Yes', desc: 'Camiseta larga con aberturas laterales', foto: 'https://http2.mlstatic.com/D_NQ_NP_742467-MLV42689288719_072020-W.jpg' }, ]; export { pricingData }; <file_sep>/src/app/shared/plans/plans.component.ts import { Component, OnInit } from '@angular/core'; import { Pricing } from './plans.model'; import { pricingData } from './data'; @Component({ selector: 'app-plans', templateUrl: './plans.component.html', styleUrls: ['./plans.component.scss'] }) /** * Plans component */ export class PlansComponent implements OnInit { pricingData: Pricing[]; constructor() { } ngOnInit(): void { // fetches the data this._fetchData(); } /** * Pricing data */ private _fetchData() { this.pricingData = pricingData; } } <file_sep>/src/app/shared/services/data.ts const serviceData = [ { icon: 'grid', title: 'Bootstrap UI based', text: 'To an English person, it will seem like English as skeptical.' }, { icon: 'edit', title: 'Easy to customize', text: 'If several languages coalesce, the grammar of the language.' }, { icon: 'headphones', title: 'Awesome Support', text: 'The languages only differ in their grammar their pronunciation' }, { icon: 'layers', title: 'Creative Design', text: 'Everyone realizes why a new common would be desirable.' }, { icon: 'code', title: 'Quality Code', text: 'To achieve this, it would be necessary to have uniform.' }, { icon: 'tablet', title: 'Responsive layout', text: 'Their separate existence is a myth. For science, music, etc.' }, ]; export { serviceData }; <file_sep>/src/app/shared/clients/clients.component.ts import { Component, OnInit } from '@angular/core'; import { OwlOptions } from 'ngx-owl-carousel-o'; import { Testimonial } from './clients.model'; import { testimonialData } from './data'; @Component({ selector: 'app-clients', templateUrl: './clients.component.html', styleUrls: ['./clients.component.scss'] }) /** * Clients component */ export class ClientsComponent implements OnInit { testimonialData: Testimonial[]; constructor() { } testimonialOptions: OwlOptions = { margin: 10, loop: true, responsive: { 0: { items: 1 }, 576: { items: 2 }, }, nav: true, navText: ['<i class=\'mdi mdi-chevron-left\'></i>', '<i class=\'mdi mdi-chevron-right\'></i>'], }; ngOnInit(): void { this._fetchData(); } private _fetchData() { this.testimonialData = testimonialData; } } <file_sep>/src/app/shared/services/services.component.ts import { Component, OnInit } from '@angular/core'; import { Services} from './services.model'; import { serviceData } from './data'; @Component({ selector: 'app-services', templateUrl: './services.component.html', styleUrls: ['./services.component.scss'] }) /** * Services component */ export class ServicesComponent implements OnInit { serviceData: Services[]; constructor() { } ngOnInit(): void { // fetches the data this._fetchData(); } /** * Service data */ private _fetchData() { this.serviceData = serviceData; } } <file_sep>/src/app/pages/index6/index6.component.ts import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-index6', templateUrl: './index6.component.html', styleUrls: ['./index6.component.scss'], encapsulation: ViewEncapsulation.None, styles: [` .dark-modal .modal-content { background-color: #000000; color: white; background: none; border: none; } .dark-modal .modal-header { border : none } .dark-modal .close { color: white; } .dark-modal .modal-dialog { max-width: 800px } `] }) /** * Index-6 component */ export class Index6Component implements OnInit { currentSection = 'home'; constructor(private modalService: NgbModal) { } ngOnInit(): void { } /** * Window scroll method */ windowScroll() { const navbar = document.getElementById('navbar'); if (document.body.scrollTop >= 50 || document.documentElement.scrollTop > 50) { navbar.classList.add('nav-sticky'); } else { navbar.classList.remove('nav-sticky'); } } /** * Section changed method * @param sectionId specify the current sectionID */ onSectionChange(sectionId: string) { this.currentSection = sectionId; } /** * Toggle navbar */ toggleMenu() { document.getElementById('navbarCollapse').classList.toggle('show'); } /** * Open modal for show the video * @param content content of modal */ openWindowCustomClass(videocontent) { this.modalService.open(videocontent, { windowClass: 'dark-modal', centered: true }); } }
e4cd196f38fc727f9b7f7dd4030a4d5d3683f628
[ "TypeScript" ]
10
TypeScript
rolysoft/landing
9277b22dd29c1b3924903a60a077ab1aee06e0ab
7bfc14cbd375bed7e0022b22f3bb6967a7f83c10
refs/heads/master
<repo_name>mdasif-raza-au13/question1heroku<file_sep>/src/index.js const express = require('express'); const userRoutes = require('./routes/user.js'); const db = require('./config/mongo-db.js') const cors = require('cors'); const app = express(); const port = process.env.PORT || 1101; app.use(cors()); app.get('/',(req,res)=>{ res.send('Welcome to node-express') }); app.use('/api',userRoutes); app.listen(port,()=>{ console.log(`listenin on http://localhost:${port}`); });<file_sep>/src/routes/user.js const express = require('express'); const User = require('../schema/User.js'); const bcrypt = require('bcryptjs'); const bodyParser = require('body-parser'); const router = express.Router(); const jwt = require('jsonwebtoken'); const config = require('../config/config.js'); router.use(bodyParser.urlencoded({extended:true})); router.use(bodyParser.json()); //for signin router.post('/signup',(req,res) => { User.findOne({email:req.body.email},(err,result)=>{ if(err) throw err; if(result) return res.send(`user already exists`); else{ const hashpassword = bcrypt.hashSync(req.body.password,8); User.create({ name: req.body.name, email: req.body.email, password: <PASSWORD>, about: req.body.about },(err,user) => { if(err) throw err; res.status(200).send(`user created and details ${user}`); }) } }) }); // for login router.post('/login',(req,res) => { User.findOne({email:req.body.email},(err,user) => { if(err) return res.status(500).send('Error while login'); if(!user) return res.send({auth: false, token: 'User not found, Register first'}); else{ const isPassValid = bcrypt.compareSync(req.body.password,user.password); if(!isPassValid) return res.send({auth: false, token: 'Inavlid Password'}); const token = jwt.sign({id:user._id},config.secret,{expiresIn:600}); res.send({auth: true, token: token}); } }) }) // loggedin user info router.get('/userinfo',(req,res) => { const token = req.headers['x-access-token']; if(!token) res.send({auth: false, token: 'No token provided'}); jwt.verify(token,config.secret,(err,user) => { if(err) res.send('error while fetching'); User.findById(user.id,(err,result) => { if(err) throw err; res.send(result); }) }) }) // to get list of all users // router.get('/users',(req,res) => { // User.find({},(err,user) => { // if(err) throw err; // res.status(200).send(user) // }) // }) module.exports = router;
88ea2fe9039840e265397bfdec0fcc5e26edf3b3
[ "JavaScript" ]
2
JavaScript
mdasif-raza-au13/question1heroku
ff347355f0f27e55fb3d83ae82eb28c6630e0a56
411747992514a09fef31331b5ebad8c8bc1e36a3
refs/heads/master
<file_sep> # -*- coding: utf-8 -*- # !/usr/local/bin/python """ ''' Author: <NAME> Affiliaton: Universidad de Buenos Aires & CONICET Year: 2016 Description: Small piece of code to find out which Netflix's OCAs are candadites for the the end-host that is running the code. The search of the OCAs is based on the information provided by fast.com ''' """ import subprocess import json import requests import socket def get_host_isp_information(): """ Thi function call Netflix's API to get the list of candidates OCAs for the user running the script. inputs ----------- None returns ----------- None (stdout) """ public_ip_request = 'https://api.ipify.org?format=json' response = requests.get(public_ip_request) ip_addr = json.loads(response.text) cymru_request = 'whois -h whois.cymru.com " -v {}"'.format(ip_addr['ip']) # Run command to extract TOKEN from FAST response host_isp_information = subprocess.check_output( cymru_request, shell=True ) print("############################################################################################################") print('> Host IP information') print(host_isp_information.decode("utf-8")) def request_for_oca(): """ Thi function call Netflix's API to get the list of candidates OCAs for the user running the script. inputs ----------- None returns ----------- None (stdout) """ cmd1 = 'curl -s https://fast.com/app-ed402d.js' cmd2 = 'egrep -om1 \'token:"[^"]+\'' # cmd3 = 'cut -f2 -d\'"\'' query = 'https://api.fast.com/netflix/speedtest?https=true&token={}' # Run command to get TOKEN from FAST.com API ps1 = subprocess.Popen(cmd1.split(), stdout=subprocess.PIPE) # Run command to extract TOKEN from FAST response token = subprocess.check_output( cmd2, shell=True, stdin=ps1.stdout ).strip()[7:].decode("utf-8") # Use TOKEN to request OCAs and URL to video chunk response = requests.get(query.format(token)) # Turns `response` into dict oca_list = json.loads(response.text) print("############################################################################################################") print('> Allocated OCAs for this user') for oca in oca_list: print(oca['url']) print("############################################################################################################") print('> IP address of the allocated OCAs') for oca in oca_list: fqdn = oca['url'].split('/')[2] print(socket.gethostbyname(fqdn)) def main(): """ asd. asd. """ get_host_isp_information() request_for_oca() if __name__ == "__main__": # execute only if run as a script main() <file_sep># Finding Netflix's OCA ## Description Little piece of Python code to find out candidate Netflix's Open Connect Appliances (OCA) for the end-host running this script. We rely on Netflix's speed-test fast.com, which measures throughput between users and their allocated OCAs. The script is two-fold: 1. It gets the token necessary to request the list of OCAs. 2. It requests the list of OCAs by inserting the token on the request. For more info: https://medium.com/netflix-techblog/building-fast-com-4857fe0f8adb ## Requirements: To install the python libraries that are required to run the script: ``` $ pip install -r requirements.txt ``` In addition, you may need to install ```whois``` and/or ```curl``` in case they ar not installed yet ``` $ sudo apt-get install whois $ sudo apt-get install curl ``` ## To run Thanks to @seblaz, scripts now supports python3 ``` python get_ocas.py ``` <file_sep>requests==2.23.0 subprocess32==3.2.7
456886f0117df905501ba2de3199cadceff6e2ff
[ "Markdown", "Python", "Text" ]
3
Python
estcarisimo/findNetflixOCA
5a02ed972006846f2997c400f93dfb1b33e9e3f7
d57d0d4a58dcfb81ee9ed69033f018a8b4d0f774
refs/heads/master
<repo_name>bettyyeo/Getting-and-Cleaning-Data<file_sep>/run_analysis.r run_analysis <- function(){ ## Merges THE TRAINING and the test sets xtrain <- read.table("train/X_train.txt") xtest <- read.table("test/X_test.txt") combinedData <- rbind(xtrain, xtest) ##Extracts only the measurements on the mean ## and standard deviation for each measurement. features <- read.table("features.txt") extractedIndex <- grep(".*mean.*|.*std.*", features[,2]) ## return the indexes extractedData <- combinedData[extractedIndex] extractedColNames <- features[extractedIndex,2] names(extractedData) <- extractedColNames ## this is for step 5 withSubjectTrain <- read.table("train/subject_train.txt") withSubjectTest <- read.table("test/subject_test.txt") withSubjects <- rbind(withSubjectTrain,withSubjectTest) names(withSubjects) <- "SubjectID" DataWithSubject <- cbind(extractedData,withSubjects) ##Uses descriptive activity names ##to name the activities in the data set activitylabel <- read.table("activity_labels.txt") names(activitylabel) <- c("ActivityID","ActivityDesc") ytrain <-read.table("train/y_train.txt") ytest <- read.table("test/y_test.txt") combinedActivity <- rbind(ytrain,ytest) names(combinedActivity) <- "ActivityID" ## 4add activities in the data set with the appropriate abel combActWithNames <- merge(combinedActivity,activitylabel, by="ActivityID") extractedDataWithActivities <- cbind(DataWithSubject,combinedActivity) write.table(extractedDataWithActivities, "extractedDataWithActivities1", sep="\t") } <file_sep>/README.md Getting-and-Cleaning-Data ========================= Part of the Coursera course is to do the assignment 3. Objective is to prepare the tidying of data. The data linked to from the course WEBSITE represent data collected from the accelerometers from the Samsung Galaxy S smartphone. A full description is available at the site where the data was obtained: http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones The data of the studies inclusive of the elaboration of the studies could be found in the following website https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip The requirement is to write R-script r_analysis.R to makes sense of the file by cleaning up and merging the records to make it comprehensible. A code book is also included that describes the variables, the data, and any transformations or work that you performed to clean up the data called CodeBook.md.
0a49296bc6ca64c7f5f5c69c4463eb99945eb089
[ "Markdown", "R" ]
2
R
bettyyeo/Getting-and-Cleaning-Data
9176f325c3e355e4f483aed9aef7dc2ead943b74
dc2c037aafdc7056a45de5a48b0b8113502a10f3
refs/heads/master
<file_sep>import telebot from bot_token import TOKEN import config from flask import Flask, request import logging import os bot = telebot.TeleBot(TOKEN) @bot.message_handler(content_types=['new_chat_members']) def chek(message): bot.delete_message(message.chat.id, message.message_id) @bot.message_handler(content_types=['text']) def kill_phrases(message): bot.send_message(message.chat.id, 'Cheking') for word in config.bad_words: if word in message.text: bot.send_message(message.chat.id, 'Gay') bot.delete_message(message.chat.id, message.message_id) bot.kick_chat_member(message.chat.id, message.from_user.id) logger = telebot.logger telebot.logger.setLevel(logging.INFO) server = Flask(__name__) @server.route('/' + TOKEN, methods=['POST']) def getMessage(): bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))]) return "!", 200 @server.route("/") def webhook(): bot.remove_webhook() bot.set_webhook(url='your heroku project.com' + TOKEN) return "?", 200 server.run(host="0.0.0.0", port=os.environ.get('PORT', 80))<file_sep>TOKEN = '488848550:<KEY>' <file_sep>import telebot from bot_token import TOKEN import config import flask WEBHOOK_HOST = '<ip/host where the bot is running>' WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open') WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_URL_PATH = "/%s/" % (TOKEN) @app.route('/', methods=['GET', 'HEAD']) def index(): return '' @app.route(WEBHOOK_URL_PATH, methods=['POST']) def webhook(): if flask.request.headers.get('content-type') == 'application/json': json_string = flask.request.get_data().decode('utf-8') update = telebot.types.Update.de_json(json_string) bot.process_new_updates([update]) return '' else: flask.abort(403) bot = telebot.TeleBot(TOKEN) @bot.message_handler(content_types=['new_chat_members']) def chek(message): bot.delete_message(message.chat.id, message.message_id) @bot.message_handler(content_types=['text']) def kill_phrases(message): bot.send_message(message.chat.id, 'Cheking') for word in config.bad_words: if word in message.text: bot.send_message(message.chat.id, 'Gay') bot.delete_message(message.chat.id, message.message_id) bot.kick_chat_member(message.chat.id, message.from_user.id) if __name__ == '__main__': bot.remove_webhook() bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH, certificate=open(WEBHOOK_SSL_CERT, 'r')) app.run(host=WEBHOOK_LISTEN, port=WEBHOOK_PORT, ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV), debug=True)<file_sep>import telebot from bot_token import TOKEN import config bot = telebot.TeleBot(TOKEN) @bot.message_handler(content_types=['new_chat_members']) def chek(message): bot.delete_message(message.chat.id, message.message_id) @bot.message_handler(content_types=['text']) def kill_phrases(message): for word in config.bad_words: if word in message.text: bot.delete_message(message.chat.id, message.message_id) bot.kick_chat_member(message.chat.id, message.from_user.id) if __name__ == '__main__': bot.polling(none_stop=True)<file_sep> bad_words=[ ]
71f02be93cfb1e9890505aa87f850e25aba38b5d
[ "Python" ]
5
Python
Meugenn/HashBot
339c7327d4e45546f109d1c47e4ec31ca9fb5a03
b06393d7f0d6ef24428cf8916edf29543905498f
refs/heads/master
<repo_name>z-soulx/my-rpc-test<file_sep>/rpc_netty/src/main/java/soulx/serialize/impl/StringSerializer.java package soulx.serialize.impl; import ch.qos.logback.core.encoder.ByteArrayUtil; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import soulx.serialize.Serializer; import soulx.serialize.Types; import java.nio.charset.StandardCharsets; /** * @program: demo * @description: 字符串序列化 * @author: soulx * @create: 2020-08-02 19:53 **/ //@Component public class StringSerializer implements Serializer<String> { @Override public int size(String entry) { return entry.getBytes(StandardCharsets.UTF_8).length; } @Override public void serialize(String entry, byte[] bytes, int offset, int length) { byte[] entryBytes = entry.getBytes(StandardCharsets.UTF_8); System.arraycopy(entry,0,bytes,offset,entry.length()); } @Override public String parse(byte[] bytes, int offset, int length) { return new String(bytes,offset,length,StandardCharsets.UTF_8); } @Override public byte type() { return Types.TYPE_STRING; } @Override public Class<String> getSerializeClass() { return String.class; } } <file_sep>/hello-api/src/main/java/soulx/HelloService.java package soulx; /** * @program: demo * @description: 服务接口 * @author: soulx * @create: 2020-08-03 10:27 **/ public interface HelloService { String hello(String name); } <file_sep>/rpc_netty/src/main/java/soulx/serialize/Types.java package soulx.serialize; /** * @program: demo * @description: 序列化类型 * @author: soulx * @create: 2020-08-02 20:27 **/ public class Types { public final static int TYPE_STRING = 0; public final static int TYPE_METADATA = 100; public final static int TYPE_RPC_REQUEST = 101; } <file_sep>/README.md # my-rpc-test 实现简单的rpc尝试 <file_sep>/client/src/main/java/soulx/proxy/T.java package soulx.proxy; import org.springframework.stereotype.Service; import soulx.HelloService; /** * @program: demo * @description: * @author: soulx * @create: 2020-08-03 12:19 **/ @Service // 为了生成bean 代理,实现了接口 // 实际中可以在注入入口入手 public class T implements HelloService { @Override public String hello(String name) { return null; } }
8bde5835726630e01c6ec895e4103fae0504b75c
[ "Markdown", "Java" ]
5
Java
z-soulx/my-rpc-test
b0288e05044a641825a25977dcca1ccf3a830290
405f8e09febda703ddf0df5f2fe52a1fe0821593
refs/heads/master
<repo_name>FateTHarlaown/GthreadPool_C<file_sep>/GthreadPool.h #ifndef GTHREAD_POOL #define GTHREAD_POOL #include "pool.h" /******************************************************* * name:Gthread_pool_init * des:this func will init Gthread_pool struct * para1: the pointer point to a Gthread_pool struct * para2:max number of tasks * para3:max number of workers * para4:min number of workers * return: state, SUCCESS or FAILURE * ****************************************************/ int Gthread_pool_init(struct Gthread_pool * pool, int max_tasks, int max_workers, int min_workers); /* *********************************************************************************************************** *name:close_pool *description:close the pool *para1: a pointer point to a pool *return SUCCESS or FAILURE *************************************************************************************************************/ int close_pool(struct Gthread_pool * pool); /* *********************************************************************************************************** *name:add_job *description:add a task to this pool *para1: a pointer point to a pool *para2:a pointer point to a fucntion like this: void * (* func)(void * arg) *return SUCCESS or FAILURE *************************************************************************************************************/ int add_job(struct Gthread_pool * pool, void * (* job)(void * arg), void * arg); #endif <file_sep>/main.c #include "GthreadPool.h" pthread_mutex_t fuck; /*just for test*/ void * test_job(void * arg) { int num = *(int *)arg; pthread_mutex_lock(&fuck); printf("job %d is proccessing by worker id %ld\n", num, pthread_self()); pthread_mutex_unlock(&fuck); sleep(4); pthread_mutex_lock(&fuck); printf("This job num: %d, finished by thread: %ld\n", num, pthread_self()); pthread_mutex_unlock(&fuck); return 0; } void test_request(void * arg) { int i; struct Gthread_pool_task * tmp_task; struct Gthread_pool * pool = (struct Gthread_pool *)arg; assert(arg); int * args = (int *)malloc(sizeof(int)*10); for(i = 0; i<10; i++) { args[i] = i; tmp_task = (struct Gthread_pool_task *)malloc(sizeof(struct Gthread_pool_task)); add_job(pool, test_job, &args[i]); printf("add task num %d\n", args[i]); } } int main() { struct Gthread_pool test_pool; Gthread_pool_init(&test_pool, 100, 20, 5); test_request(&test_pool); sleep(15); close_pool(&test_pool); while(1); return 0; }
576f4c1f1d03a3afab9dec8174a90a155cd6ab9e
[ "C" ]
2
C
FateTHarlaown/GthreadPool_C
92995ebb051b51e7c237ee109ac454b734e70b72
dd4e5bcc638a36f492d9b72111df871fdf7629b4
refs/heads/master
<repo_name>assadakram/labfinal<file_sep>/src/Bank.java /** * @author<h1> <NAME>(Sp13-bse-008)</h1> *<p>This class is use to create new accounts for new users.</p> * */ public class Bank { /** *<p> This method is use to add new account in the bank's database.</p> */ void addAccount(){ } /** * <p>This method is use to access account of any person from their id number;</p> *@param this is id of person having account. */ void selectAccount(int id){ } } <file_sep>/src/Account.java /** * <p>This class contain the accounts of the persons with there id number and balance in there account.</p> * * @author <h1><NAME>(Sp13-bse-008)</h1> * */ public abstract class Account { int number; float balance; Person ps=new Person(null, number); /** * <p>This method return the id number of the person having account.</p> * @return */ public int getNumber() { return number; } /** * <p>This method return the Balance of the person having account.</p> * @return */ public float getBalance() { return balance; } /** *<p> This method return the Object of the person having account.</p> * @return */ public Object getOwner(){ return ps; } /** * <p>This method is use to deposit fund in the persons account.</p> * @param num */ public void deposit(int num){ number=num; } /** * <p>This method is use to withdraw funds from the persons account.</p> * * @param num * @return */ public boolean withdraw(int num){ int a=num; return false; } } <file_sep>/src/SavingAccount.java /** * * @author Assad *<p>This class has the information about saving account.</p> */ public class SavingAccount extends Account { int interestrate; /** * <p>This method is use to check the account type.</p> * @param id * @param sa * @param ob */ void checkingAccount(int id,int sa,Object ob){ } /** *<p> This method is use to withdraw credit from saving account.</p> */ public boolean withdraw(int a){ return false; } /** *<p>This method is use to add interest in the main balance.</p> */ void addinterest(){ } }
1628cf8e92013fcc578d247dd1ffece59cbe0591
[ "Java" ]
3
Java
assadakram/labfinal
7e5505e5a501b55456db1a4b60fe1319af68e9f3
035219d7d56b1f976fe5dd143873ee2c2692f6ee
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { LoginPage } from '../../pages/login/login'; import { HomePage } from '../../pages/home/home'; /* Generated class for the DataProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class DataProvider { rootPage = LoginPage constructor() { console.log('Hello DataProvider Provider'); } setRootPage(root){ var newRoot = { 'login':LoginPage, 'home':HomePage } this.rootPage = newRoot[root]; console.log(this.rootPage) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import 'rxjs/add/operator/map'; import { AlertController } from 'ionic-angular'; import { HomePage } from '../home/home'; // import { DataProvider } from '../../providers/data/data'; @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage implements OnInit { user; loginUrl:string; headers; loginResponse; constructor( // public data:DataProvider, public navCtrl: NavController, public navParams: NavParams, private http: Http, public alertCtrl: AlertController ) { } setQueryHeaders(){ this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.headers.append('Olympiadbox-Api-Key', '<KEY>'); } ngOnInit(){ this.loginUrl = 'http://scripts.olympiadbox.com/services/fronty-api/user/login'; this.user = { username:null, password:<PASSWORD> } this.setQueryHeaders(); } login(){ this.http.post(this.loginUrl, this.user, {headers:this.headers}) .map((resp:Response)=>resp.json()).subscribe((data)=>{ if (data['status']==200){ this.navCtrl.push(HomePage); // this.data.setRootPage('login'); } else { this.showAlert(); } }) } showAlert() { let alert = this.alertCtrl.create({ title: 'error!', }); alert.present(); } ionViewDidLoad() { } }
b5e721c730cadb36365112e31ba27864d04f32d7
[ "TypeScript" ]
2
TypeScript
agupta8895/myapp
320f858ac678fe4ce8505b0aedb1bd0d5bf38800
a8f01ec55d6b2d40635d04db8ca5cc450d0bee9b
refs/heads/main
<file_sep># GitHubActionsIntroduction ![Swift](https://github.com/hal-cha-n/GitHubActionsIntroduction/workflows/Swift/badge.svg) このリポジトリは GitHub Actions の動作確認リポジトリです。 # 行ったこと ### 1. ワークフローを設定 ActionsタブよりSwiftのワークフローを選択しました ![d2537b4ccbf64d46432f7e1cd802ee70](https://user-images.githubusercontent.com/40711834/103928645-7dd84300-515f-11eb-9dcf-bcd9476add1a.png) ### 2. Swiftプロジェクト生成 以下のコマンドでSwiftのビルドに必要なファイルを作成しました。 ```sh $ swift package init --type executable ``` ### 3. プルリクエスト作成 動作確認用プルリクエスト作成しました - [ビルドできないコードを追加](https://github.com/hal-cha-n/GitHubActionsIntroduction/pull/1) - [テストが失敗するコードを追加](https://github.com/hal-cha-n/GitHubActionsIntroduction/pull/2) - [テストが成功するコード追加](https://github.com/hal-cha-n/GitHubActionsIntroduction/pull/3) ### 4. Branch protection rule 設定 mainブランチの`Branch protection rule` に `Require status checks to pass before merging` を有効化しました。 この設定により、mainブランチへのプルリクエストはbuildのジョブが成功していることが必須となります。 ![1db57fc83189ffc9f348159dabfe9236](https://user-images.githubusercontent.com/40711834/103929508-c3494000-5160-11eb-916e-6da0f197de16.png) <file_sep>import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(srcTests.allTests), ] } #endif <file_sep>import XCTest import srcTests var tests = [XCTestCaseEntry]() tests += srcTests.allTests() XCTMain(tests)
d639d5fae447ed1e13c67873833fd25e0f67d10f
[ "Markdown", "Swift" ]
3
Markdown
hal-cha-n/GitHubActionsIntroduction
1ad7d436221553e6d29a3396d76e1bc021d565fa
7e77727489aab8a4619d07dff78c261096943153
refs/heads/master
<repo_name>wt-tao/cf<file_sep>/创飞/pages/index/index.js //index.js var codes = require('../../utils/time.js') //获取应用实例 const app = getApp() Page({ data: { ids: 0, keywords:'', countDownList: [], }, searcg_input:function(e){ this.setData({ keywords:e.detail.value }) }, search:function(){ var that=this this.setData({ ids:'', keywords: this.data.keywords }) this.main() this.setData({ s1: false }) }, list:function(e){ console.log(e.currentTarget.id ) wx.showToast({ title: '加载中...', icon:'loading', duration:3000, }) this.setData({ keywords:'', ids: e.currentTarget.id }) var that = this if (e.currentTarget.id != 0){ var data = { cat_id: e.currentTarget.id, } this.main() } else if(e.currentTarget.id==0){ var _this = this;    //防止this对象的混杂,用一个变量来保存 wx.request({ url: getApp().globalData.url + '/home/goods/goodsList', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { // key: wx.getStorageSync('result') }, success: function (res) { console.log('商品列表', res) if (res.data.result.length == 0) { wx.showToast({ title: '暂无商品', icon: 'loading', duration: 3000, }) _this.setData({ countDownList: res.data.result, }) } else if (res.data.status == 1) { wx.hideLoading() var goodslist = res.data.result for (var i = 0; i < goodslist.length; i++) { var date = new Date(); var now = date.getTime(); console.log('now', now) var endDate = goodslist[i].end_time * 1000;//设置截止时间 // var end = endDate.getTime(); console.log('endDate', endDate) var leftTime = endDate - now; //时间差 var d, h, m, s, ms; console.log('leftTime', leftTime) if (now < goodslist[i].start_time * 1000) { console.log('等待开始') _this.setData({ start: 1, }) } else if (leftTime >= 0) { // d = Math.floor(leftTime / 1000 / 60 / 60 / 24); d = Math.floor(leftTime / 1000 / 60 / 60); // h = Math.floor(leftTime / 1000 / 60 / 60 % 24); m = Math.floor(leftTime / 1000 / 60 % 60); s = Math.floor(leftTime / 1000 % 60); ms = Math.floor(leftTime % 1000); ms = ms < 100 ? "0" + ms : ms s = s < 10 ? "0" + s : s m = m < 10 ? "0" + m : m h = h < 10 ? "0" + h : h goodslist[i].end_time = d + ":" + m + ":" + s; //递归每秒调用countTime方法,显示动态时间效果 // setTimeout(that.main, 1000); } else { goodslist[i].end_time = '已截止'; console.log('已截止') } } _this.setData({ countDownList: goodslist, }) } else { wx.showToast({ title: res.data.msg, icon: 'loading', duration: 3000, }) } } }); } }, nack:function(e){ var id = e.currentTarget.id if(id==2){ wx.navigateTo({ url: '../recruit/recruit', }) } if(id==3){ wx.navigateTo({ url: '../join/join', }) } }, // 团长 recruit:function(){ wx.navigateTo({ url: '../recruit/recruit', }) }, // 供应商 join: function () { wx.navigateTo({ url: '../join/join', }) }, comdity_detail: function(e) { wx.navigateTo({ url: '../comdity_detail/comdity_detail?id=' + e.currentTarget.id, }) }, onLoad: function () { if (wx.getStorageSync('result')==''){ wx.reLaunch({ url: '../login/login', }) } this.setData({ cat_id: '', keywords: this.data.keywords, }) var _this = this;    //防止this对象的混杂,用一个变量来保存 wx.request({ url: getApp().globalData.url + '/home/goods/goodsList', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { // cat_id: this.data.ids, // keywords: this.data.keywords, // key: wx.getStorageSync('result') }, success: function (res) { console.log('商品列表', res) if (res.data.result.length == 0) { wx.showToast({ title: '暂无商品', icon: 'loading', duration: 3000, }) _this.setData({ countDownList: res.data.result, }) } else if (res.data.status == 1) { wx.hideLoading() var goodslist = res.data.result for (var i = 0; i < goodslist.length; i++) { var date = new Date(); var now = date.getTime(); console.log('now', now) console.log('start_time', goodslist[i].start_time * 1000) var endDate = goodslist[i].end_time * 1000;//设置截止时间 // var end = endDate.getTime(); console.log('endDate', endDate) var leftTime = endDate - now; //时间差 var d, h, m, s, ms; console.log('leftTime', leftTime) if (now < goodslist[i].start_time * 1000) { console.log('等待开始') _this.setData({ start: 1, }) } else if (leftTime >= 0) { // d = Math.floor(leftTime / 1000 / 60 / 60 / 24); d = Math.floor(leftTime / 1000 / 60 / 60); // h = Math.floor(leftTime / 1000 / 60 / 60 % 24); m = Math.floor(leftTime / 1000 / 60 % 60); s = Math.floor(leftTime / 1000 % 60); ms = Math.floor(leftTime % 1000); ms = ms < 100 ? "0" + ms : ms s = s < 10 ? "0" + s : s m = m < 10 ? "0" + m : m h = h < 10 ? "0" + h : h goodslist[i].end_time = d + ":" + m + ":" + s; //递归每秒调用countTime方法,显示动态时间效果 // setTimeout(that.main, 1000); } else { goodslist[i].end_time = '已截止'; console.log('已截止') } } _this.setData({ countDownList: goodslist, }) } else { wx.showToast({ title: res.data.msg, icon: 'loading', duration: 3000, }) } } }); }, main: function (){ var _this = this;    //防止this对象的混杂,用一个变量来保存 wx.request({ url: getApp().globalData.url + '/home/goods/goodsList', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { cat_id: this.data.ids, keywords: this.data.keywords, // key: wx.getStorageSync('result') }, success: function (res) { console.log('商品列表', res) if (res.data.result.length==0){ wx.showToast({ title: '暂无商品', icon: 'loading', duration: 3000, }) _this.setData({ countDownList: res.data.result, }) } else if (res.data.status==1){ wx.hideLoading() var goodslist = res.data.result for (var i = 0; i < goodslist.length; i++) { var date = new Date(); var now = date.getTime(); console.log('now', now) console.log('start_time', goodslist[i].start_time * 1000) var endDate = goodslist[i].end_time * 1000;//设置截止时间 // var end = endDate.getTime(); console.log('endDate', endDate) var leftTime = endDate - now; //时间差 var d, h, m, s, ms; console.log('leftTime', leftTime) if (now < goodslist[i].start_time * 1000) { console.log('等待开始') _this.setData({ start: 1, }) } else if (leftTime >= 0) { // if (now < goodslist[i].start_time) { // console.log('leftTime >= 0', now) // console.log('leftTime >= 0', goodslist[i].start_time) // that.setData({ // start: 1, // }) // } else { // d = Math.floor(leftTime / 1000 / 60 / 60 / 24); d = Math.floor(leftTime / 1000 / 60 / 60); // h = Math.floor(leftTime / 1000 / 60 / 60 % 24); m = Math.floor(leftTime / 1000 / 60 % 60); s = Math.floor(leftTime / 1000 % 60); ms = Math.floor(leftTime % 1000); ms = ms < 100 ? "0" + ms : ms s = s < 10 ? "0" + s : s m = m < 10 ? "0" + m : m h = h < 10 ? "0" + h : h goodslist[i].end_time = d + ":" + m + ":" + s; //递归每秒调用countTime方法,显示动态时间效果 // setTimeout(that.main, 1000); codes.getCode(_this, leftTime);  //调用倒计时函数 // wx.hideLoading() // } } else { goodslist[i].end_time = '已截止'; console.log('已截止') } } _this.setData({ countDownList: goodslist, }) }else{ wx.showToast({ title: res.data.msg, icon:'loading', duration:3000, }) } } }); }, onShow:function(){ this.setData({ ids:0, s1: true, keywords:'', }) // wx.showLoading({ // title: '加载中...', // duration: 2000 // }) var that=this setTimeout(function() { wx.request({ url: getApp().globalData.url + '/home/index/index', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), }, success: function (res) { console.log('首页数据', res) that.setData({ list: res.data.result.goods_category, banner: res.data.result.banner, group: res.data.result.group, }) // wx.hideLoading() } }) },1000) }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } }) <file_sep>/创飞/pages/addres/addres.js // pages/addres/addres.js Page({ /** * 页面的初始数据 */ data: { }, key:function(e){ this.setData({ keyword:e.detail.value }) }, search:function(){ var that=this wx.request({ url: 'https://apis.map.qq.com/ws/place/v1/suggestion?keyword=' + this.data.keyword + '&key=<KEY>&page_index=1&page_size=20', data: {}, header: { 'Content-Type': 'application/json' }, success: function (ops) { console.log(ops) that.setData({ list: ops.data.data, }) } }) }, seclect:function(e){ console.log(e) var add = e.currentTarget.dataset.title wx.navigateTo({ url: '../nearby/nearby?add=' + add, }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/创飞/pages/recruit/recruit.js // pages/recruit/recruit.js // 引入SDK核心类 Page({ /** * 页面的初始数据 */ data: { }, name:function(e){ this.setData({ user_name:e.detail.value, }) }, area: function (e) { this.setData({ area: e.detail.value, }) }, addres: function (e) { this.setData({ addres: e.detail.value, }) }, phone: function (e) { this.setData({ phone: e.detail.value, }) }, tj:function(){ var that=this if (this.data.user_name==undefined){ wx.showModal({ title: '资料不完整', content: '请填写您的姓名', }) } else if (this.data.area == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您所在城区', }) } else if (this.data.addres == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您所在小区', }) } else if (this.data.phone == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您的手机号', }) } else{ var addr = this.data.area + this.data.addres console.log(addr) wx.request({ url: 'https://apis.map.qq.com/ws/geocoder/v1/?address=' + addr + '&key=<KEY>', data: {}, header: { 'Content-Type': 'application/json' }, success: function (ops) { console.log(ops) wx.request({ url: getApp().globalData.url + '/home/group/addGroup', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), user_name: that.data.user_name, area: that.data.area, address: that.data.addres, lng: ops.data.result.location.lng, lat: ops.data.result.location.lat, phone: that.data.phone, }, success: function (res) { console.log('团长招募', res) if (res.data.status==1){ wx.showModal({ title: '提交成功', content: res.data.msg, success:function(r){ if(r.confirm){ wx.navigateBack({ delta:1 }) } } }) } else { wx.showModal({ title: '出现错误', content: res.data.msg, success: function (r) { } }) } } }) // that.setData({ // list: ops.data.data, // }) } }) } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/创飞/pages/nearby/nearby.js // pages/nearby/nearby.js Page({ /** * 页面的初始数据 */ data: { }, addr:function(){ wx.navigateTo({ url: '../addres/addres', }) }, sec:function(e){ var that = this wx.request({ url: getApp().globalData.url + '/home/group/choose', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), group_id: e.currentTarget.id }, success: function (res) { console.log('选择团长', res) if(res.data.status==1){ wx.showToast({ title: '选择成功', duration:3000, success:function(){ wx.reLaunch({ url: '../index/index', }) } }) } } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this wx.showLoading({ title: '加载中...', duration: 2000 }) console.log(options) var types = wx.getStorageSync('type') if (types == 0) { this.setData({ typ: true, adde: '请选择地址' }) } else { this.setData({ typ: false, adde: this.data.adde }) } if (options.add==undefined){ wx.request({ url: getApp().globalData.url + '/home/group/getAccessoryGroup', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), address: options.address }, success: function (res) { console.log('附近团长', res) wx.hideLoading() that.setData({ list: res.data.result.group, adde: res.data.result.address, }) } }) }else{ wx.request({ url: getApp().globalData.url + '/home/group/getAccessoryGroup', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), address: options.add }, success: function (res) { console.log('附近团长', res) wx.hideLoading() that.setData({ list: res.data.result.group, adde: res.data.result.address, }) } }) } }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/创飞/pages/order_detail/order_detail.js // pages/order_detail/order_detail.js Page({ /** * 页面的初始数据 */ data: { }, sub:function(e){ var order_id = e.currentTarget.id var that = this wx.request({ url: getApp().globalData.url + '/home/payment/getPay', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), order_id: order_id }, success: function (res) { console.log('付款', res) if (res.data.status == 1) { wx.showLoading({ title: '请求中...', }) let timeStamp = res.data.result.timeStamp; //new Date().getTime(), console.log(timeStamp) let nonceStr = res.data.result.nonceStr; let packaged = res.data.result.package; let paySign = res.data.result.paySign; wx.hideLoading() wx.requestPayment({ 'timeStamp': timeStamp, 'nonceStr': nonceStr, //随机字符串,长度为32个字符以下。 'package': packaged, 'signType': 'MD5', 'paySign': paySign, 'success': function (res) { wx.showToast({ title: '支付成功', duration: 2000, success: function () { wx.reLaunch({ url: '../user/user', }) } }) } }) } else { wx.showToast({ title: res.data.msg, icon: "loading", duration: 3000, }) } } }) }, sub1:function(e){ var order_id = e.currentTarget.id var that = this wx.request({ url: getApp().globalData.url + '/home/order/edit_order_status', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), order_id: order_id, type:3 }, success: function (res) { console.log('确认收货', res) if(res.data.status==1){ wx.showToast({ title: '收货成功', duration:3000, success:function(){ wx.reLaunch({ url: '../uesr/uesr', }) } }) } else { wx.showToast({ title: res.data.msg, duration: 3000, }) } } }) }, sub2: function (e) { var order_id = e.currentTarget.id var that = this wx.request({ url: getApp().globalData.url + '/home/order/edit_order_status', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), order_id: order_id, type: 4 }, success: function (res) { console.log('确认收货', res) if (res.data.status == 1) { wx.showToast({ title: '取货成功', duration: 3000, success: function () { wx.reLaunch({ url: '../uesr/uesr', }) } }) } wx.showToast({ title: res.data.msg, duration: 3000, }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { console.log(options) var type = wx.getStorageSync('boss') wx.showLoading({ title: '加载中...', duration: 2000 }) var that = this wx.request({ url: getApp().globalData.url + '/home/order/detail', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), order_id: options.id, }, success: function (res) { console.log('订单详情', res) that.setData({ lists: res.data.result, type: type, }) wx.hideLoading() } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/创飞/pages/join/join.js // pages/join/join.js Page({ /** * 页面的初始数据 */ data: { }, name: function (e) { this.setData({ name: e.detail.value, }) }, user_name: function (e) { this.setData({ user_name: e.detail.value, }) }, fw: function (e) { this.setData({ fw: e.detail.value, }) }, city: function (e) { this.setData({ city: e.detail.value, }) }, phone: function (e) { this.setData({ phone: e.detail.value, }) }, tj: function () { var that = this if (this.data.user_name == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您的姓名', }) } else if (this.data.name == undefined) { wx.showModal({ title: '资料不完整', content: '请填写商品名称', }) } else if (this.data.fw == undefined) { wx.showModal({ title: '资料不完整', content: '请填写供应范围', }) } else if (this.data.city == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您所在小区', }) } else if (this.data.phone == undefined) { wx.showModal({ title: '资料不完整', content: '请填写您的手机号', }) } else { wx.request({ url: getApp().globalData.url + '/home/group/addGys', method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值 // 'content-type': 'application/json;charset=utf-8', }, data: { key: wx.getStorageSync('result'), user_name: this.data.user_name, goods_name: this.data.name, area: this.data.fw, city: this.data.city, phone: this.data.phone, }, success: function (res) { console.log('供应商加盟', res) if (res.data.status == 1) { wx.showModal({ title: '提交成功', content: res.data.msg, success: function (r) { if (r.confirm) { wx.navigateBack({ delta: 1 }) } } }) } else { wx.showModal({ title: '出现错误', content: res.data.msg, success: function (r) { } }) } } }) } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
dcd17085dee5c088c850960274fbdc1ef2d7928b
[ "JavaScript" ]
6
JavaScript
wt-tao/cf
8650ea3a55d99d7a40b625908e67127179eccb8a
79563fdd13b7285a37c650c64decff104f540fe3
refs/heads/master
<repo_name>binhetech/nlp-manual<file_sep>/README.md # 简介 本仓库主要用于收集、整理公开的自然语言处理(NLP)相关的技术资料,包括最新文献、经典书籍以及行业研究报告等。一方面便于自己对自然语言处理进行系统的认知、学习,另一方面也希望可以分享、并帮助到其他爱学习知识的人士。 目录结构的说明如下: + books: 专业书籍,格式一般为pdf + literature: 最新文献,格式一般为pdf + report: 研究报告,格式一般为pdf + docs: 其他可公开的文档,格式一般为doc, docx # 更新日志 此处记录更新日志。 # NLP技术列表 此处列出本仓库中相关的技术资料的链接。 + 语言模型language model + 词向量技术 word2vec + seq2seq + 拼写纠错GEC + sentence embedding + pretrained model + prompt learning + contrastive learning + few shot learning + reinforcement learning + ... # 说明 本仓库资料来源于网上公开收集、整理,无任何商业目的。如有侵权,请及时联系本人删除。感谢!!!<file_sep>/tools/readme.md # 语言模型训练工具 ## SRILM + 说明: SRILM is a toolkit for building and applying statistical language models (LMs), primarily for use in speech recognition, statistical tagging and segmentation, and machine translation. + 版本: 1.7.3 + [SRILM下载地址](http://www.speech.sri.com/projects/srilm/download.html) + Python wrapper package: [pysrilm](https://github.com/njsmith/pysrilm)<file_sep>/books/deep reinforcement learning/get.sh #!/usr/bin/env bash URL=http://rail.eecs.berkeley.edu/deeprlcourse/static/slides/ for i in {1..25} do wget ${URL}lec-$i.pdf done
92b03bd7d3373a5fefd26b9ce43d040de01585a8
[ "Markdown", "Shell" ]
3
Markdown
binhetech/nlp-manual
2e78b8c5833b8406a2938d9daeffec5a5623212c
33a3a7991f594d6762474b472fcbb603d74246c1
refs/heads/master
<file_sep>package com.example.carrental.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.carrental.model.Person; import com.example.carrental.model.Vehicule; public interface PersonRepository extends CrudRepository<Person, Long> { List<Vehicule> findByName(String name); }<file_sep>import {Component, OnInit} from '@angular/core'; import {Car} from '../car'; import {CarService} from '../car.service'; import {Location} from '@angular/common'; @Component({ selector: 'app-car-getback', templateUrl: './rentback.component.html', styleUrls: ['./rentback.component.css'] }) export class CarGetbackComponent implements OnInit { title = 'Car Rental'; cars: Car[]; selectedCar: Car; constructor( private carService: CarService, private location: Location ) { } getCars(): void { this.carService.getCarsWithPromise().then(cars => this.cars = cars); /*this.carService.getCarsWithObservable().subscribe( res => { this.cars = res; } ); */ } ngOnInit() { this.getCars(); } onSelect(car: Car): void { this.selectedCar = car; } goBack(): void { this.location.back(); } } <file_sep>package com.example.carrental.repository; import java.util.List; import java.util.Date; import org.springframework.data.repository.CrudRepository; import com.example.carrental.model.Rent; //Connection à la db public interface RentRepository extends CrudRepository<Rent, Long> { List<Rent> findByBeginRent(Date beginRent); }<file_sep>package com.example.carrental.repository; import java.util.List; import java.util.Date; import org.springframework.data.repository.CrudRepository; import com.example.carrental.Car; import com.example.carrental.model.Rent; //Connection à la db public interface CarRepository extends CrudRepository<Car, Long> { List<Car> findByPlateNumber(String plateNumber); Car saveAndFlush(Car car); }<file_sep>package com.example.carrental.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.carrental.model.Vehicule; //Connection à la db public interface VehiculeRepository extends CrudRepository<Vehicule, Long> { List<Vehicule> findByPlateNumber(int plateNumber); }<file_sep>import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <nav> <ul> <li><a routerLink="/cars">Rent a car</a></li> <li><a routerLink="/getbackcars">Get back a car</a></li> </ul> </nav> <router-outlet></router-outlet><br> ` }) export class AppComponent { title = 'Car Rental Service'; } <file_sep>import 'rxjs/add/operator/switchMap'; import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, ParamMap} from '@angular/router'; import {Location} from '@angular/common'; import {Car} from './car'; import {CarService} from './car.service'; @Component({ selector: 'car-detail', templateUrl: './car-detail.component.html' }) export class CarDetailComponent implements OnInit { car: Car; constructor( private carService: CarService, private route: ActivatedRoute, private location: Location ) { } ngOnInit(): void { //this.getCard(); this.route.paramMap .switchMap((params: ParamMap) => this.carService.getCar(params.get('plateNumber'))) .subscribe(car => this.car = car); /* this.route.paramMap .switchMap((params: ParamMap) => this.carService.getCarWithObservable(params.get('plateNumber'))) .subscribe(car => this.car = car);*/ } getCard(): void { const plateNumber = this.route.snapshot.params['plateNumber']; this.carService.getCar(plateNumber).then(car => this.car = car); console.log(plateNumber); } rent(car): void { this.carService.rent(car).subscribe(car => this.car = car); } cancelRental(car): void { this.carService.getBack(car).subscribe(car => this.car = car); } goBack(): void { this.location.back(); } } <file_sep>import { Car } from './car'; export const CARS: Car[] = [ { id: 0, plateNumber: '198191B', model: 'Audi', price: 1100, numberOfDays: 0, rented: false, rents: [] }, { id: 1, plateNumber: '187BYD92', model: 'FIAT', price: 1200, numberOfDays: 0, rented: false, rents: [] }, { id: 2, plateNumber: 'JK1982B', model: 'Mustang', price: 1800, numberOfDays: 0, rented: false, rents: [] }, { id: 3, plateNumber: 'JK1982BA', model: 'Ford', price: 2100, numberOfDays: 0, rented: false, rents: [] } ]; <file_sep>package com.example.carrental.service; import com.example.carrental.model.Sample; import com.example.carrental.repository.SampleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.Optional; @Service @Transactional public class SampleService { @Autowired private SampleRepository sampleRepository; public Sample save(Sample sample) { return sampleRepository.save(sample); } public Optional<Sample> getOne(Long id) { return sampleRepository.findById(id); } } <file_sep>import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {CarsComponent} from './cars.component'; import {CarDetailComponent} from './car-detail.component'; import {CarGetbackComponent} from './rentback/rentback.component'; const routes: Routes = [ {path: '', redirectTo: '/cars', pathMatch: 'full'}, {path: 'detail/:plateNumber', component: CarDetailComponent}, {path: 'cars', component: CarsComponent}, {path: 'getbackcars', component: CarGetbackComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>package com.example.carrental.repository; import com.example.carrental.model.Sample; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface SampleRepository extends JpaRepository<Sample, Long> { } <file_sep># Need a web service for run this application # CarRental download an unzip the project npm install npm start # Procedure for adding a new component Add a routerLink into <a href="https://github.com/charroux/CarRental/blob/master/src/app/app.component.ts">app.component.ts</a> Add a route into <a href="https://github.com/charroux/CarRental/blob/master/src/app/app-routing.module.ts">app-routing.module.ts</a>: a path + a component + its import Add into <a href="https://github.com/charroux/CarRental/blob/master/src/app/app.module.ts">app.module.ts</a> the declaration + the import of the component Create a component (the filename is given by the import into <a href="https://github.com/charroux/CarRental/blob/master/src/app/app-routing.module.ts">app-routing.module.ts</a>), the component name is in the routes of le nom du composant est dans les routes de <a href="https://github.com/charroux/CarRental/blob/master/src/app/app-routing.module.ts">app-routing.module.ts</a> Create an html file associated to the component (the name of the html file is given by the templateUrl of the component) <file_sep><hr> <h3>Choose the car to get back</h3> <div> <select [(ngModel)]="selectedCar" required> <option *ngFor="let car of cars" [ngValue]="car"> <div *ngIf="car.rented == false"> {{car.model}} </div> </option> </select> </div> <div *ngIf="selectedCar"> <h2>Plate number of the selected car: {{selectedCar.plateNumber | uppercase}} </h2> <button (click)="goBack()">Get Back</button> <button (click)="goBack()">Return to the main menu</button> </div>
f4ca1ae23750c0b9a685c30cfc8647d0d4592465
[ "Markdown", "Java", "TypeScript", "HTML" ]
13
Java
paulcrep/Projet_WebService
7430e6676e531d1ca76705042010b05315e1fe2d
739b5ae98a571f3c78cf231e3f5b3ef4cdf0792a
refs/heads/master
<repo_name>terpugov/greedy_algorithm<file_sep>/fractional_knapsack.py # Uses python3 import sys density = [] def get_optimal_value(capacity, weights, values): V = 0. for i in range(n): density.append(values[i]/weights[i]) for i in range(n): if capacity == 0: return V else: inde = density.index(max(density)) a = min(weights[inde], capacity) V += a*density[inde] capacity -= a density[inde] = 0 return V if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] opt_value = get_optimal_value(capacity, weights, values) print("{:.4f}".format(opt_value)) <file_sep>/changing_money_time.py # Uses python3 import time m = int(input()) #start = time.time() def change_money(m): c1 = 1 c5 = 5 c10 = 10 count = 0 condition = True while m != 0: while m>=c10: m = m - c10 count = count + 1 while m>=c5: m = m - c5 count = count + 1 while m>=c1: m = m-c1 count = count + 1 return count a = change_money(m) print(a) #print(time.time()-start)
9b2fcfdfaf8b7df78557b843a34564f376320610
[ "Python" ]
2
Python
terpugov/greedy_algorithm
bbec9d4e3eb5820eb7c49e6556f012470f1c0cca
badc0529f0635d9af0793fc8c446fcd9b60e56c2
refs/heads/master
<repo_name>Tsiory-prdx/tests-ruby<file_sep>/lib/05_timer.rb def time_string(sec) hour,minute,second = 0 , 0 , 0 hour = sec / 3600 minute = (sec / 60) %60 second = sec %60 if hour < 10 hour = "0" + hour.to_s end if minute < 10 minute = "0" + minute.to_s end if second < 10 second = "0" + second.to_s end return "#{hour}:#{minute}:#{second}" end <file_sep>/lib/04_simon_says.rb def echo(str) return str end def shout(str) return str.upcase end def repeat(str , int = 2) retour = (str + " ") * int return retour.strip end def start_of_word(str , int) retour = [] result = str.chars i = 0 result.each do |letter| if i < int retour << result[i] i+=1 end end return retour.join end def first_word(str) retour = [] result = str.chars i = 0 result.each do |letter| loop do break if result[i] == " " retour << result[i] i += 1 end end return retour.join end def littleword(str) lilword = ["the" , "and", "or"] for i in 0...lilword.size if str == lilword[i] return true end end return false end def titleize(str) retour = [] result = str.split i = 0 for i in 0...result.size if littleword(result[i]) == false retour << result[i].capitalize elsif littleword(result[i]) == true && i == 0 retour << result[i].capitalize elsif littleword(result[i]) == true retour << result[i] end end return retour.join(" ") end<file_sep>/lib/03_basics.rb #---****'who is the biggest number'****---# def who_is_bigger(a, b, c) max = a retour = "a is bigger" #test if a == nil || b == nil || c == nil #si nil est present return "nil detected" end #testez si b est max if b > max max = b retour = "b is bigger" end #testez si c est max if c > max max = c retour = "c is bigger" end return retour end #---****'crazy stuff on strings'****---# #fonction recherche de LTA dans la phrase def noLTA(caractere) ltas = ['a','l','t'] ltas.each do |lta| if caractere.downcase == lta return true end end return false end def reverse_upcase_noLTA(text) result = text.chars retour = [] #receuillir tous les lettres differents de ALT result.each do |letter| if noLTA(letter) == false retour << letter end end #sortir les lettres du tableau sentence_noLTA = retour.join #Rendre en majuscule sentence_upcase = sentence_noLTA.upcase #renverser les lettres sentence_reverse = sentence_upcase.reverse return sentence_reverse end #---****'42 finder'****---# def array_42(arr) for i in (0...arr.length) if arr[i] == 42 return true end end return false end #---****'crazy stuff on arrays'****---# def flattened(arr) #diminue la dimension du tableau en argument retour = [] #la variable à retourner for i in (0 ... arr.size) #parcours du tableau if arr[i].class.to_s == "Array" #la valeur du cellule du tableau est encore est tableau for j in (0 ... arr[i].size) retour << arr[i][j] #on developpe ce tableau pour que sa dimension diminue end else retour << arr[i] #si ce n'est pas un tableau on continue de concatener la valeur suivant à celle de la variable retour end end return retour end def multiplicatebytwo(arr) #fonction qui retourne la la multiplication de chaque cellule par 2 for i in (0 ... arr.size) arr [i] = 2 * arr[i] end return arr end def removemultiplyofthree(arr) #supprime les valeurs multiple de 3 retour = [] #valeur à retourner for i in (0 ... arr.size) if arr[i] % 3 != 0 #si le reste de la division par 3 est different de 0 retour << arr[i] #alors on le met dans la variable retour end end return retour end def removeelement(arr,index) #fonction qui supprime un indice retour = [] for i in (0...arr.size) do if index != i retour << arr[i] end end return retour end def existduplicate(tab) #recherche du doublon dans le tableau tab for i in (0...tab.size) do # parcourir le tableau depuis l'indice i = 0 for j in (i+1...tab.size) do # comparer la valeur du tableau indice i et i+1 jusqu'a sa taille if(tab[i]==tab[j]) #si il y a 2 valeurs egaux alors return [true,j] #on retourne true et l'indice du second pour qu'on puisse supprimer end end end return [false] #si non, on retourne false (il n'y a plus de doublon) end def removeduplicate(tableau) while existduplicate(tableau)[0] == true tableau = removeelement(tableau, existduplicate(tableau)[1]) end return tableau end def sortbyasc(arr) arraysize = arr.size #on recupere la taille de l' array i = 0 # On a besoin de i pour parcourir le array while i<arraysize #tant que i<longueur du array while i+1<arraysize # et i+1 <arraysize if arr[i]>arr[i+1] # on met le plus grand à droite pour qu'on puisse avoir des tris croissants temp = arr[i] arr[i] = arr[i+1] arr[i+1] = temp end i+=1 #on incremente le i end arraysize-=1 #on decremente la longueur du array pour qu'on trie les inferieurs au plus grand du tableau end return arr end def magic_array(arr) i = 0 while i<arr.size while arr[i].class.to_s == "Array" arr = flattened(arr) i=0 end i+=1 end arr = multiplicatebytwo(arr) arr = removemultiplyofthree(arr) #duplicate arr = removeduplicate(arr) #sortbyasc arr = sortbyasc(arr) return arr end<file_sep>/lib/02_calculator.rb def add(a , b) #Additionne a et b return a + b end def subtract(a , b) #Soustraire a et b return a - b end def sum(tab) #somme de nombre return tab.sum end def multiply(a , b) #Multiplie a et b return a * b end def power(a , b) #calcul de a puissance b i = 0 result = 1 for i in (0 ... b) result *= a end return result end def factorial(a) fact = 1 i = 1 #Calcul de factoriel de a for i in (1..a) fact *= i end return fact end <file_sep>/lib/01_temperature.rb def ftoc(degre_C) #conversion de fahrenheit to celsius return (degre_C - 32) * 5 / 9 end def ctof(degre_F) #conversion de celsius to fahrenheit return (degre_F * 1.8) + 32 end
2297e2592ee1bc5fd2f095156dfb6d392d10a1b5
[ "Ruby" ]
5
Ruby
Tsiory-prdx/tests-ruby
1d12bbafa83bb17c3fa0d683aa2a4a927cf8a7af
e0085afbddabb222544dd98fe441a0c70be179d3
refs/heads/master
<repo_name>Thawny/hangman-react-redux<file_sep>/src/containers/Word.js import PropTypes from 'prop-types'; import React, {Component} from 'react'; import { connect } from "react-redux"; const mapStateToProps = state => { return { word: state.word, usedLetters: state.usedLetters}; }; class Word extends Component { static propTypes = { word: PropTypes.string.isRequired, usedLetters: PropTypes.object.isRequired } // Produit une représentation textuelle de l’état de la partie, // chaque lettre non découverte étant représentée par un _underscore_. // (CSS assurera de l’espacement entre les lettres pour mieux // visualiser le tout). displayWord(word, usedLetters) { return word.replace(/\w/g, (letter) => (usedLetters.has(letter) ? letter : '_') ) } render() { const word = this.props.word; const usedLetters = this.props.usedLetters; return ( <div id="word">{this.displayWord(word, usedLetters)}</div> ) } } export default Word = connect(mapStateToProps)(Word); <file_sep>/src/actions/index.js import * as types from '../constants/ActionsTypes'; export const startNewGame = () => ({ type: types.START_NEW_GAME }) export const winGame = (payload = false) => ({ type: types.START_NEW_GAME, payload: payload }) export const clickLetter = (payload) => ({ type: types.CLICK_LETTER, payload: payload }) <file_sep>/src/constants/ActionsTypes.js export const START_NEW_GAME = "START_NEW_GAME"; export const WIN_GAME = "WIN_GAME"; export const CLICK_LETTER = "CLICK_LETTER"; <file_sep>/src/containers/App.js import PropTypes from 'prop-types'; import React, {Component} from 'react'; import { connect } from "react-redux"; import '../App.css'; import Keyboard from './Keyboard'; import Word from './Word'; import WonFooter from './WonFooter'; const mapStateToProps = state => { return { gameIsWon: state.gameIsWon }; }; class App extends Component { static propTypes = { gameIsWon: PropTypes.bool.isRequired } constructor(props) { super(props); this.props = props } render() { const gameIsWon = this.props.gameIsWon; let footer; if (gameIsWon) { footer = <WonFooter/>; } else { footer = <div> <Word /> <Keyboard/> </div> } return ( <div className="container"> <h2 className="pendu">Jeu du pendu</h2> {footer} </div> ) } } export default App = connect(mapStateToProps)(App); <file_sep>/src/constants/Words.js export const WORDS = [ "FACILE", "BONJOUR", "TRUC", "BOBINE", "INTUITION", "MACHIN", "CHALET" ] export const pickRandomWord = () => { return WORDS[Math.floor(Math.random() * WORDS.length)]; } <file_sep>/src/containers/WonFooter.js import PropTypes from 'prop-types'; import React, {Component} from 'react'; import { connect } from "react-redux"; import { startNewGame } from "../actions/index"; function mapDispatchToProps(dispatch) { return { startNewGame: letter => dispatch(startNewGame()) }; } class WonFooter extends Component { static propTypes = { startNewGame: PropTypes.func.isRequired, } handleClick(e) { this.props.startNewGame(); } render() { return ( <div> <h3>Félicitations!</h3> <button onClick={this.handleClick.bind(this)}>recommencer</button> </div> ) } } WonFooter = connect( null, mapDispatchToProps )(WonFooter); export default WonFooter
3fa3f525a5de084a3d9c0227c8e0e598defa7576
[ "JavaScript" ]
6
JavaScript
Thawny/hangman-react-redux
7f0f202c7957a2d82878af332e687537a767e74f
71561644d0ae6e62d1c82964b1739c075d2b947b
refs/heads/main
<repo_name>KimJongHyun98/Leafy<file_sep>/Leafy save/Leafy/src/main/java/com/plant/mapper/PCBoardMapper.java package com.plant.mapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.plant.dto.PCBCommentDTO; import com.plant.dto.PCBoardDTO; @Mapper public interface PCBoardMapper { // 분양게시판 매퍼 ArrayList<PCBoardDTO> selectAllPCBoard(int page); int selectPCBoardCount(); PCBoardDTO selectPCBoardContent(int fcbno); List<PCBCommentDTO> selectPCBoardComment(int fcbno); PCBCommentDTO insertPCBComment(PCBCommentDTO pcbcdto); int selectPCBoardSearchCount(HashMap<String, Object> map); int addPCBoardCount(int fcbno); int insertPCBoardRecommand(HashMap<String, Object> map); int deletePCBoardRecommand(HashMap<String, Object> map); } <file_sep>/1/Leafy/src/main/java/com/plant/mapper/MTMRequestMapper.java package com.plant.mapper; public interface MTMRequestMapper { //고객센터(1:1문의) 매퍼 } <file_sep>/Leafy/src/main/resources/application.properties spring.datasource.driver-class-name=oracle.jdbc.OracleDriver spring.datasource.url=jdbc:oracle:thin:@nam2626.synology.me:32769:xe spring.datasource.username=error501 spring.datasource.password=<PASSWORD> spring.datasource.connection-test-query=SELECT 1 mybatis.type-aliases-package=com.plant.dto mybatis.mapper-locations=mapper/**/*.xml logging.level.com.plant=trace spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp server.port=9999 <file_sep>/1/Leafy/src/main/java/com/plant/service/MTMRequsetService.java package com.plant.service; public class MTMRequsetService {//고객센터-1:1문의 서비스 } <file_sep>/Leafy/src/main/java/com/plant/service/TBoardService.java package com.plant.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.springframework.stereotype.Service; import com.plant.dto.TBoardDTO; import com.plant.mapper.TBoardMapper; @Service public class TBoardService { // 팁 게시판 서비스 private TBoardMapper tbMapper; public TBoardService(TBoardMapper tbMapper) { super(); this.tbMapper = tbMapper; } public ArrayList<TBoardDTO> selectAllTBoard(int pageNo) { return tbMapper.selectAllTBoard(pageNo); } public int selectTBoardCount() { return tbMapper.selectTBoardCount(); } public List<TBoardDTO> selectTBoard(String kind, String search) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("kind", kind); map.put("search", search); return tbMapper.selectTBoard(map); } public ArrayList<TBoardDTO> selectAllTip(int pageNo) { return tbMapper.selectAllTip(pageNo); } } <file_sep>/Leafy/src/main/java/com/plant/mapper/MessageMapper.java package com.plant.mapper; import java.util.ArrayList; import org.apache.ibatis.annotations.Mapper; import com.plant.dto.messageDTO; @Mapper public interface MessageMapper { ArrayList<messageDTO> messageList(messageDTO dto); int countUnread(messageDTO mto); String getOtherProfile(messageDTO mto); ArrayList roomContentList(messageDTO dto); void messageReadChk(messageDTO dto); int existChat(messageDTO dto); int maxRoom(messageDTO dto); String selectRoom(messageDTO dto); int messageSendInlist(messageDTO dto); } <file_sep>/Leafy/src/main/java/com/plant/service/NoticeService.java package com.plant.service; import java.util.ArrayList; import org.springframework.stereotype.Service; import com.plant.dto.NoticeDTO; import com.plant.mapper.NoticeMapper; @Service //고객센터-공지사항 서비스 public class NoticeService { private NoticeMapper mapper; public NoticeService(NoticeMapper mapper) { super(); this.mapper = mapper; } public ArrayList<NoticeDTO> selectNotice(int pageNo) { return mapper.selectNotice(pageNo); } } <file_sep>/1/Leafy/src/main/java/com/plant/mapper/FBoardMapper.java package com.plant.mapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.plant.dto.FBCommentDTO; import com.plant.dto.FBoardDTO; @Mapper public interface FBoardMapper { // 자유게시판 매퍼 ArrayList<FBoardDTO> selectAllFBoard(int pageNo); int selectFBoardCount(); ArrayList<FBoardDTO> selectFBoard(HashMap<String, Object> map); FBoardDTO selectFBoardContent(int fb_no); List<FBCommentDTO> selectFBoardComment(int fb_no); FBCommentDTO insertFBComment(FBCommentDTO fbcdto); int selectFBoardSearchCount(HashMap<String, Object> map); int addFBoardCount(int fb_no); int insertFBoardRecommand(HashMap<String, Object> map); int deleteFBoardRecommand(HashMap<String, Object> map); } <file_sep>/Leafy/src/main/java/com/plant/service/PBoardService.java package com.plant.service; import java.util.ArrayList; import java.util.HashMap; import org.springframework.stereotype.Service; import com.plant.dto.PBoardDTO; import com.plant.mapper.PBoardMapper; @Service public class PBoardService { // 포토게시판 서비스 private PBoardMapper pbMapper; public PBoardService(PBoardMapper pbMapper) { super(); this.pbMapper = pbMapper; } public ArrayList<PBoardDTO> selectAllPBoard(int pageNo) { return pbMapper.selectAllPBoard(pageNo); } public ArrayList<PBoardDTO> selectMVPBoard() { return pbMapper.selectMVPBoard(); } public int selectPBoardCount() { return pbMapper.selectPBoardCount(); } public ArrayList<PBoardDTO> selectPBoard(String kind, String search, int currentPageNo) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("kind", kind); map.put("search", search); map.put("pageNo", currentPageNo); return pbMapper.selectPBoard(map); } public int selectPBoardSearchCount(String kind, String search) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("kind", kind); map.put("search", search); return pbMapper.selectPBoardSearchCount(map); } public void addPBoardCount(int pb_no) { pbMapper.addPBoardCount(pb_no); } public PBoardDTO selectPBoardContent(int pb_no) { return pbMapper.selectPBoardContent(pb_no); } // public ArrayList<PBFileDTO> selectFileList(int pb_no) { // return pbMapper.selectFileList(pb_no); // } // public PBFileDTO selectFile(int pb_fno) { // return pbMapper.selectFile(pb_fno); // } // public ArrayList<PBCommentDTO> selectPBoardComment(int pb_no) { // return pbMapper.selectPBoardComment(pb_no); // } // public int insertPBComment(PBCommentDTO pbcdto) { // return pbMapper.insertPBComment(pbcdto); // } public void deletePBComment(int pbc_no) { pbMapper.deletePBComment(pbc_no); } public int insertPBoard(PBoardDTO pbdto) { int pb_no = pbMapper.selectPBoardNo(); pbdto.setPb_no(pb_no); pbMapper.insertPBoard(pbdto); return pb_no; } // public void insertFileList(ArrayList<PBFileDTO> flist) { // for(int i=0;i<flist.size();i++) { // pbMapper.insertFileInfo(flist.get(i)); // } // } public void updatePBoard(int pb_no, String pb_title, String pb_content) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("pb_no", pb_no); map.put("pb_title", pb_title); map.put("pb_content", pb_content); pbMapper.updatePBoard(map); } public void deletePBoard(int pb_no) { pbMapper.deletePBoard(pb_no); } public boolean insertPBoardRecommand(String id, int pb_no) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id", id); map.put("pb_no", pb_no); int count = 0; try { count = pbMapper.insertPBoardRecommand(map); } catch (Exception e) { System.out.println("게시글 추천을 이미 하였습니다."); } if(count==0) pbMapper.deletePBoardRecommand(map); return count==1; } }<file_sep>/1/Leafy/src/main/java/com/plant/mapper/TBoardMapper.java package com.plant.mapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.plant.dto.TBoardDTO; @Mapper public interface TBoardMapper { // 팁 게시판 매퍼 ArrayList<TBoardDTO> selectAllTBoard(int pageNo); int selectTBoardCount(); List<TBoardDTO> selectTBoard(HashMap<String, Object> map); } <file_sep>/Leafy/src/main/java/com/plant/dto/FBCommentDTO.java package com.plant.dto; import org.apache.ibatis.type.Alias; @Alias("fbComment") // 자유게시판 댓글 DTO public class FBCommentDTO { private int fbc_no; private int fb_no; private String commentor_id; private String fb_comment_content; private String fb_comment_date; public FBCommentDTO() { } public FBCommentDTO(int fbc_no, int fb_no, String commentor_id, String fb_comment_content, String fb_comment_date) { super(); this.fbc_no = fbc_no; this.fb_no = fb_no; this.commentor_id = commentor_id; this.fb_comment_content = fb_comment_content; this.fb_comment_date = fb_comment_date; } public int getFbc_no() { return fbc_no; } public void setFbc_no(int fbc_no) { this.fbc_no = fbc_no; } public int getFb_no() { return fb_no; } public void setFb_no(int fb_no) { this.fb_no = fb_no; } public String getCommentor_id() { return commentor_id; } public void setCommentor_id(String commentor_id) { this.commentor_id = commentor_id; } public String getFb_comment_content() { return fb_comment_content; } public void setFb_comment_content(String fb_comment_content) { this.fb_comment_content = fb_comment_content; } public String getFb_comment_date() { return fb_comment_date; } public void setFb_comment_date(String fb_comment_date) { this.fb_comment_date = fb_comment_date; } @Override public String toString() { return "FBCommentDTO [fbc_no=" + fbc_no + ", fb_no=" + fb_no + ", commentor_id=" + commentor_id + ", fb_comment_content=" + fb_comment_content + ", fb_comment_date=" + fb_comment_date + "]"; } } <file_sep>/Leafy/src/main/java/com/plant/dto/NoticeFileDTO.java package com.plant.dto; import java.io.File; import org.apache.ibatis.type.Alias; @Alias("noticefile") public class NoticeFileDTO { private int nfno; private int nbno; private String id; private String path; private String fdate; private String fileName; private String type; private String originFileName; public NoticeFileDTO() { } public NoticeFileDTO(File file) { this.path = file.getAbsolutePath(); this.fileName = file.getName(); switch (fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase()) { case "png": case "bmp": case "jpg": case "gif": type = "image"; break; default: type = "normal"; } } public NoticeFileDTO(int nfno, int nbno, String id, String path,String fdate, String fileName, String type, String originFileName) { super(); this.nfno = nfno; this.nbno = nbno; this.id = id; this.path = path; this.fdate = fdate; this.fileName = fileName; this.type = type; this.originFileName = originFileName; } @Override public String toString() { return "NoticeFileDTO [nfno=" + nfno + ", nbno=" + nbno + ", id=" + id + ", fdate=" + fdate + ", path=" + path + ", fileName=" + fileName + ", type=" + type + "]"; } public int getNfno() { return nfno; } public void setNfno(int nfno) { this.nfno = nfno; } public int getNbno() { return nbno; } public void setNbno(int nbno) { this.nbno = nbno; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFdate() { return fdate; } public void setFdate(String fdate) { this.fdate = fdate; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getOriginFileName() { return originFileName; } public void setOriginFileName(String originFileName) { this.originFileName = originFileName; } } <file_sep>/Leafy/src/main/java/com/plant/mapper/LoginMapper.java package com.plant.mapper; import java.util.HashMap; import org.apache.ibatis.annotations.Mapper; import com.plant.dto.FBoardDTO; import com.plant.dto.MemberDTO; import com.plant.dto.NaverDTO; @Mapper public interface LoginMapper { MemberDTO Login(HashMap<String, Object> map); int insertMember(MemberDTO dto); int insertNaver(NaverDTO dto); int nickCheck(String nickname); } <file_sep>/Leafy/src/main/java/com/plant/dto/TFileDTO.java package com.plant.dto; import java.io.File; import org.apache.ibatis.type.Alias; @Alias("tFile") public class TFileDTO { private int tfno; private int tno; private String id; private String path; private String fdate; private String originFileName; private String fileName; private String type; public TFileDTO() { } public TFileDTO(File file) { this.path = file.getAbsolutePath(); this.fileName = file.getName(); switch (fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase()) { case "png": case "bmp": case "jpg": case "gif": type = "image"; break; default: type = "normal"; } } public TFileDTO(int tfno, int tno, String id, String path, String fdate, String originFileName, String fileName, String type) { super(); this.tfno = tfno; this.tno = tno; this.id = id; this.path = path; this.fdate = fdate; this.originFileName = originFileName; this.fileName = fileName; this.type = type; } @Override public String toString() { return "TFileDTO [tfno=" + tfno + ", tno=" + tno + ", id=" + id + ", path=" + path + ", fdate=" + fdate + ", originFileName=" + originFileName + ", fileName=" + fileName + ", type=" + type + "]"; } public int getTfno() { return tfno; } public void setTfno(int tfno) { this.tfno = tfno; } public int getTno() { return tno; } public void setTno(int tno) { this.tno = tno; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getFdate() { return fdate; } public void setFdate(String fdate) { this.fdate = fdate; } public String getOriginFileName() { return originFileName; } public void setOriginFileName(String originFileName) { this.originFileName = originFileName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep>/Leafy/src/main/java/com/plant/service/FBoardService.java package com.plant.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.springframework.stereotype.Service; import com.plant.dto.FBCommentDTO; import com.plant.dto.FBoardDTO; import com.plant.mapper.FBoardMapper; @Service public class FBoardService { // 자유게시판 서비스 private FBoardMapper fbMapper; public FBoardService(FBoardMapper fbMapper) { this.fbMapper = fbMapper; } public ArrayList<FBoardDTO> selectAllFBoard(int pageNo) { return fbMapper.selectAllFBoard(pageNo); } public int selectFBoardCount() { return fbMapper.selectFBoardCount(); } public ArrayList<FBoardDTO> selectFBoard(String kind, String search, int currentPageNo) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("kind", kind); map.put("search", search); map.put("pageNo", currentPageNo); return fbMapper.selectFBoard(map); } public int selectFBoardSearchCount(String kind, String search) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("kind", kind); map.put("search", search); return fbMapper.selectFBoardSearchCount(map); } public FBoardDTO selectFBoardContent(int fb_no) { return fbMapper.selectFBoardContent(fb_no); } public List<FBCommentDTO> selectFBoardComment(int fb_no) { return fbMapper.selectFBoardComment(fb_no); } public FBCommentDTO insertFBComment(FBCommentDTO fbcdto) { return fbMapper.insertFBComment(fbcdto); } public void addFBoardCount(int fb_no) { fbMapper.addFBoardCount(fb_no); } public boolean insertFBoardRecommand(String id, int fb_no) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id", id); map.put("fb_no", fb_no); int count=0; try { count = fbMapper.insertFBoardRecommand(map); } catch (Exception e) { System.out.println("게시글 추천을 이미 하였습니다."); } if(count==0) fbMapper.deleteFBoardRecommand(map); return count==1; } } <file_sep>/Leafy/src/main/java/com/plant/service/messageService.java package com.plant.service; import java.util.ArrayList; import org.springframework.stereotype.Service; import com.plant.dto.messageDTO; import com.plant.mapper.MessageMapper; @Service public class messageService { private static MessageMapper msMapper; public messageService(MessageMapper msMapper) { this.msMapper = msMapper; } public static ArrayList<messageDTO> messageList(messageDTO dto){ String nick = dto.getNick(); ArrayList<messageDTO> list = (ArrayList) msMapper.messageList(dto); for (messageDTO mto : list) { mto.setNick(nick); //현재 사용자가 해당 room에서 안읽은 메세지의 갯수를 가져온다. int unread = msMapper.countUnread(mto); //현재 사용자가 메세지를 주고 받는 상대 profile을 가져온다. String profile = msMapper.getOtherProfile(mto); //안읽은 메세지 갯수를 mto에 set한다. mto.setUnread(unread); //메세지 상대의 프로필 사진을 mto에 set 한다. mto.setProfile(profile); //메세지 상대의 닉넴을 세팅한다 if (nick.equals(mto.getSend_nick())) { mto.setOther_nick(mto.getRecv_nick()); }else { mto.setOther_nick(mto.getSend_nick()); } } return list; } public static ArrayList<messageDTO> roomContentList(messageDTO dto){ System.out.println("room : " + dto.getRoom()); System.out.println("recv_nick : " + dto.getRecv_nick()); System.out.println("nick : " + dto.getNick()); ArrayList<messageDTO> clist = (ArrayList) msMapper.roomContentList(dto); msMapper.messageReadChk(dto); return clist; } public static int messageSendInlist(messageDTO dto) { if(dto.getRoom() == 0) { int exist_chat = msMapper.existChat(dto); if(exist_chat == 0) { int max_room = msMapper.maxRoom(dto); dto.setRoom(max_room + 1); }else { int room = Integer.parseInt(msMapper.selectRoom(dto)); dto.setRoom(room); } } int flag = msMapper.messageSendInlist(dto); return flag; } } <file_sep>/Leafy/src/main/java/com/plant/dto/TBoardDTO.java package com.plant.dto; import org.apache.ibatis.type.Alias; @Alias("tBoard") // 팁 게시판 DTO public class TBoardDTO { private int tb_no; private String id; private String tb_title; private String tb_content; private String tb_date; private String tb_addfile_url; private int tb_recommand; private int tb_visit; private int tb_comment; public TBoardDTO() { } public TBoardDTO(int tb_no, String id, String tb_title, String tb_content, String tb_date, String tb_addfile_url, int tb_recommand, int tb_visit, int tb_comment) { super(); this.tb_no = tb_no; this.id = id; this.tb_title = tb_title; this.tb_content = tb_content; this.tb_date = tb_date; this.tb_addfile_url = tb_addfile_url; this.tb_recommand = tb_recommand; this.tb_visit = tb_visit; this.tb_comment = tb_comment; } @Override public String toString() { return "TBoardDTO [tb_no=" + tb_no + ", id=" + id + ", tb_title=" + tb_title + ", tb_content=" + tb_content + ", tb_date=" + tb_date + ", tb_addfile_url=" + tb_addfile_url + ", tb_recommand=" + tb_recommand + ", tb_visit=" + tb_visit + ", tb_comment=" + tb_comment + "]"; } public int getTb_no() { return tb_no; } public void setTb_no(int tb_no) { this.tb_no = tb_no; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTb_title() { return tb_title; } public void setTb_title(String tb_title) { this.tb_title = tb_title; } public String getTb_content() { return tb_content; } public void setTb_content(String tb_content) { this.tb_content = tb_content; } public String getTb_date() { return tb_date; } public void setTb_date(String tb_date) { this.tb_date = tb_date; } public String getTb_addfile_url() { return tb_addfile_url; } public void setTb_addfile_url(String tb_addfile_url) { this.tb_addfile_url = tb_addfile_url; } public int getTb_recommand() { return tb_recommand; } public void setTb_recommand(int tb_recommand) { this.tb_recommand = tb_recommand; } public int getTb_visit() { return tb_visit; } public void setTb_visit(int tb_visit) { this.tb_visit = tb_visit; } public int getTb_comment() { return tb_comment; } public void setTb_comment(int tb_comment) { this.tb_comment = tb_comment; } }
bd5d2fba31f55f392f74f20d436d0aeee50d60d2
[ "Java", "INI" ]
17
Java
KimJongHyun98/Leafy
502d644b03da932511bcfa230eb48edfdd15823a
0968a746e3f006e0242c840b4c45a5adaedf3157
refs/heads/master
<file_sep>package com.study.spring.ch4.concert; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; /** * Created by tianyuzhi on 17/12/19. */ @Aspect public class Audience3 { @Pointcut(value = "execution(** com.study.spring.ch4.concert.Peformance.perform(..))") public void perform() {} @Around("perform()") public void watchPerformance(ProceedingJoinPoint jp) { try { silenceCellPhones(); takeSeats(); jp.proceed(); applause(); } catch (Throwable throwable) { demandRefund(); } } public void silenceCellPhones() { System.out.println("Silencing cell phones"); } public void takeSeats() { System.out.println("take seats"); } public void applause() { System.out.println("CLAP CLAP CLAP!!!"); } public void demandRefund() { System.out.println("Demanding a refund"); } } <file_sep>package com.study.spring.person.dao; /** * Created by tianyuzhi on 17/12/7. * @author tianzhiyu */ public interface IPersonDao { default void save(){ //dummy, do nothing } } <file_sep>package com.study.spring.soundsystem; /** * Created by tianyuzhi on 17/12/12. */ public interface IMediaPlayer { default void play() {} } <file_sep>package com.study.spring.knight.service; /** * Created by tianyuzhi on 17/12/8. */ public interface IKNight { default void embarkQuest() { } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring_study</groupId> <artifactId>spring_study</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>5.0.2.RELEASE</spring.version> <lombok.version>1.16.18</lombok.version> <testng.versino>6.9.6</testng.versino> <junit.version>4.12</junit.version> <jmockit.version>1.37</jmockit.version> <jacoco.version>0.7.9</jacoco.version> <mockito.version>2.0.2-beta</mockito.version> <powermock.version>2.0.0-beta.5</powermock.version> </properties> <dependencies> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-easymock</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jmockit</groupId> <artifactId>jmockit</artifactId> <version>${jmockit.version}</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.github.stefanbirkner/system-rules --> <dependency> <groupId>com.github.stefanbirkner</groupId> <artifactId>system-rules</artifactId> <version>1.17.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.versino}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- AOP的依赖,@Aspect注解在里面 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.10</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <configuration> <parallel>methods</parallel> <threadCount>1</threadCount> <perCoreThreadCount>true</perCoreThreadCount> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.19.1</version> </dependency> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-testng</artifactId> <version>2.19.1</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>reference.conf</resource> </transformer> </transformers> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.6.201602180812</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>default-report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> <execution> <id>default-check</id> <goals> <goal>check</goal> </goals> <configuration> <rules> <rule implementation="org.jacoco.maven.RuleConfiguration"> <element>BUNDLE</element> <limits> <limit implementation="org.jacoco.report.check.Limit"> <counter>COMPLEXITY</counter> <value>COVEREDRATIO</value> <minimum>0.60</minimum> </limit> </limits> </rule> </rules> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>package com.study.spring.person.dao; /** * * @author tianyuzhi * @date 17/12/7 */ public class PersonDao implements IPersonDao { @Override public void save() { System.out.println("=====PersonDao.save()===="); } } <file_sep>package com.study.spring.soundsystem2; import com.study.spring.soundsystem.ICompactDisc; import com.study.spring.soundsystem.IMediaPlayer; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.SystemOutRule; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.testng.Assert.*; /** * Created by tianyuzhi on 17/12/12. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CDPlayerJavaConfig.class) public class CDPlayerJavaConfigTest { @Rule public final SystemOutRule rule = new SystemOutRule(); @Autowired private IMediaPlayer mediaPlayer; @Autowired private ICompactDisc cd; @Test public void cdShouldNotNull() { assertNotNull(cd); } @Test public void play() { mediaPlayer.play(); //cd.play();// has the same output with mediaPlayer.play(); assertEquals(rule.enableLog().getLog(), "Playing Sgt. Peppers's Lonely Hearts Club Band by The Beatles"); } }<file_sep>package com.study.spring.soundsystem; import org.springframework.beans.factory.annotation.Autowired; /** * Created by tianyuzhi on 17/12/11. */ public class CDPlayer { private ICompactDisc compactDisc; @Autowired public CDPlayer(ICompactDisc compactDisc) { this.compactDisc = compactDisc; } } <file_sep>package com.study.spring.soundsystem; /** * * @author tianyuzhi * @date 17/12/11 */ public interface ICompactDisc { default void play() { } default void playTrack(int i) { } } <file_sep>package com.study.spring.knight.service; import com.study.spring.knight.dao.IQuest; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.mockito.Mockito.*; /** * Created by tianyuzhi on 17/12/8. */ public class BraveKNightTest { @Test public void testEmbarkQuest() throws Exception { IQuest quest = Mockito.mock(IQuest.class); BraveKNight kNight = new BraveKNight(quest); kNight.embarkQuest(); verify(quest, times(1)).embark(); } @Test public void testXML() { BeanFactory factory = new ClassPathXmlApplicationContext("braveKnight_content.xml"); BraveKNight braveKNight = (BraveKNight)factory.getBean("knight"); braveKNight.embarkQuest(); } }<file_sep>package com.study.spring.knight.service; import com.study.spring.knight.dao.IQuest; import lombok.Data; /** * * @author tianyuzhi * @date 17/12/8 */ @Data public class BraveKNight implements IKNight { private IQuest quest = null; public BraveKNight(IQuest quest) { this.quest = quest; } @Override public void embarkQuest() { quest.embark(); } }
e3e86fe47c097a8f958e670a3a730106b3149b61
[ "Java", "Maven POM" ]
11
Java
siyu618/spring_study
e49f40b0aa53d52ae33d3a01fffd79bf64875657
f374c6e405a616ab30c34362f67e93cfb28d70e1
refs/heads/master
<file_sep>package interfaces; import model.Data; /* An ordered collection interface * @param <T> Generic class */ public interface Listable<T> extends Iterable<T> { /** * Creates one element of the defined class * * @param newClass Defined class to createList instance from * @return Return instance of the defined class * @throws IllegalAccessException * @throws InstantiationException */ T createNewEmptyElement(Class<T> newClass) throws IllegalAccessException, InstantiationException; /** * Creates one element of the defined enum type * @param element Enum type to createList instance of * @return Instance of the defined class */ T createNewEmptyElementWithEnum(Data.Element element); /** * Returns the element of the list * @param index Index of the element in the list * @return The element of the list */ T get(int index); /** * Set element in the list * @param index Index to set element into * @param element Element to set */ void set(int index, T element); /** * Adds element as the first * @param element Element to add */ void addFirst(T element); /** * Adds element as the last * @param element Element to add */ void addLast(T element); /** * Prints element to standard output * @param index Index of the element */ void printElement(int index); /** * Prints all elements of the list */ void printAll(); /** * Prints the number of elements of the list */ void printSize(); /** * Returns the number of elements of the list * @return The number of elements of the list */ int size(); /** * Removes the element with the specified key * @param key Element to deleteByKey */ void deleteByKey(T key); /** * Removes the element with the specified index * @param index Element to delete */ void deleteByIndex(int index) throws RuntimeException; /** * Clears the list */ void clear(); /** * Find the defined elements of the list * @param o String to find in the elements of the list * @param finder Finder to execute the implementation of the find() method * @return Return {@link Listable} instance with founded elements */ Listable<T> find(String o, Finder<T> finder); /** * Swaps elements in the list * @param i 1st element to swap * @param j 2nd element to swap */ void swap(int i, int j); } <file_sep>package model; /** * POJO class that holds information about the student */ public class Student { private String firstName; private String lastName; private int number; private int majorId; public Student() { firstName = ""; lastName = ""; } public Student(String firstName, String lastName, Integer number, Integer majorId) { this.firstName = firstName; this.lastName = lastName; this.number = number; this.majorId = majorId; } /** * Gets the string representation of the class * @return String representation of the class */ @Override public String toString() { return "Student{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", number=" + number + ", majorId=" + majorId + '}'; } /** * Gets first name of the student * @return First name of the student */ public String getFirstName() { return firstName; } /** * Gets last name of the student * @return Last name of the student */ public String getLastName() { return lastName; } /** * Gets number of the student * @return Number of the student */ public Integer getNumber() { return number; } /** * Gets major id of the student * @return Major id of the student */ public Integer getMajorId() { return majorId; } /** * Sets the first name of the student * @param firstName First name to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Sets the last name of the student * @param lastName Last name to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Sets the number of the student * @param number Number to set */ public void setNumber(int number) { this.number = number; } /** * Sets the majorId of the student * @param majorId Major id to set */ public void setMajorId(int majorId) { this.majorId = majorId; } } <file_sep>package model.comparator; import interfaces.Comparator; import model.Student; /** * Class with a comparison function, which imposes a total ordering based on the first names on some * collection of students. */ public class FirstNameComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { if (s1.getFirstName() == null && s2.getFirstName() == null) { return 0; } else if (s1.getFirstName() == null) { return 1; } else if (s2.getFirstName() == null) { return -1; } return s1.getFirstName().compareTo(s2.getFirstName()); } } <file_sep>package model.comparator; import interfaces.Comparator; import model.Student; /** * Class with a comparison function, which imposes a total ordering based on the student number on some * collection of students. */ public class StudentNumberComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { if (s1.getNumber() == null && s2.getNumber() == null) { return 0; } else if (s1.getNumber() == null) { return 1; } else if (s2.getNumber() == null) { return -1; } else if(s1.getNumber() < s2.getNumber()) { return -2; } else { return 2; } } }<file_sep>import interfaces.Listable; import interfaces.Sortable; import model.DoublyLinkedList; import model.SinglyLinkedList; import model.Student; import model.comparator.DegreeNumberComparator; import model.comparator.FirstNameComparator; import model.comparator.SecondNameComparator; import model.comparator.StudentNumberComparator; import model.finders.FirstNameFinder; import model.finders.LastNameFinder; import model.finders.StudentDegreeProgrammFinder; import model.sort.SelectionSort; import utils.Utils; import values.Strings; import java.util.Scanner; public class Main { private static ConsoleApplication consoleApplication; private static Scanner scanner; private static Listable<Student> list; private static boolean operationMenu; public static void main(String[] args) throws InstantiationException, IllegalAccessException { // Greetings System.out.println(Strings.GREETING); // scanner scanner = new Scanner(System.in); // start the program boolean mainMenu = true; consoleApplication = new ConsoleApplication(); // Main menu. Get the list while (mainMenu) { boolean isCreated = createList(); while (!isCreated) { isCreated = createList(); } int listType; if (list instanceof DoublyLinkedList) { listType = 1; } else { listType = 0; } // Operation menu. Choose operation operationMenu = true; while (operationMenu) { int choice = consoleApplication.createOperation(listType); while (choice == -1) { choice = consoleApplication.createOperation(listType); } if (choice == 0) { System.exit(0); } // pass an operation choice to run // Singly if (listType == 0) { singlyOperationChoice(choice); } else { doublyOperationChoice(choice); } } } } /** * Create an element in the list */ private static void createNewElement() { Student student1 = consoleApplication.runCreateNewElementOperation(list); while (student1 == null) { System.out.println("Error creating an element. Trying one more time"); student1 = consoleApplication.runCreateNewElementOperation(list); // ask to quit if (askToMainMenu()) { break; } } // set parameter to the element setParameters(student1); } /** * Adds element as first */ private static void addFirst() { System.out.println("Creating an element\n"); Student student2 = new Student(); setParameters(student2); System.out.println("Adding an element as the first element\n"); list.addFirst(student2); list.printAll(); System.out.println(); } /** * Adds element as last */ private static void addLast() { System.out.println("Creating an element\n"); Student student3 = new Student(); setParameters(student3); System.out.println("Adding an element as the last element\n"); list.addLast(student3); list.printAll(); System.out.println(); } /** * Print specified element */ private static void printElement() { int choice = -1; while (choice < 0 && choice < list.size()) { choice = Utils.getIntegerFromUser("Please set the number of the list you want to print"); if (choice >= list.size()) { System.out.println("No element to print"); choice = -1; } } list.printElement(choice); System.out.println(); } /** * Prints all elements in the list */ private static void printAll() { try { list.printAll(); System.out.println(); } catch (UnsupportedOperationException e) { e.printStackTrace(); System.out.println("Operation not supported on doubly linked list. Returning to the operation menu\n"); } catch (RuntimeException e) { System.out.println("There is nothing to print. Returning to the operation menu\n"); } } /** * Deletes an element */ private static void deleteElement() { int choice = -1; while (choice < 0 && choice < list.size()) { choice = Utils.getIntegerFromUser("Please set the number of the list you want to delete"); if (choice >= list.size()) { System.out.println("No elements to delete"); choice = -1; } if (list.size() == 0) { break; } } try { list.deleteByIndex(choice); } catch (Exception e) { e.printStackTrace(); } System.out.println(); } /** * Searches the elements based on the specified string * @param searchOption Finder option */ private static void searchByString(int searchOption) { String string = Utils.getStringFromUser(Strings.STRING_SEARCH); while (string.equals("-1") || string.trim().equals("")) { string = Utils.getStringFromUser(Strings.STRING_SEARCH); } Listable<Student> findings = new SinglyLinkedList<>(); switch(searchOption) { case 0: findings = list.find(string, new FirstNameFinder()); if (findings.size() == 0) { System.out.println("No findings"); } else { findings.printAll(); } System.out.println(); break; case 1: findings = list.find(string, new LastNameFinder()); if (findings.size() == 0) { System.out.println("No findings"); } else { findings.printAll(); } System.out.println(); break; } } /** * Searches the elements based on the specified integer * @param searchOption Finder option */ private static void searchByInteger(int searchOption) { String search = Utils.getIntegerStringFromUser(Strings.INTEGER_SEARCH); while (search.equals("-1") || search.trim().equals("")) { search = Utils.getIntegerStringFromUser(Strings.INTEGER_SEARCH); } Listable<Student> findings = new SinglyLinkedList<>(); switch (searchOption) { case 0: findings = list.find(search, new StudentDegreeProgrammFinder()); if (findings.size() == 0) { System.out.println("No findings"); } else { findings.printAll(); } System.out.println(); break; case 1: findings = list.find(search, new StudentDegreeProgrammFinder()); if (findings.size() == 0) { System.out.println("No findings"); } else { findings.printAll(); } System.out.println(); break; } } /** * Sorts the elements by name and last name * @param sortOption Comparator option */ private static void sortByString(int sortOption) { Sortable<Student> sortVar = new SelectionSort<>(); switch(sortOption) { case 0: sortVar.sort(list, new FirstNameComparator()); if (list.size() == 0) { System.out.println("No items to sort"); } else { list.printAll(); } System.out.println(); break; case 1: sortVar.sort(list, new SecondNameComparator()); if (list.size() == 0) { System.out.println("No items to sort"); } else { list.printAll(); } System.out.println(); break; } } /** * Sorts the elements by student number and major id * @param sortOption Comparator option */ private static void sortByInteger(int sortOption) { Sortable<Student> sortVar = new SelectionSort<>(); switch (sortOption) { case 0: sortVar.sort(list, new StudentNumberComparator()); if (list.size() == 0) { System.out.println("No items to sort"); } else { list.printAll(); } System.out.println(); break; case 1: sortVar.sort(list, new DegreeNumberComparator()); if (list.size() == 0) { System.out.println("No items to sort"); } else { list.printAll(); } System.out.println(); break; } } /** Sets parameter for the student * @param student Newly created student object */ private static void setParameters(Student student) { boolean isGivenParameters = false; while (!isGivenParameters) { isGivenParameters = consoleApplication.setParameterForTheElement(student); } } /** * Displays dialog that asks user to return to main menu * @return true or false */ private static boolean askToMainMenu() { String answer; while (true) { System.out.println("Do you want to return to the main menu? (y/n)"); answer = scanner.nextLine(); if (answer.equals("y")) { return true; } else if (answer.equals("n")) { System.exit(0); } } } /** * Creates a list * @return true or false */ private static boolean createList() { list = consoleApplication.createList(); if (list == null) { System.out.println(Strings.ERROR_REPEAT); String choice = scanner.nextLine(); while (!choice.equals("y")) { System.out.println(Strings.ERROR_REPEAT); choice = scanner.nextLine(); if (choice.equals("n")) { System.exit(0); } } return false; } else { return true; } } /** * Represents the choice operation by singly linked list * @param choice Choice from the chosen menu point */ private static void singlyOperationChoice(int choice) { switch (choice) { // create new element through listable interface case 1: createNewElement(); break; // add element before the first element case 2: // create element with constructor addFirst(); break; // add element after the last element case 3: addLast(); break; // output an element of the list case 4: printElement(); break; // print all elements case 5: printAll(); break; // print size of the list case 6: list.printSize(); System.out.println(); break; // delete an item case 7: deleteElement(); break; // delete list case 8: list.clear(); break; // search case 9: searchByString(0); break; case 10: searchByString(1); break; case 11: searchByInteger(0); break; case 12: searchByInteger(1); break; // sort case 13: sortByString(0); break; case 14: sortByString(1); break; case 15: sortByInteger(0); break; case 16: sortByInteger(1); break; // exit case 17: System.exit(0); break; } } /** * Represents the choice operation by doubly linked list * @param choice Choice from the chosen menu point */ private static void doublyOperationChoice(int choice) { switch (choice) { // create new element through listable interface case 1: System.out.println("operation not supported"); System.out.println(); break; // add element before the first element case 2: // create element with constructor addFirst(); break; // add element after the last element case 3: addLast(); break; case 4: printAll(); break; // print size of the list case 5: list.printSize(); System.out.println(); break; // delete an item case 6: deleteElement(); break; // delete list case 7: list.clear(); break; // exit case 8: System.exit(0); break; } } } <file_sep>package interfaces; /** * Interface with a comparison function, which imposes a total ordering on some * collection of objects. * * @param <T> Generic class */ public interface Comparator<T> { int compare(T o1, T o2); } <file_sep>import interfaces.Listable; import model.DoublyLinkedList; import model.SinglyLinkedList; import model.Student; import utils.Utils; import values.Strings; import java.util.Scanner; /** * Helper class for the main class */ class ConsoleApplication { private Scanner mScanner; ConsoleApplication() { mScanner = new Scanner(System.in); } Listable<Student> createList() { // Choose the list mScanner = new Scanner(System.in); // get user input int choice = Utils.getListChoiceFromUser(); // decide what to do switch (choice) { case 1: System.out.println(Strings.SINGLY_CREATION); return new SinglyLinkedList<>(); case 2: System.out.println(Strings.DOUBLY_CREATION); return new DoublyLinkedList<>(); case 3: System.exit(0); break; default: return null; } return null; } /** * Displays the list of operation based on the chosen implementation of {@link Listable} * @param listType Type of the list * @return Choice of the user */ // choose the operation int createOperation(int listType) { // parse integer return Utils.parseOperationChoiceFromUser(Utils.getOperationChoiceFromUser(listType), listType); } /** * Creates new element in the list * @param list List to add element to * @return Element of the list */ // create new element Student runCreateNewElementOperation(Listable<Student> list) { return createNewElement(list); } /** * Helper method to create ne elemene * @param list List to add element to * @return Element of the list */ // create new element private Student createNewElement(Listable<Student> list) { System.out.println(Strings.CREATE_ELEMENT); Student student = null; try { student = list.createNewEmptyElement(Student.class); } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); System.out.println(Strings.FAIL_CREATE_ELEMENT); if (list instanceof DoublyLinkedList) { createOperation(1); } else { createOperation(0); } } return student; } /** * Sets parameters for the newly created element * @param student Object to set parameters to * @return Result of the operation */ // set parameters to the element boolean setParameterForTheElement(Student student) { // name mScanner = new Scanner(System.in); String name = student.getFirstName(); while (name == null || name.trim().equals("")) { System.out.println("Please set the name\n"); name = mScanner.nextLine(); if (name == null || name.trim().equals("")) { return false; } else { student.setFirstName(name); System.out.println(student.toString()); System.out.println(); } } // last name String lastName = student.getLastName(); while (lastName == null || lastName.trim().equals("")) { System.out.println("Please set the last name\n"); lastName = mScanner.nextLine(); if (lastName == null || lastName.trim().equals("")) { return false; } else { student.setLastName(lastName); System.out.println(student.toString()); System.out.println(); } } // student number int number = student.getNumber(); while (number < 1) { number = Utils.getStudentNumberFromUser(); } student.setNumber(number); System.out.println(student.toString()); System.out.println(); // major id int majorId = student.getMajorId(); while (majorId < 1) { majorId = Utils.getMajorIdFromUser(); } student.setMajorId(majorId); System.out.println(student.toString()); System.out.println(); // parameters are set -> return return true; } } <file_sep>package model; import interfaces.Finder; import interfaces.Listable; import java.util.Iterator; import java.util.NoSuchElementException; /** * Resizable implementation of the Listable interface * in the form of Singly linked list * @param <T> Generic class */ public class SinglyLinkedList<T> implements Listable<T>, Iterable<T> { private Node<T> head; /** Class that represents the element of the list * @param <T> Generic class */ private static class Node<T> { private T data; private Node<T> next; Node(T data, Node<T> next) { this.data = data; this.next = next; } } /** * Iterator class for iterating/traversing through the list. Implements {@link Iterator} */ private class SinglyListIterator implements Iterator<T> { private Node<T> nextNode; SinglyListIterator() { nextNode = head; } public boolean hasNext() { return nextNode != null; } /** * The method to get the next element * @return Generic class - element of the list */ public T next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException(); T res = nextNode.data; nextNode = nextNode.next; return res; } /** * Removes iterator. Not supported */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } /** * Creates iterator to iterate through list * * @return Iterator */ @Override public Iterator<T> iterator() { return new SinglyListIterator(); } public SinglyLinkedList() { } /** * Creates one element of the defined class * * @param newClass Defined class to createList instance from * @return Return instance of the defined class * @throws IllegalAccessException * @throws InstantiationException */ @Override public T createNewEmptyElement(Class<T> newClass) throws IllegalAccessException, InstantiationException { T t = newClass.newInstance(); head = new Node<>(t, head); return t; } /** * Creates one element of the defined enum type * @param element Enum type to createList instance of * @return Instance of the defined class */ @Override public T createNewEmptyElementWithEnum(Data.Element element) { T t = (T)new Data(element).createElement(); head = new Node<>(t, head); return t; } /** * Returns the element of the list * @param index Index of the element in the list * @return The element of the list */ @Override public T get(int index) throws IndexOutOfBoundsException { if (index >= this.size() || index < 0) { throw new IndexOutOfBoundsException(); } if (head == null) { throw new NoSuchFieldError(); } else { int counter = 0; Node<T> tmp = head; while (tmp.next != null) { if (counter == index) { return tmp.data; } tmp = tmp.next; ++counter; } return tmp.data; } } /** * Set element in the list * @param index Index to set element into * @param element Element to set */ @Override public void set(int index, T element) throws IndexOutOfBoundsException { if (index >= this.size() || index < 0) { throw new IndexOutOfBoundsException(); } if (head == null) { addFirst(element); } else { int counter = 0; Node<T> tmp = head; while (tmp.next != null) { if (counter == index) { tmp.data = element; } tmp = tmp.next; counter++; } if (tmp.next == null && counter == index)tmp.data = element; } } /** * Adds element as the first * @param element Element to add */ @Override public void addFirst(T element) { head = new Node<>(element, head); } /** * Adds element as the last * @param element Element to add */ @Override public void addLast(T element) { if (head == null) { addFirst(element); } else { Node<T> tmp = head; while (tmp.next != null) tmp = tmp.next; tmp.next = new Node<>(element, null); } } /** * Prints element to standard output * @param index Index of the element */ @Override public void printElement(int index) throws RuntimeException { if (head == null || index < 0) { throw new RuntimeException("nothing to print"); } else if (index == 0) { System.out.println(head.data); } else { int counter = -1; Node<T> tmp = head; while (tmp.next != null) { counter++; if (counter == index) { System.out.println(tmp.data); } tmp = tmp.next; } counter++; if (counter == index) { System.out.println(tmp.data); } else if (index > counter) { throw new RuntimeException("nothing to print"); } } } /** * Prints all elements of the list */ @Override public void printAll() throws RuntimeException { if (head == null) { throw new RuntimeException("nothing to print"); } else { Node<T> tmp = head; while (tmp.next != null) { System.out.println(tmp.data); tmp = tmp.next; } System.out.println(tmp.data); } } /** * Prints the number of elements of the list */ @Override public void printSize() { if (head == null) { System.out.println(0); } else { int counter = 0; Node<T> tmp = head; while (tmp.next != null) { tmp = tmp.next; counter++; } System.out.println(++counter); } } /** * Returns the number of elements of the list * @return The number of elements of the list */ @Override public int size() { if (head == null) { return 0; } else { int counter = 0; Node<T> tmp = head; while (tmp.next != null) { tmp = tmp.next; counter++; } return ++counter; } } /** * Removes the element with the specified key * @param key Element to delete */ @Override public void deleteByKey(T key) throws RuntimeException { if (head == null) throw new RuntimeException("cannot deleteByKey"); if (head.data.equals(key)) { head = head.next; return; } Node<T> cur = head; Node<T> prev = null; while (cur != null && !cur.data.equals(key)) { prev = cur; cur = cur.next; } if (cur == null) throw new RuntimeException("no findings"); prev.next = cur.next; } /** * Removes the element with the specified index * @param index Element to delete */ @Override public void deleteByIndex(int index) throws RuntimeException { T t = this.get(index); this.deleteByKey(t); } /** * Clears the list */ @Override public void clear() { head = null; } /** * Find the defined elements of the list * @param o String to find in the elements of the list * @param finder Finder to execute the implementation of the find() method * @return Return {@link Listable} instance with founded elements */ @Override public Listable<T> find(String o, Finder<T> finder) throws RuntimeException { if (o == null || o.equals("")) { System.out.println("no findings"); } return finder.find(o, this); } /** * Swaps elements in the list * @param i 1st element to swap * @param j 2nd element to swap */ @Override public void swap(int i, int j) { T memorizedObject = this.get(i); this.set(i, this.get(j)); this.set(j, memorizedObject); } }
6ae82adfdbc8f3d4e933499ee12d888a226f238e
[ "Java" ]
8
Java
KonstantinKochetov/Algorithms_1
70e2634f7851dcc75a7b6210877c8a252fa2ac68
c7f1f801af2373fa4545a9ae4631a2f3f5f4db25