repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Vyraax/VulkanLab
docs/html/structVkExternalMemoryBufferCreateInfo.js
var structVkExternalMemoryBufferCreateInfo = [ [ "handleTypes", "structVkExternalMemoryBufferCreateInfo.html#ace9ed7f7f1ffc7299deebc46afbf638e", null ], [ "pNext", "structVkExternalMemoryBufferCreateInfo.html#a94fb9f684f35746d99bfe68bcc61c2e1", null ], [ "sType", "structVkExternalMemoryBufferCreateInfo.html#a9e5344a5a0c1b855bf67691ce2728caf", null ] ];
Rampopula/mazda_dp_parktronic
app/mdp.c
#include "mdp.h" #include "beeper.h" #include "common.h" #include "can_bus.h" #include "can_bypass_switch.h" #include "ptronic_decoder.h" #include "ptronic_switch.h" #include "system_led.h" #ifdef MDP_MODULE #undef MDP_MODULE #endif #define MDP_MODULE "mdp_app" #define MDP_BEEP_FREQ 2755 #define MDP_INIT_BLINK_DELAY 100 /* Init done blink delay msec */ #define MDP_INIT_BEEP_DELAY 600 /* Beep time after parktronic on */ #define MDP_DIST_BEEP_NONE 150 /* Distance in centimeters */ #define MDP_DIST_BEEP_SLOW 90 /* Distance in centimeters */ #define MDP_DIST_BEEP_FAST 30 /* Distance in centimeters */ #define MDP_NO_DATA_STR " -.-m " #define MDP_DATA_TMPL_STR " %u.%um " #define MDP_STEP 30 #define MDP_STEP_CNT 9 #define MDP_STEP_STRLEN 4 #define MDP_STEP_STR \ { \ "\xF0\xF0\xF0\xF0", "\xF0\xF0\xF0\x3E", "\xF0\xF0\xF0 ", \ "\xF0\xF0\x3E ", "\xF0\xF0 ", "\xF0\x3E ", \ "\xF0 ", "\x3E ", "\x3E " \ } struct mdp_state { uint32_t curr; uint32_t prev; }; static struct mdp_state ptronic_state; static struct mdp_can dp_can, pjb_can; static const char *dist_steps[] = MDP_STEP_STR; static uint8_t mdp_buffer[MAZDA_DP_REG_NUM][MAZDA_DP_MSG_SIZE]; static void error_handler(void) { mdp_can_bypass_on(); __disable_irq(); while(true) { } } static void log_app_info(void) { const char *line = "*****************************************"; const char *app_name = "Mazda Display Parktronic"; const char *author = "by <NAME> <<EMAIL>>"; printf("\r\n\r\n"); log_sys("%s\r\n", line); log_sys("%s\r\n", app_name); log_sys("%s\r\n", author); log_sys("%s\r\n", line); log_sys("Chip: %s\r\n", MDP_BOARD_CHIP_NAME); log_sys("System clock %lu MHz\r\n", MDP_CLOCK_FREQ_MHZ) log_sys("Software version: %s %s\r\n", MDP_APP_VERSION, MDP_APP_DEBUG ? "debug" : "release"); log_sys("Board revision: %s\r\n", MDP_BOARD_REVISION); log_sys("Build date: %s\r\n", __TIMESTAMP__); log_sys("%s\r\n", line); } static void update_display(char *string) { size_t string_len; static char dp_string[MAZDA_DP_CHAR_NUM]; /* Prepare string for displaying: trim or add trailing spaces */ string_len = strlen(string); if (string_len > MAZDA_DP_CHAR_NUM) { string_len = MAZDA_DP_CHAR_NUM; } memcpy(dp_string, string, string_len); memset(&dp_string[string_len], ' ', MAZDA_DP_CHAR_NUM - string_len); /** * Fill display buffer * * Mazda 3 has 12-symbol LCD display, and it has two logical parts: * 1. Left half of display with CAN bus address 0x290. * 2. Right half of display with CAN bus address 0x291. * * To write data to the display, we need to * send 2 data packets 8 bytes each. * * Start byte of each data packet is service byte and it is different * for each packet: * 1. 0xC0 - For the left half of display. * 2. 0x85 - For the right half of display. * * Thus, effective payload of display is 14 bytes. * Due to the fact that the display has only 12 characters to display, * we need to place data in buffer in a certain way: in left half we * will write first 7 bytes of our data with offset 1 (service byte); * in right half we will write next 7 bytes of data, with an data offset * not of 7 bytes, but 5. * * Example: Write string "Initializing" to the display * Index: 0 1 2 3 4 5 6 7 * Left half: [0xC0] ['I'] ['n'] ['i'] ['t'] ['i'] ['a'] ['l'] * Right half: [0x85] ['a'] ['l'] ['i'] ['z'] ['i'] ['n'] ['g'] */ mdp_buffer[MAZDA_DP_LHALF][0] = MAZDA_DP_LHALF_BYTE; mdp_buffer[MAZDA_DP_RHALF][0] = MAZDA_DP_RHALF_BYTE; memcpy(&mdp_buffer[MAZDA_DP_LHALF][1], dp_string, MAZDA_DP_MSG_SIZE - 1); memcpy(&mdp_buffer[MAZDA_DP_RHALF][1], &dp_string[MAZDA_DP_CHAR_NUM - MAZDA_DP_MSG_SIZE + 1], MAZDA_DP_MSG_SIZE - 1); } static void distance_to_string(struct ptronic_data *ptronic, char *string) { const uint32_t dist_step = MDP_STEP; const uint32_t l_flag = 0x80000000, r_flag = 0x00008000; uint16_t main_dist, left_dist, right_dist; uint32_t dist_flag = 0; /* No data from sensors */ if (!ptronic->valid) { sprintf(string, MDP_NO_DATA_STR); return; } /* Get minimum distance for left and right halfs */ left_dist = MIN(ptronic->distance[MDP_SENSOR_A], ptronic->distance[MDP_SENSOR_B]); right_dist = MIN(ptronic->distance[MDP_SENSOR_C], ptronic->distance[MDP_SENSOR_D]); main_dist = MIN(left_dist, right_dist); /* Write distance in meters */ sprintf(string, MDP_DATA_TMPL_STR, (main_dist / 100), (main_dist % 100) / 10); /* Write arrows for the left and right halfs of the display */ for (int i = 0; i < MDP_STEP_CNT; ++i) { if (!(dist_flag & l_flag) && left_dist <= (dist_step * i)) { for (int j = 0; j < MDP_STEP_STRLEN; j++) { string[j] = dist_steps[i][j]; } dist_flag |= l_flag; } if (!(dist_flag & r_flag) && right_dist <= (dist_step * i)) { for (int j = MDP_STEP_STRLEN - 1; j >= 0; j--) { char *ch = &string[MAZDA_DP_CHAR_NUM - 1 - j]; switch(dist_steps[i][j]) { case '\xF0': /* Solid right arrow */ *ch = '\xF1'; /* Solid left arrow */ break; case '\x3E': /* Usual right arrow */ *ch = '\x3C'; /* Usual left arrow */ break; } } dist_flag |= r_flag; } if (dist_flag & l_flag & r_flag) break; } } static mdp_beep_mode_t distance_to_beep(struct ptronic_data *ptronic) { uint16_t main_dist, left_dist, right_dist; /* No data from sensors */ if (!ptronic->valid) return MDP_BEEP_NONE; /* Get minimum distance for left and right halfs */ left_dist = MIN(ptronic->distance[MDP_SENSOR_A], ptronic->distance[MDP_SENSOR_B]); right_dist = MIN(ptronic->distance[MDP_SENSOR_C], ptronic->distance[MDP_SENSOR_D]); main_dist = MIN(left_dist, right_dist); if (main_dist >= MDP_DIST_BEEP_NONE) { return MDP_BEEP_NONE; } else if (main_dist < MDP_DIST_BEEP_NONE && main_dist >= MDP_DIST_BEEP_SLOW) { return MDP_BEEP_SLOW; } else if (main_dist < MDP_DIST_BEEP_SLOW && main_dist >= MDP_DIST_BEEP_FAST) { return MDP_BEEP_FAST; } return MDP_BEEP_CONST; } static bool get_bit_state_updated(uint8_t byte, uint8_t bit, struct mdp_state *state) { if ((byte & BIT(bit)) && !state->curr) { state->curr = true; state->prev = false; return true; } if (!(byte & BIT(bit)) && state->curr) { state->curr = false; state->prev = true; return true; } return false; } static void app_inited_blink(void) { mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_toggle(); mdp_tm_msleep(MDP_INIT_BLINK_DELAY); mdp_sysled_off(); } static void mdp_can_replace_data(struct mdp_can_msg *msg) { static const uint8_t dp_misc_symb0[] = MAZDA_DP_MISC_SYMB0_BIT; static const uint8_t dp_misc_symb1[] = MAZDA_DP_MISC_SYMB1_BIT; static const uint8_t dp_misc_symb2[] = MAZDA_DP_MISC_SYMB2_BIT; switch(msg->id) { case MAZDA_DP_MISC_SYMB_ID: /* Turn off all active symbols */ /* CD IN/MD IN/ST/Dolby/RPT/RDM/AF symbols */ for (int i = 0; i < ARRAY_SIZE(dp_misc_symb0); i++) { RESET_BIT(msg->data[MAZDA_DP_MISC_SYMB0], dp_misc_symb0[i]); } /* Turn off all active symbols */ /* PTY/TA/TP/AUTO-M symbols */ for (int i = 0; i < ARRAY_SIZE(dp_misc_symb1); i++) { RESET_BIT(msg->data[MAZDA_DP_MISC_SYMB1], dp_misc_symb1[i]); } /* Turn off all active symbols */ /* "":"/"'"/"." symbols */ for (int i = 0; i < ARRAY_SIZE(dp_misc_symb2); i++) { RESET_BIT(msg->data[MAZDA_DP_MISC_SYMB2], dp_misc_symb2[i]); } break; case MAZDA_DP_LHALF_ID: memcpy(msg->data, mdp_buffer[MAZDA_DP_LHALF], msg->size); break; case MAZDA_DP_RHALF_ID: memcpy(msg->data, mdp_buffer[MAZDA_DP_RHALF], msg->size); break; default: return; } } static void mdp_can_transfer_pjb_to_dp_replace_dp(void) { int ret; ret = mdp_can_read(&pjb_can); if (ret > 0) { mdp_can_replace_data(&pjb_can.msg); memcpy(&dp_can.msg, &pjb_can.msg, sizeof(dp_can.msg)); ret = mdp_can_write(&dp_can); if (ret < 0) { log_err("MDP CAN DP write failed!\r\n"); error_handler(); } } else if (ret < 0) { log_err("MDP CAN PJB read failed!\r\n"); error_handler(); } } void mdp_init(void) { int ret; log_app_info(); dp_can = mdp_get_can_spi_interface(); pjb_can = mdp_get_can_hal_interface(); /* Bypass all CAN packets through while board is not inited */ mdp_can_bypass_on(); mdp_sysled_off(); #if (MDP_BEEPER_ENABLED == 1) if (!mdp_beeper_init(MDP_BEEP_FREQ)) log_err("Beeper init failed\r\n"); if (!mdp_beeper_set_mode(MDP_BEEP_NONE)) log_err("Beeper set mode failed!\r\n"); #endif ret = mdp_can_start(&dp_can); if (ret) { log_err("DP CAN (SPI) start failed!\r\n"); goto exit_error; } ret = mdp_can_start(&pjb_can); if (ret) { log_err("PJB CAN (HAL) start failed!\r\n"); goto exit_error; } app_inited_blink(); return; exit_error: error_handler(); } void mdp_run(void) { bool state_updated; state_updated = get_bit_state_updated(mdp_ptronic_is_enabled(), 0, &ptronic_state); if (state_updated) { if (ptronic_state.curr) { log_info("Parktronic enabled!\r\n"); mdp_beeper_set_mode(MDP_BEEP_CONST); mdp_beeper_beep(); mdp_tm_msleep(MDP_INIT_BEEP_DELAY); mdp_beeper_set_mode(MDP_BEEP_NONE); mdp_beeper_beep(); mdp_can_bypass_off(); } else { log_info("Parktronic disabled!\r\n"); mdp_can_bypass_on(); mdp_beeper_set_mode(MDP_BEEP_NONE); mdp_beeper_beep(); } } if (ptronic_state.curr) { char dist_str[MAZDA_DP_CHAR_NUM * 2]; struct ptronic_data data = ptronic_read_data(); mdp_beeper_set_mode(distance_to_beep(&data)); mdp_beeper_beep(); distance_to_string(&data, dist_str); update_display(dist_str); mdp_can_transfer_pjb_to_dp_replace_dp(); } }
aehmttw/TankGame
src/main/java/basewindow/BaseWindow.java
package basewindow; import basewindow.transformation.ScaleAboutPoint; import basewindow.transformation.Shear; import basewindow.transformation.Transformation; import basewindow.transformation.Translation; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; public abstract class BaseWindow { protected ArrayList<String> overrideLocations = new ArrayList<>(); public BaseShapeRenderer shapeRenderer; public BaseFontRenderer fontRenderer; public boolean angled = false; public double pointWidth = -1; public double pointHeight = -1; public double absoluteWidth; public double absoluteHeight; public double absoluteDepth; public boolean hasResized; public double absoluteMouseX; public double absoluteMouseY; public boolean constrainMouse; public double colorR; public double colorG; public double colorB; public double colorA; public double glow; public boolean fullscreen; public HashMap<Integer, InputPoint> touchPoints = new HashMap<>(); public ArrayList<Integer> pressedKeys = new ArrayList<>(); public ArrayList<Integer> validPressedKeys = new ArrayList<>(); public ArrayList<Integer> textPressedKeys = new ArrayList<>(); public ArrayList<Integer> textValidPressedKeys = new ArrayList<>(); public ArrayList<Integer> pressedButtons = new ArrayList<>(); public ArrayList<Integer> validPressedButtons = new ArrayList<>(); public boolean validScrollUp; public boolean validScrollDown; public String os = ""; public boolean mac = false; public boolean vsync; public boolean showMouseOnLaunch; public boolean touchscreen = false; public boolean showKeyboard = false; public double keyboardOffset = 0; public double keyboardFraction = 1; public ArrayList<Long> framesList = new ArrayList<>(); public ArrayList<Double> frameFrequencies = new ArrayList<>(); public long lastFrame = System.currentTimeMillis(); public double frameFrequency = 1; public String name; public IDrawer drawer; public IUpdater updater; public IWindowHandler windowHandler; public ArrayList<Transformation> transformations = new ArrayList<>(); public double yaw = 0; public double pitch = 0; public double roll = 0; public double xOffset = 0; public double yOffset = 0; public double zOffset = 0; public Transformation[] baseTransformations = new Transformation[]{new Translation(this, -0.5, -0.5, -1)}; public Transformation[] lightBaseTransformation = new Transformation[]{new ScaleAboutPoint(this, 0.8, 0.8, 0.8, 0.5, 0.5, 0.5), new Shear(this, 0, 0, 0, 0, 0.5, 0.5)}; public BaseSoundPlayer soundPlayer; public boolean soundsEnabled = false; public BaseVibrationPlayer vibrationPlayer; public boolean vibrationsEnabled = false; public boolean antialiasingSupported = false; public boolean antialiasingEnabled = false; public boolean drawingShadow = false; public static final HashMap<Integer, String> keyNames = new HashMap<>(); public BasePlatformHandler platformHandler; public ModelPart.ShapeDrawer shapeDrawer; public BaseWindow(String name, int x, int y, int z, IUpdater u, IDrawer d, IWindowHandler w, boolean vsync, boolean showMouse) { this.name = name; this.absoluteWidth = x; this.absoluteHeight = y; this.absoluteDepth = z; this.updater = u; this.drawer = d; this.vsync = vsync; this.windowHandler = w; this.showMouseOnLaunch = showMouse; if (System.getProperties().toString().contains("Mac OS X")) mac = true; this.setupKeyCodes(); } public void startTiming() { long milliTime = System.currentTimeMillis(); this.framesList.add(milliTime); ArrayList<Long> removeList = new ArrayList<>(); for (Long l : this.framesList) { if (milliTime - l > 1000) removeList.add(l); } for (Long l : removeList) { this.framesList.remove(l); } } public void stopTiming() { long time = System.currentTimeMillis(); long lastFrameTime = lastFrame; lastFrame = time; double freq = (time - lastFrameTime) / 10.0; frameFrequencies.add(freq); if (frameFrequencies.size() > 5) { frameFrequencies.remove(0); } double totalFrequency = 0; for (Double frequency : frameFrequencies) { totalFrequency += frequency; } //frameFrequency = Math.max(0, totalFrequency / frameFrequencies.size()); frameFrequency = freq; } public abstract void run(); public abstract void setShowCursor(boolean show); public abstract void setCursorLocked(boolean locked); public abstract void setCursorPos(double x, double y); public abstract void setFullscreen(boolean enabled); public abstract void setOverrideLocations(ArrayList<String> loc, BaseFileManager fileManager); public abstract void setIcon(String icon); public abstract void setColor(double r, double g, double b, double a, double glow); public abstract void setColor(double r, double g, double b, double a); public abstract void setColor(double r, double g, double b); public abstract void setUpPerspective(); public abstract void applyTransformations(); public abstract void loadPerspective(); public abstract void clearDepth(); public abstract String getClipboard(); public abstract void setClipboard(String s); public abstract void setVsync(boolean enable); public abstract ArrayList<Integer> getRawTextKeys(); public abstract String getKeyText(int key); public abstract String getTextKeyText(int key); public abstract int translateKey(int key); public abstract int translateTextKey(int key); public abstract void transform(double[] matrix); public abstract void calculateBillboard(); public abstract double getEdgeBounds(); public abstract void createImage(String image, InputStream in); public abstract void setTextureCoords(double u, double v); public abstract void setTexture(String image); public abstract void stopTexture(); public abstract void addVertex(double x, double y, double z); public abstract void addVertex(double x, double y); public abstract void openLink(URL url) throws Exception; public abstract void setResolution(int x, int y); public abstract void setShadowQuality(double quality); public abstract double getShadowQuality(); public abstract void setLighting(double light, double glowLight, double shadow, double glowShadow); public abstract void addMatrix(); public abstract void removeMatrix(); public abstract void setMatrixProjection(); public abstract void setMatrixModelview(); public abstract ModelPart createModelPart(); public abstract ModelPart createModelPart(Model model, ArrayList<ModelPart.Shape> shapes, Model.Material material); public abstract PosedModel createPosedModel(Model m); public abstract BaseShapeBatchRenderer createShapeBatchRenderer(); public void setupKeyCodes() { keyNames.put(InputCodes.KEY_UNKNOWN, "Unknown key"); keyNames.put(InputCodes.KEY_SPACE, "Space"); keyNames.put(InputCodes.KEY_WORLD_1, "World 1"); keyNames.put(InputCodes.KEY_WORLD_2, "World 2"); keyNames.put(InputCodes.KEY_ESCAPE, "Escape"); keyNames.put(InputCodes.KEY_ENTER, "Enter"); keyNames.put(InputCodes.KEY_TAB, "Tab"); keyNames.put(InputCodes.KEY_BACKSPACE, "Backspace"); keyNames.put(InputCodes.KEY_INSERT, "Insert"); keyNames.put(InputCodes.KEY_DELETE, "Delete"); keyNames.put(InputCodes.KEY_RIGHT, "Right"); keyNames.put(InputCodes.KEY_LEFT, "Left"); keyNames.put(InputCodes.KEY_DOWN, "Down"); keyNames.put(InputCodes.KEY_UP, "Up"); keyNames.put(InputCodes.KEY_PAGE_UP, "Page up"); keyNames.put(InputCodes.KEY_PAGE_DOWN, "Page down"); keyNames.put(InputCodes.KEY_HOME, "Home"); keyNames.put(InputCodes.KEY_END, "End"); keyNames.put(InputCodes.KEY_CAPS_LOCK, "Caps lock"); keyNames.put(InputCodes.KEY_SCROLL_LOCK, "Scroll lock"); keyNames.put(InputCodes.KEY_NUM_LOCK, "Num lock"); keyNames.put(InputCodes.KEY_PRINT_SCREEN, "Print screen"); keyNames.put(InputCodes.KEY_PAUSE, "Pause"); keyNames.put(InputCodes.KEY_F1, "F1"); keyNames.put(InputCodes.KEY_F2, "F2"); keyNames.put(InputCodes.KEY_F3, "F3"); keyNames.put(InputCodes.KEY_F4, "F4"); keyNames.put(InputCodes.KEY_F5, "F5"); keyNames.put(InputCodes.KEY_F6, "F6"); keyNames.put(InputCodes.KEY_F7, "F7"); keyNames.put(InputCodes.KEY_F8, "F8"); keyNames.put(InputCodes.KEY_F9, "F9"); keyNames.put(InputCodes.KEY_F10, "F10"); keyNames.put(InputCodes.KEY_F11, "F11"); keyNames.put(InputCodes.KEY_F12, "F12"); keyNames.put(InputCodes.KEY_F13, "F13"); keyNames.put(InputCodes.KEY_F14, "F14"); keyNames.put(InputCodes.KEY_F15, "F15"); keyNames.put(InputCodes.KEY_F16, "F16"); keyNames.put(InputCodes.KEY_F17, "F17"); keyNames.put(InputCodes.KEY_F18, "F18"); keyNames.put(InputCodes.KEY_F19, "F19"); keyNames.put(InputCodes.KEY_F20, "F20"); keyNames.put(InputCodes.KEY_F21, "F21"); keyNames.put(InputCodes.KEY_F22, "F22"); keyNames.put(InputCodes.KEY_F23, "F23"); keyNames.put(InputCodes.KEY_F24, "F24"); keyNames.put(InputCodes.KEY_F25, "F25"); keyNames.put(InputCodes.KEY_KP_0, "Keypad 0"); keyNames.put(InputCodes.KEY_KP_1, "Keypad 1"); keyNames.put(InputCodes.KEY_KP_2, "Keypad 2"); keyNames.put(InputCodes.KEY_KP_3, "Keypad 3"); keyNames.put(InputCodes.KEY_KP_4, "Keypad 4"); keyNames.put(InputCodes.KEY_KP_5, "Keypad 5"); keyNames.put(InputCodes.KEY_KP_6, "Keypad 6"); keyNames.put(InputCodes.KEY_KP_7, "Keypad 7"); keyNames.put(InputCodes.KEY_KP_8, "Keypad 8"); keyNames.put(InputCodes.KEY_KP_9, "Keypad 9"); keyNames.put(InputCodes.KEY_KP_DECIMAL, "Keypad decimal"); keyNames.put(InputCodes.KEY_KP_DIVIDE, "Keypad divide"); keyNames.put(InputCodes.KEY_KP_MULTIPLY, "Keypad multiply"); keyNames.put(InputCodes.KEY_KP_SUBTRACT, "Keypad subtract"); keyNames.put(InputCodes.KEY_KP_ADD, "Keypad add"); keyNames.put(InputCodes.KEY_KP_ENTER, "Keypad enter"); keyNames.put(InputCodes.KEY_KP_EQUAL, "Keypad equal"); keyNames.put(InputCodes.KEY_LEFT_SHIFT, "Left shift"); keyNames.put(InputCodes.KEY_LEFT_CONTROL, "Left control"); keyNames.put(InputCodes.KEY_LEFT_ALT, "Left alt"); keyNames.put(InputCodes.KEY_LEFT_SUPER, "Left super"); keyNames.put(InputCodes.KEY_RIGHT_SHIFT, "Right shift"); keyNames.put(InputCodes.KEY_RIGHT_CONTROL, "Right control"); keyNames.put(InputCodes.KEY_RIGHT_ALT, "Right alt"); keyNames.put(InputCodes.KEY_RIGHT_SUPER, "Right super"); keyNames.put(InputCodes.KEY_MENU, "Menu"); } }
Diffblue-benchmarks/Imyzt-learning-technology-code
mq-series/RabbitMQ/springboot-rabbitmq-simple/springboot-rabbitmq-producer/src/main/java/top/imyzt/learning/rabbitmq/producer/mapper/OrderMapper.java
<reponame>Diffblue-benchmarks/Imyzt-learning-technology-code<filename>mq-series/RabbitMQ/springboot-rabbitmq-simple/springboot-rabbitmq-producer/src/main/java/top/imyzt/learning/rabbitmq/producer/mapper/OrderMapper.java package top.imyzt.learning.rabbitmq.producer.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import top.imyzt.learning.rabbitmq.common.entity.Order; /** * @author imyzt * @date 2019/5/23 * @description 订单对象数据库操作接口 */ public interface OrderMapper extends BaseMapper<Order> { }
daxyonis/GBOerp
app/assets/javascripts/soumflex/views/soumflexview.js
<reponame>daxyonis/GBOerp<gh_stars>1-10 //*****************************************************/ // SOUMFLEXVIEW // Vue qui contrôle et réagit à l'ensemble de la // soumission rapide flexible. //*****************************************************/ define(['jquery', 'underscore', 'backbone', 'handlebars', 'bootstrap', 'bootstrap_fh' ], function($, _, Backbone, Handlebars, Bootstrap, BootstrapFH){ var SoumflexView = Backbone.View.extend({ // Reflechir sur comment passer les evenements d'items a cette vue (sur changement dans un item on doit mettre a jour cette vue) initialize : function(options){ this.bus = options.bus; }, events : { "click #soumettreSoum" : "validateAndPost" }, // Render soum stats & prices render : function(){ var soum = this.model; if(soum.get('items').length > 0 && soum.get('items').any(function(m){ return m.produitChoisi(); })) { this.$('#soumCoutantTotal').html(soum.coutantTotal().toFixed(2) + "$"); this.$('#soumVendantTotal').html(soum.vendantTotal().toFixed(2) + "$"); this.$('#soumMargeEffective').html(soum.margeEffective().toFixed(0) + "%"); this.$('.soumCommission').html(soum.commissionTotal().toFixed(2) + "$"); this.$('#soumPrixPiCar').html(soum.totalPiCar().toFixed(2) + "$"); this.$('#soumPrixTotal').html(soum.grandTotal().toFixed(2) + "$"); this.$('.soumVentesTotal').html(soum.ventesTotal().toFixed(2) + "$"); // Values for the server $('#margeGlobale:input').val(soum.get('items').first().get("marge")); $('#inputCommission').val(soum.get('SOUM_COMMISSION') * 100); } else { this.$('#soumCoutantTotal').html("-"); this.$('#soumVendantTotal').html("-"); this.$('#soumMargeEffective').html("-"); this.$('.soumCommission').html("-"); this.$('#soumPrixPiCar').html("-"); this.$('#soumPrixTotal').html("-"); this.$('.soumVentesTotal').html(""); } return this; }, updateMontantVente : function(montant){ this.$('#soumMontantVente').html(parseFloat(montant).toFixed(2) + "$"); }, /**************************************/ /* FORM FINAL VALIDATION AND SUBMIT */ /**************************************/ validateAndPost : function(event){ event.preventDefault(); var self = this; this.bus.trigger('submit'); // for enteteView setTimeout(function(){ var noError = self.model.get('entete').get('noError') && self.model.get('items').all(function(i){ return(i.isValid()); }); if(noError){ // submit $('form').submit(); } }, 0); }, }); return SoumflexView; });
filippovdenis/liquibase
liquibase-core/src/main/java/liquibase/database/Database.java
<reponame>filippovdenis/liquibase<gh_stars>0 package liquibase.database; import liquibase.CatalogAndSchema; import liquibase.change.Change; import liquibase.changelog.ChangeSet; import liquibase.changelog.DatabaseChangeLog; import liquibase.changelog.RanChangeSet; import liquibase.structure.DatabaseObject; import liquibase.exception.*; import liquibase.servicelocator.PrioritizedService; import liquibase.sql.visitor.SqlVisitor; import liquibase.statement.SqlStatement; import liquibase.statement.DatabaseFunction; import java.io.IOException; import java.io.Writer; import java.math.BigInteger; import java.util.Collection; import java.util.Date; import java.util.List; public interface Database extends PrioritizedService { String databaseChangeLogTableName = "DatabaseChangeLog".toUpperCase(); String databaseChangeLogLockTableName = "DatabaseChangeLogLock".toUpperCase(); /** * Is this AbstractDatabase subclass the correct one to use for the given connection. */ boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException; /** * If this database understands the given url, return the default driver class name. Otherwise return null. */ String getDefaultDriver(String url); DatabaseConnection getConnection(); void setConnection(DatabaseConnection conn); boolean requiresUsername(); boolean requiresPassword(); /** * Auto-commit mode to run in */ public boolean getAutoCommitMode(); /** * Determines if the database supports DDL within a transaction or not. * * @return True if the database supports DDL within a transaction, otherwise false. */ boolean supportsDDLInTransaction(); String getDatabaseProductName(); String getDatabaseProductVersion() throws DatabaseException; int getDatabaseMajorVersion() throws DatabaseException; int getDatabaseMinorVersion() throws DatabaseException; /** * Returns an all-lower-case short name of the product. Used for end-user selecting of database type * such as the DBMS precondition. */ String getShortName(); String getDefaultCatalogName(); void setDefaultCatalogName(String catalogName) throws DatabaseException; String getDefaultSchemaName(); void setDefaultSchemaName(String schemaName) throws DatabaseException; Integer getDefaultPort(); Integer getFetchSize(); String getLiquibaseCatalogName(); void setLiquibaseCatalogName(String catalogName); String getLiquibaseSchemaName(); void setLiquibaseSchemaName(String schemaName); /** * Returns whether this database support initially deferrable columns. */ boolean supportsInitiallyDeferrableColumns(); public boolean supportsSequences(); public boolean supportsDropTableCascadeConstraints(); public boolean supportsAutoIncrement(); String getDateLiteral(String isoDate); /** * Returns database-specific function for generating the current date/time. */ String getCurrentDateTimeFunction(); void setCurrentDateTimeFunction(String function); String getLineComment(); String getAutoIncrementClause(BigInteger startWith, BigInteger incrementBy); String getDatabaseChangeLogTableName(); String getDatabaseChangeLogLockTableName(); String getLiquibaseTablespaceName(); void setLiquibaseTablespaceName(String tablespaceName); /** * Set the table name of the change log to the given table name * * @param tableName */ public void setDatabaseChangeLogTableName(String tableName); /** * Set the table name of the change log lock to the given table name * * @param tableName */ public void setDatabaseChangeLogLockTableName(String tableName); /** * Returns SQL to concat the passed values. */ String getConcatSql(String... values); public void setCanCacheLiquibaseTableInfo(boolean canCacheLiquibaseTableInfo); void dropDatabaseObjects(CatalogAndSchema schema) throws LiquibaseException; void tag(String tagString) throws DatabaseException; boolean doesTagExist(String tag) throws DatabaseException; boolean isSystemObject(DatabaseObject example); boolean isLiquibaseObject(DatabaseObject object); String getViewDefinition(CatalogAndSchema schema, String name) throws DatabaseException; String getDateLiteral(java.sql.Date date); String getTimeLiteral(java.sql.Time time); String getDateTimeLiteral(java.sql.Timestamp timeStamp); String getDateLiteral(Date defaultDateValue); String escapeObjectName(String catalogName, String schemaName, String objectName, Class<? extends DatabaseObject> objectType); String escapeTableName(String catalogName, String schemaName, String tableName); String escapeIndexName(String catalogName, String schemaName, String indexName); String escapeObjectName(String objectName, Class<? extends DatabaseObject> objectType); /** * Escapes a single column name in a database-dependent manner so reserved words can be used as a column * name (i.e. "return"). * * @param schemaName * @param tableName * @param columnName column name * @return escaped column name */ String escapeColumnName(String catalogName, String schemaName, String tableName, String columnName); String escapeColumnName(String catalogName, String schemaName, String tableName, String columnName, boolean quoteNamesThatMayBeFunctions); /** * Escapes a list of column names in a database-dependent manner so reserved words can be used as a column * name (i.e. "return"). * * @param columnNames list of column names * @return escaped column name list */ String escapeColumnNameList(String columnNames); // Set<UniqueConstraint> findUniqueConstraints(String schema) throws DatabaseException; boolean supportsTablespaces(); boolean supportsCatalogs(); boolean supportsSchemas(); boolean supportsCatalogInObjectName(Class<? extends DatabaseObject> type); String generatePrimaryKeyName(String tableName); String escapeSequenceName(String catalogName, String schemaName, String sequenceName); String escapeViewName(String catalogName, String schemaName, String viewName); ChangeSet.RunStatus getRunStatus(ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException; RanChangeSet getRanChangeSet(ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException; void markChangeSetExecStatus(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException; List<RanChangeSet> getRanChangeSetList() throws DatabaseException; Date getRanDate(ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException; void removeRanStatus(ChangeSet changeSet) throws DatabaseException; void commit() throws DatabaseException; void rollback() throws DatabaseException; String escapeStringForDatabase(String string); void close() throws DatabaseException; boolean supportsRestrictForeignKeys(); String escapeConstraintName(String constraintName); boolean isAutoCommit() throws DatabaseException; void setAutoCommit(boolean b) throws DatabaseException; boolean isSafeToRunUpdate() throws DatabaseException; void executeStatements(Change change, DatabaseChangeLog changeLog, List<SqlVisitor> sqlVisitors) throws LiquibaseException;/* * Executes the statements passed as argument to a target {@link Database} * * @param statements an array containing the SQL statements to be issued * @param database the target {@link Database} * @throws DatabaseException if there were problems issuing the statements */ void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors) throws LiquibaseException; void saveStatements(Change change, List<SqlVisitor> sqlVisitors, Writer writer) throws IOException, StatementNotSupportedOnDatabaseException, LiquibaseException; void executeRollbackStatements(Change change, List<SqlVisitor> sqlVisitors) throws LiquibaseException, RollbackImpossibleException; void executeRollbackStatements(SqlStatement[] statements, List<SqlVisitor> sqlVisitors) throws LiquibaseException, RollbackImpossibleException; void saveRollbackStatement(Change change, List<SqlVisitor> sqlVisitors, Writer writer) throws IOException, RollbackImpossibleException, StatementNotSupportedOnDatabaseException, LiquibaseException; public Date parseDate(String dateAsString) throws DateParseException; /** * Returns list of database native date functions */ public List<DatabaseFunction> getDateFunctions(); void resetInternalState(); boolean supportsForeignKeyDisable(); boolean disableForeignKeyChecks() throws DatabaseException; void enableForeignKeyChecks() throws DatabaseException; public boolean isCaseSensitive(); public boolean isReservedWord(String string); /** * Returns a new CatalogAndSchema adjusted for this database. Examples of adjustments include: * fixes for case issues, * replacing null schema or catalog names with the default values * removing set schema or catalog names if they are not supported * @deprecated use {@link liquibase.CatalogAndSchema#standardize(Database)} */ CatalogAndSchema correctSchema(CatalogAndSchema schema); /** * Fix the object name to the format the database expects, handling changes in case, etc. */ String correctObjectName(String name, Class<? extends DatabaseObject> objectType); boolean isFunction(String string); int getDataTypeMaxParameters(String dataTypeName); CatalogAndSchema getDefaultSchema(); /** * Types like int4 in postgres cannot have a modifier. e.g. int4(10) * Checks whether the type is allowed to have a modifier * * @param typeName type name * @return Whether data type can have a modifier */ boolean dataTypeIsNotModifiable(String typeName); /** * Some function names are placeholders that need to be replaced with the specific database value. * e.g. nextSequenceValue(sequenceName) should be replaced with NEXT_VAL('sequenceName') for Postgresql * @param databaseFunction database function to check. * @return the string value to use for an update or generate */ String generateDatabaseFunctionValue(DatabaseFunction databaseFunction); void setObjectQuotingStrategy(ObjectQuotingStrategy quotingStrategy); ObjectQuotingStrategy getObjectQuotingStrategy(); boolean createsIndexesForForeignKeys(); /** * Whether the default schema should be included in generated SQL */ void setOutputDefaultSchema(boolean outputDefaultSchema); boolean getOutputDefaultSchema(); boolean isDefaultSchema(String catalog, String schema); boolean isDefaultCatalog(String catalog); boolean getOutputDefaultCatalog(); void setOutputDefaultCatalog(boolean outputDefaultCatalog); boolean supportsPrimaryKeyNames(); public String getSystemSchema(); public void addReservedWords(Collection<String> words); String escapeDataTypeName(String dataTypeName); String unescapeDataTypeName(String dataTypeName); String unescapeDataTypeString(String dataTypeString); ValidationErrors validate(); }
dl-stuff/dl
adv/chrom.py
from core.advbase import * class Aether(Skill): def __init__(self, name=None, acts=None, true_sp=1, maxcharge=3): super().__init__(name=name, acts=acts) self.maxcharge = maxcharge self.true_sp = true_sp @property def ac(self): if self.flames == 3 and self.count == 3: return self.act_dict["awakening"] return self.act_dict[self._static.current_s[self.name]] @property def real_sp(self): return self.true_sp def check(self): return self.flames and super().check() def cast(self): self.charged -= self.ac.conf.sp self._static.s_prev = self.name self.silence_end_timer.on(self.silence_duration) self._static.silence = 1 if self.ac.uses > 0: self.ac.uses -= 1 if loglevel >= 2: log("silence", "start") return 1 class Chrom(Adv): def __init__(self, **kwargs): super().__init__(**kwargs) self.a_s_dict["s2"] = Aether("s2", true_sp=self.conf.s2.sp, maxcharge=3) self.a_s_dict["s2"].flames = 0 @property def flames(self): return self.s2.flames def s1_proc(self, e): # get fucked if self.nihilism: return if self.s2.flames < 3: self.s2.flames += 1 def s2_proc(self, e): self.s2.flames = 0 variants = {None: Chrom}
tsconn23/alvarium-sdk-java
src/main/java/com/alvarium/sign/KeyInfo.java
<filename>src/main/java/com/alvarium/sign/KeyInfo.java /******************************************************************************* * Copyright 2021 Dell Inc. * * 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.alvarium.sign; import java.io.Serializable; import com.google.gson.Gson; /** * a java bean that encapsulates the metadata related to a specific crypto key */ public class KeyInfo implements Serializable { private final String path; private final SignType type; public KeyInfo(String path, SignType type) { this.path = path; this.type = type; } public String getPath() { return this.path; } public SignType getType() { return this.type; } public String toJson() { Gson gson = new Gson(); return gson.toJson(this); } public static KeyInfo fromJson(String json) { Gson gson = new Gson(); return gson.fromJson(json, KeyInfo.class); } }
leonarduk/unison
src/test/java/uk/co/sleonard/unison/datahandling/UNISoNDatabaseTest.java
<filename>src/test/java/uk/co/sleonard/unison/datahandling/UNISoNDatabaseTest.java<gh_stars>1-10 /** * UNISoNDatabaseTest * * @author ${author} * @since 20-Jun-2016 */ package uk.co.sleonard.unison.datahandling; import java.util.Date; import java.util.Vector; import org.hibernate.Session; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import uk.co.sleonard.unison.NewsGroupFilter; import uk.co.sleonard.unison.datahandling.DAO.Message; import uk.co.sleonard.unison.datahandling.DAO.Topic; import uk.co.sleonard.unison.datahandling.DAO.UsenetUser; public class UNISoNDatabaseTest { private UNISoNDatabase database; private NewsGroupFilter filter2; private Session session2; private HibernateHelper helper2; private int i; @Before public void setUp() throws Exception { this.filter2 = Mockito.mock(NewsGroupFilter.class); final Vector<Message> mesgs = new Vector<>(); Mockito.when(this.filter2.getMessagesFilter()).thenReturn(mesgs); this.helper2 = Mockito.mock(HibernateHelper.class); final DataQuery dataquery = Mockito.mock(DataQuery.class); this.database = new UNISoNDatabase(this.filter2, this.session2, this.helper2, dataquery); this.i = 0; } @SuppressWarnings("unchecked") @Test public final void testGetMessages() { final Topic topic = new Topic("topic", null); final Vector<Message> messages = new Vector<>(); final byte[] messageBody = "eggs".getBytes(); final Message msg = new Message(new Date(), "234", "All about me", new UsenetUser("poster", "<EMAIL>", "127.0.0.1", null, null), new Topic("topic", null), null, null, messageBody); messages.add(msg); Mockito.when(this.helper2.runQuery(Matchers.anyString(), Matchers.any(Session.class), Matchers.any(Class.class))).thenReturn(messages); this.database.getMessages(topic, this.session2); } @Test public final void testNotifyObservers() { Assert.assertEquals(0, this.i); this.database.addObserver((o, arg) -> { this.i++; }); this.database.notifyObservers(); Assert.assertEquals(1, this.i); } @Test public final void testRefreshDataFromDatabase() { this.database.refreshDataFromDatabase(); } }
LaudateCorpus1/squest
tests/test_resource_tracker/test_api/test_resource_group_api_views/test_rg_attribute_definition_api_views/test_list.py
from rest_framework import status from rest_framework.reverse import reverse from resource_tracker.api.serializers.resource_group.attribute_definition_serializers import \ ResourceGroupAttributeDefinitionSerializer from resource_tracker.models import ResourceGroupAttributeDefinition from tests.test_resource_tracker.test_api.base_test_api import BaseTestAPI class TestAttributeDefinitionList(BaseTestAPI): def setUp(self): super(TestAttributeDefinitionList, self).setUp() self.url = reverse('api_attribute_definition_list_create', args=[self.rg_physical_servers.id]) def test_attribute_definition_list(self): response = self.client.get(self.url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(ResourceGroupAttributeDefinition.objects. filter(resource_group=self.rg_physical_servers).count(), len(response.data)) all_instances = ResourceGroupAttributeDefinition.objects.\ filter(resource_group=self.rg_physical_servers) serializer = ResourceGroupAttributeDefinitionSerializer(all_instances, many=True) self.assertEqual(response.data, serializer.data)
dexhorthy/gatekeeper
pkg/tls/gatekeeper_tls_test.go
<filename>pkg/tls/gatekeeper_tls_test.go /* Copyright 2018 Replicated. 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 gatekeepertls import ( "crypto/tls" "testing" "github.com/cloudflare/cfssl/helpers" "github.com/cloudflare/cfssl/revoke" "github.com/onsi/gomega" "github.com/replicatedhq/gatekeeper/pkg/logger" "k8s.io/apimachinery/pkg/types" ) func TestCreateCertificateAuthority(t *testing.T) { g := gomega.NewGomegaWithT(t) logger := logger.New() ca, key, err := CreateCertificateAuthority(logger) g.Expect(err).NotTo(gomega.HaveOccurred()) parsedCA, err := helpers.ParseCertificatePEM(ca) g.Expect(err).NotTo(gomega.HaveOccurred()) g.Expect(parsedCA.IsCA).To(gomega.BeTrue()) revoked, ok := revoke.VerifyCertificate(parsedCA) g.Expect(revoked).To(gomega.BeFalse()) g.Expect(ok).To(gomega.BeTrue()) _, err = helpers.ParsePrivateKeyPEM(key) g.Expect(err).NotTo(gomega.HaveOccurred()) _, err = tls.X509KeyPair(ca, key) g.Expect(err).NotTo(gomega.HaveOccurred()) } func TestCreateCertFromCA(t *testing.T) { g := gomega.NewGomegaWithT(t) logger := logger.New() caCert, caKey, err := CreateCertificateAuthority(logger) g.Expect(err).NotTo(gomega.HaveOccurred()) parsedCA, err := helpers.ParseCertificatePEM(caCert) g.Expect(err).NotTo(gomega.HaveOccurred()) cert, _, err := CreateCertFromCA(logger, types.NamespacedName{Namespace: "namesspace", Name: "name"}, caCert, caKey) g.Expect(err).NotTo(gomega.HaveOccurred()) parsedCert, err := helpers.ParseCertificatePEM(cert) g.Expect(err).NotTo(gomega.HaveOccurred()) g.Expect(parsedCert.IsCA).To(gomega.BeFalse()) err = parsedCert.CheckSignatureFrom(parsedCA) g.Expect(err).NotTo(gomega.HaveOccurred()) }
blackdaemon/enso-launcher-continued
enso/contrib/calc/ipgetter.py
#!/usr/bin/env python """ This module is designed to fetch your external IP address from the internet. It is used mostly when behind a NAT. It picks your IP randomly from a serverlist to minimize request overhead on a single server If you want to add or remove your server from the list contact me on github API Usage ========= >>> import ipgetter >>> myip = ipgetter.myip() >>> myip '8.8.8.8' >>> ipgetter.IPgetter().test() Number of servers: 47 IP's : 8.8.8.8 = 47 ocurrencies Copyright 2014 <EMAIL> This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. """ import re import random from sys import version_info from contextlib import closing PY3K = version_info >= (3, 0) if PY3K: import urllib.request as urllib else: import urllib2 as urllib __version__ = "0.6" __updated__ = "2017-02-23" URL_OPENER = urllib.build_opener() URL_OPENER.addheaders = [( 'User-agent', "Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0" )] SERVER_LIST = [ 'http://api.ipify.org', 'http://ip.dnsexit.com', 'http://ifconfig.me/ip', 'http://echoip.com', 'http://ipecho.net/plain', 'http://checkip.dyndns.org/plain', 'http://ipogre.com/linux.php', 'http://whatismyipaddress.com/', 'http://websiteipaddress.com/WhatIsMyIp', 'http://getmyipaddress.org/', 'http://www.my-ip-address.net/', 'http://myexternalip.com/raw', 'http://www.canyouseeme.org/', 'http://www.trackip.net/', 'http://icanhazip.com/', 'http://www.iplocation.net/', 'http://www.howtofindmyipaddress.com/', 'http://www.ipchicken.com/', 'http://whatsmyip.net/', 'http://www.ip-adress.com/', 'http://checkmyip.com/', 'http://www.tracemyip.org/', 'http://www.lawrencegoetz.com/programs/ipinfo/', 'http://www.findmyip.co/', 'http://ip-lookup.net/', 'http://www.dslreports.com/whois', 'http://www.mon-ip.com/en/my-ip/', 'http://www.myip.ru', 'http://ipgoat.com/', 'http://www.myipnumber.com/my-ip-address.asp', 'http://www.whatsmyipaddress.net/', 'http://formyip.com/', 'http://www.displaymyip.com/', 'http://www.bobborst.com/tools/whatsmyip/', 'http://www.geoiptool.com/', 'http://checkip.dyndns.com/', 'http://myexternalip.com/', 'http://www.ip-adress.eu/', 'http://www.infosniper.net/', 'http://wtfismyip.com/text', 'http://ipinfo.io/', 'http://httpbin.org/ip', 'http://ip.ajn.me', 'http://diagnostic.opendns.com/myip', ] DISABLED_SERVERS = [] def myip(): return IPgetter().get_externalip() class IPgetter(object): ''' This class is designed to fetch your external IP address from the internet. It is used mostly when behind a NAT. It picks your IP randomly from a serverlist to minimize request overhead on a single server ''' def __init__(self): pass def get_externalip(self, samples=10): ''' This function gets your IP from a random server ''' for server in random.sample(set(SERVER_LIST) - set(DISABLED_SERVERS), samples): myip = self.fetch(server) if myip: return myip else: DISABLED_SERVERS.append(server) return '' def fetch(self, server): ''' This function gets your IP from a specific server. ''' try: with closing(URL_OPENER.open(server, timeout=2)) as resp: content = resp.read() # Didn't want to import chardet. Prefered to stick to stdlib if PY3K: try: content = content.decode('UTF-8') except UnicodeDecodeError: content = content.decode('ISO-8859-1') m = re.search( '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', content) myip = m.group(0) return myip if myip else '' except Exception as e: print e return '' def test(self): ''' This functions tests the consistency of the servers on the list when retrieving your IP. All results should be the same. ''' resultdict = {} for server in self.server_list: resultdict.update(**{server: self.fetch(server)}) ips = sorted(resultdict.values()) ips_set = set(ips) print('\nNumber of servers: {}'.format(len(self.server_list))) print("IP's :") for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)): print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies')) print('\n') print(resultdict) if __name__ == '__main__': print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip()) print(myip())
rainmanwy/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/test/java/org/rf/ide/core/testdata/text/write/tables/keywords/creation/ACreationOfKeywordTeardownTest.java
<filename>src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/test/java/org/rf/ide/core/testdata/text/write/tables/keywords/creation/ACreationOfKeywordTeardownTest.java /* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.text.write.tables.keywords.creation; import org.junit.Test; import org.rf.ide.core.testdata.model.RobotFile; import org.rf.ide.core.testdata.model.table.KeywordTable; import org.rf.ide.core.testdata.model.table.keywords.KeywordTeardown; import org.rf.ide.core.testdata.model.table.keywords.UserKeyword; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.write.NewRobotFileTestHelper; public abstract class ACreationOfKeywordTeardownTest { public static final String PRETTY_NEW_DIR_LOCATION = "keywords//setting//teardown//new//"; private final String extension; public ACreationOfKeywordTeardownTest(final String extension) { this.extension = extension; } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardownDecOnly() throws Exception { test_teardownDecOnly("EmptyKeywordTeardownNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardownDecOnly() throws Exception { test_teardownDecOnly("EmptyKeywordTeardown", "User Keyword"); } private void test_teardownDecOnly(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); uk.newTeardown(0); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardown_andComment() throws Exception { test_teardownWithCommentOnly("EmptyKeywordTeardownCommentNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardown_andComment() throws Exception { test_teardownWithCommentOnly("EmptyKeywordTeardownComment", "User Keyword"); } private void test_teardownWithCommentOnly(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); final KeywordTeardown keyTear = uk.newTeardown(0); final RobotToken cmTok1 = new RobotToken(); cmTok1.setText("cm1"); final RobotToken cmTok2 = new RobotToken(); cmTok2.setText("cm2"); final RobotToken cmTok3 = new RobotToken(); cmTok3.setText("cm3"); keyTear.addCommentPart(cmTok1); keyTear.addCommentPart(cmTok2); keyTear.addCommentPart(cmTok3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardown_andExecKey() throws Exception { test_teardownWithExec("KeywordTeardownExecKeywordNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardown_andExecKey() throws Exception { test_teardownWithExec("KeywordTeardownExecKeyword", "User Keyword"); } private void test_teardownWithExec(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); final KeywordTeardown keyTear = uk.newTeardown(0); final RobotToken keywordName = new RobotToken(); keywordName.setText("execKey"); keyTear.setKeywordName(keywordName); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardown_andExecKey_andComment() throws Exception { test_teardownWithExec_andComment("KeywordTeardownExecKeywordAndCommentNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardown_andExecKey_andComment() throws Exception { test_teardownWithExec_andComment("KeywordTeardownExecKeywordAndComment", "User Keyword"); } private void test_teardownWithExec_andComment(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); final KeywordTeardown keyTear = uk.newTeardown(0); final RobotToken keywordName = new RobotToken(); keywordName.setText("execKey"); keyTear.setKeywordName(keywordName); final RobotToken cmTok1 = new RobotToken(); cmTok1.setText("cm1"); final RobotToken cmTok2 = new RobotToken(); cmTok2.setText("cm2"); final RobotToken cmTok3 = new RobotToken(); cmTok3.setText("cm3"); keyTear.addCommentPart(cmTok1); keyTear.addCommentPart(cmTok2); keyTear.addCommentPart(cmTok3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardown_andExecKey_and3Args() throws Exception { test_teardownWithExec_and3Args("KeywordTeardownExecKeywordAnd3ArgsNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardown_andExecKey_and3Args() throws Exception { test_teardownWithExec_and3Args("KeywordTeardownExecKeywordAnd3Args", "User Keyword"); } private void test_teardownWithExec_and3Args(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); final KeywordTeardown keyTear = uk.newTeardown(0); final RobotToken keywordName = new RobotToken(); keywordName.setText("execKey"); keyTear.setKeywordName(keywordName); final RobotToken arg1 = new RobotToken(); arg1.setText("arg1"); final RobotToken arg2 = new RobotToken(); arg2.setText("arg2"); final RobotToken arg3 = new RobotToken(); arg3.setText("arg3"); keyTear.addArgument(arg1); keyTear.addArgument(arg2); keyTear.addArgument(arg3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withoutKeywordName_andTeardown_andExecKey_and3Args_andComment() throws Exception { test_teardownWithExec_and3Args_andComment("KeywordTeardownExecKeywordAnd3ArgsAndCommentNoKeywordName", ""); } @Test public void test_emptyFile_and_thanCreateKeywordTeardown_withKeywordName_andTeardown_andExecKey_and3Args_andComment() throws Exception { test_teardownWithExec_and3Args_andComment("KeywordTeardownExecKeywordAnd3ArgsAndComment", "User Keyword"); } private void test_teardownWithExec_and3Args_andComment(final String fileNameWithoutExt, final String userKeywordName) throws Exception { // prepare final String filePath = PRETTY_NEW_DIR_LOCATION + fileNameWithoutExt + "." + getExtension(); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify("2.9"); // test data prepare modelFile.includeKeywordTableSection(); final KeywordTable keywordTable = modelFile.getKeywordTable(); final RobotToken keyName = new RobotToken(); keyName.setText(userKeywordName); final UserKeyword uk = new UserKeyword(keyName); keywordTable.addKeyword(uk); final KeywordTeardown keyTear = uk.newTeardown(0); final RobotToken keywordName = new RobotToken(); keywordName.setText("execKey"); keyTear.setKeywordName(keywordName); final RobotToken arg1 = new RobotToken(); arg1.setText("arg1"); final RobotToken arg2 = new RobotToken(); arg2.setText("arg2"); final RobotToken arg3 = new RobotToken(); arg3.setText("arg3"); keyTear.addArgument(arg1); keyTear.addArgument(arg2); keyTear.addArgument(arg3); final RobotToken cmTok1 = new RobotToken(); cmTok1.setText("cm1"); final RobotToken cmTok2 = new RobotToken(); cmTok2.setText("cm2"); final RobotToken cmTok3 = new RobotToken(); cmTok3.setText("cm3"); keyTear.addCommentPart(cmTok1); keyTear.addCommentPart(cmTok2); keyTear.addCommentPart(cmTok3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(filePath, modelFile); } public String getExtension() { return extension; } }
mudchina/es2-mudlib-utf8
mudlib/d/latemoon/room/npc/annihi.c
inherit NPC; void create() { set_name("安妮儿", ({ "annihier" }) ); set("gender", "女性" ); set("age",37); set("long", @TEXT TEXT ); set("attitude", "peaceful"); set("class", "dancer"); set("combat_exp", 5000000); set("score", 7000); set_skill("unarmed",100); set_skill("dodge", 100); set_skill("force", 100); set_skill("parry", 100); set_skill("pyrobat-steps", 100); set_skill("snowshade-force", 100); set_skill("snowshade-sword", 100); set_skill("sword", 100); map_skill("sword","snowshade-sword"); map_skill("parry","snowshade-sword"); map_skill("force","snowshade-force"); map_skill("dodge","pyrobat-steps"); set("force", 5000); set("max_force", 5000); set("force_factor", 10); create_family("东方神教", 1, "教主"); setup(); carry_object("/d/latemoon/obj/deer_boot")->wear(); carry_object("/d/latemoon/obj/redbelt")->wear(); carry_object("/d/latemoon/obj/sword")->wield(); } void attempt_apprentice(object ob) { command("say 拜师! 不敢当,我都老了!你去找「芷萍」好了,看她收不收你? "); return 0; }
SovietBear/xchange-clean
xchange-bter/src/main/java/com/xeiam/xchange/bter/dto/BTERBaseResponse.java
<reponame>SovietBear/xchange-clean<filename>xchange-bter/src/main/java/com/xeiam/xchange/bter/dto/BTERBaseResponse.java package com.xeiam.xchange.bter.dto; import com.fasterxml.jackson.annotation.JsonProperty; public class BTERBaseResponse { private final boolean result; private final String message; protected BTERBaseResponse(@JsonProperty("result") final boolean result, @JsonProperty("msg") final String message) { this.result = result; this.message = message; } public boolean isResult() { return result; } public String getMessage() { return message; } @Override public String toString() { return "BTERBaseResponse [result=" + result + ", message=" + message + "]"; } }
cdcdec/DesignPatterns
src/com/aaron/abstractfactory/SendMailFactory.java
package com.aaron.abstractfactory; public class SendMailFactory implements Provider{ @Override public Sender produce() { // TODO Auto-generated method stub return new MailSender(); } }
hujunchina/java-learning
learn01/extends/src/demo01/Father.java
package demo01; public class Father { int num=1; public Father(){ System.out.println("Father construct"); } public void say(){ System.out.println("Father method"); } }
ATrain951/01.python-com_Qproject
hackerrank/Algorithms/XOR Matrix/solution.py
#!/bin/python3 import os # # Complete the xorMatrix function below. # def xorMatrix(m, first_row): # # Write your code here. # n = len(first_row) m -= 1 # now 0 row is first row, 1 row is the first row to compute mb = str(bin(m))[2:] lmb = len(mb) result = first_row.copy() for i in range(lmb): if mb[i] == '1': tmp = result.copy() offset = 2 ** (lmb - 1 - i) for j in range(n): result[j] = tmp[j] ^ tmp[(j + offset) % n] return result if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nm = input().split() n = int(nm[0]) m = int(nm[1]) first_row = list(map(int, input().rstrip().split())) last_row = xorMatrix(m, first_row) fptr.write(' '.join(map(str, last_row))) fptr.write('\n') fptr.close()
ichitaso/TwitterListEnabler
Twitter-Dumped/7.51.5/tfnui/TFNFollowButtonAnimator.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <TFNUI/TFNButtonAnimator.h> @interface TFNFollowButtonAnimator : TFNButtonAnimator { } - (_Bool)animateButton:(id)arg1 fromVisualFacade:(id)arg2 toVisualFacade:(id)arg3 forTransitionFromState:(unsigned long long)arg4 toState:(unsigned long long)arg5; @end
onap/policy-models
models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java
<reponame>onap/policy-models /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Bell Canada. * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.policy.cds.client; import static org.assertj.core.api.Assertions.assertThatCode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import io.grpc.ManagedChannel; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcCleanupRule; import io.grpc.util.MutableHandlerRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; import org.onap.policy.cds.api.CdsProcessorListener; import org.onap.policy.cds.api.TestCdsProcessorListenerImpl; import org.onap.policy.cds.properties.CdsServerProperties; public class CdsProcessorGrpcClientTest { // Generate a unique in-process server name. private static final String SERVER_NAME = InProcessServerBuilder.generateName(); // Manages automatic graceful shutdown for the registered server and client channels at the end of test. @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); private final CdsProcessorListener listener = spy(new TestCdsProcessorListenerImpl()); private final CdsServerProperties props = new CdsServerProperties(); private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); private final AtomicReference<StreamObserver<ExecutionServiceOutput>> responseObserverRef = new AtomicReference<>(); private final List<String> messagesDelivered = new ArrayList<>(); private final CountDownLatch allRequestsDelivered = new CountDownLatch(1); private CdsProcessorGrpcClient client; /** * Setup the test. * * @throws IOException on failure to register the test grpc server for graceful shutdown */ @Before public void setUp() throws IOException { // Setup the CDS properties props.setHost(SERVER_NAME); props.setPort(2000); props.setUsername("testUser"); props.setPassword("<PASSWORD>"); props.setTimeout(60); // Create a server, add service, start, and register for automatic graceful shutdown. grpcCleanup.register(InProcessServerBuilder.forName(SERVER_NAME) .fallbackHandlerRegistry(serviceRegistry).directExecutor().build().start()); // Create a client channel and register for automatic graceful shutdown ManagedChannel channel = grpcCleanup .register(InProcessChannelBuilder.forName(SERVER_NAME).directExecutor().build()); // Create an instance of the gRPC client client = new CdsProcessorGrpcClient(channel, new CdsProcessorHandler(listener, "gRPC://localhost:1234/")); // Implement the test gRPC server BluePrintProcessingServiceImplBase testCdsBlueprintServerImpl = new BluePrintProcessingServiceImplBase() { @Override public StreamObserver<ExecutionServiceInput> process( final StreamObserver<ExecutionServiceOutput> responseObserver) { responseObserverRef.set(responseObserver); return new StreamObserver<ExecutionServiceInput>() { @Override public void onNext(final ExecutionServiceInput executionServiceInput) { messagesDelivered.add(executionServiceInput.getActionIdentifiers().getActionName()); } @Override public void onError(final Throwable throwable) { // Test method } @Override public void onCompleted() { allRequestsDelivered.countDown(); } }; } }; serviceRegistry.addService(testCdsBlueprintServerImpl); } @After public void tearDown() { client.close(); } @Test public void testCdsProcessorGrpcClientConstructor() { assertThatCode(() -> new CdsProcessorGrpcClient(listener, props).close()).doesNotThrowAnyException(); } @Test(expected = IllegalStateException.class) public void testCdsProcessorGrpcClientConstructorFailure() { props.setHost(null); new CdsProcessorGrpcClient(listener, props).close(); } @Test public void testSendRequestFail() throws InterruptedException { // Setup ExecutionServiceInput testReq = ExecutionServiceInput.newBuilder() .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("policy-to-cds").build()) .build(); // Act CountDownLatch finishLatch = client.sendRequest(testReq); responseObserverRef.get().onError(new Throwable("failed to send testReq.")); verify(listener).onError(any(Throwable.class)); assertTrue(finishLatch.await(0, TimeUnit.SECONDS)); } @Test public void testSendRequestSuccess() throws InterruptedException { // Setup request ExecutionServiceInput testReq1 = ExecutionServiceInput.newBuilder() .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("policy-to-cds-req1").build()).build(); // Act final CountDownLatch finishLatch = client.sendRequest(testReq1); // Assert that request message was sent and delivered once to the server assertTrue(allRequestsDelivered.await(1, TimeUnit.SECONDS)); assertEquals(Collections.singletonList("policy-to-cds-req1"), messagesDelivered); // Setup the server to send out two simple response messages and verify that the client receives them. ExecutionServiceOutput testResp1 = ExecutionServiceOutput.newBuilder() .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("policy-to-cds-resp1").build()).build(); ExecutionServiceOutput testResp2 = ExecutionServiceOutput.newBuilder() .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("policy-to-cds-resp2").build()).build(); responseObserverRef.get().onNext(testResp1); verify(listener).onMessage(testResp1); responseObserverRef.get().onNext(testResp2); verify(listener).onMessage(testResp2); // let server complete. responseObserverRef.get().onCompleted(); assertTrue(finishLatch.await(0, TimeUnit.SECONDS)); } }
investira/dbsfaces
src/main/resources/META-INF/resources/js/dbsfaces_button.js
dbs_button = function(pId) { dbsfaces.ui.ajaxShowLoading(pId); //Força to tamanho da div para ter o mesmo comportamento do button // $(pId + "[disabled]").css("height", $(pId).outerHeight()) // .css("width", $(pId).outerWidth()); // $(pId + ".-disabled").css("height", $(pId).outerHeight()) // .css("width", $(pId).outerWidth()); // $(pId).on(dbsfaces.EVENT.ON_AJAX_SUCCESS, function(e){ // var xButton = $(this); // if (xButton.attr("asid")){ // $(dbsfaces.util.jsid(xButton.attr("asid"))).click(); // } // }); } dbsfaces.button = { }
eurosabuj/Terminalmulator
app/src/main/java/ohi/andre/consolelauncher/commands/main/raw/devutils.java
<reponame>eurosabuj/Terminalmulator package ohi.andre.consolelauncher.commands.main.raw; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import java.util.List; import ohi.andre.consolelauncher.BuildConfig; import ohi.andre.consolelauncher.R; import ohi.andre.consolelauncher.commands.CommandAbstraction; import ohi.andre.consolelauncher.commands.ExecutePack; import ohi.andre.consolelauncher.commands.main.MainPack; import ohi.andre.consolelauncher.commands.specific.ParamCommand; import ohi.andre.consolelauncher.tuils.Tuils; /** * Created by francescoandreuzzi on 22/08/2017. */ public class devutils extends ParamCommand { private enum Param implements ohi.andre.consolelauncher.commands.main.Param { notify { @Override public String exec(ExecutePack pack) { List<String> text = pack.get(List.class, 1); String title, txt = null; if(text.size() == 0) return null; else { title = text.remove(0); if(text.size() >= 2) txt = Tuils.toPlanString(text, Tuils.SPACE); } NotificationManagerCompat.from(pack.context).notify(200, new NotificationCompat.Builder(pack.context) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(txt) .build()); return null; } @Override public int[] args() { return new int[] {CommandAbstraction.TEXTLIST}; } }, check_notifications { @Override public int[] args() { return new int[0]; } @Override public String exec(ExecutePack pack) { return "Notification access: " + NotificationManagerCompat.getEnabledListenerPackages(pack.context).contains(BuildConfig.APPLICATION_ID) + Tuils.NEWLINE + "Notification service running: " + Tuils.notificationServiceIsRunning(pack.context); } }; static Param get(String p) { p = p.toLowerCase(); Param[] ps = values(); for (Param p1 : ps) if (p.endsWith(p1.label())) return p1; return null; } static String[] labels() { Param[] ps = values(); String[] ss = new String[ps.length]; for (int count = 0; count < ps.length; count++) { ss[count] = ps[count].label(); } return ss; } @Override public String label() { return Tuils.MINUS + name(); } @Override public String onNotArgEnough(ExecutePack pack, int n) { return pack.context.getString(R.string.help_devutils); } @Override public String onArgNotFound(ExecutePack pack, int index) { return null; } } @Override protected ohi.andre.consolelauncher.commands.main.Param paramForString(MainPack pack, String param) { return Param.get(param); } @Override public int priority() { return 2; } @Override public int helpRes() { return R.string.help_devutils; } @Override public String[] params() { return Param.labels(); } @Override protected String doThings(ExecutePack pack) { return null; } }
bcaglayan/pcap4j
pcap4j-core/src/main/java/org/pcap4j/packet/namednumber/LlcControlSupervisoryFunction.java
<gh_stars>100-1000 /*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet.namednumber; import java.util.HashMap; import java.util.Map; /** * LLC Control Supervisory Function * * @see <a href="http://standards.ieee.org/about/get/802/802.2.html">IEEE 802.2</a> * @author <NAME> * @since pcap4j 1.6.5 */ public final class LlcControlSupervisoryFunction extends NamedNumber<Byte, LlcControlSupervisoryFunction> { /** */ private static final long serialVersionUID = 6818202103839595038L; /** Receive ready (RR): 0 */ public static final LlcControlSupervisoryFunction RR = new LlcControlSupervisoryFunction((byte) 0, "Receive ready"); /** Receive not ready: 1 */ public static final LlcControlSupervisoryFunction RNR = new LlcControlSupervisoryFunction((byte) 1, "Receive not ready"); /** Reject: 2 */ public static final LlcControlSupervisoryFunction REJ = new LlcControlSupervisoryFunction((byte) 2, "Reject"); private static final Map<Byte, LlcControlSupervisoryFunction> registry = new HashMap<Byte, LlcControlSupervisoryFunction>(); static { registry.put(RR.value(), RR); registry.put(RNR.value(), RNR); registry.put(REJ.value(), REJ); } /** * @param value value * @param name name */ public LlcControlSupervisoryFunction(Byte value, String name) { super(value, name); if ((value & 0xFC) != 0) { throw new IllegalArgumentException(value + " is invalid value. It must be between 0 and 3"); } } /** * @param value value * @return a LlcSupervisoryFunction object. */ public static LlcControlSupervisoryFunction getInstance(Byte value) { if (registry.containsKey(value)) { return registry.get(value); } else { return new LlcControlSupervisoryFunction(value, "unknown"); } } /** * @param number number * @return a LlcSupervisoryFunction object. */ public static LlcControlSupervisoryFunction register(LlcControlSupervisoryFunction number) { return registry.put(number.value(), number); } @Override public int compareTo(LlcControlSupervisoryFunction o) { return value().compareTo(o.value()); } }
tsmalls93/ember-nrg-ui
app/components/nrg-flash-message-wrapper/component.js
<filename>app/components/nrg-flash-message-wrapper/component.js<gh_stars>0 export { default, } from 'ember-nrg-ui/components/nrg-flash-message-wrapper/component';
moorepatrick/oyster
public/app/controllers/sourceFeedCtrl.js
<filename>public/app/controllers/sourceFeedCtrl.js angular.module('SourceFeedCtrl', ['SourceFeedService', 'AuthService']) .controller('SourceFeedController', function(SourceFeed, Auth) { var vm = this; vm.processing = true; Auth.getUser() .then(function(data) { vm.user = data.data; // Get all source feeds SourceFeed.all(vm.user.username) .success(function(data) { vm.processing = false; vm.sourceFeeds = data.sourceFeeds; }); }); // Remove SourceFeed vm.deleteFeed = function(id) { vm.processing = true; console.log(id) SourceFeed.delete(vm.user.username, id) .success(function(data) { vm.message = data.message; console.log(vm.message); SourceFeed.all(vm.user.username) .success(function(data) { vm.processing = false; vm.sourceFeeds = data.sourceFeeds; }); }); }; }) // SourceFeed Creation .controller('SourceFeedAddController', function(SourceFeed, Auth) { var vm = this; Auth.getUser() .then(function(data) { vm.user = data.data; vm.addSourceFeed = function() { console.log("Data: " + encodeURIComponent(vm.feedData.url)) console.log("Data: " + encodeURI(vm.feedData.url)) vm.processing = true; vm.message = ''; // Create saveSourceFeed SourceFeed.create(vm.user.username, vm.feedData) .success(function(data) { vm.processing = false; vm.feedData = {}; vm.message = data.message; }); }; }) }) // View full Source Feed Data .controller('SourceFeedDetailController', function($routeParams, SourceFeed, Auth) { var vm = this; vm.processing = true; Auth.getUser() .then(function(data) { vm.user = data.data; console.log($routeParams.feed_id) SourceFeed.get(vm.user.username, $routeParams.feed_id) .success(function(data) { console.log(data) vm.processing = false; vm.feedData = data; }); }) });
ucsdlib/damsmanager
src/edu/ucsd/library/xdre/collection/ChecksumsHandler.java
package edu.ucsd.library.xdre.collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import edu.ucsd.library.xdre.utils.DAMSClient; import edu.ucsd.library.xdre.utils.DFile; import edu.ucsd.library.xdre.utils.DamsURI; /** * * ChecksumsHandler: perform checksum validation. * @author <EMAIL> */ public class ChecksumsHandler extends CollectionHandler{ private static Logger log = Logger.getLogger(ChecksumsHandler.class); private int count = 0; private int failedCount = 0; private int totalFiles = 0; private Date checksumDate = null; /** * Constructor for ChecksumsHandler * @param damsClient * @throws Exception */ public ChecksumsHandler(DAMSClient damsClient) throws Exception{ this(damsClient, null); } /** * Constructor for ChecksumsHandler * @param damsClient * @param collectionId * @throws Exception */ public ChecksumsHandler(DAMSClient damsClient, String collectionId) throws Exception{ this(damsClient, collectionId, null); } /** * Constructor for ChecksumsHandler * @param damsClient * @param collectionId * @param chechsumDate * @throws Exception */ public ChecksumsHandler(DAMSClient damsClient, String collectionId, Date checksumDate) throws Exception{ super(damsClient, collectionId); this.checksumDate = checksumDate; } /** * Procedure for checksums validation */ public boolean execute() throws Exception { String eMessage; String subjectURI = null; for(int i=0; i<itemsCount; i++){ count++; subjectURI = items.get(i); try{ setStatus("Processing checksums validation for subject " + subjectURI + " (" + (i+1) + " of " + itemsCount + ") ... " ); DFile dFile = null; List<DFile> files = damsClient.listObjectFiles(subjectURI); for(Iterator<DFile> it=files.iterator(); it.hasNext();){ totalFiles++; dFile = it.next(); DamsURI damsURI = DamsURI.toParts(dFile.getId(), subjectURI); try{ boolean suceeded = damsClient.checksum(damsURI.getObject(), damsURI.getComponent(), damsURI.getFileName()); if(!suceeded){ failedCount++; logError("Checksums validation for subject " + subjectURI + " failed (" + (i+1) + " of " + itemsCount + "). "); }else{ logMessage("Checksums validation for subject " + subjectURI + " succeeded (" + (i+1) + " of " + itemsCount + "). "); } } catch (Exception e) { failedCount++; e.printStackTrace(); logError("Checksums validation failed (" +(i+1)+ " of " + itemsCount + "): " + e.getMessage()); } } } catch (Exception e) { failedCount++; e.printStackTrace(); logError("Checksums validation failed (" +(i+1)+ " of " + itemsCount + "): " + e.getMessage()); } setProgressPercentage( ((i + 1) * 100) / itemsCount); try{ Thread.sleep(10); } catch (InterruptedException e1) { failedCount++; logError("Checksums validation interrupted for subject " + subjectURI + ". Error: " + e1.getMessage()); setStatus("Canceled"); clearSession(); break; } } return exeResult; } /** * Execution result message */ public String getExeInfo() { if(exeResult) exeReport.append("Checksums validation succeeded. \n "); else exeReport.append("Checksums validation failed (" + failedCount + " of " + totalFiles + " failed): \n "); exeReport.append("Total items found " + itemsCount + ". Number of items processed " + count + ". Number of files exists " + totalFiles + ".\n"); String exeInfo = exeReport.toString(); log("log", exeInfo); return exeInfo; } }
fadils/aws-sdk-android
src/main/java/com/amazonaws/services/s3/model/BucketLifecycleConfiguration.java
<reponame>fadils/aws-sdk-android /* * Copyright 2011-2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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.amazonaws.services.s3.model; import java.util.Arrays; import java.util.Date; import java.util.List; /** * Container for bucket lifecycle configuration operations. */ public class BucketLifecycleConfiguration { /** * Constant for an enabled rule. * * @see Rule#setStatus(String) */ public static final String ENABLED = "Enabled"; /** * Constant for a disabled rule. * * @see Rule#setStatus(String) */ public static final String DISABLED = "Disabled"; private List<Rule> rules; /** * Returns the list of rules that comprise this configuration. */ public List<Rule> getRules() { return rules; } /** * Sets the rules that comprise this configuration. */ public void setRules(List<Rule> rules) { this.rules = rules; } /** * Sets the rules that comprise this configuration and returns a reference * to this object for easy method chaining. */ public BucketLifecycleConfiguration withRules(List<Rule> rules) { setRules(rules); return this; } /** * Convenience array style method for * {@link BucketLifecycleConfiguration#withRules(List)} */ public BucketLifecycleConfiguration withRules(Rule... rules) { setRules(Arrays.asList(rules)); return this; } /** * Constructs a new {@link BucketLifecycleConfiguration} object with the * rules given. * * @param rules */ public BucketLifecycleConfiguration(List<Rule> rules) { this.rules = rules; } public BucketLifecycleConfiguration() { super(); } public static class Rule { private String id; private String prefix; private String status; /** * The time, in days, between when the object is uploaded to the bucket * and when it expires. Should not coexist with expirationDate within * one lifecycle rule. */ private int expirationInDays = -1; /** * The time, in days, between when a new version of the object is * uploaded to the bucket and when older versions of the object * expire. */ private int noncurrentVersionExpirationInDays = -1; /** * The expiration date of the object and should not coexist with expirationInDays within * one lifecycle rule. */ private Date expirationDate; private Transition transition; private NoncurrentVersionTransition noncurrentVersionTransition; /** * Sets the ID of this rule. Rules must be less than 255 alphanumeric * characters, and must be unique for a bucket. If you do not assign an * ID, one will be generated. */ public void setId(String id) { this.id = id; } /** * Sets the key prefix for which this rule will apply. */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Sets the time, in days, between when an object is uploaded to the * bucket and when it expires. */ public void setExpirationInDays(int expirationInDays) { this.expirationInDays = expirationInDays; } /** * Sets the time, in days, between when a new version of the object is * uploaded to the bucket and when older versions of the object expire. */ public void setNoncurrentVersionExpirationInDays(int value) { this.noncurrentVersionExpirationInDays = value; } /** * Returns the ID of this rule. */ public String getId() { return id; } /** * Sets the ID of this rule and returns a reference to this object for * method chaining. * * @see Rule#setId(String) */ public Rule withId(String id) { this.id = id; return this; } /** * Returns the key prefix for which this rule will apply. */ public String getPrefix() { return prefix; } /** * Sets the key prefix for this rule and returns a reference to this * object for method chaining. * * @see Rule#setPrefix(String) */ public Rule withPrefix(String prefix) { this.prefix = prefix; return this; } /** * Returns the time in days from an object's creation to its expiration. */ public int getExpirationInDays() { return expirationInDays; } /** * Sets the time, in days, between when an object is uploaded to the * bucket and when it expires, and returns a reference to this object * for method chaining. * * @see Rule#setExpirationInDays(int) */ public Rule withExpirationInDays(int expirationInDays) { this.expirationInDays = expirationInDays; return this; } /** * Returns the time, in days, between when a new version of the object * is uploaded to the bucket and when older versions of the object * expire. */ public int getNoncurrentVersionExpirationInDays() { return noncurrentVersionExpirationInDays; } /** * Sets the time, in days, between when a new version of the object is * uploaded to the bucket and when older versions of the object expire, * and returns a reference to this object for method chaining. */ public Rule withNoncurrentVersionExpirationInDays(int value) { setNoncurrentVersionExpirationInDays(value); return this; } /** * Returns the status of this rule. * * @see BucketLifecycleConfiguration#DISABLED * @see BucketLifecycleConfiguration#ENABLED */ public String getStatus() { return status; } /** * Sets the status of this rule. * * @see BucketLifecycleConfiguration#DISABLED * @see BucketLifecycleConfiguration#ENABLED */ public void setStatus(String status) { this.status = status; } /** * Sets the status of this rule and returns a reference to this object * for method chaining. * * @see Rule#setStatus(String) * @see BucketLifecycleConfiguration#DISABLED * @see BucketLifecycleConfiguration#ENABLED */ public Rule withStatus(String status) { setStatus(status); return this; } /** * Sets the expiration date of the object. */ public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } /** * Returns the expiration date of the object. */ public Date getExpirationDate() { return this.expirationDate; } /** * Sets the expiration date of the object and returns a reference to this * object(Rule) for method chaining. */ public Rule withExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; return this; } /** * Sets the transition describing how this object will move between * different storage classes in Amazon S3. */ public void setTransition(Transition transition) { this.transition = transition; } /** * Returns the transition attribute of the rule. */ public Transition getTransition() { return this.transition; } /** * Sets the transition describing how this object will move between * different storage classes in Amazon S3 and returns a reference to * this object(Rule) for method chaining. */ public Rule withTransition(Transition transition) { this.transition = transition; return this; } /** * Sets the transition describing how non-current versions of objects * will move between different storage classes in Amazon S3. */ public void setNoncurrentVersionTransition( NoncurrentVersionTransition value) { noncurrentVersionTransition = value; } /** * Returns the transition describing how non-current versions of * objects will move between different storage classes in Amazon S3. */ public NoncurrentVersionTransition getNoncurrentVersionTransition() { return noncurrentVersionTransition; } /** * Sets the transition describing how non-current versions of objects * will move between different storage classes in Amazon S3, and * returns a reference to this object for method chaining. */ public Rule withNoncurrentVersionTransition( NoncurrentVersionTransition value) { setNoncurrentVersionTransition(value); return this; } } /** * The transition attribute of the rule describing how this object will move * between different storage classes in Amazon S3. */ public static class Transition { /** * The time, in days, between when the object is uploaded to the bucket * and when it expires. Should not coexist with expirationDate within * one lifecycle rule. */ private int days = -1; /** * The expiration date of the object and should not coexist with expirationInDays within * one lifecycle rule. */ private Date date; private StorageClass storageClass; /** * Sets the time, in days, between when an object is uploaded to the * bucket and when it expires. */ public void setDays(int expirationInDays) { this.days = expirationInDays; } /** * Returns the time in days from an object's creation to its expiration. */ public int getDays() { return days; } /** * Sets the time, in days, between when an object is uploaded to the * bucket and when it expires, and returns a reference to this object * for method chaining. * * @see Rule#setExpirationInDays(int) */ public Transition withDays(int expirationInDays) { this.days = expirationInDays; return this; } /** * Sets the storage class of this object. */ public void setStorageClass(StorageClass storageClass) { this.storageClass = storageClass; } /** * Returns the storage class of this object. */ public StorageClass getStorageClass() { return this.storageClass; } /** * Sets the storage class of this object and returns a reference to this * object(Transition) for method chaining. */ public Transition withStorageClass(StorageClass storageClass) { this.storageClass = storageClass; return this; } /** * Set the expiration date of this object. */ public void setDate(Date expirationDate) { this.date = expirationDate; } /** * Returns the expiration date of this object. */ public Date getDate() { return this.date; } /** * Set the expiration date of this object and returns a reference to * this object(Transition) for method chaining. */ public Transition withDate(Date expirationDate) { this.date = expirationDate; return this; } } /** * The non-current-version transition attribute of the rule, describing * how non-current versions of objects will move between different storage * classes in Amazon S3. */ public static class NoncurrentVersionTransition { /** * The time, in days, between when a new version of the object is * uploaded to the bucket and when older version are archived. */ private int days = -1; private StorageClass storageClass; /** * Sets the time, in days, between when a new version of the object * is uploaded to the bucket and when older versions are archived. */ public void setDays(int expirationInDays) { this.days = expirationInDays; } /** * Returns the time in days from when a new version of the object * is uploaded to the bucket and when older versions are archived. */ public int getDays() { return days; } /** * Sets the time in days from when a new version of the object * is uploaded to the bucket and when older versions are archived, * and returns a reference to this object for method chaining. */ public NoncurrentVersionTransition withDays(int expirationInDays) { this.days = expirationInDays; return this; } /** * Sets the storage class of this object. */ public void setStorageClass(StorageClass storageClass) { this.storageClass = storageClass; } /** * Returns the storage class of this object. */ public StorageClass getStorageClass() { return this.storageClass; } /** * Sets the storage class of this object and returns a reference to * this object for method chaining. */ public NoncurrentVersionTransition withStorageClass( StorageClass storageClass) { this.storageClass = storageClass; return this; } } }
timhoer/core
projects/biogears/src/cdm/patient/actions/SEHemorrhage.cpp
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. 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. **************************************************************************************/ #include <biogears/cdm/stdafx.h> #include <biogears/cdm/patient/actions/SEHemorrhage.h> #include <biogears/cdm/properties/SEScalar0To1.h> #include <biogears/cdm/properties/SEScalarVolumePerTime.h> #include <biogears/schema/HemorrhageData.hxx> #include <biogears/schema/IntegerArray.hxx> #include <biogears/schema/IntegerList.hxx> #include <biogears/schema/ScalarVolumePerTimeData.hxx> SEHemorrhage::SEHemorrhage() : SEPatientAction() { m_Compartment = ""; //User input, location of hemorrhage m_MCIS; m_InitialRate = nullptr; //User input, initial rate of bleeding m_BleedResistance = nullptr; //Maps input to resistance on bleeding path from specified compartment } SEHemorrhage::~SEHemorrhage() { Clear(); } void SEHemorrhage::Clear() { SEPatientAction::Clear(); m_Compartment = ""; m_MCIS.clear(); organMap.clear(); SAFE_DELETE(m_InitialRate); SAFE_DELETE(m_BleedResistance); } bool SEHemorrhage::IsValid() const { return SEPatientAction::IsValid() && HasCompartment() && HasInitialRate(); } bool SEHemorrhage::IsActive() const { return IsValid() ? !(m_InitialRate->GetValue(VolumePerTimeUnit::mL_Per_min) <= ZERO_APPROX) : false; } bool SEHemorrhage::Load(const CDM::HemorrhageData& in) { SEPatientAction::Load(in); m_Compartment = in.Compartment(); GetInitialRate().Load(in.InitialRate()); //Place compartments in torso in a map so that we don't get too messy with nested conditionals. Each vector is digits 2-4 of the MCIS code organMap["VenaCava"] = std::vector<unsigned int>{ 6, 6, 0 }; organMap["LeftLung"] = std::vector<unsigned int>{ 7, 1, 0 }; organMap["RightLung"] = std::vector<unsigned int>{ 7, 1, 0 }; organMap["Myocardium"] = std::vector<unsigned int>{ 7, 2, 0 }; organMap["Liver"] = std::vector<unsigned int>{ 8, 1, 0 }; organMap["Spleen"] = std::vector<unsigned int>{ 8, 2, 0 }; organMap["Splanchnic"] = std::vector<unsigned int>{ 8, 3, 0 }; organMap["LeftKidney"] = std::vector<unsigned int>{ 8, 4, 0 }; organMap["RightKidney"] = std::vector<unsigned int>{ 8, 4, 0 }; organMap["SmallIntestine"] = std::vector<unsigned int>{ 8, 5, 0 }; organMap["LargeIntestine"] = std::vector<unsigned int>{ 8, 6, 0 }; SetMCIS(); return true; } CDM::HemorrhageData* SEHemorrhage::Unload() const { CDM::HemorrhageData* data(new CDM::HemorrhageData()); Unload(*data); return data; } void SEHemorrhage::Unload(CDM::HemorrhageData& data) const { SEPatientAction::Unload(data); if (HasCompartment()) data.Compartment(m_Compartment); if (HasInitialRate()) data.InitialRate(std::unique_ptr<CDM::ScalarVolumePerTimeData>(m_InitialRate->Unload())); } void SEHemorrhage::SetMCIS() { bool found = false; //Scale initial bleeding rate by a max value of 250 mL/min-->this would cause hypovolemic shock in 10 minutes assuming blood volume = 5L //Max this our "worst case" double flowScale_mL_Per_min = 250.0; int sev = 0; if (m_InitialRate->GetValue(VolumePerTimeUnit::mL_Per_min) > flowScale_mL_Per_min) { sev = 5; } else { sev = (int)ceil(5.0 * m_InitialRate->GetValue(VolumePerTimeUnit::mL_Per_min) / flowScale_mL_Per_min); } m_MCIS.push_back(sev); if (m_Compartment == "Brain") { m_MCIS.insert(m_MCIS.end(), { 1, 6, 1, 0 }); found = true; } else if (m_Compartment == "Aorta") { m_MCIS.insert(m_MCIS.end(), { 2, 6, 4, 0 }); found = true; } else if (m_Compartment == "LeftArm" || m_Compartment == "RightArm") { m_MCIS.insert(m_MCIS.end(), { 3, 0, 0, 0 }); found = true; } else if (m_Compartment == "LeftLeg" || m_Compartment == "RightLeg") { m_MCIS.insert(m_MCIS.end(), { 4, 0, 0, 0 }); found = true; } else { m_MCIS.push_back(2); //This inserts the code of integers stored in the organ map (associated with the compartment) at the end of the mcis vector m_MCIS.insert(m_MCIS.end(), organMap[m_Compartment].begin(), organMap[m_Compartment].end()); found = true; } if (!found) { SetComment("Could not find compartment, defaulting to Aorta"); m_MCIS.insert(m_MCIS.end(), { 2, 6, 4, 0 }); } } bool SEHemorrhage::HasMCIS() const { return !m_MCIS.empty(); } std::string SEHemorrhage::GetCompartment() const { return m_Compartment; } bool SEHemorrhage::HasCompartment() const { return !m_Compartment.empty(); } void SEHemorrhage::SetCompartment(const std::string& name) { m_Compartment = name; } void SEHemorrhage::InvalidateCompartment() { m_Compartment = ""; } bool SEHemorrhage::HasInitialRate() const { return m_InitialRate == nullptr ? false : true; } SEScalarVolumePerTime& SEHemorrhage::GetInitialRate() { if (m_InitialRate == nullptr) m_InitialRate = new SEScalarVolumePerTime(); return *m_InitialRate; } bool SEHemorrhage::HasBleedResistance() const { return m_BleedResistance == nullptr ? false : true; } SEScalarFlowResistance& SEHemorrhage::GetBleedResistance() { if (m_BleedResistance == nullptr) { m_BleedResistance = new SEScalarFlowResistance(); } return *m_BleedResistance; } void SEHemorrhage::ToString(std::ostream& str) const { if (m_InitialRate->GetValue(VolumePerTimeUnit::mL_Per_min) < ZERO_APPROX) { str << "Patient Action : Stop Hemorrhage"; if (HasComment()) str << "\n\tComment: "; str << m_Comment; str << "\n\tCompartment: "; HasCompartment() ? str << GetCompartment() : str << "No Compartment Set"; } else { str << "Patient Action : Hemorrhage"; if (HasComment()) str << "\n\tComment: " << m_Comment; str << "\n\tInitial Bleeding Rate: "; str << *m_InitialRate; str << "\n\tCompartment: "; HasCompartment() ? str << GetCompartment() : str << "No Compartment Set"; str << "\n\tInjury Code: "; for (int i : m_MCIS) str << i; } str << std::flush; }
Kitsune224/megumin-selfbot
src/commands/eval/deferred.js
<filename>src/commands/eval/deferred.js const { Command } = require('discord-akairo'); class DeferredCommand extends Command { constructor() { super('deferred', { aliases: ['deferred', 'def'], category: 'eval', args: [ { id: 'lang', type: [['eval', 'e', 'js'], ['async', 'a'], ['python', 'py'], ['ruby', 'rb']], default: 'eval' } ] }); } exec(message, { lang }) { const collector = message.channel.createMessageCollector(m => m.id !== message.id && m.author.id === message.author.id); this.handler.addPrompt(message); collector.on('collect', m => { if (m.content === '.') return collector.stop('stop'); if (m.content === '..') return collector.stop('cancel'); return undefined; }); collector.on('end', async (coll, reason) => { this.handler.removePrompt(message); let msgs = await message.channel.messages.fetch({ after: message.id, limit: 100 }); msgs = msgs.filter(m => coll.has(m.id)); if (reason === 'cancel' || msgs.size === 1) { await Promise.all(msgs.deleteAll()); return message.delete(); } await Promise.all(msgs.deleteAll()); const code = msgs.map(m => m.content).slice(1).reverse().join('\n'); return this.handler.modules.get(lang).exec(message, { code }); }); } } module.exports = DeferredCommand;
jakesjews/ember-macro-helpers
node-tests/blueprints/macro-test-test.js
<reponame>jakesjews/ember-macro-helpers<gh_stars>10-100 'use strict'; const describe = require('../helpers/describe-blueprint'); describe( 'Acceptance: ember generate and destroy macro-test', 'macro-test', 'fooBar', 'tests/unit/macros/foo-bar-test.js', function(test) { // eslint-disable-next-line mocha/no-pending-tests test('foo-bar-test.txt'); } );
MartyMcAir/OtherCodeAndTrash
OtherTrash/src/main/java/z_ClassLoader/sympleLoader/Itvdn_Examples.java
package z_ClassLoader.sympleLoader; public class Itvdn_Examples { // https://www.youtube.com/watch?v=xfCt0g5EQs4 __ - ITVDN public static void main(String[] args) throws ClassNotFoundException { // getByGetClass(); // getByClass(); // 3 by .forName(..) _ т.е. здесь мы подставляяем либо стандартный загрузчик // так же этот способ предпочтителен, если есть только пути к файлам.. Integer numberInt = 33; ClassLoader integerClassLoader = numberInt.getClass().getClassLoader(); ClassLoader loader = Itvdn_Examples.class.getClassLoader(); // стандартный загрузчик для конкретного класса // ClassLoader loader2 = new MyLoaderExtendtsClassLoader; // или наш личный загрузчик наследующий ClassLoader Class<?> cl1 = Class.forName("z_ClassLoader.sympleLoader.Itvdn_Examples", true, loader); Class<?> cl2 = Class.forName("java.lang.String"); // без подстановки своего загрузчика System.out.println(cl1); System.out.println(cl2); // 4 by Reflection API } private static void getByClass() { // 2 int[] arrInt = new int[]{3, 4, 5, 6}; Class<?> cl1 = Itvdn_Examples.class; Class<?> cl2 = int[].class; // arrInt.class; - don't work } private static void getByGetClass() { // 1 способ получения Class<?> Itvdn_Examples examples1 = new Itvdn_Examples(); int[] arrInt = new int[]{3, 4, 5, 6}; Integer numberInt = 33; // Class<?> - используется в рефлекссии для получения инфы об объекте, его методы поля и т.д. Class<?> cl1 = examples1.getClass(); Class<?> cl2 = arrInt.getClass(); Class<?> cl3 = "String".getClass(); Class<?> cl4 = numberInt.getClass(); } }
omec-project/ngap
ngapType/QoSFlowsUsageReportItem.go
<filename>ngapType/QoSFlowsUsageReportItem.go // Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) // // SPDX-License-Identifier: Apache-2.0 package ngapType import "github.com/free5gc/aper" // Need to import "github.com/free5gc/aper" if it uses "aper" type QoSFlowsUsageReportItem struct { QosFlowIdentifier QosFlowIdentifier RATType aper.Enumerated QoSFlowsTimedReportList VolumeTimedReportList IEExtensions *ProtocolExtensionContainerQoSFlowsUsageReportItemExtIEs `aper:"optional"` }
linyiwei/qiciengine-core
src/geom/Matrix.js
/** * @author weism * copyright 2015 Qcplay All Rights Reserved. */ qc.Matrix = Phaser.Matrix; /** * 类名 */ Object.defineProperty(qc.Matrix.prototype, 'class', { get : function() { return 'qc.Matrix'; } }); /** * 序列化 */ qc.Matrix.prototype.toJson = function() { return this.toArray(); } /** * 反序列化 */ qc.Matrix.prototype.fromJson = function(v) { this.fromArray(v); }
mamadbiabon/iGibson
igibson/examples/observations/generate_lidar_colored_pointcloud.py
import logging import os from sys import platform import matplotlib.pyplot as plt import numpy as np import yaml from mpl_toolkits.mplot3d import Axes3D import igibson from igibson.envs.igibson_env import iGibsonEnv def get_lidar_sampling_pattern(): lidar_vertical_low = -15 / 180.0 * np.pi lidar_vertical_high = 15 / 180.0 * np.pi lidar_vertical_n_beams = 16 lidar_vertical_beams = np.arange( lidar_vertical_low, lidar_vertical_high + (lidar_vertical_high - lidar_vertical_low) / (lidar_vertical_n_beams - 1), (lidar_vertical_high - lidar_vertical_low) / (lidar_vertical_n_beams - 1), ) lidar_horizontal_low = -45 / 180.0 * np.pi lidar_horizontal_high = 45 / 180.0 * np.pi lidar_horizontal_n_beams = 468 lidar_horizontal_beams = np.arange( lidar_horizontal_low, lidar_horizontal_high, (lidar_horizontal_high - lidar_horizontal_low) / (lidar_horizontal_n_beams), ) xx, yy = np.meshgrid(lidar_vertical_beams, lidar_horizontal_beams) xx = xx.flatten() yy = yy.flatten() height = 128 x_samples = (np.tan(xx) / np.cos(yy) * height // 2 + height // 2).astype(np.int) y_samples = (np.tan(yy) * height // 2 + height // 2).astype(np.int) x_samples = x_samples.flatten() y_samples = y_samples.flatten() return x_samples, y_samples x_samples, y_samples = get_lidar_sampling_pattern() def generate_data_lidar(nav_env, num_samples=3): rgb_all = [] lidar_all = [] lidar_all_2 = [] label_all = [] # Set initial point (not used) point = nav_env.scene.get_random_point()[1] for _ in range(num_samples): # Sample a new point new_point = nav_env.scene.get_random_point()[1] # If it is too far away, sample again while np.linalg.norm(new_point - point) > 1: new_point = nav_env.scene.get_random_point()[1] # Get vector of distance and change to (y, z, x) delta_pos = new_point - point delta_pos = np.array([delta_pos[1], delta_pos[2], delta_pos[0]]) # Set new robot's position nav_env.robots[0].set_position(new_point) # Get observations (panorama RGB, 3D/Depth and semantic segmentation) pano_rgb = nav_env.simulator.renderer.get_cube(mode="rgb", use_robot_camera=True) pano_3d = nav_env.simulator.renderer.get_cube(mode="3d", use_robot_camera=True) pano_seg = nav_env.simulator.renderer.get_cube(mode="seg", use_robot_camera=True) r3 = np.array( [[np.cos(-np.pi / 2), 0, -np.sin(-np.pi / 2)], [0, 1, 0], [np.sin(-np.pi / 2), 0, np.cos(-np.pi / 2)]] ) transformatiom_matrix = np.eye(3) for i in range(4): lidar_all.append(pano_3d[i][:, :, :3].dot(transformatiom_matrix)[x_samples, y_samples] - delta_pos[None, :]) rgb_all.append(pano_rgb[i][:, :, :3][x_samples, y_samples]) label_all.append(pano_seg[i][:, :, 0][x_samples, y_samples] * 255.0) lidar_all_2.append( pano_3d[i][:, :, :3].dot(transformatiom_matrix)[x_samples, y_samples] * 0.9 - delta_pos[None, :] ) transformatiom_matrix = r3.dot(transformatiom_matrix) lidar_all = np.concatenate(lidar_all, 0).astype(np.float32) lidar_all_2 = np.concatenate(lidar_all_2, 0).astype(np.float32) rgb_all = np.concatenate(rgb_all, 0).astype(np.float32) label_all = np.concatenate(label_all, 0).astype(np.int32) assert len(label_all) == len(label_all) direction = lidar_all - lidar_all_2 direction = direction / (np.linalg.norm(direction, axis=1)[:, None] + 1e-5) return lidar_all, direction, rgb_all, label_all def main(): """ Example of rendering and visualizing a single lidar-like pointcloud Loads Rs (non interactive) and a robot and renders a dense panorama depth map from the robot's camera Samples the depth map with a lidar-like pattern It plots the point cloud with matplotlib, colored with the RGB values It also generates segmentation and "direction" """ logging.info("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80) # Create environment mode = "headless" scene_id = "Rs_int" config = os.path.join(igibson.example_config_path, "fetch_rearrangement.yaml") config_data = yaml.load(open(config, "r"), Loader=yaml.FullLoader) # Reduce texture scale for Mac. if platform == "darwin": config_data["texture_scale"] = 0.5 nav_env = iGibsonEnv( config_file=config_data, mode=mode, scene_id=scene_id, action_timestep=1.0 / 120.0, physics_timestep=1.0 / 120.0 ) # Generate data pts, direction, color, label = generate_data_lidar(nav_env) # Create visualization: 3D points with RGB color fig = plt.figure() ax = Axes3D(fig) ax.scatter(pts[:, 0], pts[:, 2], pts[:, 1], s=3, c=color[:, :3]) plt.show() if __name__ == "__main__": main()
panekk/avs_commons
net/src/net_impl.h
/* * Copyright 2017 AVSystem <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NET_H #define NET_H #include <stdint.h> #include <avsystem/commons/socket_v_table.h> #define MODULE_NAME avs_net #include <x_log_config.h> VISIBILITY_PRIVATE_HEADER_BEGIN #if defined(WITH_IPV4) && defined(WITH_IPV6) #define WITH_AVS_V4MAPPED #endif /** * An owned PSK/identity pair. avs_commons will free() * @ref avs_net_owned_psk_t#psk and @ref avs_net_owned_psk_t#identity pointers * when they are no longer needed. */ typedef struct { void *psk; size_t psk_size; void *identity; size_t identity_size; } avs_net_owned_psk_t; /** * Note: the _actual_ maximum hostname length is not precisely defined. * NI_MAXHOST on Linux is actually a very generous 1025 (incl. nullbyte). DNS * frame format allows for up to 253 (excl. nullbyte), and also each segment * (substring between the dots) may be at most 64 characters long. Maximum * length of a TLS certificate's CN is 64 (excl. nullbyte), but it may contain * wildcards (even though we don't support them here in Commons). * * So... let's use 256 ;) */ #define NET_MAX_HOSTNAME_SIZE 256 #define NET_PORT_SIZE 6 #define AVS_NET_RESOLVE_DUMMY_PORT "1337" int _avs_net_create_tcp_socket(avs_net_abstract_socket_t **socket, const void *socket_configuration); int _avs_net_create_udp_socket(avs_net_abstract_socket_t **socket, const void *socket_configuration); #ifdef WITH_SSL int _avs_net_create_ssl_socket(avs_net_abstract_socket_t **socket, const void *socket_configuration); int _avs_net_create_dtls_socket(avs_net_abstract_socket_t **socket, const void *socket_configuration); #endif VISIBILITY_PRIVATE_HEADER_END #endif /* NET_H */
codesoftware/NSIGEMCO
src/main/java/co/com/codesoftware/logica/productos/ProductoParamLogica.java
<reponame>codesoftware/NSIGEMCO<gh_stars>0 package co.com.codesoftware.logica.productos; import java.util.List; import co.com.codesoftware.servicio.producto.ProductosParamEntity; import co.com.codesoftware.utilities.WSGeneralInterface; public class ProductoParamLogica implements WSGeneralInterface{ /** * metodo que consulta todos los productos parametrizados del sistema * @return */ public List<ProductosParamEntity> consultaProdParam(){ return conexionWSNewProd().getPortNewProductos().obtenerProductosParametrizado(); } /** * metodo que consulta el producto por id * @param idProducto * @return */ public ProductosParamEntity consultaUnicoProd(Integer idProducto){ return conexionWSNewProd().getPortNewProductos().obtenerProdParametrizado(idProducto); } /** * metodo que inserta un producto para paraametrizar * @param entidad * @return */ public boolean insertaProducto(ProductosParamEntity entidad){ return conexionWSNewProd().getPortNewProductos().insertarProdParametrizado(entidad); } /** * metodo que actualiza el producto parametrizado * @param entidad * @return */ public boolean actualizaProducto(ProductosParamEntity entidad){ return conexionWSNewProd().getPortNewProductos().actualizaProdParametrizado(entidad); } }
naichazhenhaohe/Nei
src/components/cascader/style.js
<filename>src/components/cascader/style.js<gh_stars>1-10 export const getSize = (size = 'default', theme) => { const sizes = { small: { size: `calc(1.2 * ${theme.layout.gap})`, fontSize: theme.layout.fontSizeSmall }, default: { size: `calc(1.5 * ${theme.layout.gap})`, fontSize: theme.layout.fontSize }, large: { size: `calc(2 * ${theme.layout.gap})`, fontSize: theme.layout.fontSizeLarge } } return sizes[size] }
andyChenHuaYing/scattered-items
items-design-pattern/src/main/java/org/nanshan/design/pattern/command/common/command/Command.java
<filename>items-design-pattern/src/main/java/org/nanshan/design/pattern/command/common/command/Command.java<gh_stars>1-10 package org.nanshan.design.pattern.command.common.command; /** * Description : * * @author : oscar * @version :1.0, 2016/9/4 */ public abstract class Command { public abstract void execute(); }
moonbirddk/networked-toolbox
tools/migrations/0016_tooluser_should_notify.py
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-02-03 21:03 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tools', '0015_tool_created_date'), ]
AnonymousHacker1279/ImmersiveWeapons-Mod
src/main/java/com/anonymoushacker1279/immersiveweapons/entity/ai/goal/RangedGunAttackGoal.java
package com.anonymoushacker1279.immersiveweapons.entity.ai.goal; import com.anonymoushacker1279.immersiveweapons.init.DeferredRegistryHandler; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.item.BowItem; import java.util.EnumSet; import java.util.function.Predicate; public class RangedGunAttackGoal<T extends PathfinderMob & RangedAttackMob> extends Goal { private final T entity; private final double moveSpeedAmp; private final float maxAttackDistance; private int attackCooldown; private int attackTime = -1; private int seeTime; private boolean strafingClockwise; private boolean strafingBackwards; private int strafingTime = -1; /** * Constructor for RangedGunAttackGoal. * @param mob the <code>MonsterEntity</code> that will be using the goal, * must implement IRangedAttackMob * @param moveSpeedAmpIn the movement speed amplifier * @param attackCooldownIn the attack cooldown * @param maxAttackDistanceIn the max attack distance */ public RangedGunAttackGoal(T mob, double moveSpeedAmpIn, int attackCooldownIn, float maxAttackDistanceIn) { entity = mob; moveSpeedAmp = moveSpeedAmpIn; attackCooldown = attackCooldownIn; maxAttackDistance = maxAttackDistanceIn * maxAttackDistanceIn; setFlags(EnumSet.of(Goal.Flag.MOVE, Goal.Flag.LOOK)); } /** * Set the max attack cooldown. * @param attackCooldownIn the max attack cooldown */ public void setAttackCooldown(int attackCooldownIn) { attackCooldown = attackCooldownIn; } /** * Returns whether execution should begin. You can also read and cache any state necessary for execution in this * method as well. * @return boolean */ @Override public boolean canUse() { return entity.getTarget() != null && isGunInMainHand(); } /** * Check if an instance of SimplePistolItem is held * by the entity * @return boolean */ private boolean isGunInMainHand() { return entity.isHolding(DeferredRegistryHandler.FLINTLOCK_PISTOL.get()); } /** * Returns whether an in-progress EntityAIBase should continue executing * @return boolean */ @Override public boolean canContinueToUse() { return (canUse() || !entity.getNavigation().isDone()) && isGunInMainHand(); } /** * Execute a one shot task or start executing a continuous task */ @Override public void start() { super.start(); entity.setAggressive(true); } /** * Reset the task's internal state. Called when this task is interrupted by another one */ @Override public void stop() { super.stop(); entity.setAggressive(false); seeTime = 0; attackTime = -1; entity.stopUsingItem(); } /** * Keep ticking a continuous task that has already been started */ @Override public void tick() { LivingEntity livingentity = entity.getTarget(); if (livingentity != null) { double d0 = entity.distanceToSqr(livingentity.getX(), livingentity.getY(), livingentity.getZ()); boolean flag = entity.getSensing().hasLineOfSight(livingentity); boolean flag1 = seeTime > 0; if (flag != flag1) { seeTime = 0; } if (flag) { ++seeTime; } else { --seeTime; } if (!(d0 > (double) maxAttackDistance) && seeTime >= 20) { entity.getNavigation().stop(); ++strafingTime; } else { entity.getNavigation().moveTo(livingentity, moveSpeedAmp); strafingTime = -1; } if (strafingTime >= 20) { if ((double) entity.getRandom().nextFloat() < 0.3D) { strafingClockwise = !strafingClockwise; } if ((double) entity.getRandom().nextFloat() < 0.3D) { strafingBackwards = !strafingBackwards; } strafingTime = 0; } if (strafingTime > -1) { if (d0 > (double) (maxAttackDistance * 0.75F)) { strafingBackwards = false; } else if (d0 < (double) (maxAttackDistance * 0.25F)) { strafingBackwards = true; } entity.getMoveControl().strafe(strafingBackwards ? -0.5F : 0.5F, strafingClockwise ? 0.5F : -0.5F); entity.lookAt(livingentity, 30.0F, 30.0F); } else { entity.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); } if (entity.isUsingItem()) { if (!flag && seeTime < -60) { entity.stopUsingItem(); } else if (flag) { int i = entity.getTicksUsingItem(); if (i >= 20) { entity.stopUsingItem(); entity.performRangedAttack(livingentity, BowItem.getPowerForTime(i)); attackTime = attackCooldown; } } } else if (--attackTime <= 0 && seeTime >= -60) { entity.startUsingItem(ProjectileUtil.getWeaponHoldingHand(entity, Predicate.isEqual(DeferredRegistryHandler.FLINTLOCK_PISTOL.get()))); } } } }
PiRK/silx
silx/gui/fit/test/testFitWidget.py
<reponame>PiRK/silx<filename>silx/gui/fit/test/testFitWidget.py # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016 European Synchrotron Radiation Facility # # 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. # # ###########################################################################*/ """Basic tests for :class:`FitWidget`""" import unittest from ...test.utils import TestCaseQt from ... import qt from .. import FitWidget from ....math.fit.fittheory import FitTheory from ....math.fit.fitmanager import FitManager __authors__ = ["<NAME>"] __license__ = "MIT" __date__ = "05/12/2016" class TestFitWidget(TestCaseQt): """Basic test for FitWidget""" def setUp(self): super(TestFitWidget, self).setUp() self.fit_widget = FitWidget() self.fit_widget.show() self.qWaitForWindowExposed(self.fit_widget) def tearDown(self): self.fit_widget.setAttribute(qt.Qt.WA_DeleteOnClose) self.fit_widget.close() del self.fit_widget super(TestFitWidget, self).tearDown() def testShow(self): pass def testInteract(self): self.mouseClick(self.fit_widget, qt.Qt.LeftButton) self.keyClick(self.fit_widget, qt.Qt.Key_Enter) self.qapp.processEvents() def testCustomConfigWidget(self): class CustomConfigWidget(qt.QDialog): def __init__(self): qt.QDialog.__init__(self) self.setModal(True) self.ok = qt.QPushButton("ok", self) self.ok.clicked.connect(self.accept) cancel = qt.QPushButton("cancel", self) cancel.clicked.connect(self.reject) layout = qt.QVBoxLayout(self) layout.addWidget(self.ok) layout.addWidget(cancel) self.output = {"hello": "world"} def fitfun(x, a, b): return a * x + b x = list(range(0, 100)) y = [fitfun(x_, 2, 3) for x_ in x] def conf(**kw): return {"spam": "eggs", "hello": "world!"} theory = FitTheory( function=fitfun, parameters=["a", "b"], configure=conf) fitmngr = FitManager() fitmngr.setdata(x, y) fitmngr.addtheory("foo", theory) fitmngr.addtheory("bar", theory) fitmngr.addbgtheory("spam", theory) fw = FitWidget(fitmngr=fitmngr) fw.associateConfigDialog("spam", CustomConfigWidget(), theory_is_background=True) fw.associateConfigDialog("foo", CustomConfigWidget()) fw.show() self.qWaitForWindowExposed(fw) fw.bgconfigdialogs["spam"].accept() self.assertTrue(fw.bgconfigdialogs["spam"].result()) self.assertEqual(fw.bgconfigdialogs["spam"].output, {"hello": "world"}) fw.bgconfigdialogs["spam"].reject() self.assertFalse(fw.bgconfigdialogs["spam"].result()) fw.configdialogs["foo"].accept() self.assertTrue(fw.configdialogs["foo"].result()) # todo: figure out how to click fw.configdialog.ok to close dialog # open dialog # self.mouseClick(fw.guiConfig.FunConfigureButton, qt.Qt.LeftButton) # clove dialog # self.mouseClick(fw.configdialogs["foo"].ok, qt.Qt.LeftButton) # self.qapp.processEvents() def suite(): test_suite = unittest.TestSuite() test_suite.addTest( unittest.defaultTestLoader.loadTestsFromTestCase(TestFitWidget)) return test_suite if __name__ == '__main__': unittest.main(defaultTest='suite')
airslie/renalware-core
app/presenters/renalware/hd/profile_presenter.rb
<reponame>airslie/renalware-core # frozen_string_literal: true module Renalware module HD class ProfilePresenter < DumbDelegator attr_reader :preference_set delegate :dialysis, :anticoagulant, :transport, :drugs, :care_level, to: :document delegate :dialyser, :cannulation_type, :bicarbonate, :needle_size, :single_needle, :temperature, :blood_flow, :has_sodium_profiling, :sodium_first_half, :sodium_second_half, :substitution_percent, to: :dialysis, allow_nil: true delegate :type, :loading_dose, :hourly_dose, to: :anticoagulant, allow_nil: true, prefix: true delegate :unit_code, to: :hospital_unit, prefix: true, allow_nil: true delegate :on_esa, :on_iron, :on_warfarin, to: :drugs, prefix: true, allow_nil: true delegate :has_transport, :type, :decided_on, to: :transport, prefix: true, allow_nil: true def initialize(profile, preference_set: nil) super(profile) @preference_set = preference_set end def document ProfileDocumentPresenter.new(__getobj__.document) end def hospital_unit_hint if preference_set.hospital_unit.present? "Preference: #{@preference_set.hospital_unit}" end end def schedule_hint return if preference_set.preferred_schedule.blank? "Preference: #{@preference_set.preferred_schedule}" end def current_schedule return other_schedule if other_schedule.present? schedule_definition end def schedule_definitions ScheduleDefinition .includes(:diurnal_period) .ordered .map { |definition| [definition.to_s, definition.id] } end def last_update "#{::I18n.l(updated_at)} by #{updated_by}" end def hd_type document.dialysis.hd_type.try(:text) end def prescribed_times (60..360).step(15).map { |mins| [Duration.from_minutes(mins).to_s, mins] } end def formatted_prescribed_time return unless prescribed_time ::Renalware::Duration.from_minutes(prescribed_time).to_s end def blood_flow "#{dialysis.blood_flow} ml/min" if dialysis.blood_flow.present? end def anticoagulant_stop_time return if anticoagulant.stop_time.blank? Duration.from_minutes(anticoagulant.stop_time).to_s end def transport_summary return if transport.blank? [transport.has_transport&.text, transport.type&.text].compact.join(": ") end # Although stored as a PG time data type, Rails adds a date internally when loaded from the db # so make sure we display just a 24 hour time eg 08:30. def scheduled_time super&.strftime("%H:%M") end end end end
zhangyifei/mud
d/city/ma_lianwu1.c
<filename>d/city/ma_lianwu1.c #include <room.h> inherit ROOM; void create() { set("short", "练武场"); set("long", @LONG 空阔的场地上铺满了细细的黄土,正好适合演武。四面有 几个丐帮的弟子正在练武。练武场的中心竖着几根木桩,木桩 周围还挖了若干个大沙坑。西边是兵器库。而右边有一扇小门。 LONG); set("outdoors", "city"); set("exits", ([ "west" : __DIR__"ma_bingqi", "east" : __DIR__"ma_xiaojing", "south" : __DIR__"ma_zoulang2", ])); set("objects", ([ "/d/gaibang/npc/1dai" : 1 + random(2), "/d/gaibang/npc/2dai" : 1, "/d/gaibang/npc/6dai" : 1, "/d/gaibang/npc/7dai" : 1, ])); create_door("east", "木门", "west", DOOR_CLOSED); set("no_clean_up", 0); setup(); replace_program(ROOM); }
peezy/BulHar-Fullstack
src/app/shell/crud-operations/graphql/actions.js
<gh_stars>0 export default { searchItem() { }, };
codeboxldd/photon-ml
photon-api/src/test/scala/com/linkedin/photon/ml/projector/IndexMapProjectorTest.scala
/* * Copyright 2017 LinkedIn Corp. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linkedin.photon.ml.projector import breeze.linalg.{DenseVector, SparseVector, Vector} import org.testng.Assert import org.testng.annotations.Test import com.linkedin.photon.ml.util.VectorUtils /** * */ class IndexMapProjectorTest { import IndexMapProjectorTest._ private val projector = buildIndexMapProjector( List[Vector[Double]]( new SparseVector[Double](Array(0, 4, 6, 7, 9), Array(1.0, 4.0, 6.0, 7.0, 9.0), 10), new SparseVector[Double](Array(0, 1), Array(1.0, 1.0), 10), new DenseVector[Double](Array(0.0, 0.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 0.0, 0.0)))) @Test def testBuilder(): Unit = { Assert.assertEquals(projector.originalToProjectedSpaceMap.size, 7) Assert.assertEquals(projector.originalToProjectedSpaceMap.keySet, Set[Int](0, 1, 4, 5, 6, 7, 9)) Assert.assertEquals(projector.originalSpaceDimension, 10) Assert.assertEquals(projector.projectedSpaceDimension, 7) } @Test def testProjectFeatures(): Unit = { val fv = new SparseVector[Double](Array(0, 2, 4, 5, 8), Array(1.0, 2.0, 4.0, 5.0, 8.0), 10) val expectedActiveTuples = Set[(Int, Double)]((projector.originalToProjectedSpaceMap(0), 1.0), (projector.originalToProjectedSpaceMap(4), 4.0), (projector.originalToProjectedSpaceMap(5), 5.0)) val projected = projector.projectFeatures(fv) // ensure it is in the expected space Assert.assertEquals(projected.length, 7) // ensure active tuples are the ones expected and non-existent features are ignored Assert.assertEquals(projected.iterator .filter(x => math.abs(x._2) > 0.0) .toSet, expectedActiveTuples) } @Test def testProjectCoefficients(): Unit = { val coefficients = new DenseVector[Double](Array(0.0, 0.1, 0.2, 0.3, 0.0, 0.5, 0.6)) val expectedActiveTuples = Set[(Int, Double)]((projector.projectedToOriginalSpaceMap(1), 0.1), (projector.projectedToOriginalSpaceMap(2), 0.2), (projector.projectedToOriginalSpaceMap(3), 0.3), (projector.projectedToOriginalSpaceMap(5), 0.5), (projector.projectedToOriginalSpaceMap(6), 0.6)) val projected = projector.projectCoefficients(coefficients) // ensure it is back in the original space Assert.assertEquals(projected.length, 10) // ensure active tuples are the ones expected Assert.assertEquals(projected.iterator .filter(x => math.abs(x._2) > 0.0) .toSet, expectedActiveTuples) } } object IndexMapProjectorTest { /** * Generate the index map projector given an iterator of feature vectors. * * @param features An [[Iterable]] of feature vectors * @return The generated projection map */ private def buildIndexMapProjector(features: Iterable[Vector[Double]]): IndexMapProjector = { val originalToProjectedSpaceMap = features .flatMap(VectorUtils.getActiveIndices) .toSet .zipWithIndex .toMap val originalSpaceDimension = features.head.length val projectedSpaceDimension = originalToProjectedSpaceMap.values.max + 1 new IndexMapProjector(originalToProjectedSpaceMap, originalSpaceDimension, projectedSpaceDimension) } }
ParisStefanou/SmartGridSimulation
ElectricalDeviceSimulationModels/src/main/java/upatras/simulationmodels/devices/PowerPlant.java
<gh_stars>0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package upatras.simulationmodels.devices; import org.joda.time.DateTime; import upatras.electricaldevicesimulation.simulationcore.enviromentbase.PowerEnviroment; import upatras.simulationmodels.devices.basic.VariableRampGenerator; import upatras.utilitylibrary.library.measurements.units.electrical.ComplexPower; /** * * @author Paris */ public class PowerPlant extends VariableRampGenerator { public PowerPlant(ComplexPower initial_power, ComplexPower max_power, ComplexPower ramp_rate_ms, PowerEnviroment enviroment) { super(initial_power, max_power, ramp_rate_ms, enviroment); } public final void produceMaximum(DateTime command_time) { setProduction(command_time, getMaxPower()); } public final void produceMinimum(DateTime command_time) { setProduction(command_time, new ComplexPower()); } public void increaseProduction(DateTime command_time, ComplexPower power) { increasePower(command_time, power); } public final void decreaseProduction(DateTime command_time, ComplexPower power) { increaseProduction(command_time, power.multipliedBy(-1, -1)); } public final void setProduction(DateTime command_time, ComplexPower power) { setPower(command_time, power); } }
h0lmes/mockservice
src/test/java/com/mockservice/domain/ScenarioTest.java
package com.mockservice.domain; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.web.bind.annotation.RequestMethod; import static org.junit.jupiter.api.Assertions.*; public class ScenarioTest { private static final String STR_1 = "1"; private static final String STR_2 = "2"; @Test public void setGroup_Null_GroupIsEmptyString() { assertTrue(new Scenario().setGroup(null).getGroup().isEmpty()); } @Test public void setAlias_Null_AliasIsEmptyString() { assertTrue(new Scenario().setAlias(null).getAlias().isEmpty()); } @Test public void setType_Null_TypeIsMap() { assertEquals(ScenarioType.MAP, new Scenario().setType(null).getType()); } @Test public void setData_Null_DataIsEmptyString() { assertTrue(new Scenario().setData(null).getData().isEmpty()); } @DisplayName("Test Scenario equality based on alias (other parameters don't matter).") @Test public void equals_SameMethodPathAlt_OtherFieldsDiffer_True() { Scenario scenario1 = new Scenario().setAlias(STR_1) .setGroup(STR_1) .setData(STR_1) .setType(ScenarioType.QUEUE); Scenario scenario2 = new Scenario().setAlias(STR_1) .setGroup(STR_2) .setData(STR_2) .setType(ScenarioType.CIRCULAR_QUEUE); assertEquals(scenario1, scenario2); } @Test public void equals_Null_False() { Scenario scenario = new Scenario().setAlias(STR_1); assertNotEquals(null, scenario); } @Test public void equals_ObjectOfOtherType_False() { Scenario scenario = new Scenario().setAlias(STR_1); assertNotEquals(scenario, new Object()); } @Test public void hashCode_EqualsForEqualObjects() { Scenario scenario1 = new Scenario().setGroup(STR_1).setAlias(STR_1); Scenario scenario2 = new Scenario().setGroup(STR_1).setAlias(STR_1); assertEquals(scenario1.hashCode(), scenario2.hashCode()); } @Test public void compareTo_Equal() { Scenario scenario1 = new Scenario().setGroup(STR_1).setAlias(STR_1); Scenario scenario2 = new Scenario().setGroup(STR_1).setAlias(STR_1); assertEquals(0, scenario1.compareTo(scenario2)); } @Test public void compareTo_ByGroup() { Scenario scenario1 = new Scenario().setGroup(STR_1).setAlias(STR_1); Scenario scenario2 = new Scenario().setGroup(STR_2).setAlias(STR_1); assertTrue(0 > scenario1.compareTo(scenario2)); } @Test public void compareTo_ByType() { Scenario scenario1 = new Scenario().setGroup(STR_1).setAlias(STR_1); Scenario scenario2 = new Scenario().setGroup(STR_1).setAlias(STR_2); assertTrue(0 > scenario1.compareTo(scenario2)); } private static final String METHOD = "GET"; private static final String PATH = "/test"; private static final String ALT = "400"; private static final String SCENARIO_WITH_ALT = METHOD + ";/test;" + ALT; private static final String SCENARIO_WITH_EMPTY_ALT = METHOD + ";" + PATH; private static final String SCENARIO_WITH_EMPTY_LINES = "\n\n" + METHOD + ";" + PATH + ";\"" + ALT + "\n"; private static final String SCENARIO_WITH_ONE_PARAMETER = METHOD; @Test public void create_ActivateValidScenario_ParsedSuccessfully() { Scenario activeScenario = new Scenario().setData(SCENARIO_WITH_ALT).setActive(true); assertTrue(activeScenario.getActive()); assertTrue(activeScenario.getAltFor(RequestMethod.valueOf(METHOD), PATH).isPresent()); } @Test public void create_ActivateValidScenarioWithEmptyAlt_ParsedSuccessfully() { Scenario activeScenario = new Scenario().setData(SCENARIO_WITH_EMPTY_ALT).setActive(true); assertTrue(activeScenario.getActive()); assertTrue(activeScenario.getAltFor(RequestMethod.valueOf(METHOD), PATH).isPresent()); } @Test public void create_ActivateValidScenarioWithEmptyLine_ParsedSuccessfully() { Scenario activeScenario = new Scenario().setData(SCENARIO_WITH_EMPTY_LINES).setActive(true); assertTrue(activeScenario.getActive()); assertTrue(activeScenario.getAltFor(RequestMethod.valueOf(METHOD), PATH).isPresent()); } @Test public void create_ActivateInvalidScenarioWithOneParameter_RouteExists() { Scenario scenario = new Scenario().setData(SCENARIO_WITH_ONE_PARAMETER); assertThrows(ScenarioParseException.class, () -> scenario.setActive(true)); } @Test public void create_AssignToActiveScenario_ScenarioActive() { Scenario activeScenario = new Scenario().setData(SCENARIO_WITH_ALT).setActive(true); Scenario scenario2 = new Scenario().setData(SCENARIO_WITH_EMPTY_ALT); activeScenario.assignFrom(scenario2); assertTrue(activeScenario.getActive()); assertTrue(activeScenario.getAltFor(RequestMethod.valueOf(METHOD), PATH).isPresent()); } }
adam-collins/parsers
src/test/java/org/gbif/common/parsers/TypeStatusParserTest.java
<reponame>adam-collins/parsers package org.gbif.common.parsers; import org.gbif.api.vocabulary.TypeStatus; import java.io.IOException; import java.nio.charset.Charset; import com.google.common.io.Resources; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * */ public class TypeStatusParserTest extends ParserTestBase<TypeStatus> { public TypeStatusParserTest() { super(TypeStatusParser.getInstance()); } /** * This ensures that ALL enum values are at least parsable by the name they * are created with. */ @Test public void testCompleteness() { for (TypeStatus t : TypeStatus.values()) { assertParseSuccess(t, t.name()); } } @Test public void testFailures() { assertParseFailure(null); assertParseFailure(""); assertParseFailure("Tim"); } @Test public void testParse() { // run a few basic tests to check it bootstraps and appears to work assertParseSuccess(TypeStatus.ALLOTYPE, "allotype"); assertParseSuccess(TypeStatus.HOLOTYPE, "Holotype of Abies alba"); assertParseSuccess(TypeStatus.HOLOTYPE, "Holotype for Abies alba"); assertParseSuccess(TypeStatus.PARATYPE, "paratype(s)"); assertParseSuccess(TypeStatus.PARATYPE, "Parátipo"); } @Test public void testFileCoverage() throws IOException { // parses all values in our test file (generated from real occurrence data) and verifies we never get worse at parsing Resources.readLines(Resources.getResource("parse/typestatus/type_status.txt"), Charset.forName("UTF8"), this); BatchParseResult result = getResult(); System.out.println(String.format("%s out of %s lines failed to parse", result.failed, result.total)); assertTrue(result.failed <= 26813); } }
epam/openvasp-java-core
src/main/java/org/openvasp/core/model/ivms101/NaturalPersonNameTypeCode.java
<reponame>epam/openvasp-java-core /* * Bridge * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 2 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openvasp.core.model.ivms101; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Gets or Sets NaturalPersonNameTypeCode */ @JsonAdapter(NaturalPersonNameTypeCode.Adapter.class) public enum NaturalPersonNameTypeCode { ALIA("ALIA"), BIRT("BIRT"), MAID("MAID"), LEGL("LEGL"), MISC("MISC"); private String value; NaturalPersonNameTypeCode(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static NaturalPersonNameTypeCode fromValue(String value) { for (NaturalPersonNameTypeCode b : NaturalPersonNameTypeCode.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<NaturalPersonNameTypeCode> { @Override public void write(final JsonWriter jsonWriter, final NaturalPersonNameTypeCode enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public NaturalPersonNameTypeCode read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return NaturalPersonNameTypeCode.fromValue(value); } } }
Smoudii/MigrantHub
MigrantHub/server/test/service/ServiceSuggestionServiceTest.js
var { assert } = require('sinon'); var sinon = require('sinon'); var sinonTest = require('sinon-test'); var test = sinonTest(sinon); var ServiceSuggestionService = require('../../service/ServiceSuggestionService'); var ServiceSuggestionRepository = require('../../repository/ServiceSuggestionRepository'); var ServiceRepository = require('../../repository/ServiceRepository'); var ServiceSuggestionFactory = require('../factories/ServiceSuggestionFactory'); var { ServerError } = require('../../errors/ServerError'); var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe('Service Service', function () { let req = { body: ServiceSuggestionFactory.serviceSuggestionObj(), serviceSuggestionId: "5bda52305ccfd051484ea790", }, serviceSuggestion = ServiceSuggestionFactory.serviceSuggestion(); it('should call createSuggestion repo with correct parameters from createSuggestion service', test(async function () { this.stub(ServiceSuggestionRepository, 'createSuggestion'); this.stub(ServiceSuggestionRepository, 'getSuggestions').returns([]); this.stub(ServiceRepository, 'getServices').returns([]); await ServiceSuggestionService.createSuggestion(req.body); assert.calledWith(ServiceSuggestionRepository.createSuggestion, req.body); })); it('should call not call repo with duplicate suggestion and have error', test(async function () { this.stub(ServiceSuggestionRepository, 'createSuggestion'); this.stub(ServiceSuggestionRepository, 'getSuggestions').returns([serviceSuggestion]); this.stub(ServiceRepository, 'getServices').returns([]); chai.assert.isRejected(ServiceSuggestionService.createSuggestion(req.body), ServerError, 'There was an error adding suggestion'); })); it('should call getSuggestions repo from getSuggestions service', test(async function () { this.stub(ServiceSuggestionRepository, 'getSuggestions'); await ServiceSuggestionService.getSuggestions({ deleted: false }); assert.calledWith(ServiceSuggestionRepository.getSuggestions, { deleted: false }); })); it('should call deleteSuggestion repo from deleteSuggestion service', test(async function () { this.stub(ServiceSuggestionRepository, 'deleteSuggestion'); await ServiceSuggestionService.deleteSuggestion(req.serviceSuggestionId); assert.calledWith(ServiceSuggestionRepository.deleteSuggestion, req.serviceSuggestionId); })); });
anduleh/paint-github
src/reducers/subscription.js
const subscription = (state = { hover: "", level: null }, action) => { switch (action.type) { case "updateSubscriptionHover": return { ...state, hover: action.payload }; case "updateSubscriptionLevel": return { ...state, level: action.payload }; default: return state; } }; export default subscription;
Keneral/apackages
apps/UnifiedEmail/src/com/android/mail/photo/MailPhotoViewActivity.java
/* * Copyright (C) 2012 Google Inc. * Licensed to 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.android.mail.photo; import android.content.Context; import android.content.Intent; import com.android.ex.photo.Intents; import com.android.ex.photo.PhotoViewActivity; import com.android.ex.photo.PhotoViewController; import com.android.mail.R; import com.android.mail.browse.ConversationMessage; import com.android.mail.providers.UIProvider; /** * Derives from {@link PhotoViewActivity} to allow customization. * Delegates all work to {@link MailPhotoViewController}. */ public class MailPhotoViewActivity extends PhotoViewActivity implements MailPhotoViewController.ActivityInterface { static final String EXTRA_ACCOUNT = MailPhotoViewActivity.class.getName() + "-acct"; static final String EXTRA_ACCOUNT_TYPE = MailPhotoViewActivity.class.getName() + "-accttype"; static final String EXTRA_MESSAGE = MailPhotoViewActivity.class.getName() + "-msg"; static final String EXTRA_HIDE_EXTRA_OPTION_ONE = MailPhotoViewActivity.class.getName() + "-hide-extra-option-one"; /** * Start a new MailPhotoViewActivity to view the given images. * * @param context The context. * @param account The email address of the account. * @param accountType The type of the account. * @param msg The text of the message for this photo. * @param photoIndex The index of the photo within the album. */ public static void startMailPhotoViewActivity(final Context context, final String account, final String accountType, final ConversationMessage msg, final int photoIndex) { final Intents.PhotoViewIntentBuilder builder = Intents.newPhotoViewIntentBuilder(context, context.getString(R.string.photo_view_activity)); builder .setPhotosUri(msg.attachmentListUri.toString()) .setProjection(UIProvider.ATTACHMENT_PROJECTION) .setPhotoIndex(photoIndex); context.startActivity(wrapIntent(builder.build(), account, accountType, msg)); } /** * Start a new MailPhotoViewActivity to view the given images. * * @param initialPhotoUri The uri of the photo to show first. */ public static void startMailPhotoViewActivity(final Context context, final String account, final String accountType, final ConversationMessage msg, final String initialPhotoUri) { context.startActivity( buildMailPhotoViewActivityIntent(context, account, accountType, msg, initialPhotoUri)); } public static Intent buildMailPhotoViewActivityIntent( final Context context, final String account, final String accountType, final ConversationMessage msg, final String initialPhotoUri) { final Intents.PhotoViewIntentBuilder builder = Intents.newPhotoViewIntentBuilder( context, context.getString(R.string.photo_view_activity)); builder.setPhotosUri(msg.attachmentListUri.toString()) .setProjection(UIProvider.ATTACHMENT_PROJECTION) .setInitialPhotoUri(initialPhotoUri); return wrapIntent(builder.build(), account, accountType, msg); } private static Intent wrapIntent( final Intent intent, final String account, final String accountType, final ConversationMessage msg) { intent.putExtra(EXTRA_MESSAGE, msg); intent.putExtra(EXTRA_ACCOUNT, account); intent.putExtra(EXTRA_ACCOUNT_TYPE, accountType); intent.putExtra(EXTRA_HIDE_EXTRA_OPTION_ONE, msg.getConversation() == null); return intent; } @Override public PhotoViewController createController() { return new MailPhotoViewController(this); } }
PurpleSweetPotatoes/BQOCKit
BQOCKit/Classes/Category/UI/UINavigationBar+Custom.h
// // UINavigationBar+Custom.h // AccountBook // // Created by baiqiang on 2020/12/23. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UINavigationBar (Custom) - (void)lt_setBackgroundColor:(UIColor *)backgroundColor; - (void)lt_setElementsAlpha:(CGFloat)alpha; - (void)lt_setTranslationY:(CGFloat)translationY; - (void)lt_reset; @end NS_ASSUME_NONNULL_END
jerryjappinen/linna-util
src/getNameFromEmail.js
<gh_stars>0 import startCase from 'lodash/startCase' export default (email) => { const replacedEmail = email.replace(/@.*$/, '') return startCase(replacedEmail !== email ? replacedEmail : email) }
so931/poseidonos
test/integration-tests/journal/fake/test_journal_write_completion.cpp
<filename>test/integration-tests/journal/fake/test_journal_write_completion.cpp #include "test/integration-tests/journal/fake/test_journal_write_completion.h" #include "test/integration-tests/journal/utils/written_logs.h" namespace pos { TestJournalWriteCompletion::TestJournalWriteCompletion(WrittenLogs* writtenLogs) { logs = writtenLogs; } bool TestJournalWriteCompletion::Execute(void) { logs->JournalWriteDone(); return true; } } // namespace pos
turbonomic/oneview-sdk-java
samples/src/main/java/com/hp/ov/sdk/fcnetwork/FcNetworkClientSample.java
/******************************************************************************* * (C) Copyright 2015 Hewlett Packard Enterprise Development LP * * 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.hp.ov.sdk.fcnetwork; import com.hp.ov.sdk.constants.ResourceCategory; import com.hp.ov.sdk.dto.JsonRequest; import com.hp.ov.sdk.dto.ResourceCollection; import com.hp.ov.sdk.dto.TaskResourceV2; import com.hp.ov.sdk.dto.generated.FcNetwork; import com.hp.ov.sdk.exceptions.SDKApplianceNotReachableException; import com.hp.ov.sdk.exceptions.SDKBadRequestException; import com.hp.ov.sdk.exceptions.SDKInvalidArgumentException; import com.hp.ov.sdk.exceptions.SDKNoResponseException; import com.hp.ov.sdk.exceptions.SDKNoSuchUrlException; import com.hp.ov.sdk.exceptions.SDKResourceNotFoundException; import com.hp.ov.sdk.exceptions.SDKTasksException; import com.hp.ov.sdk.rest.client.FcNetworkClient; import com.hp.ov.sdk.rest.client.FcNetworkClientImpl; import com.hp.ov.sdk.rest.http.core.client.RestParams; import com.hp.ov.sdk.util.UrlUtils; import com.hp.ov.sdk.util.samples.HPOneViewCredential; /* * FcNetworkClientSample is a sample program to consume fiber channel networks resource of HPE OneView * It invokes APIs of FcNetworkClient which is in sdk library to perform GET/PUT/POST/DELETE * operations on fiber channel networks resource */ public class FcNetworkClientSample { private final FcNetworkClient fcNetworkClient; private TaskResourceV2 taskResourceV2; private RestParams params; // test values - user input // ================================ private static final String resourceName = "FC_Network_A"; private static final String resourceId = "fd735c74-ed67-4c71-b6b0-5b5112776d13"; // ================================ private FcNetworkClientSample() { this.fcNetworkClient = FcNetworkClientImpl.getClient(); } private void getFcNetworkById() throws InstantiationException, IllegalAccessException { FcNetwork fcNetworkDto = null; // first get the session Id try { // OneView credentials params = HPOneViewCredential.createCredentials(); // then make sdk service call to get resource fcNetworkDto = fcNetworkClient.getFcNetwork(params, resourceId); System.out.println("FcNetworkClientTest : getFcNetworkById :" + " fcNetwork group object returned to client : " + fcNetworkDto.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : getFcNetworkById :" + " resource you are looking is not found "); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : getFcNetworkById :" + " no such url : " + params.getUrl()); return; } catch (final SDKApplianceNotReachableException e) { System.out .println("FcNetworkClientTest : getFcNetworkById :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out .println("FcNetworkClientTest : getFcNetworkById :" + " No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : getFcNetworkById :" + " arguments are null "); return; } } private void getAllFcNetwork() throws InstantiationException, IllegalAccessException, SDKResourceNotFoundException, SDKNoSuchUrlException { ResourceCollection<FcNetwork> fcNetworkCollectionDto = null; try { // OneView credentials params = HPOneViewCredential.createCredentials(); // then make sdk service call to get resource fcNetworkCollectionDto = fcNetworkClient.getAllFcNetworks(params); System.out.println("FcNetworkClientTest : getAllFcNetwork :" + " fcNetwork groups object returned to client : " + fcNetworkCollectionDto.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : getAllFcNetwork " + "resource you are looking is not found"); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : getAllFcNetwork :" + " no such url : " + params.getHostname()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : getAllFcNetwork :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out.println("FcNetworkClientTest : getAllFcNetwork :" + " No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : getAllFcNetwork :" + " arguments are null "); return; } } private void getFcNetworkByFilter() throws InstantiationException, IllegalAccessException, SDKResourceNotFoundException, SDKNoSuchUrlException { ResourceCollection<FcNetwork> fcNetworkCollectionDto = null; try { // OneView credentials params = HPOneViewCredential.createCredentials(); // then make sdk service call to get resource fcNetworkCollectionDto = fcNetworkClient.getFcNetworkByFilter(params, 0, 10); System.out.println("FcNetworkClientTest : getFcNetworkByFilter :" + " fcNetwork groups object returned to client : " + fcNetworkCollectionDto.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByFilter " + ": resource you are looking is not found "); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByFilter :" + " no such url : " + params.getHostname()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : getFcNetworkByFilter :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByFilter :" + " No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByFilter :" + " arguments are null "); return; } } private void getFcNetworkByName() throws InstantiationException, IllegalAccessException { FcNetwork fcNetworkDto = null; // first get the session Id try { // OneView credentials params = HPOneViewCredential.createCredentials(); // then make sdk service call to get resource fcNetworkDto = fcNetworkClient.getFcNetworkByName(params, resourceName); System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " fcNetwork group object returned to client : " + fcNetworkDto.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " resource you are looking is not found "); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " no such url : " + params.getUrl()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : getFcNetworkByName :" + " arguments are null "); return; } } private void createFcNetwork() throws InstantiationException, IllegalAccessException { try { // OneView credentials params = HPOneViewCredential.createCredentials(); // create network request body final FcNetwork fcNetworkDto = this.buildFcNetworkDto(resourceName); /** * then make sdk service call to get resource aSync parameter * indicates sync vs async useJsonRequest parameter indicates * whether json input request present or not */ taskResourceV2 = fcNetworkClient.createFcNetwork(params, fcNetworkDto, false, false); System.out.println("FcNetworkClientTest : createFcNetwork : fcNetwork" + " group object returned to client : " + taskResourceV2.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "resource you are looking is not found"); return; } catch (final SDKBadRequestException ex) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "bad request, try again : " + "may be duplicate resource name or invalid inputs. check inputs and try again"); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "no such url : " + params.getHostname()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "arguments are null "); return; } catch (final SDKTasksException e) { System.out.println("FcNetworkClientTest : createFcNetwork : " + "errors in task, please check task resource for " + "more details "); return; } } private void updateFcNetwork() throws InstantiationException, IllegalAccessException { String resourceId = null; FcNetwork fcNetworkDto = null; try { // OneView credentials params = HPOneViewCredential.createCredentials(); // fetch resource Id using name fcNetworkDto = fcNetworkClient.getFcNetworkByName(params, resourceName); fcNetworkDto.setName(resourceName + "_updated"); if (null != fcNetworkDto.getUri()) { resourceId = UrlUtils.getResourceIdFromUri(fcNetworkDto.getUri()); } /** * then make sdk service call to get resource aSync parameter * indicates sync vs async useJsonRequest parameter indicates * whether json input request present or not */ taskResourceV2 = fcNetworkClient.updateFcNetwork(params, resourceId, fcNetworkDto, false, false); System.out.println("FcNetworkClientTest : updateFcNetwork : " + "FcNetwork group object returned to client : " + taskResourceV2.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : updateFcNetwork :" + " resource you are looking is not found for update "); return; } catch (final SDKBadRequestException ex) { System.out.println("FcNetworkClientTest : updateFcNetwork :" + " bad request, try again : " + "may be duplicate resource name or invalid inputs. check inputs and try again"); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : updateFcNetwork :" + " no such url : " + params.getUrl()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : updateFcNetwork :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out.println("FcNetworkClientTest : updateFcNetwork :" + " No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : updateFcNetwork : " + "arguments are null "); return; } catch (final SDKTasksException e) { System.out.println("FcNetworkClientTest : updateFcNetwork : " + "errors in task, please check task " + "resource for more details "); return; } } private void deleteFcNetwork() throws InstantiationException, IllegalAccessException { String resourceId = null; // first get the session Id try { // OneView credentials params = HPOneViewCredential.createCredentials(); // get resource ID resourceId = fcNetworkClient.getId(params, resourceName); // then make sdk service call to get resource taskResourceV2 = fcNetworkClient.deleteFcNetwork(params, resourceId, false); System.out.println("FcNetworkClientTest : deleteFcNetwork : " + "fcNetwork group object returned to client : " + taskResourceV2.toString()); } catch (final SDKResourceNotFoundException ex) { System.out.println("FcNetworkClientTest : deleteFcNetwork :" + " resource you are looking is not found for delete "); return; } catch (final SDKNoSuchUrlException ex) { System.out.println("FcNetworkClientTest : deleteFcNetwork :" + " no such url : " + params.getUrl()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : deleteFcNetwork :" + " Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKNoResponseException ex) { System.out.println("FcNetworkClientTest : deleteFcNetwork : " + "No response from appliance : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : deleteFcNetwork :" + " arguments are null "); return; } } private void createFcNetworkUsingJsonRequest() throws InstantiationException, IllegalAccessException { try { // OneView credentials params = HPOneViewCredential.createCredentials(); // create network request body final FcNetwork fcNetworkDto = buildTestFcNetworkDtoWithJsonRequest(); /** * then make sdk service call to get resource aSync parameter * indicates sync vs async useJsonRequest parameter indicates * whether json input request present or not */ taskResourceV2 = fcNetworkClient.createFcNetwork(params, fcNetworkDto, false, true); System.out.println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : fcNetwork" + " group object returned to client : " + taskResourceV2.toString()); } catch (final SDKResourceNotFoundException ex) { System.out .println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "resource you are looking is not found"); return; } catch (final SDKBadRequestException ex) { System.out.println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "bad request, try again : " + "may be duplicate resource name or invalid inputs. check inputs and try again"); return; } catch (final SDKNoSuchUrlException ex) { System.out .println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "no such url : " + params.getHostname()); return; } catch (final SDKApplianceNotReachableException e) { System.out.println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "Applicance Not reachabe at : " + params.getHostname()); return; } catch (final SDKInvalidArgumentException ex) { System.out.println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "arguments are null "); return; } catch (final SDKTasksException e) { System.out.println("FcNetworkClientTest : createFcNetworkUsingJsonRequest : " + "errors in task, please check task resource for " + "more details "); return; } } private FcNetwork buildTestFcNetworkDtoWithJsonRequest() { final FcNetwork fcNetworkDto = new FcNetwork(); final JsonRequest jsonRequest = new JsonRequest(); jsonRequest .setBody("{\"type\":\"fc-networkV2\",\"fabricType\":\"FabricAttach\",\"linkStabilityTime\":30,\"managedSanUri\":null,\"autoLoginRedistribution\":true,\"description\":null,\"name\":\"FC_Network_D\",\"state\":\"Active\",\"category\":\"fc-networks\"}"); fcNetworkDto.setJsonRequest(jsonRequest); return fcNetworkDto; } private FcNetwork buildFcNetworkDto(String fcNetworkName) { FcNetwork fcNetworkDto = new FcNetwork(); fcNetworkDto.setName(fcNetworkName); fcNetworkDto.setConnectionTemplateUri(null); fcNetworkDto.setLinkStabilityTime(30); fcNetworkDto.setAutoLoginRedistribution(true); fcNetworkDto.setFabricType(FcNetwork.FabricType.FabricAttach); fcNetworkDto.setType(ResourceCategory.RC_FCNETWORK); return fcNetworkDto; } public static void main(final String[] args) throws Exception { FcNetworkClientSample client = new FcNetworkClientSample(); client.createFcNetwork(); client.getFcNetworkById(); client.getFcNetworkByFilter(); client.getFcNetworkByName(); client.updateFcNetwork(); client.createFcNetwork(); client.getAllFcNetwork(); client.deleteFcNetwork(); client.createFcNetworkUsingJsonRequest(); } }
merry-team/head_study_java
src/main/java/com/neteye/xinzhizhu/utils/MultimeLength.java
package com.neteye.xinzhizhu.utils; import java.io.File; import java.security.MessageDigest; import it.sauronsoftware.jave.Encoder; import it.sauronsoftware.jave.MultimediaInfo; public class MultimeLength { public static long getMultimeLength(String str) { if (str == null) { return 0; } try { File source= new File(str); Encoder encoder = new Encoder(); MultimediaInfo m = encoder.getInfo(source); long ls = m.getDuration(); return (ls)/1000; } catch (Exception e) { return 0; } } }
bitigchi/MuditaOS
module-gui/gui/widgets/SideListView.cpp
// Copyright (c) 2017-2021, <NAME>. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "Image.hpp" #include "InputEvent.hpp" #include "SideListView.hpp" #include "Style.hpp" namespace gui { SideListView::SideListView(Item *parent, unsigned int x, unsigned int y, unsigned int w, unsigned int h, std::shared_ptr<ListItemProvider> prov, PageBarType pageBarType) : Rect{parent, x, y, w, h}, ListViewEngine(prov) { setEdges(RectangleEdge::All); bodyOverlay = new VBox{this, 0, 0, w, h}; bodyOverlay->setEdges(RectangleEdge::None); if (pageBarType != PageBarType::None) { createPageBar(); applyScrollCallbacks(); } body = new HBox{bodyOverlay, 0, 0, 0, 0}; body->setMaximumSize(w, h); body->setAlignment(Alignment::Horizontal::Center); body->setEdges(RectangleEdge::None); bodyOverlay->resizeItems(); body->borderCallback = [this](const InputEvent &inputEvent) -> bool { if (!inputEvent.isShortRelease()) { return false; } if (inputEvent.is(KeyCode::KEY_RF) && pageLoaded) { return this->requestPreviousPage(); } else if (inputEvent.is(KeyCode::KEY_ENTER) && pageLoaded) { return this->requestNextPage(); } else { return false; } }; focusChangedCallback = [this]([[maybe_unused]] Item &item) -> bool { if (focus) { setFocus(); } else { setFocusItem(nullptr); } return true; }; type = gui::ItemType::LIST; } auto SideListView::createPageBar() -> void { pageBar = new HBarGraph(bodyOverlay, 0U, 0U, 0); pageBar->setMinimumHeight(style::sidelistview::progress_bar::h); pageBar->setMargins(Margins(style::sidelistview::progress_bar::margin_left, style::sidelistview::progress_bar::margin_top, style::sidelistview::progress_bar::margin_right, style::sidelistview::progress_bar::margin_bottom)); pageBar->setAlignment(Alignment(gui::Alignment::Horizontal::Center, gui::Alignment::Vertical::Center)); pageBar->activeItem = false; } auto SideListView::applyScrollCallbacks() -> void { updateScrollCallback = [this](ListViewScrollUpdateData data) { if (pageBar != nullptr) { auto elementsOnPage = body->widgetArea.w / data.elementMinimalSpaceRequired; auto pagesCount = data.elementsCount % elementsOnPage == 0 ? data.elementsCount / elementsOnPage : data.elementsCount / elementsOnPage + 1; auto currentPage = data.startIndex / elementsOnPage + 1; pageBar->setMaximum(pagesCount); pageBar->createGraph(); pageBar->setValue(currentPage); } }; } auto SideListView::createArrowsOverlay(unsigned int x, unsigned y, unsigned int w, unsigned int h) -> void { arrowsOverlay = new HBox{this, x, y, w, h}; arrowsOverlay->setEdges(gui::RectangleEdge::None); auto arrowLeft = new gui::Image(style::sidelistview::arrow_left_image); arrowLeft->setAlignment(Alignment(gui::Alignment::Horizontal::Left, gui::Alignment::Vertical::Center)); arrowLeft->activeItem = false; arrowLeft->setEdges(RectangleEdge::None); arrowsOverlay->addWidget(arrowLeft); auto arrowRight = new Image(style::sidelistview::arrow_right_image); arrowRight->setAlignment(Alignment(Alignment::Horizontal::Right, Alignment::Vertical::Center)); arrowRight->activeItem = false; arrowRight->setEdges(RectangleEdge::None); auto rectFiller = new gui::Rect(arrowsOverlay, 0U, 0U, arrowsOverlay->getWidth() - arrowLeft->getWidth() - arrowRight->getWidth(), arrowsOverlay->getHeight()); rectFiller->setMaximumSize(arrowsOverlay->getWidth(), arrowsOverlay->getHeight()); rectFiller->setEdges(RectangleEdge::None); arrowsOverlay->addWidget(arrowRight); } auto SideListView::setFocus() -> void { if (!focus) { return; } setFocusItem(body); ListViewEngine::setFocus(); } auto SideListView::onInput(const InputEvent &inputEvent) -> bool { if (body->onInput(inputEvent)) { return true; } if (body->borderCallback && body->borderCallback(inputEvent)) { return true; } return false; } } /* namespace gui */
lakeslove/springSourceCodeTest
spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java
<reponame>lakeslove/springSourceCodeTest /* * Copyright 2002-2015 the original author or authors. * * 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 org.springframework.http.client; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.util.StreamUtils; /** * Simple implementation of {@link ClientHttpResponse} that reads the response's body * into memory, thus allowing for multiple invocations of {@link #getBody()}. * * @author <NAME> * @since 3.1 */ final class BufferingClientHttpResponseWrapper implements ClientHttpResponse { private final ClientHttpResponse response; private byte[] body; BufferingClientHttpResponseWrapper(ClientHttpResponse response) { this.response = response; } @Override public HttpStatus getStatusCode() throws IOException { return this.response.getStatusCode(); } @Override public int getRawStatusCode() throws IOException { return this.response.getRawStatusCode(); } @Override public String getStatusText() throws IOException { return this.response.getStatusText(); } @Override public HttpHeaders getHeaders() { return this.response.getHeaders(); } @Override public InputStream getBody() throws IOException { if (this.body == null) { this.body = StreamUtils.copyToByteArray(this.response.getBody()); } return new ByteArrayInputStream(this.body); } @Override public void close() { this.response.close(); } }
RippeR37/GLUL
tests/src/GLUL/Image.cpp
<reponame>RippeR37/GLUL #include <gtest/gtest.h> #include <GLUL/Image.h> #include <glm/vec2.hpp> #include <cstring> bool isValidImageData(unsigned char* imageData, unsigned int bits) { static unsigned char templateData24[16] = { 255, 0, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 0, 0, 0, }; static unsigned char templateData32[16] = { 255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255 }; bool areSame = true; if(bits == 24) { areSame = areSame && (0 == std::memcmp(imageData, templateData24, 6)); // ignore row alignment areSame = areSame && (0 == std::memcmp(imageData + 8, templateData24 + 8, 6)); // ignore row alignment } else { areSame = areSame && (0 == std::memcmp(imageData, templateData32, 16)); } return areSame; } TEST(GLUL_Image, Constructor_Empty) { GLUL::Image image; ASSERT_EQ(nullptr, image.getData()); ASSERT_EQ(0u, image.getBits()); ASSERT_EQ(0u, image.getWidth()); ASSERT_EQ(0u, image.getHeight()); ASSERT_EQ(0u, image.getSize()); } TEST(GLUL_Image, Constructor_Path_Format_Existing) { ASSERT_NO_THROW( { GLUL::Image image("test_assets/image/image.bmp"); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); }); } TEST(GLUL_Image, Constructor_Path_Format_Non_Existing) { ASSERT_THROW({ GLUL::Image image("test_assets/image/nonexisting.bmp"); }, GLUL::Exception::InitializationFailed); } TEST(GLUL_Image, Constructor_Copy_Empty) { ASSERT_NO_THROW({ GLUL::Image image; GLUL::Image imageCopy(image); ASSERT_EQ(nullptr, image.getData()); ASSERT_EQ(0u, image.getBits()); ASSERT_EQ(0u, image.getWidth()); ASSERT_EQ(0u, image.getHeight()); ASSERT_EQ(0u, image.getSize()); ASSERT_EQ(nullptr, imageCopy.getData()); ASSERT_EQ(0u, imageCopy.getBits()); ASSERT_EQ(0u, imageCopy.getWidth()); ASSERT_EQ(0u, imageCopy.getHeight()); ASSERT_EQ(0u, imageCopy.getSize()); }); } TEST(GLUL_Image, Constructor_Copy_Loaded) { ASSERT_NO_THROW({ GLUL::Image image("test_assets/image/image.bmp"); GLUL::Image imageCopy(image); ASSERT_NE(nullptr, image.getData()); ASSERT_NE(nullptr, imageCopy.getData()); ASSERT_NE(image.getData(), imageCopy.getData()); ASSERT_EQ(0, std::memcmp(image.getData(), imageCopy.getData(), image.getSize())); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(24u, imageCopy.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, imageCopy.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(2u, imageCopy.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_EQ(16u, imageCopy.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); ASSERT_TRUE(isValidImageData(imageCopy.getData(), 24u)); }); } TEST(GLUL_Image, Constructor_Move) { ASSERT_NO_THROW({ GLUL::Image image("test_assets/image/image.bmp"); // this should be empty after being moved GLUL::Image image2(std::move(image)); // this should be image.bmp ASSERT_EQ(nullptr, image.getData()); ASSERT_EQ(0u, image.getBits()); ASSERT_EQ(0u, image.getWidth()); ASSERT_EQ(0u, image.getHeight()); ASSERT_EQ(0u, image.getSize()); ASSERT_NE(nullptr, image2.getData()); ASSERT_EQ(24u, image2.getBits()); ASSERT_EQ(2u, image2.getWidth()); ASSERT_EQ(2u, image2.getHeight()); ASSERT_EQ(16u, image2.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image2.getData(), 24u)); }); } TEST(GLUL_Image, Assignment_Existing) { ASSERT_NO_THROW({ GLUL::Image image("test_assets/image/image.bmp"); GLUL::Image image2; image2 = image; ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); ASSERT_NE(nullptr, image2.getData()); ASSERT_EQ(24u, image2.getBits()); ASSERT_EQ(2u, image2.getWidth()); ASSERT_EQ(2u, image2.getHeight()); ASSERT_EQ(16u, image2.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image2.getData(), 24u)); ASSERT_NE(image.getData(), image2.getData()); }); } TEST(GLUL_Image, Load_Unsupported) { GLUL::Image image; ASSERT_THROW({ image.load("test_assets/image/image.unsupported_extension"); }, GLUL::Exception::InitializationFailed); ASSERT_EQ(nullptr, image.getData()); ASSERT_EQ(0u, image.getBits()); ASSERT_EQ(0u, image.getWidth()); ASSERT_EQ(0u, image.getHeight()); ASSERT_EQ(0u, image.getSize()); } TEST(GLUL_Image, Load_From_Array) { GLUL::Image image("test_assets/image/image.bmp"); GLUL::Image image2; image2.load(image.getWidth(), image.getHeight(), image.getBits(), image.getData(), true); ASSERT_NE(image.getData(), image2.getData()); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); } TEST(GLUL_Image, Load_BMP) { GLUL::Image image; image.load("test_assets/image/image.bmp"); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); } TEST(GLUL_Image, Load_TGA) { GLUL::Image image; image.load("test_assets/image/image.tga"); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 24u)); } TEST(GLUL_Image, Load_PNG) { GLUL::Image image; image.load("test_assets/image/image.png"); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(32u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) ASSERT_TRUE(isValidImageData(image.getData(), 32u)); } TEST(GLUL_Image, Load_JPG) { GLUL::Image image; image.load("test_assets/image/image.jpg"); ASSERT_NE(nullptr, image.getData()); ASSERT_EQ(24u, image.getBits()); ASSERT_EQ(2u, image.getWidth()); ASSERT_EQ(2u, image.getHeight()); ASSERT_EQ(16u, image.getSize()); // size = (bits / 8) * height * rowStride (where rowstride is aligned row's size) /** * Due to JPEG compression some color data are lost on write, so we have special test case for this format. */ static unsigned char templateData[16] = { 254, 0, 0, 255, 255, 255, 0, 0, 0, 0, 254, 0, 255, 1, 0, 0, }; ASSERT_EQ(0, std::memcmp(image.getData(), templateData, 1)); } TEST(GLUL_Image, Load_Reset) { GLUL::Image image; image.load("test_assets/image/image.bmp"); ASSERT_NE(nullptr, image.getData()); ASSERT_NE(0u, image.getBits()); ASSERT_NE(0u, image.getWidth()); ASSERT_NE(0u, image.getHeight()); ASSERT_NE(0u, image.getSize()); image.reset(); ASSERT_EQ(nullptr, image.getData()); ASSERT_EQ(0u, image.getBits()); ASSERT_EQ(0u, image.getWidth()); ASSERT_EQ(0u, image.getHeight()); ASSERT_EQ(0u, image.getSize()); } TEST(GLUL_Image, Swap_Components_One_Line) { unsigned char rgbData[12] = { 0, 0, 1, 1, 0, 0, 2, 0, 1, 3, 2, 1 }; unsigned char bgrData[12] = { 1, 0, 0, 0, 0, 1, 1, 0, 2, 1, 2, 3 }; unsigned char rgbaData[16] = { 0, 0, 1, 5, 1, 0, 0, 5, 2, 0, 1, 5, 3, 2, 1, 5 }; unsigned char bgraData[16] = { 1, 0, 0, 5, 0, 0, 1, 5, 1, 0, 2, 5, 1, 2, 3, 5 }; unsigned char array1[12]; std::copy(std::begin(rgbData), std::end(rgbData), std::begin(array1)); unsigned char array2[12]; std::copy(std::begin(bgrData), std::end(bgrData), std::begin(array2)); unsigned char array3[16]; std::copy(std::begin(rgbaData), std::end(rgbaData), std::begin(array3)); unsigned char array4[16]; std::copy(std::begin(bgraData), std::end(bgraData), std::begin(array4)); GLUL::Image::swapComponents(4, 1, 24, array1); GLUL::Image::swapComponents(4, 1, 24, array2); GLUL::Image::swapComponents(4, 1, 32, array3); GLUL::Image::swapComponents(4, 1, 32, array4); ASSERT_EQ(0, std::memcmp(array1, bgrData, 12)); ASSERT_EQ(0, std::memcmp(array2, rgbData, 12)); ASSERT_EQ(0, std::memcmp(array3, bgraData, 16)); ASSERT_EQ(0, std::memcmp(array4, rgbaData, 16)); } TEST(GLUL_Image, Swap_Components_Multiline) { unsigned char rgbData[16] = { 0, 0, 1, 1, 0, 0, 9, 9, 2, 0, 1, 3, 2, 1, 9, 9 }; // 9s are rowStride unsigned char bgrData[16] = { 1, 0, 0, 0, 0, 1, 9, 9, 1, 0, 2, 1, 2, 3, 9, 9 }; // 9s are rowstride unsigned char array1[16]; std::copy(std::begin(rgbData), std::end(rgbData), std::begin(array1)); unsigned char array2[16]; std::copy(std::begin(bgrData), std::end(bgrData), std::begin(array2)); GLUL::Image::swapComponents(2, 2, 24, array1); GLUL::Image::swapComponents(2, 2, 24, array2); ASSERT_EQ(0, std::memcmp(array1, bgrData, 16)); ASSERT_EQ(0, std::memcmp(array2, rgbData, 16)); } TEST(GLUL_Image, Get_Aligned_Row_Size) { ASSERT_EQ(0u, GLUL::Image::getAlignedRowSize(0, 24)); ASSERT_EQ(4u, GLUL::Image::getAlignedRowSize(1, 24)); ASSERT_EQ(8u, GLUL::Image::getAlignedRowSize(2, 24)); ASSERT_EQ(12u, GLUL::Image::getAlignedRowSize(3, 24)); ASSERT_EQ(12u, GLUL::Image::getAlignedRowSize(4, 24)); ASSERT_EQ(16u, GLUL::Image::getAlignedRowSize(5, 24)); ASSERT_EQ(0u, GLUL::Image::getAlignedRowSize(0, 32)); ASSERT_EQ(4u, GLUL::Image::getAlignedRowSize(1, 32)); ASSERT_EQ(8u, GLUL::Image::getAlignedRowSize(2, 32)); ASSERT_EQ(12u, GLUL::Image::getAlignedRowSize(3, 32)); ASSERT_EQ(16u, GLUL::Image::getAlignedRowSize(4, 32)); ASSERT_EQ(20u, GLUL::Image::getAlignedRowSize(5, 32)); } TEST(GLUL_Image, Algorithm_Crop) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image.bmp"); image.load("test_assets/image/image_cropping_test.bmp"); image.crop(glm::uvec2(1u, 1u), glm::uvec2(2u, 2u)); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Rotate_90) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_r90.bmp"); image.load("test_assets/image/image.bmp"); image.rotate90CW(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Rotate_180) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_r180.bmp"); image.load("test_assets/image/image.bmp"); image.rotate180(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Rotate_270) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_r270.bmp"); image.load("test_assets/image/image.bmp"); image.rotate90CCW(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Invert_Horizontal) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_invert_h.bmp"); image.load("test_assets/image/image.bmp"); image.invertHorizontal(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Invert_Vertical) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_invert_v.bmp"); image.load("test_assets/image/image.bmp"); image.invertVertical(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Invert_Colors) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_invert_colors.bmp"); image.load("test_assets/image/image.bmp"); image.invertColors(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); } TEST(GLUL_Image, Algorithm_Grayscale) { GLUL::Image imgTemplate; GLUL::Image image; imgTemplate.load("test_assets/image/image_greyscale.bmp"); image.load("test_assets/image/image.bmp"); image.toGrayscale(); ASSERT_EQ(0, std::memcmp(imgTemplate.getData(), image.getData(), image.getSize())); }
lechium/iOS1351Headers
usr/libexec/com.apple/NSDictionary-EscrowRequest.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <Foundation/NSDictionary.h> @interface NSDictionary (EscrowRequest) - (id)base64EncodedStringFromDict; // IMP=0x0000000100014324 - (void)recordIDAndClientMetadataForSilentAttemptFromRecords:(id)arg1 passphraseLength:(unsigned long long)arg2 platform:(int)arg3 reply:(CDUnknownBlockType)arg4; // IMP=0x000000010004b634 - (long long)compare:(id)arg1 with:(id)arg2; // IMP=0x000000010004af48 - (id)keysOfEntriesContainingObject:(id)arg1; // IMP=0x000000010004ae8c @end
jiapeish/leetcode-c-cpp
cpp/cpp_primer_code/chap13/account.h
<filename>cpp/cpp_primer_code/chap13/account.h #ifndef ACCOUNT_H #define ACCOUNT_H #include <string> using std::string; class Account { public: Account( double amount, const string &owner ); string owner(); double dailyReturn(); static void raiseInterest( double ); static double interest(); friend int compareRevenue( Account& , Account* ); private: static double _interestRate; double _amount; string _owner; static const int nameSize = 16; static const char name[nameSize]; }; inline Account::Account( double amount, const string &owner ) : _amount( amount ), _owner( owner ) { /* all the work is done with the member initialization list */ } inline string Account::owner() { return _owner; } inline double Account::dailyReturn() { return( _interestRate / 365 * _amount ); } inline void Account::raiseInterest( double incr ) { _interestRate += incr; } inline double Account::interest() { return _interestRate; } #endif
vlehtola/questmud
lib/wizards/manta/castle/cas19.c
#include "room.h" #undef EXTRA_RESET #define EXTRA_RESET\ extra_reset(); object mon24,mon25,mon26; extra_reset() { if(!mon24) { mon24 = clone_object("/wizards/manta/castle/dem2.c"); move_object(mon24, this_object()); } if(!mon25) { mon25 = clone_object("/wizards/manta/castle/dem5.c"); move_object(mon25, this_object()); } if(!mon26) { mon26 = clone_object("/wizards/manta/castle/dem3.c"); move_object(mon26, this_object()); } } ONE_EXIT("/wizards/manta/castle/cas14.c", "south", "A dead end", "this room seems to be destroyed you can't continue this way\n" + "walls have crumbled and blocked all exits.\n", 1)
Gathros/SegVL
include/animators/vector_animator.h
<reponame>Gathros/SegVL #ifndef GATHVL_VECTOR_ANIMATOR_H #define GATHVL_VECTOR_ANIMATOR_H #include <vector> #include "animator.h" template <typename T> struct vector_animator : animator { std::vector<T> data; std::vector<T> *vector_ptr; int start_point; void update(const int frame) override { if (!data.empty() && frame >= start_frame && frame < end_frame) { int index = vector_ptr->size(); int new_size = vector_ptr->size() + (data.size() - start_point) / (end_frame - start_frame); while (vector_ptr->size() < new_size && vector_ptr) { vector_ptr->push_back(data[index]); index++; } } } vector_animator(int start_frame, int end_frame, int start_point, const std::vector<T>& data, std::vector<T> *vector_ptr) : animator(start_frame, end_frame), data(data), vector_ptr(vector_ptr), start_point(start_point) {} }; #endif //GATHVL_VECTOR_ANIMATOR_H
potherca-contrib/origin-community-cartridges
openshift-origin-cartridge-jbossrhq-4/template/deployments/rhq.ear/rhq-core-domain-ejb3.jar/org/rhq/core/domain/criteria/EventCriteria.java
<filename>openshift-origin-cartridge-jbossrhq-4/template/deployments/rhq.ear/rhq-core-domain-ejb3.jar/org/rhq/core/domain/criteria/EventCriteria.java /* * RHQ Management Platform * Copyright (C) 2005-2008 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation, and/or the GNU Lesser * General Public License, version 2.1, also as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License and the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.rhq.core.domain.criteria; import java.util.Arrays; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.event.Event; import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.util.PageOrdering; /** * @author <NAME> */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings("unused") public class EventCriteria extends Criteria { private static final long serialVersionUID = 1L; private Integer filterId; private String filterDetail; private String filterSourceName; // requires overrides private List<EventSeverity> filterSeverities; private Long filterStartTime; // requires overrides private Long filterEndTime; // requires overrides private Integer filterResourceId; // requires overrides private Integer filterResourceGroupId; // requires overrides private Integer filterAutoGroupResourceTypeId; // requires overrides private Integer filterAutoGroupParentResourceId; // requires overrides private Integer filterSourceId; // requires overrides private boolean fetchSource; private PageOrdering sortTimestamp; private PageOrdering sortSeverity; public EventCriteria() { filterOverrides.put("sourceName", "source.location like ?"); filterOverrides.put("sourceId","source.id = ?"); filterOverrides.put("startTime", "timestamp >= ?"); filterOverrides.put("endTime", "timestamp <= ?"); filterOverrides.put("resourceId", "source.resourceId = ?"); filterOverrides.put("resourceGroupId", "source.resourceId IN " // + "( SELECT res.id " // + " FROM Resource res " // + " JOIN res.implicitGroups ig " // + " WHERE ig.id = ? )"); filterOverrides.put("autoGroupResourceTypeId", "source.resourceId IN " // + "( SELECT res.id " // + " FROM Resource res " // + " JOIN res.resourceType type " // + " WHERE type.id = ? )"); filterOverrides.put("autoGroupParentResourceId", "source.resourceId IN " // + "( SELECT res.id " // + " FROM Resource res " // + " JOIN res.parentResource parent " // + " WHERE parent.id = ? )"); filterOverrides.put("severities", "severity IN ( ? )"); } @Override public Class<Event> getPersistentClass() { return Event.class; } public void addFilterId(Integer filterId) { this.filterId = filterId; } public void addFilterDetail(String filterDetail) { this.filterDetail = filterDetail; } public void addFilterSourceName(String filterSourceName) { this.filterSourceName = filterSourceName; } public void addFilterSourceId(Integer sourceId) { this.filterSourceId = sourceId; } public void addFilterStartTime(Long filterStartTime) { this.filterStartTime = filterStartTime; } public void addFilterEndTime(Long filterEndTime) { this.filterEndTime = filterEndTime; } public void addFilterSeverities(EventSeverity... filterSeverities) { if (filterSeverities != null && filterSeverities.length > 0) { this.filterSeverities = Arrays.asList(filterSeverities); } } public void addFilterEntityContext(EntityContext filterEntityContext) { if (filterEntityContext.getType() == EntityContext.Type.Resource) { addFilterResourceId(filterEntityContext.getResourceId()); } else if (filterEntityContext.getType() == EntityContext.Type.ResourceGroup) { addFilterResourceGroupId(filterEntityContext.getGroupId()); } else if (filterEntityContext.getType() == EntityContext.Type.AutoGroup) { addFilterAutoGroupParentResourceId(filterEntityContext.getParentResourceId()); addFilterAutoGroupResourceTypeId(filterEntityContext.getResourceTypeId()); } } public void addFilterResourceId(Integer filterResourceId) { this.filterResourceId = filterResourceId; } public void addFilterResourceGroupId(Integer filterResourceGroupId) { this.filterResourceGroupId = filterResourceGroupId; } public void addFilterAutoGroupResourceTypeId(Integer filterAutoGroupResourceTypeId) { this.filterAutoGroupResourceTypeId = filterAutoGroupResourceTypeId; } public void addFilterAutoGroupParentResourceId(Integer filterAutoGroupParentResourceId) { this.filterAutoGroupParentResourceId = filterAutoGroupParentResourceId; } public void fetchSource(boolean fetchSource) { this.fetchSource = fetchSource; } public void addSortTimestamp(PageOrdering sortTimestamp) { addSortField("timestamp"); this.sortTimestamp = sortTimestamp; } public void addSortSeverity(PageOrdering sortSeverity) { addSortField("severity"); this.sortSeverity = sortSeverity; } }
AmyliaScarlet/amyliascarletlib
src/test/java/com/amyliascarlet/jsontest/bvt/parser/deser/asm/TestASM_List.java
<reponame>AmyliaScarlet/amyliascarletlib package com.amyliascarlet.jsontest.bvt.parser.deser.asm; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import com.amyliascarlet.lib.json.JSON; import com.amyliascarlet.lib.json.serializer.SerializerFeature; public class TestASM_List extends TestCase { public void test_decimal_3() throws Exception { V0 v = new V0(); v.getList().add(new V1()); v.getList().add(new V1()); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue); System.out.println(text); // Assert.assertEquals("{'list':[{},{}]}", text); } public static class V0 { private List<V1> list = new ArrayList<V1>(); public List<V1> getList() { return list; } public void setList(List<V1> list) { this.list = list; } } public static class V1 { private int id; private TimeUnit unit = TimeUnit.SECONDS; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public TimeUnit getUnit() { return unit; } public void setUnit(TimeUnit unit) { this.unit = unit; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
damoresa/nodejs-beginner-examples
2-basics/2-nodejs/singleton-sample/cache.service.js
<reponame>damoresa/nodejs-beginner-examples<filename>2-basics/2-nodejs/singleton-sample/cache.service.js 'use strict'; class CacheService { constructor() { this._cache = {}; } put(key, value) { console.log(`Added ${key}: ${value}`); this._cache[key] = value; } get(key) { return this._cache[key]; } hasKey(key) { return this._cache.hasOwnProperty(key); } getKeys() { return Object.keys(this._cache); } } module.exports = new CacheService();
wt201501/ytlib
ytlib/container/graph_test.cpp
<filename>ytlib/container/graph_test.cpp<gh_stars>0 #include <gtest/gtest.h> #include "graph.hpp" namespace ytlib { // todo 未完成 TEST(GRAPH_TEST, BASE_test) { typedef Graph<uint32_t> myGraph; std::vector<myGraph*> myGraphVec; uint32_t num = 10; for (uint32_t ii = 0; ii < num; ++ii) { myGraphVec.push_back(new myGraph(ii)); } connectGraphNode<uint32_t>(*myGraphVec[0], *myGraphVec[1], 1); connectGraphNode<uint32_t>(*myGraphVec[0], *myGraphVec[5], 2); connectGraphNode<uint32_t>(*myGraphVec[0], *myGraphVec[9], 3); connectGraphNode<uint32_t>(*myGraphVec[1], *myGraphVec[2], 4); connectGraphNode<uint32_t>(*myGraphVec[2], *myGraphVec[8], 5); connectGraphNode<uint32_t>(*myGraphVec[3], *myGraphVec[4], 6); connectGraphNode<uint32_t>(*myGraphVec[3], *myGraphVec[7], 7); connectGraphNode<uint32_t>(*myGraphVec[4], *myGraphVec[5], 8); connectGraphNode<uint32_t>(*myGraphVec[6], *myGraphVec[7], 9); connectGraphNode<uint32_t>(*myGraphVec[6], *myGraphVec[8], 10); connectGraphNode<uint32_t>(*myGraphVec[8], *myGraphVec[9], 11); ASSERT_TRUE(isUndirGraph(myGraphVec)); std::vector<myGraph*> myGraphVec2 = copyGraph(myGraphVec); ASSERT_EQ(myGraphVec.size(), myGraphVec2.size()); for (size_t ii = 0; ii < myGraphVec.size(); ++ii) { ASSERT_NE(myGraphVec[ii], myGraphVec2[ii]); ASSERT_EQ(myGraphVec[ii]->obj, myGraphVec2[ii]->obj); } releaseGraphVec(myGraphVec2); // dfs std::vector<myGraph*> vec; clearFlag(myGraphVec); DFS(*myGraphVec[0], vec); // bfs vec.clear(); clearFlag(myGraphVec); BFS(*myGraphVec[0], vec); //邻接矩阵 g_sideMatrix M = createAdjMatrix<uint32_t>(myGraphVec); std::cout << M << std::endl; std::cout << std::endl; // dijkstra auto dj = dijkstra(*myGraphVec[0], myGraphVec); for (size_t ii = 0; ii < dj.first.size(); ++ii) { std::cout << dj.first[ii] << " "; } std::cout << std::endl; for (size_t ii = 0; ii < dj.first.size(); ++ii) { std::cout << dj.second[ii] << " "; } std::cout << std::endl; std::vector<int32_t> djpath = dijkstraPath(7, dj.second); for (size_t ii = 0; ii < djpath.size(); ++ii) { std::cout << myGraphVec[djpath[ii]]->obj << "-"; } std::cout << std::endl; // floyd auto fl = floyd(myGraphVec); std::cout << fl.first << std::endl; std::cout << std::endl; std::cout << fl.second << std::endl; std::cout << std::endl << std::endl; std::vector<int32_t> flpath = floydPath(0, 7, fl.second); for (size_t ii = 0; ii < flpath.size(); ++ii) { std::cout << myGraphVec[flpath[ii]]->obj << "-"; } std::cout << std::endl; releaseGraphVec(myGraphVec); } } // namespace ytlib
SunFlowerY1/kyuubi
kyuubi-server/src/test/scala/yaooqinn/kyuubi/ha/HighAvailableServiceSuite.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 yaooqinn.kyuubi.ha import java.io.{File, IOException} import org.apache.curator.framework.imps.CuratorFrameworkState import org.apache.spark.{KyuubiConf, KyuubiSparkUtil, SparkConf, SparkFunSuite} import org.apache.zookeeper.{WatchedEvent, Watcher, ZooDefs} import org.apache.zookeeper.KeeperException.ConnectionLossException import org.apache.zookeeper.Watcher.Event.KeeperState import org.scalatest.{BeforeAndAfterEach, Matchers} import yaooqinn.kyuubi.SecuredFunSuite import yaooqinn.kyuubi.server.{FrontendService, KyuubiServer} import yaooqinn.kyuubi.service.ServiceException class HighAvailableServiceSuite extends SparkFunSuite with Matchers with SecuredFunSuite with ZookeeperFunSuite with BeforeAndAfterEach { private var server: KyuubiServer = _ private var haService: HighAvailableService = _ conf.set(KyuubiConf.HA_MODE.key, "failover") override def beforeEach(): Unit = { server = new KyuubiServer() haService = new HighAvailableService("test", server) { override def reset(): Unit = {} } super.beforeEach() } override def afterEach(): Unit = { if (server != null) { server.stop() } if (haService != null) { haService.stop() } super.afterEach() } test("ACL Provider") { val aclProvider = HighAvailableService.aclProvider aclProvider.getDefaultAcl should be(ZooDefs.Ids.OPEN_ACL_UNSAFE) aclProvider.getAclForPath("") should be(ZooDefs.Ids.OPEN_ACL_UNSAFE) tryWithSecurityEnabled { assert(aclProvider.getDefaultAcl.containsAll(ZooDefs.Ids.READ_ACL_UNSAFE)) assert(aclProvider.getDefaultAcl.containsAll(ZooDefs.Ids.CREATOR_ALL_ACL)) } } test("New Zookeeper Client") { val client = HighAvailableService.newZookeeperClient(conf) client.getState should be(CuratorFrameworkState.STARTED) } test("Get Quorum Servers") { val conf = new SparkConf(true) val e = intercept[IllegalArgumentException](HighAvailableService.getQuorumServers(conf)) e.getMessage should startWith(KyuubiConf.HA_ZOOKEEPER_QUORUM.key) val host1 = "127.0.0.1:1234" val host2 = "127.0.0.1" conf.set(KyuubiConf.HA_ZOOKEEPER_QUORUM.key, host1) HighAvailableService.getQuorumServers(conf) should be(host1) conf.set(KyuubiConf.HA_ZOOKEEPER_QUORUM.key, host1 + "," + host2) HighAvailableService.getQuorumServers(conf) should be(host1 + "," + host2 + ":2181") val port = "2180" conf.set(KyuubiConf.HA_ZOOKEEPER_CLIENT_PORT.key, port) HighAvailableService.getQuorumServers(conf) should be(host1 + "," + host2 + ":" + port) } test("get service instance uri") { val fe = new FrontendService(server.beService) intercept[ServiceException](HighAvailableService.getServerInstanceURI(null)) fe.getServerIPAddress intercept[ServiceException](HighAvailableService.getServerInstanceURI(fe)) fe.init(conf) HighAvailableService.getServerInstanceURI(fe) should startWith( fe.getServerIPAddress.getHostName) } test("set up zookeeper auth") { tryWithSecurityEnabled { val keytab = File.createTempFile("user", "keytab") val principal = KyuubiSparkUtil.getCurrentUserName + "/localhost@" + "yaooqinn" conf.set(KyuubiSparkUtil.KEYTAB, keytab.getCanonicalPath) conf.set(KyuubiSparkUtil.PRINCIPAL, principal) HighAvailableService.setUpZooKeeperAuth(conf) conf.set(KyuubiSparkUtil.KEYTAB, keytab.getName) val e = intercept[IOException](HighAvailableService.setUpZooKeeperAuth(conf)) e.getMessage should startWith(KyuubiSparkUtil.KEYTAB) } } test("init") { // connect to right zk haService.init(conf) // connect to wrong zk val confClone = conf.clone() .set(KyuubiConf.HA_ZOOKEEPER_QUORUM.key, connectString.split(":")(0)) .set(KyuubiConf.HA_ZOOKEEPER_CLIENT_PORT.key, "2000") val e1 = intercept[ServiceException](haService.init(confClone)) e1.getMessage should startWith("Unable to create Kyuubi namespace") assert(e1.getCause.isInstanceOf[ConnectionLossException]) } test("deregister watcher") { val ha = new HighAvailableService("ha", server) { self => override def reset(): Unit = {} } import Watcher.Event.EventType._ val watcher = new ha.DeRegisterWatcher val nodeDel = new WatchedEvent(NodeDeleted, KeeperState.Expired, "") watcher.process(nodeDel) watcher.process(new WatchedEvent(NodeCreated, KeeperState.Expired, "")) } }
SuperMap/GAF
gaf-cloud/gaf-commons/gaf-common-auth/src/main/java/com/supermap/gaf/shiro/commontypes/Permission.java
<reponame>SuperMap/GAF /* * Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html. */ package com.supermap.gaf.shiro.commontypes; import java.util.List; import com.alibaba.fastjson.annotation.JSONField; /** * @author:yj * @date:2021/3/25 */ public class Permission { @JSONField(name = "rsid") private String resourceId; @JSONField(name = "rsname") private String resourceName; private List<String> scopes; public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public List<String> getScopes() { return scopes; } public void setScopes(List<String> scopes) { this.scopes = scopes; } }
FriendsOfShopware/go-shopware-admin-api-sdk
repo_number_range_state.go
<filename>repo_number_range_state.go<gh_stars>1-10 package go_shopware_admin_sdk import ( "net/http" "time" ) type NumberRangeStateRepository ClientService func (t NumberRangeStateRepository) Search(ctx ApiContext, criteria Criteria) (*NumberRangeStateCollection, *http.Response, error) { req, err := t.Client.NewRequest(ctx, "POST", "/api/search/number-range-state", criteria) if err != nil { return nil, nil, err } uResp := new(NumberRangeStateCollection) resp, err := t.Client.Do(ctx.Context, req, uResp) if err != nil { return nil, resp, err } return uResp, resp, nil } func (t NumberRangeStateRepository) SearchAll(ctx ApiContext, criteria Criteria) (*NumberRangeStateCollection, *http.Response, error) { if criteria.Limit == 0 { criteria.Limit = 50 } if criteria.Page == 0 { criteria.Page = 1 } c, resp, err := t.Search(ctx, criteria) if err != nil { return c, resp, err } for { criteria.Page++ nextC, nextResp, nextErr := t.Search(ctx, criteria) if nextErr != nil { return c, nextResp, nextErr } if len(nextC.Data) == 0 { break } c.Data = append(c.Data, nextC.Data...) } c.Total = int64(len(c.Data)) return c, resp, err } func (t NumberRangeStateRepository) SearchIds(ctx ApiContext, criteria Criteria) (*SearchIdsResponse, *http.Response, error) { req, err := t.Client.NewRequest(ctx, "POST", "/api/search-ids/number-range-state", criteria) if err != nil { return nil, nil, err } uResp := new(SearchIdsResponse) resp, err := t.Client.Do(ctx.Context, req, uResp) if err != nil { return nil, resp, err } return uResp, resp, nil } func (t NumberRangeStateRepository) Upsert(ctx ApiContext, entity []NumberRangeState) (*http.Response, error) { return t.Client.Bulk.Sync(ctx, map[string]SyncOperation{"number_range_state": { Entity: "number_range_state", Action: "upsert", Payload: entity, }}) } func (t NumberRangeStateRepository) Delete(ctx ApiContext, ids []string) (*http.Response, error) { payload := make([]entityDelete, 0) for _, id := range ids { payload = append(payload, entityDelete{Id: id}) } return t.Client.Bulk.Sync(ctx, map[string]SyncOperation{"number_range_state": { Entity: "number_range_state", Action: "delete", Payload: payload, }}) } type NumberRangeState struct { Id string `json:"id,omitempty"` NumberRangeId string `json:"numberRangeId,omitempty"` LastValue float64 `json:"lastValue,omitempty"` NumberRange *NumberRange `json:"numberRange,omitempty"` CreatedAt time.Time `json:"createdAt,omitempty"` UpdatedAt time.Time `json:"updatedAt,omitempty"` } type NumberRangeStateCollection struct { EntityCollection Data []NumberRangeState `json:"data"` }
OlivierLAVAUD/hyperledger
orderer/multichain/manager.go
<reponame>OlivierLAVAUD/hyperledger /* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package multichain import ( "fmt" "github.com/hyperledger/fabric/common/cauthdsl" "github.com/hyperledger/fabric/common/configtx" "github.com/hyperledger/fabric/common/policies" "github.com/hyperledger/fabric/orderer/common/sharedconfig" "github.com/hyperledger/fabric/orderer/rawledger" cb "github.com/hyperledger/fabric/protos/common" "github.com/hyperledger/fabric/protos/utils" "github.com/op/go-logging" "github.com/golang/protobuf/proto" ) var logger = logging.MustGetLogger("orderer/multichain") // XXX This crypto helper is a stand in until we have a real crypto handler // it considers all signatures to be valid type xxxCryptoHelper struct{} func (xxx xxxCryptoHelper) VerifySignature(sd *cb.SignedData) error { return nil } func (xxx xxxCryptoHelper) NewSignatureHeader() *cb.SignatureHeader { return &cb.SignatureHeader{} } func (xxx xxxCryptoHelper) Sign(message []byte) []byte { return message } // Signer is a temporary stub interface which will be implemented by the local MSP type Signer interface { // NewSignatureHeader creates a SignatureHeader with the correct signing identity and a valid nonce NewSignatureHeader() *cb.SignatureHeader // Sign a message which should embed a signature header created by NewSignatureHeader Sign(message []byte) []byte } // Manager coordinates the creation and access of chains type Manager interface { // GetChain retrieves the chain support for a chain (and whether it exists) GetChain(chainID string) (ChainSupport, bool) // ProposeChain accepts a configuration transaction for a chain which does not already exists // The status returned is whether the proposal is accepted for consideration, only after consensus // occurs will the proposal be committed or rejected ProposeChain(env *cb.Envelope) cb.Status } type multiLedger struct { chains map[string]*chainSupport consenters map[string]Consenter ledgerFactory rawledger.Factory sysChain *systemChain } func getConfigTx(reader rawledger.Reader) *cb.Envelope { lastBlock := rawledger.GetBlock(reader, reader.Height()-1) index, err := utils.GetLastConfigurationIndexFromBlock(lastBlock) if err != nil { logger.Panicf("Chain did not have appropriately encoded last configuration in its latest block: %s", err) } configBlock := rawledger.GetBlock(reader, index) if configBlock == nil { logger.Panicf("Configuration block does not exist") } return utils.ExtractEnvelopeOrPanic(configBlock, 0) } // NewManagerImpl produces an instance of a Manager func NewManagerImpl(ledgerFactory rawledger.Factory, consenters map[string]Consenter) Manager { ml := &multiLedger{ chains: make(map[string]*chainSupport), ledgerFactory: ledgerFactory, consenters: consenters, } existingChains := ledgerFactory.ChainIDs() for _, chainID := range existingChains { rl, err := ledgerFactory.GetOrCreate(chainID) if err != nil { logger.Fatalf("Ledger factory reported chainID %s but could not retrieve it: %s", chainID, err) } configTx := getConfigTx(rl) if configTx == nil { logger.Fatalf("Could not find configuration transaction for chain %s", chainID) } configManager, policyManager, backingLedger, sharedConfigManager := ml.newResources(configTx) chainID := configManager.ChainID() if sharedConfigManager.ChainCreators() != nil { if ml.sysChain != nil { logger.Fatalf("There appear to be two system chains %s and %s", ml.sysChain.support.ChainID(), chainID) } logger.Debugf("Starting with system chain: %x", chainID) chain := newChainSupport(createSystemChainFilters(ml, configManager, policyManager, sharedConfigManager), configManager, policyManager, backingLedger, sharedConfigManager, consenters, &xxxCryptoHelper{}) ml.chains[string(chainID)] = chain ml.sysChain = newSystemChain(chain) // We delay starting this chain, as it might try to copy and replace the chains map via newChain before the map is fully built defer chain.start() } else { logger.Debugf("Starting chain: %x", chainID) chain := newChainSupport(createStandardFilters(configManager, policyManager, sharedConfigManager), configManager, policyManager, backingLedger, sharedConfigManager, consenters, &xxxCryptoHelper{}) ml.chains[string(chainID)] = chain chain.start() } } return ml } // ProposeChain accepts a configuration transaction for a chain which does not already exists // The status returned is whether the proposal is accepted for consideration, only after consensus // occurs will the proposal be committed or rejected func (ml *multiLedger) ProposeChain(env *cb.Envelope) cb.Status { return ml.sysChain.proposeChain(env) } // GetChain retrieves the chain support for a chain (and whether it exists) func (ml *multiLedger) GetChain(chainID string) (ChainSupport, bool) { cs, ok := ml.chains[chainID] return cs, ok } func newConfigTxManagerAndHandlers(configEnvelope *cb.ConfigurationEnvelope) (configtx.Manager, policies.Manager, sharedconfig.Manager, error) { policyProviderMap := make(map[int32]policies.Provider) for pType := range cb.Policy_PolicyType_name { rtype := cb.Policy_PolicyType(pType) switch rtype { case cb.Policy_UNKNOWN: // Do not register a handler case cb.Policy_SIGNATURE: policyProviderMap[pType] = cauthdsl.NewPolicyProvider( cauthdsl.NewMockDeserializer()) // FIXME: here we should pass in the orderer MSP as soon as it's ready case cb.Policy_MSP: // Add hook for MSP Handler here } } policyManager := policies.NewManagerImpl(policyProviderMap) sharedConfigManager := sharedconfig.NewManagerImpl() configHandlerMap := make(map[cb.ConfigurationItem_ConfigurationType]configtx.Handler) for ctype := range cb.ConfigurationItem_ConfigurationType_name { rtype := cb.ConfigurationItem_ConfigurationType(ctype) switch rtype { case cb.ConfigurationItem_Policy: configHandlerMap[rtype] = policyManager case cb.ConfigurationItem_Orderer: configHandlerMap[rtype] = sharedConfigManager default: configHandlerMap[rtype] = configtx.NewBytesHandler() } } configManager, err := configtx.NewConfigurationManager(configEnvelope, policyManager, configHandlerMap) if err != nil { return nil, nil, nil, fmt.Errorf("Error unpacking configuration transaction: %s", err) } return configManager, policyManager, sharedConfigManager, nil } func (ml *multiLedger) newResources(configTx *cb.Envelope) (configtx.Manager, policies.Manager, rawledger.ReadWriter, sharedconfig.Manager) { payload := &cb.Payload{} err := proto.Unmarshal(configTx.Payload, payload) if err != nil { logger.Fatalf("Error unmarshaling a config transaction payload: %s", err) } configEnvelope := &cb.ConfigurationEnvelope{} err = proto.Unmarshal(payload.Data, configEnvelope) if err != nil { logger.Fatalf("Error unmarshaling a config transaction to config envelope: %s", err) } configManager, policyManager, sharedConfigManager, err := newConfigTxManagerAndHandlers(configEnvelope) if err != nil { logger.Fatalf("Error creating configtx manager and handlers: %s", err) } chainID := configManager.ChainID() ledger, err := ml.ledgerFactory.GetOrCreate(chainID) if err != nil { logger.Fatalf("Error getting ledger for %s", chainID) } return configManager, policyManager, ledger, sharedConfigManager } func (ml *multiLedger) systemChain() *systemChain { return ml.sysChain } func (ml *multiLedger) newChain(configtx *cb.Envelope) { configManager, policyManager, backingLedger, sharedConfig := ml.newResources(configtx) backingLedger.Append(rawledger.CreateNextBlock(backingLedger, []*cb.Envelope{configtx})) // Copy the map to allow concurrent reads from broadcast/deliver while the new chainSupport is newChains := make(map[string]*chainSupport) for key, value := range ml.chains { newChains[key] = value } cs := newChainSupport(createStandardFilters(configManager, policyManager, sharedConfig), configManager, policyManager, backingLedger, sharedConfig, ml.consenters, &xxxCryptoHelper{}) chainID := configManager.ChainID() logger.Debugf("Created and starting new chain %s", chainID) newChains[string(chainID)] = cs cs.start() ml.chains = newChains }
JasperFloorBloomreach/gov-scot
repository-data/webfiles/test/specs/pubsub_spec.js
// 'use strict'; // jasmine.getFixtures().fixturesPath = 'base/test/fixtures'; // import pubsub from '../../src/scripts/govscot/pubsub'; // describe('"Pubsub"', function () { // });
chengc017/cat
cat-home/src/main/java/com/dianping/cat/report/task/notify/AppDataComparisonNotifier.java
<filename>cat-home/src/main/java/com/dianping/cat/report/task/notify/AppDataComparisonNotifier.java package com.dianping.cat.report.task.notify; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.unidal.helper.Splitters; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.util.StringUtils; import com.dianping.cat.Cat; import com.dianping.cat.config.app.AppComparisonConfigManager; import com.dianping.cat.config.app.AppConfigManager; import com.dianping.cat.configuration.app.comparison.entity.AppComparison; import com.dianping.cat.configuration.app.comparison.entity.AppComparisonConfig; import com.dianping.cat.configuration.app.comparison.entity.Item; import com.dianping.cat.message.Transaction; import com.dianping.cat.report.page.app.service.AppDataService; import com.dianping.cat.report.page.app.service.CommandQueryEntity; import com.dianping.cat.report.alert.sender.AlertChannel; import com.dianping.cat.report.alert.sender.AlertMessageEntity; import com.dianping.cat.report.alert.sender.sender.SenderManager; import com.dianping.cat.report.task.notify.render.AppDataComparisonRender; public class AppDataComparisonNotifier { @Inject private AppDataService m_appDataService; @Inject private AppComparisonConfigManager m_appComparisonConfigManager; @Inject private AppConfigManager m_appConfigManager; @Inject private SenderManager m_sendManager; @Inject private AppDataComparisonRender m_render; private SimpleDateFormat m_sdf = new SimpleDateFormat("yyyy-MM-dd"); public void doNotifying(Date period) { Transaction t = Cat.newTransaction("AppDataComparitonNotifier", m_sdf.format(period)); try { Map<String, AppDataComparisonResult> results = buildAppDataComparisonResults(period, m_appComparisonConfigManager.getConfig()); Map<List<String>, List<AppDataComparisonResult>> results2Receivers = buildReceivers2Results(results); for (Entry<List<String>, List<AppDataComparisonResult>> entry : results2Receivers.entrySet()) { notify(period, entry.getValue(), entry.getKey()); } t.setStatus(Transaction.SUCCESS); } catch (Exception e) { t.setStatus(e); } finally { t.complete(); } } private Set<String> buildAllUsers(Map<String, AppDataComparisonResult> results) { Set<String> allUsers = new HashSet<String>(); for (Entry<String, AppDataComparisonResult> entry : results.entrySet()) { AppDataComparisonResult result = entry.getValue(); String id = result.getId(); allUsers.addAll(m_appComparisonConfigManager.queryEmails(id)); } return allUsers; } private Map<String, String> buildUser2Ids(Set<String> allUsers, Map<String, AppDataComparisonResult> results) { Map<String, String> user2Id = new HashMap<String, String>(); for (String user : allUsers) { for (Entry<String, AppDataComparisonResult> entry : results.entrySet()) { AppDataComparisonResult result = entry.getValue(); String id = result.getId(); String emails = m_appComparisonConfigManager.queryEmailStr(id); if (emails.contains(user)) { String ids = user2Id.get(user); if (StringUtils.isEmpty(ids)) { user2Id.put(user, id); } else { user2Id.put(user, ids + "," + id); } } } } return user2Id; } private Map<String, String> buildid2Users(Map<String, String> user2Id) { Map<String, String> id2Users = new HashMap<String, String>(); for (Entry<String, String> entry : user2Id.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String users = user2Id.get(value); if (StringUtils.isEmpty(users)) { id2Users.put(value, key); } else { id2Users.put(value, users + "," + value); } } return id2Users; } private Map<List<String>, List<AppDataComparisonResult>> buildReceivers2Results( Map<String, AppDataComparisonResult> results) { Set<String> allUsers = buildAllUsers(results); Map<String, String> user2Ids = buildUser2Ids(allUsers, results); Map<String, String> id2Users = buildid2Users(user2Ids); Map<List<String>, List<AppDataComparisonResult>> users2Results = buildUsers2Results(id2Users, results); return users2Results; } private Map<List<String>, List<AppDataComparisonResult>> buildUsers2Results(Map<String, String> id2Users, Map<String, AppDataComparisonResult> results) { Map<List<String>, List<AppDataComparisonResult>> users2Results = new HashMap<List<String>, List<AppDataComparisonResult>>(); for (Entry<String, String> entry : id2Users.entrySet()) { List<String> emails = Splitters.by(",").noEmptyItem().split(entry.getValue()); List<String> ids = Splitters.by(",").noEmptyItem().split(entry.getKey()); List<AppDataComparisonResult> userResults = new ArrayList<AppDataComparisonResult>(); for (String id : ids) { userResults.add(results.get(id)); } users2Results.put(emails, userResults); } return users2Results; } private void notify(Date yesterday, List<AppDataComparisonResult> results, List<String> emails) { String title = renderTitle(); String content = m_render.renderReport(yesterday, results); AlertMessageEntity message = new AlertMessageEntity("", title, "AppDataComparison", content, emails); m_sendManager.sendAlert(AlertChannel.MAIL, message); } private String renderTitle() { return "CAT端到端报告"; } private Map<String, AppDataComparisonResult> buildAppDataComparisonResults(Date date, AppComparisonConfig config) { Map<String, AppDataComparisonResult> results = new LinkedHashMap<String, AppDataComparisonResult>(); for (Entry<String, AppComparison> entry : config.getAppComparisons().entrySet()) { AppDataComparisonResult result = queryDelay4AppComparison(date, entry.getValue()); results.put(entry.getKey(), result); } return results; } private AppDataComparisonResult queryDelay4AppComparison(Date yesterday, AppComparison appComparison) { String id = appComparison.getId(); AppDataComparisonResult result = new AppDataComparisonResult(); result.setId(id); for (Item item : appComparison.getItems()) { try { String itemId = item.getId(); String command = item.getCommand(); double delay = queryOneDayDelay4Command(yesterday, command); result.addItem(itemId, command, delay); } catch (Exception e) { Cat.logError(e); } } return result; } private double queryOneDayDelay4Command(Date yesterday, String url) { String yesterdayStr = m_sdf.format(yesterday); Integer command = m_appConfigManager.getCommands().get(url); if (command != null) { CommandQueryEntity entity = new CommandQueryEntity(yesterdayStr + ";" + command + ";;;;;;;;;"); return m_appDataService.queryOneDayDelayAvg(entity); } else { throw new RuntimeException("Unrecognized command configuration in app comparison config, command id: " + url); } } }
dplopez09/CursoJAva
src/javaadvanced/viernes/networking/Socket1/Cliente.java
<gh_stars>0 package javaadvanced.viernes.networking.Socket1; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class Cliente { public static void main(String[] args) { try{ Socket s= new Socket("localhost",3000); DataOutputStream dot= new DataOutputStream(s.getOutputStream()); dot.writeUTF("Hola servidor"); dot.flush(); dot.close(); s.close(); }catch(IOException ioe){ioe.printStackTrace();} } }
AjabShahar/Ajab-Shahar-TW
web/app/user/js/common/directives/soundCloud/soundcloud_player.js
<reponame>AjabShahar/Ajab-Shahar-TW mediaPlayer.directive('soundCloud', function ($http, $compile) { return { restrict: "E", scope: { height: "@", width: "@", audioUrl: '@', shouldStopVideo: '&' }, link: function (scope, element) { scope.$watch("audioUrl",function(newValue){ scope.maxHeight = scope.maxHeight || ""; scope.maxWidth = scope.maxWidth || ""; var soundcloudOembedUrl = "https://soundcloud.com/oembed.json?show_comments=false&"; var embedOptions = "url=" + scope.audioUrl + "&maxheight=" + scope.maxHeight + "&maxwidth=" + scope.maxWidth; $http.get(soundcloudOembedUrl + embedOptions) .success(function (response) { element.html(response.html).show(); $compile(element.contents())(scope); }) .error(function(response){ element.html("<div></div>").show(); $compile(element.contents())(scope); }); }); } }; });
Andreas237/AndroidPolicyAutomation
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/jakewharton/rxbinding/widget/AdapterDataChangeOnSubscribe$2.java
<filename>ExtractedJars/PACT_com.pactforcure.app/javafiles/com/jakewharton/rxbinding/widget/AdapterDataChangeOnSubscribe$2.java // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.jakewharton.rxbinding.widget; import android.database.DataSetObserver; import android.widget.Adapter; import com.jakewharton.rxbinding.internal.MainThreadSubscription; // Referenced classes of package com.jakewharton.rxbinding.widget: // AdapterDataChangeOnSubscribe class AdapterDataChangeOnSubscribe$2 extends MainThreadSubscription { protected void onUnsubscribe() { AdapterDataChangeOnSubscribe.access$000(AdapterDataChangeOnSubscribe.this).unregisterDataSetObserver(val$observer); // 0 0:aload_0 // 1 1:getfield #17 <Field AdapterDataChangeOnSubscribe this$0> // 2 4:invokestatic #28 <Method Adapter AdapterDataChangeOnSubscribe.access$000(AdapterDataChangeOnSubscribe)> // 3 7:aload_0 // 4 8:getfield #19 <Field DataSetObserver val$observer> // 5 11:invokeinterface #34 <Method void Adapter.unregisterDataSetObserver(DataSetObserver)> // 6 16:return } final AdapterDataChangeOnSubscribe this$0; final DataSetObserver val$observer; AdapterDataChangeOnSubscribe$2() { this$0 = final_adapterdatachangeonsubscribe; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #17 <Field AdapterDataChangeOnSubscribe this$0> val$observer = DataSetObserver.this; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #19 <Field DataSetObserver val$observer> super(); // 6 10:aload_0 // 7 11:invokespecial #22 <Method void MainThreadSubscription()> // 8 14:return } }
spraetor/amdis2
src/ProblemInstat.hpp
<reponame>spraetor/amdis2 #pragma once #include "AdaptInstationary.hpp" #include "ProblemStat.hpp" #include "ProblemTimeInterface.hpp" namespace AMDiS { /** * \ingroup Problem * * \brief * Base class for \ref ProblemInstat. */ class ProblemInstatBase : public ProblemTimeInterface, public ProblemStatBase // NOTE: Why is this derived from ProblemStatBase { public: /// Constructor. ProblemInstatBase(std::string probName, ProblemStatBase* initialProb) : name(probName), initialProblem(initialProb ? initialProb : this) {} /// Destructor. virtual ~ProblemInstatBase() {} /// Implementation of \ref ProblemTimeInterface::setTime(). virtual void setTime(AdaptInfo& adaptInfo) override { cTime = adaptInfo.getTime(); tau = adaptInfo.getTimestep(); invTau = 1.0 / tau; } void solve(AdaptInfo& /*adaptInfo*/) {} /// Implementation of \ref ProblemStatBase::solve(). virtual void solve(AdaptInfo& adaptInfo, bool, bool) override { solve(adaptInfo); } /// Implementation of \ref ProblemStatBase::estimate(). virtual void estimate(AdaptInfo& /*adaptInfo*/) override {} /// Implementation of \ref ProblemStatBase::buildBeforeRefine(). virtual void buildBeforeRefine(AdaptInfo& /*adaptInfo*/, Flag) override {} /// Implementation of \ref ProblemStatBase::buildBeforeCoarsen(). virtual void buildBeforeCoarsen(AdaptInfo& /*adaptInfo*/, Flag) override {} /// Implementation of \ref ProblemStatBase::buildAfterCoarsen(). virtual void buildAfterCoarsen(AdaptInfo& /*adaptInfo*/, Flag, bool, bool) override {} /// Implementation of \ref ProblemStatBase::markElements(). virtual Flag markElements(AdaptInfo& /*adaptInfo*/) override { return {0}; } /// Implementation of \ref ProblemStatBase::refineMesh(). virtual Flag refineMesh(AdaptInfo& /*adaptInfo*/) override { return {0}; } /// Implementation of \ref ProblemStatBase::coarsenMesh(). virtual Flag coarsenMesh(AdaptInfo& /*adaptInfo*/) override { return {0}; } /// Implementation of \ref ProblemTimeInterface::closeTimestep(). virtual void closeTimestep(AdaptInfo& /*adaptInfo*/) override {} /// Implementation of \ref ProblemStatBase::getName(). std::string getName() const { return name; } /// Implementation of \ref ProblemTimeInterface::solveInitialProblem(). virtual void solveInitialProblem(AdaptInfo& adaptInfo) override; double* getTime() { return &cTime; } double* getTau() { return &tau; } double* getInvTau() { return &invTau; } protected: /// Name of the problem. std::string name; ProblemStatBase* initialProblem; /// Time double cTime = 0.0; /// Timestep double tau = 1.0; /// 1 / timestep double invTau = 1.0; }; /** * \ingroup Problem * * \brief * Standard implementation of ProblemTimeInterface for a time * dependent problems. */ class ProblemInstat : public ProblemInstatBase { public: /// Constructs a ProblemInstatVec with prob as its stationary problem. ProblemInstat(std::string name, ProblemStatSeq& prob) : ProblemInstatBase(name, NULL), problemStat(prob) {} ProblemInstat(std::string name, ProblemStatSeq& prob, ProblemStatBase& initialProb) : ProblemInstatBase(name, &initialProb), problemStat(prob) {} /// Destructor. virtual ~ProblemInstat(); /// Initialisation of the problem. virtual void initialize(Flag initFlag, ProblemInstat* adoptProblem = NULL, Flag adoptFlag = INIT_NOTHING); /// Used in \ref initialize(). virtual void createUhOld(); /// Implementation of \ref ProblemTimeInterface::initTimestep(). virtual void initTimestep(AdaptInfo& adaptInfo) override; /// Implementation of \ref ProblemTimeInterface::closeTimestep(). virtual void closeTimestep(AdaptInfo& adaptInfo) override; /// Returns \ref problemStat. ProblemStatSeq& getStatProblem() { return problemStat; } /// Returns \ref oldSolution. SystemVector* getOldSolution() { return oldSolution; } DOFVector<double>* getOldSolution(int i) { return oldSolution->getDOFVector(i); } /// Implementation of \ref ProblemTimeInterface::transferInitialSolution(). virtual void transferInitialSolution(AdaptInfo& adaptInfo); protected: /// Space problem solved in each timestep. ProblemStatSeq& problemStat; /// Solution of the last timestep. SystemVector* oldSolution = NULL; /// In parallel computations, we want to print the overall computational time /// that is used for one timestep. #ifdef HAVE_PARALLEL_DOMAIN_AMDIS double lastTimepoint = 0.0; #endif }; } // end namespace AMDiS
AaronGlanville/Barry
barry/models/bao_correlation_Beutler2017.py
<gh_stars>0 import logging import numpy as np from barry.models.bao_correlation import CorrelationFunctionFit class CorrBeutler2017(CorrelationFunctionFit): """ xi(s) model inspired from Beutler 2017 and Ross 2015. """ def __init__(self, name="<NAME>", smooth_type="hinton2017", fix_params=("om"), smooth=False, correction=None): super().__init__(name, smooth_type, fix_params, smooth, correction=correction) def declare_parameters(self): # Define parameters super().declare_parameters() self.add_param("sigma_nl", r"$\Sigma_{NL}$", 1.0, 20.0, 1.0) # dampening self.add_param("a1", r"$a_1$", -100, 100, 0) # Polynomial marginalisation 1 self.add_param("a2", r"$a_2$", -2, 2, 0) # Polynomial marginalisation 2 self.add_param("a3", r"$a_3$", -0.2, 0.2, 0) # Polynomial marginalisation 3 def compute_correlation_function(self, d, p, smooth=False): # Get base linear power spectrum from camb ks = self.camb.ks pk_smooth, pk_ratio_dewiggled = self.compute_basic_power_spectrum(p["om"]) # Blend the two if smooth: pk_dewiggled = pk_smooth else: pk_linear_weight = np.exp(-0.5 * (ks * p["sigma_nl"]) ** 2) pk_dewiggled = (pk_linear_weight * (1 + pk_ratio_dewiggled) + (1 - pk_linear_weight)) * pk_smooth # Convert to correlation function and take alpha into account xi = self.pk2xi(ks, pk_dewiggled, d * p["alpha"]) # Polynomial shape shape = p["a1"] / (d ** 2) + p["a2"] / d + p["a3"] # Add poly shape to xi model, include bias correction model = xi * p["b"] + shape return model if __name__ == "__main__": import sys import timeit from barry.datasets.dataset_correlation_function import CorrelationFunction_SDSS_DR12_Z061_NGC sys.path.append("../..") logging.basicConfig(level=logging.DEBUG, format="[%(levelname)7s |%(funcName)20s] %(message)s") logging.getLogger("matplotlib").setLevel(logging.ERROR) dataset = CorrelationFunction_SDSS_DR12_Z061_NGC(recon=False) data = dataset.get_data() model_pre = CorrBeutler2017() model_pre.set_data(data) dataset = CorrelationFunction_SDSS_DR12_Z061_NGC(recon=True) data = dataset.get_data() model_post = CorrBeutler2017() model_post.set_data(data) p = {"om": 0.3, "alpha": 1.0, "sigma_nl": 5.0, "sigma_s": 5, "b": 2.0, "a1": 0, "a2": 0, "a3": 0, "a4": 0, "a5": 0} n = 200 def test_pre(): model_pre.get_likelihood(p, data[0]) def test_post(): model_post.get_likelihood(p, data[0]) print("Pre-reconstruction likelihood takes on average, %.2f milliseconds" % (timeit.timeit(test_pre, number=n) * 1000 / n)) print("Post-reconstruction likelihood takes on average, %.2f milliseconds" % (timeit.timeit(test_post, number=n) * 1000 / n)) if True: p, minv = model_pre.optimize() print("Pre reconstruction optimisation:") print(p) print(minv) model_pre.plot(p) print("Post reconstruction optimisation:") p, minv = model_post.optimize() print(p) print(minv) model_post.plot(p)
ScalablyTyped/SlinkyTyped
r/react-native-elements/src/main/scala/typingsSlinky/reactNativeElements/anon/ViewPropertiesrightboolea.scala
package typingsSlinky.reactNativeElements.anon import slinky.core.SyntheticEvent import typingsSlinky.reactNative.anon.Layout import typingsSlinky.reactNative.anon.ReadonlyactionNamestring import typingsSlinky.reactNative.mod.AccessibilityActionInfo import typingsSlinky.reactNative.mod.AccessibilityRole import typingsSlinky.reactNative.mod.AccessibilityState import typingsSlinky.reactNative.mod.AccessibilityTrait import typingsSlinky.reactNative.mod.AccessibilityValue import typingsSlinky.reactNative.mod.Insets import typingsSlinky.reactNative.mod.NativeTouchEvent import typingsSlinky.reactNative.mod.NodeHandle import typingsSlinky.reactNative.mod.StyleProp import typingsSlinky.reactNative.mod.TVParallaxProperties import typingsSlinky.reactNative.mod.ViewStyle import typingsSlinky.reactNativeElements.reactNativeElementsStrings.`box-none` import typingsSlinky.reactNativeElements.reactNativeElementsStrings.`box-only` import typingsSlinky.reactNativeElements.reactNativeElementsStrings.`no-hide-descendants` import typingsSlinky.reactNativeElements.reactNativeElementsStrings.assertive import typingsSlinky.reactNativeElements.reactNativeElementsStrings.auto import typingsSlinky.reactNativeElements.reactNativeElementsStrings.button import typingsSlinky.reactNativeElements.reactNativeElementsStrings.no import typingsSlinky.reactNativeElements.reactNativeElementsStrings.none import typingsSlinky.reactNativeElements.reactNativeElementsStrings.polite import typingsSlinky.reactNativeElements.reactNativeElementsStrings.radiobutton_checked import typingsSlinky.reactNativeElements.reactNativeElementsStrings.radiobutton_unchecked import typingsSlinky.reactNativeElements.reactNativeElementsStrings.yes import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /* Inlined react-native.react-native.ViewProperties & { right :boolean | undefined} */ @js.native trait ViewPropertiesrightboolea extends StObject { /** * Provides an array of custom actions available for accessibility. */ var accessibilityActions: js.UndefOr[js.Array[AccessibilityActionInfo]] = js.native /** * In some cases, we also want to alert the end user of the type of selected component (i.e., that it is a “button”). * If we were using native buttons, this would work automatically. Since we are using javascript, we need to * provide a bit more context for TalkBack. To do so, you must specify the ‘accessibilityComponentType’ property * for any UI component. For instances, we support ‘button’, ‘radiobutton_checked’ and ‘radiobutton_unchecked’ and so on. * @platform android */ var accessibilityComponentType: js.UndefOr[none | button | radiobutton_checked | radiobutton_unchecked] = js.native /** * A Boolean value indicating whether the accessibility elements contained within this accessibility element * are hidden to the screen reader. * @platform ios */ var accessibilityElementsHidden: js.UndefOr[Boolean] = js.native /** * An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not obvious from the accessibility label. */ var accessibilityHint: js.UndefOr[String] = js.native /** * https://reactnative.dev/docs/accessibility#accessibilityignoresinvertcolorsios * @platform ios */ var accessibilityIgnoresInvertColors: js.UndefOr[Boolean] = js.native /** * Overrides the text that's read by the screen reader when the user interacts with the element. By default, the * label is constructed by traversing all the children and accumulating all the Text nodes separated by space. */ var accessibilityLabel: js.UndefOr[String] = js.native /** * Indicates to accessibility services whether the user should be notified when this view changes. * Works for Android API >= 19 only. * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references. * @platform android */ var accessibilityLiveRegion: js.UndefOr[none | polite | assertive] = js.native /** * Accessibility Role tells a person using either VoiceOver on iOS or TalkBack on Android the type of element that is focused on. */ var accessibilityRole: js.UndefOr[AccessibilityRole] = js.native /** * Accessibility State tells a person using either VoiceOver on iOS or TalkBack on Android the state of the element currently focused on. */ var accessibilityState: js.UndefOr[AccessibilityState] = js.native /** * Accessibility traits tell a person using VoiceOver what kind of element they have selected. * Is this element a label? A button? A header? These questions are answered by accessibilityTraits. * @platform ios */ var accessibilityTraits: js.UndefOr[AccessibilityTrait | js.Array[AccessibilityTrait]] = js.native /** * Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, * it contains range information (minimum, current, and maximum). */ var accessibilityValue: js.UndefOr[AccessibilityValue] = js.native /** * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. * @platform ios */ var accessibilityViewIsModal: js.UndefOr[Boolean] = js.native /** * When true, indicates that the view is an accessibility element. * By default, all the touchable elements are accessible. */ var accessible: js.UndefOr[Boolean] = js.native /** * Views that are only used to layout their children or otherwise don't draw anything * may be automatically removed from the native hierarchy as an optimization. * Set this property to false to disable this optimization and ensure that this View exists in the native view hierarchy. */ var collapsable: js.UndefOr[Boolean] = js.native /** * Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. */ var focusable: js.UndefOr[Boolean] = js.native /** * *(Apple TV only)* May be set to true to force the Apple TV focus engine to move focus to this view. * * @platform ios */ var hasTVPreferredFocus: js.UndefOr[Boolean] = js.native /** * This defines how far a touch event can start away from the view. * Typical interface guidelines recommend touch targets that are at least * 30 - 40 points/density-independent pixels. If a Touchable view has * a height of 20 the touchable height can be extended to 40 with * hitSlop={{top: 10, bottom: 10, left: 0, right: 0}} * NOTE The touch area never extends past the parent view bounds and * the Z-index of sibling views always takes precedence if a touch * hits two overlapping views. */ var hitSlop: js.UndefOr[Insets] = js.native /** * Controls how view is important for accessibility which is if it fires accessibility events * and if it is reported to accessibility services that query the screen. * Works for Android only. See http://developer.android.com/reference/android/R.attr.html#importantForAccessibility for references. * * Possible values: * 'auto' - The system determines whether the view is important for accessibility - default (recommended). * 'yes' - The view is important for accessibility. * 'no' - The view is not important for accessibility. * 'no-hide-descendants' - The view is not important for accessibility, nor are any of its descendant views. */ var importantForAccessibility: js.UndefOr[auto | yes | no | `no-hide-descendants`] = js.native /** * *(Apple TV only)* When set to true, this view will be focusable * and navigable using the Apple TV remote. * * @platform ios */ var isTVSelectable: js.UndefOr[Boolean] = js.native /** * Used to reference react managed views from native code. */ var nativeID: js.UndefOr[String] = js.native /** * Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. * The default (false) falls back to drawing the component and its children * with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. * This default may be noticeable and undesired in the case where the View you are setting an opacity on * has multiple overlapping elements (e.g. multiple overlapping Views, or text and a background). * * Rendering offscreen to preserve correct alpha behavior is extremely expensive * and hard to debug for non-native developers, which is why it is not turned on by default. * If you do need to enable this property for an animation, * consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame). * If that property is enabled, this View will be rendered off-screen once, * saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU. */ var needsOffscreenAlphaCompositing: js.UndefOr[Boolean] = js.native /** * When `accessible` is true, the system will try to invoke this function when the user performs an accessibility custom action. */ var onAccessibilityAction: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, ReadonlyactionNamestring], Unit]] = js.native /** * When accessibile is true, the system will invoke this function when the user performs the escape gesture (scrub with two fingers). * @platform ios */ var onAccessibilityEscape: js.UndefOr[js.Function0[Unit]] = js.native /** * When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture. * @platform ios */ var onAccessibilityTap: js.UndefOr[js.Function0[Unit]] = js.native /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ var onLayout: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, Layout], Unit]] = js.native /** * When accessible is true, the system will invoke this function when the user performs the magic tap gesture. * @platform ios */ var onMagicTap: js.UndefOr[js.Function0[Unit]] = js.native /** * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? */ var onMoveShouldSetResponder: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Boolean]] = js.native /** * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, * where the deepest node is called first. * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. * This is desirable in most cases, because it makes sure all controls and buttons are usable. * * However, sometimes a parent will want to make sure that it becomes responder. * This can be handled by using the capture phase. * Before the responder system bubbles up from the deepest component, * it will do a capture phase, firing on*ShouldSetResponderCapture. * So if a parent View wants to prevent the child from becoming responder on a touch start, * it should have a onStartShouldSetResponderCapture handler which returns true. */ var onMoveShouldSetResponderCapture: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Boolean]] = js.native /** * If the View returns true and attempts to become the responder, one of the following will happen: */ var onResponderEnd: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * The View is now responding for touch events. * This is the time to highlight and show the user what is happening */ var onResponderGrant: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * If the view is responding, the following handlers can be called: */ /** * The user is moving their finger */ var onResponderMove: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * Something else is the responder right now and will not release it */ var onResponderReject: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * Fired at the end of the touch, ie "touchUp" */ var onResponderRelease: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native var onResponderStart: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * The responder has been taken from the View. * Might be taken by other views after a call to onResponderTerminationRequest, * or might be taken by the OS without asking (happens with control center/ notification center on iOS) */ var onResponderTerminate: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * Something else wants to become responder. * Should this view release the responder? Returning true allows release */ var onResponderTerminationRequest: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Boolean]] = js.native /** * A view can become the touch responder by implementing the correct negotiation methods. * There are two methods to ask the view if it wants to become responder: */ /** * Does this view want to become responder on the start of a touch? */ var onStartShouldSetResponder: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Boolean]] = js.native /** * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, * where the deepest node is called first. * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. * This is desirable in most cases, because it makes sure all controls and buttons are usable. * * However, sometimes a parent will want to make sure that it becomes responder. * This can be handled by using the capture phase. * Before the responder system bubbles up from the deepest component, * it will do a capture phase, firing on*ShouldSetResponderCapture. * So if a parent View wants to prevent the child from becoming responder on a touch start, * it should have a onStartShouldSetResponderCapture handler which returns true. */ var onStartShouldSetResponderCapture: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Boolean]] = js.native var onTouchCancel: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native var onTouchEnd: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native var onTouchEndCapture: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native var onTouchMove: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native var onTouchStart: js.UndefOr[js.Function1[SyntheticEvent[NodeHandle, NativeTouchEvent], Unit]] = js.native /** * * In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: * * .box-none { * pointer-events: none; * } * .box-none * { * pointer-events: all; * } * * box-only is the equivalent of * * .box-only { * pointer-events: all; * } * .box-only * { * pointer-events: none; * } * * But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, * we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. */ var pointerEvents: js.UndefOr[`box-none` | none | `box-only` | auto] = js.native /** * * This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, * most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. * The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). */ var removeClippedSubviews: js.UndefOr[Boolean] = js.native /** * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. * * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. */ var renderToHardwareTextureAndroid: js.UndefOr[Boolean] = js.native var right: js.UndefOr[Boolean] = js.native /** * Whether this view should be rendered as a bitmap before compositing. * * On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; * for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view * and quickly composite it during each frame. * * Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. * Test and measure when using this property. */ var shouldRasterizeIOS: js.UndefOr[Boolean] = js.native var style: js.UndefOr[StyleProp[ViewStyle]] = js.native /** * Used to locate this view in end-to-end tests. */ var testID: js.UndefOr[String] = js.native /** * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 1.0. * * @platform ios */ var tvParallaxMagnification: js.UndefOr[Double] = js.native /** * *(Apple TV only)* Object with properties to control Apple TV parallax effects. * * @platform ios */ var tvParallaxProperties: js.UndefOr[TVParallaxProperties] = js.native /** * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. * * @platform ios */ var tvParallaxShiftDistanceX: js.UndefOr[Double] = js.native /** * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. * * @platform ios */ var tvParallaxShiftDistanceY: js.UndefOr[Double] = js.native /** * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 0.05. * * @platform ios */ var tvParallaxTiltAngle: js.UndefOr[Double] = js.native } object ViewPropertiesrightboolea { @scala.inline def apply(): ViewPropertiesrightboolea = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[ViewPropertiesrightboolea] } @scala.inline implicit class ViewPropertiesrightbooleaMutableBuilder[Self <: ViewPropertiesrightboolea] (val x: Self) extends AnyVal { @scala.inline def setAccessibilityActions(value: js.Array[AccessibilityActionInfo]): Self = StObject.set(x, "accessibilityActions", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityActionsUndefined: Self = StObject.set(x, "accessibilityActions", js.undefined) @scala.inline def setAccessibilityActionsVarargs(value: AccessibilityActionInfo*): Self = StObject.set(x, "accessibilityActions", js.Array(value :_*)) @scala.inline def setAccessibilityComponentType(value: none | button | radiobutton_checked | radiobutton_unchecked): Self = StObject.set(x, "accessibilityComponentType", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityComponentTypeUndefined: Self = StObject.set(x, "accessibilityComponentType", js.undefined) @scala.inline def setAccessibilityElementsHidden(value: Boolean): Self = StObject.set(x, "accessibilityElementsHidden", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityElementsHiddenUndefined: Self = StObject.set(x, "accessibilityElementsHidden", js.undefined) @scala.inline def setAccessibilityHint(value: String): Self = StObject.set(x, "accessibilityHint", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityHintUndefined: Self = StObject.set(x, "accessibilityHint", js.undefined) @scala.inline def setAccessibilityIgnoresInvertColors(value: Boolean): Self = StObject.set(x, "accessibilityIgnoresInvertColors", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityIgnoresInvertColorsUndefined: Self = StObject.set(x, "accessibilityIgnoresInvertColors", js.undefined) @scala.inline def setAccessibilityLabel(value: String): Self = StObject.set(x, "accessibilityLabel", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityLabelUndefined: Self = StObject.set(x, "accessibilityLabel", js.undefined) @scala.inline def setAccessibilityLiveRegion(value: none | polite | assertive): Self = StObject.set(x, "accessibilityLiveRegion", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityLiveRegionUndefined: Self = StObject.set(x, "accessibilityLiveRegion", js.undefined) @scala.inline def setAccessibilityRole(value: AccessibilityRole): Self = StObject.set(x, "accessibilityRole", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityRoleUndefined: Self = StObject.set(x, "accessibilityRole", js.undefined) @scala.inline def setAccessibilityState(value: AccessibilityState): Self = StObject.set(x, "accessibilityState", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityStateUndefined: Self = StObject.set(x, "accessibilityState", js.undefined) @scala.inline def setAccessibilityTraits(value: AccessibilityTrait | js.Array[AccessibilityTrait]): Self = StObject.set(x, "accessibilityTraits", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityTraitsUndefined: Self = StObject.set(x, "accessibilityTraits", js.undefined) @scala.inline def setAccessibilityTraitsVarargs(value: AccessibilityTrait*): Self = StObject.set(x, "accessibilityTraits", js.Array(value :_*)) @scala.inline def setAccessibilityValue(value: AccessibilityValue): Self = StObject.set(x, "accessibilityValue", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityValueUndefined: Self = StObject.set(x, "accessibilityValue", js.undefined) @scala.inline def setAccessibilityViewIsModal(value: Boolean): Self = StObject.set(x, "accessibilityViewIsModal", value.asInstanceOf[js.Any]) @scala.inline def setAccessibilityViewIsModalUndefined: Self = StObject.set(x, "accessibilityViewIsModal", js.undefined) @scala.inline def setAccessible(value: Boolean): Self = StObject.set(x, "accessible", value.asInstanceOf[js.Any]) @scala.inline def setAccessibleUndefined: Self = StObject.set(x, "accessible", js.undefined) @scala.inline def setCollapsable(value: Boolean): Self = StObject.set(x, "collapsable", value.asInstanceOf[js.Any]) @scala.inline def setCollapsableUndefined: Self = StObject.set(x, "collapsable", js.undefined) @scala.inline def setFocusable(value: Boolean): Self = StObject.set(x, "focusable", value.asInstanceOf[js.Any]) @scala.inline def setFocusableUndefined: Self = StObject.set(x, "focusable", js.undefined) @scala.inline def setHasTVPreferredFocus(value: Boolean): Self = StObject.set(x, "hasTVPreferredFocus", value.asInstanceOf[js.Any]) @scala.inline def setHasTVPreferredFocusUndefined: Self = StObject.set(x, "hasTVPreferredFocus", js.undefined) @scala.inline def setHitSlop(value: Insets): Self = StObject.set(x, "hitSlop", value.asInstanceOf[js.Any]) @scala.inline def setHitSlopUndefined: Self = StObject.set(x, "hitSlop", js.undefined) @scala.inline def setImportantForAccessibility(value: auto | yes | no | `no-hide-descendants`): Self = StObject.set(x, "importantForAccessibility", value.asInstanceOf[js.Any]) @scala.inline def setImportantForAccessibilityUndefined: Self = StObject.set(x, "importantForAccessibility", js.undefined) @scala.inline def setIsTVSelectable(value: Boolean): Self = StObject.set(x, "isTVSelectable", value.asInstanceOf[js.Any]) @scala.inline def setIsTVSelectableUndefined: Self = StObject.set(x, "isTVSelectable", js.undefined) @scala.inline def setNativeID(value: String): Self = StObject.set(x, "nativeID", value.asInstanceOf[js.Any]) @scala.inline def setNativeIDUndefined: Self = StObject.set(x, "nativeID", js.undefined) @scala.inline def setNeedsOffscreenAlphaCompositing(value: Boolean): Self = StObject.set(x, "needsOffscreenAlphaCompositing", value.asInstanceOf[js.Any]) @scala.inline def setNeedsOffscreenAlphaCompositingUndefined: Self = StObject.set(x, "needsOffscreenAlphaCompositing", js.undefined) @scala.inline def setOnAccessibilityAction(value: SyntheticEvent[NodeHandle, ReadonlyactionNamestring] => Unit): Self = StObject.set(x, "onAccessibilityAction", js.Any.fromFunction1(value)) @scala.inline def setOnAccessibilityActionUndefined: Self = StObject.set(x, "onAccessibilityAction", js.undefined) @scala.inline def setOnAccessibilityEscape(value: () => Unit): Self = StObject.set(x, "onAccessibilityEscape", js.Any.fromFunction0(value)) @scala.inline def setOnAccessibilityEscapeUndefined: Self = StObject.set(x, "onAccessibilityEscape", js.undefined) @scala.inline def setOnAccessibilityTap(value: () => Unit): Self = StObject.set(x, "onAccessibilityTap", js.Any.fromFunction0(value)) @scala.inline def setOnAccessibilityTapUndefined: Self = StObject.set(x, "onAccessibilityTap", js.undefined) @scala.inline def setOnLayout(value: SyntheticEvent[NodeHandle, Layout] => Unit): Self = StObject.set(x, "onLayout", js.Any.fromFunction1(value)) @scala.inline def setOnLayoutUndefined: Self = StObject.set(x, "onLayout", js.undefined) @scala.inline def setOnMagicTap(value: () => Unit): Self = StObject.set(x, "onMagicTap", js.Any.fromFunction0(value)) @scala.inline def setOnMagicTapUndefined: Self = StObject.set(x, "onMagicTap", js.undefined) @scala.inline def setOnMoveShouldSetResponder(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Boolean): Self = StObject.set(x, "onMoveShouldSetResponder", js.Any.fromFunction1(value)) @scala.inline def setOnMoveShouldSetResponderCapture(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Boolean): Self = StObject.set(x, "onMoveShouldSetResponderCapture", js.Any.fromFunction1(value)) @scala.inline def setOnMoveShouldSetResponderCaptureUndefined: Self = StObject.set(x, "onMoveShouldSetResponderCapture", js.undefined) @scala.inline def setOnMoveShouldSetResponderUndefined: Self = StObject.set(x, "onMoveShouldSetResponder", js.undefined) @scala.inline def setOnResponderEnd(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderEnd", js.Any.fromFunction1(value)) @scala.inline def setOnResponderEndUndefined: Self = StObject.set(x, "onResponderEnd", js.undefined) @scala.inline def setOnResponderGrant(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderGrant", js.Any.fromFunction1(value)) @scala.inline def setOnResponderGrantUndefined: Self = StObject.set(x, "onResponderGrant", js.undefined) @scala.inline def setOnResponderMove(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderMove", js.Any.fromFunction1(value)) @scala.inline def setOnResponderMoveUndefined: Self = StObject.set(x, "onResponderMove", js.undefined) @scala.inline def setOnResponderReject(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderReject", js.Any.fromFunction1(value)) @scala.inline def setOnResponderRejectUndefined: Self = StObject.set(x, "onResponderReject", js.undefined) @scala.inline def setOnResponderRelease(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderRelease", js.Any.fromFunction1(value)) @scala.inline def setOnResponderReleaseUndefined: Self = StObject.set(x, "onResponderRelease", js.undefined) @scala.inline def setOnResponderStart(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderStart", js.Any.fromFunction1(value)) @scala.inline def setOnResponderStartUndefined: Self = StObject.set(x, "onResponderStart", js.undefined) @scala.inline def setOnResponderTerminate(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onResponderTerminate", js.Any.fromFunction1(value)) @scala.inline def setOnResponderTerminateUndefined: Self = StObject.set(x, "onResponderTerminate", js.undefined) @scala.inline def setOnResponderTerminationRequest(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Boolean): Self = StObject.set(x, "onResponderTerminationRequest", js.Any.fromFunction1(value)) @scala.inline def setOnResponderTerminationRequestUndefined: Self = StObject.set(x, "onResponderTerminationRequest", js.undefined) @scala.inline def setOnStartShouldSetResponder(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Boolean): Self = StObject.set(x, "onStartShouldSetResponder", js.Any.fromFunction1(value)) @scala.inline def setOnStartShouldSetResponderCapture(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Boolean): Self = StObject.set(x, "onStartShouldSetResponderCapture", js.Any.fromFunction1(value)) @scala.inline def setOnStartShouldSetResponderCaptureUndefined: Self = StObject.set(x, "onStartShouldSetResponderCapture", js.undefined) @scala.inline def setOnStartShouldSetResponderUndefined: Self = StObject.set(x, "onStartShouldSetResponder", js.undefined) @scala.inline def setOnTouchCancel(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onTouchCancel", js.Any.fromFunction1(value)) @scala.inline def setOnTouchCancelUndefined: Self = StObject.set(x, "onTouchCancel", js.undefined) @scala.inline def setOnTouchEnd(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onTouchEnd", js.Any.fromFunction1(value)) @scala.inline def setOnTouchEndCapture(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onTouchEndCapture", js.Any.fromFunction1(value)) @scala.inline def setOnTouchEndCaptureUndefined: Self = StObject.set(x, "onTouchEndCapture", js.undefined) @scala.inline def setOnTouchEndUndefined: Self = StObject.set(x, "onTouchEnd", js.undefined) @scala.inline def setOnTouchMove(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onTouchMove", js.Any.fromFunction1(value)) @scala.inline def setOnTouchMoveUndefined: Self = StObject.set(x, "onTouchMove", js.undefined) @scala.inline def setOnTouchStart(value: SyntheticEvent[NodeHandle, NativeTouchEvent] => Unit): Self = StObject.set(x, "onTouchStart", js.Any.fromFunction1(value)) @scala.inline def setOnTouchStartUndefined: Self = StObject.set(x, "onTouchStart", js.undefined) @scala.inline def setPointerEvents(value: `box-none` | none | `box-only` | auto): Self = StObject.set(x, "pointerEvents", value.asInstanceOf[js.Any]) @scala.inline def setPointerEventsUndefined: Self = StObject.set(x, "pointerEvents", js.undefined) @scala.inline def setRemoveClippedSubviews(value: Boolean): Self = StObject.set(x, "removeClippedSubviews", value.asInstanceOf[js.Any]) @scala.inline def setRemoveClippedSubviewsUndefined: Self = StObject.set(x, "removeClippedSubviews", js.undefined) @scala.inline def setRenderToHardwareTextureAndroid(value: Boolean): Self = StObject.set(x, "renderToHardwareTextureAndroid", value.asInstanceOf[js.Any]) @scala.inline def setRenderToHardwareTextureAndroidUndefined: Self = StObject.set(x, "renderToHardwareTextureAndroid", js.undefined) @scala.inline def setRight(value: Boolean): Self = StObject.set(x, "right", value.asInstanceOf[js.Any]) @scala.inline def setRightUndefined: Self = StObject.set(x, "right", js.undefined) @scala.inline def setShouldRasterizeIOS(value: Boolean): Self = StObject.set(x, "shouldRasterizeIOS", value.asInstanceOf[js.Any]) @scala.inline def setShouldRasterizeIOSUndefined: Self = StObject.set(x, "shouldRasterizeIOS", js.undefined) @scala.inline def setStyle(value: StyleProp[ViewStyle]): Self = StObject.set(x, "style", value.asInstanceOf[js.Any]) @scala.inline def setStyleNull: Self = StObject.set(x, "style", null) @scala.inline def setStyleUndefined: Self = StObject.set(x, "style", js.undefined) @scala.inline def setTestID(value: String): Self = StObject.set(x, "testID", value.asInstanceOf[js.Any]) @scala.inline def setTestIDUndefined: Self = StObject.set(x, "testID", js.undefined) @scala.inline def setTvParallaxMagnification(value: Double): Self = StObject.set(x, "tvParallaxMagnification", value.asInstanceOf[js.Any]) @scala.inline def setTvParallaxMagnificationUndefined: Self = StObject.set(x, "tvParallaxMagnification", js.undefined) @scala.inline def setTvParallaxProperties(value: TVParallaxProperties): Self = StObject.set(x, "tvParallaxProperties", value.asInstanceOf[js.Any]) @scala.inline def setTvParallaxPropertiesUndefined: Self = StObject.set(x, "tvParallaxProperties", js.undefined) @scala.inline def setTvParallaxShiftDistanceX(value: Double): Self = StObject.set(x, "tvParallaxShiftDistanceX", value.asInstanceOf[js.Any]) @scala.inline def setTvParallaxShiftDistanceXUndefined: Self = StObject.set(x, "tvParallaxShiftDistanceX", js.undefined) @scala.inline def setTvParallaxShiftDistanceY(value: Double): Self = StObject.set(x, "tvParallaxShiftDistanceY", value.asInstanceOf[js.Any]) @scala.inline def setTvParallaxShiftDistanceYUndefined: Self = StObject.set(x, "tvParallaxShiftDistanceY", js.undefined) @scala.inline def setTvParallaxTiltAngle(value: Double): Self = StObject.set(x, "tvParallaxTiltAngle", value.asInstanceOf[js.Any]) @scala.inline def setTvParallaxTiltAngleUndefined: Self = StObject.set(x, "tvParallaxTiltAngle", js.undefined) } }
zopefoundation/Products.CMFDefault
Products/CMFDefault/formlib/vocabulary.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Formlib schema vocabulary base classes. """ from zope.interface import implements from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleVocabulary class SimpleVocabulary(SimpleVocabulary): def fromTitleItems(cls, items, *interfaces): """Construct a vocabulary from a list of (token, value, title) tuples. """ terms = [ cls.createTerm(value, token, title) for (token, value, title) in items ] return cls(terms, *interfaces) fromTitleItems = classmethod(fromTitleItems) class StaticVocabulary(object): """Vocabulary factory for static items. """ implements(IVocabularyFactory) def __init__(self, items): self._vocabulary = SimpleVocabulary.fromTitleItems(items) def __call__(self, context): return self._vocabulary
EvgeniyGal/goit-js
hw-03/js/task-04.js
<reponame>EvgeniyGal/goit-js function countTotalSalary(employees) { const salerys = Object.values(employees); return salerys.reduce((a, b) => a + b); } console.group('Task-04'); console.log( countTotalSalary({ mango: 100, poly: 150, alfred: 80, }), ); // 330 console.log( countTotalSalary({ kiwi: 200, lux: 50, chelsy: 150, }), ); // 400 console.groupEnd();
yuanz271/PyDSTool
tests/generator/test_odesystem_set_through_vode.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function from numpy.testing import assert_almost_equal, assert_array_almost_equal import pytest from PyDSTool import PyDSTool_ValueError, PyDSTool_TypeError from PyDSTool.Generator import Vode_ODEsystem @pytest.fixture() def ode(): return Vode_ODEsystem({ 'name': 'ode', 'vars': ['x'], 'pars': {'p': 0.5}, 'varspecs': {'x': 'x+p'}, 'pdomain': {'p': [0,1]} }) def test_setting_invalid_key(ode): with pytest.raises(KeyError): ode.set(invalid_key='') def test_setting_globalt0(ode): ode.set(globalt0=11.0) assert_almost_equal(11.0, ode.globalt0) assert ode._extInputsChanged def test_setting_checklevel(ode): ode.set(checklevel=10) assert ode.checklevel == 10 def test_setting_abseps(ode): ode.set(abseps=0.001) assert_almost_equal(1e-3, ode._abseps) def test_setting_ics(ode): ode.set(ics={'x': -1.0}) assert_almost_equal(-1.0, ode.initialconditions['x']) def test_setting_ics_raises_exception_for_illegal_varname(ode): with pytest.raises(ValueError): ode.set(ics={'y': 0.0}) def test_setting_tdata(ode): ode.set(tdata=[0, 10]) assert_array_almost_equal([0, 10], ode.tdata) def test_setting_tdomain(ode): ode.set(tdomain=[0, 20]) assert_array_almost_equal([0, 20], ode.tdomain) def test_setting_tdata_respects_domain(ode): ode.set(tdomain=[0, 20]) ode.set(tdata=[-10, 30]) assert_array_almost_equal([0, 20], ode.tdata) def test_setting_xdomain(ode): ode.set(xdomain={'x': [0, 20]}) assert_array_almost_equal([0, 20], ode.variables['x'].depdomain.get()) def test_setting_xdomain_using_single_value(ode): ode.set(xdomain={'x': 0}) assert_array_almost_equal([0, 0], ode.variables['x'].depdomain.get()) def test_setting_xdomain_raises_exception_for_illegal_varname(ode): with pytest.raises(ValueError): ode.set(xdomain={'y': []}) def test_setting_xdomain_raises_exception_for_nondictionary_value(ode): with pytest.raises(AttributeError): ode.set(xdomain=('x', [])) def test_setting_xdomain_raises_exception_for_wrongly_sorted_values(ode): with pytest.raises(PyDSTool_ValueError): ode.set(xdomain={'x': [20, 0]}) def test_settting_xdomain_raises_exception_for_nonsequence_value(ode): with pytest.raises(PyDSTool_TypeError): ode.set(xdomain={'x': {}}) def test_setting_pdomain(ode): ode.set(pdomain={'p': [0, 20]}) assert_array_almost_equal([0, 20], ode.parameterDomains['p'].get()) def test_setting_pdomain_using_single_value(ode): ode.set(pdomain={'p': 0}) assert_array_almost_equal([0, 0], ode.parameterDomains['p'].get()) def test_setting_pdomain_raises_exception_for_illegal_parname(ode): with pytest.raises(ValueError): ode.set(pdomain={'q': []}) def test_setting_pdomain_raises_exception_for_nondictionary_value(ode): with pytest.raises(AttributeError): ode.set(pdomain=('p', [])) def test_setting_pdomain_raises_exception_for_wrongly_sorted_values(ode): with pytest.raises(PyDSTool_ValueError): ode.set(pdomain={'p': [20, 0]}) def test_settting_pdomain_raises_exception_for_nonsequence_value(ode): with pytest.raises(PyDSTool_TypeError): ode.set(pdomain={'p': {}})
MOAMaster/AudioPlugSharp-SamplePlugins
vst3sdk/doc/vstsdk/VST3Plugin_8mm.js
var VST3Plugin_8mm = [ [ "bundleEntry", "VST3Plugin_8mm.html#a6763fb3bf363ffc54ee132d466c50297", null ], [ "bundleExit", "VST3Plugin_8mm.html#a65451ddd317f3c796347114f42638024", null ], [ "__attribute__", "VST3Plugin_8mm.html#ab2feb4fc133a7b3e0cdb5f9cdf941382", null ] ];
xiapeng612430/multi-thread
src/main/java/synchronizedAndVolatile/synchronized_/throwExceptionNotLock/Service.java
package synchronizedAndVolatile.synchronized_.throwExceptionNotLock; import synchronizedAndVolatile.synchronized_.synLockIn_2.Main; /** * Created by xianpeng.xia * on 2019-06-07 21:09 */ public class Service { synchronized public void testMethod() { if (Thread.currentThread().getName().equals("a")) { System.out.println("ThreadName=" + Thread.currentThread().getName() + " run beginTime = " + System.currentTimeMillis()); int i = 1; while (i == 1) { if (("" + Math.random()).substring(0, 3).equals(0.1)) { System.out.println("ThreadName=" + Thread.currentThread().getName() + " run exceptionTime = " + System.currentTimeMillis()); Integer.parseInt("a"); } } } else { System.out.println("Thread B run time = " + System.currentTimeMillis()); } } }
TouchBistro/frigging-bootstrap
src/js/components/number.js
<reponame>TouchBistro/frigging-bootstrap<filename>src/js/components/number.js import React from 'react' import cx from 'classnames' import Numeral from 'numeral' import InputErrorList from './input_error_list' import Saved from './saved' import Label from './label' import { sizeClassNames, formGroupCx } from '../util.js' import defaultProps from '../default_props.js' import defaultPropTypes from '../default_prop_types.js' export default class Number extends React.Component { static displayName = 'FriggingBootstrap.Number' static defaultProps = Object.assign({}, defaultProps, { format: '0,0[.][00]', }) static propTypes = Object.assign({}, defaultPropTypes, { format: React.PropTypes.string, } ) state = { formattedValue: '', } _formatNumber(currentNumber) { return currentNumber ? currentNumber.format(this.props.format) : '' } _onBlur() { let value = this.props.value value = value.toString().replace(/,/g, '') value = this._toNumeral(value) || '' value = this._formatNumber(value) this.setState({ formattedValue: value }) } _onChange(e) { const value = e.target.value this.setState({ formattedValue: value }) this.props.onChange(value.replace(/,/g, '')) } _inputCx() { return cx( this.props.inputHtml.className, 'form-control', ) } _input() { const inputProps = Object.assign({}, this.props.inputHtml, { className: this._inputCx(), onBlur: this._onBlur.bind(this), value: (this.state.formattedValue || this._formatNumber( this._toNumeral(this.props.value) || '') ), onChange: this._onChange.bind(this), }) return <input {...inputProps} /> } _toNumeral(value) { const n = Numeral(value) // eslint-disable-line new-cap // numeral.js converts empty strings into 0 for no reason, so if given // value was not '0' or 0, treat it as null. // or // numeral.js can sometimes convert values (like '4.5.2') into NaN // and we would rather null than NaN. if (n.value() === 0 && (value !== 0 && value !== '0') || isNaN(n.value())) { return null } return n } render() { return ( <div className={cx(sizeClassNames(this.props))}> <div className={formGroupCx(this.props)}> <div> <Label {...this.props} /> </div> {this._input()} <Saved saved={this.props.saved} /> <InputErrorList errors={this.props.errors} /> </div> </div> ) } }
maaili/good_frame2
src/main/java/com/daxiang/typehandler/StepListTypeHandler.java
<filename>src/main/java/com/daxiang/typehandler/StepListTypeHandler.java<gh_stars>100-1000 package com.daxiang.typehandler; import com.daxiang.model.action.Step; /** * Created by jiangyitao. */ public class StepListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return Step.class; } }
mambrola/AMBROAFB
AmbroAFB/src/ambroafb/minitables/merchandises/MerchandiseDataFetchProvider.java
<gh_stars>0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ambroafb.minitables.merchandises; import ambroafb.general.interfaces.DataFetchProvider; import ambroafb.general.interfaces.FilterModel; import authclient.db.ConditionBuilder; import java.util.List; import org.json.JSONObject; /** * * @author dkobuladze */ public class MerchandiseDataFetchProvider extends DataFetchProvider { private final String DB_TABLE_NAME = "process_merchandises"; @Override public List<Merchandise> getFilteredBy(JSONObject params) throws Exception { List<Merchandise> merchandises = getObjectsListFromDBTable(Merchandise.class, DB_TABLE_NAME, params); return merchandises; } @Override public List<Merchandise> getFilteredBy(FilterModel model) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Merchandise getOneFromDB(int recId) throws Exception { JSONObject params = new ConditionBuilder().where().and(DB_ID, "=", recId).condition().build(); return getObjectFromDB(Merchandise.class, DB_TABLE_NAME, params); } }
jennyrobertsonbbc/bbc-a11y
features/support/nullReporter.js
<reponame>jennyrobertsonbbc/bbc-a11y module.exports = class NullReporter { runStarted () { this.results = [] } unexpectedError (e) { console.log(e) throw e } pageChecked (page, results) { this.results[page.url] = results } runEnded () { } }
moneytech/skift
libraries/libsystem/system.c
/* Copyright © 2018-2020 <NAME>. */ /* This code is licensed under the MIT License. */ /* See: LICENSE.md */ #include <libsystem/__plugs__.h> #include <libsystem/system.h> SystemInfo system_get_info(void) { SystemInfo info; __plug_system_get_info(&info); return info; } SystemStatus system_get_status(void) { SystemStatus status; __plug_system_get_status(&status); return status; } uint system_get_ticks(void) { return __plug_system_get_ticks(); }
larsvers/winter-olympics
js/force-worker.js
var log = console.log.bind(console); var dir = console.dir.bind(console); // Import scripts importScripts("https://d3js.org/d3-collection.v1.min.js"); importScripts("https://d3js.org/d3-dispatch.v1.min.js"); importScripts("https://d3js.org/d3-quadtree.v1.min.js"); importScripts("https://d3js.org/d3-timer.v1.min.js"); importScripts("https://d3js.org/d3-force.v1.min.js"); // Pick up messages from the main script onmessage = function(e) { // This is all running synchronously // Get the data var nodes = e.data.nodes; var event = e.data.event; var width = e.data.width; var height = e.data.height; // Base simulation - 1 var simulation = d3.forceSimulation(nodes) .alpha(0.85) .alphaMin(0.001) // <-- default .alphaDecay(1 - Math.pow(0.001, 1 / 50)) // we save a lot of time by adjusting the denominator (and hence reducing the max ticks from 300 to 50). Reduced calculation time for 22 forces from c. 220 sec to 22 sec - yay ! .force('charge', d3.forceManyBody().strength(-3.125)) .force('xPos', d3.forceX(width/2).strength(1)) .force('yPos', d3.forceY(height/2).strength(1)) .force('collide', d3.forceCollide(1.5)) .stop(); // Calculate the position for each tick manually (n explained: default total number of ticks per simulation (300, see https://github.com/d3/d3-force#simulation_alphaMin)) for (var i = 0, n = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())); i < n; ++i) { simulation.tick(); } // // We could let it calculate the final positions but for performance reasons let it be like that // // Split simulation - 2 | time to complete: 135 sec's // simulation // .force('xPos', d3.forceX(function(d) { return d.cluster === 0 ? width * 0.3 : width * 0.7; }).strength(0.7) ) // .force('yPos', d3.forceY(height/2).strength(0.7)); // simulation.alpha(0.2).restart(); // for (var i = 0, n = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())); i < n; ++i) { // simulation.tick(); // } // // Unite simulation - 3 | time to complete: 202 sec's // simulation // .force('xPos', d3.forceX(width/2).strength(0.5)) // .force('yPos', d3.forceY(height/2).strength(0.5)); // simulation.alpha(0.2).restart(); // for (var i = 0, n = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())); i < n; ++i) { // simulation.tick(); // } // console.log('from worker: event', event, 'result', nodes); // Send the calculated positions back to the main script in a new nodes object for drawing postMessage({ type: 'end', event: event, nodes: nodes }); close(); }; // onmessage()
CornellProjects/cancercare
mobile/project/js/components/RecordDetail/index.js
import React, { Component } from 'react'; import { Text } from 'react-native'; import { Button } from 'native-base'; import { connect } from 'react-redux'; import { selectRecord } from '../../actions/records'; import { Actions } from 'react-native-router-flux'; class RecordDetail extends Component { static propTypes = { openDrawer: React.PropTypes.func, selectRecord: React.PropTypes.func, } getDate(str) { let myDate = new Date(str); let onlyDate = myDate.toLocaleDateString(); return onlyDate; } // IN-PROGRESS goToEditView(id) { this.props.selectRecord(id); } render() { const { id, date } = this.props.element; console.log(this.props.selectedRecord); return ( <Button full bordered onPress={() => this.goToEditView(id)} > <Text>{this.getDate(date)}</Text> </Button> ); } }; function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), selectRecord: id => dispatch(selectRecord(id)) }; } const mapStateToProps = state => ({ selectedRecord: state.records.selectedRecord, }); export default connect(mapStateToProps, bindAction)(RecordDetail);
sthagen/svaarala-duktape
tests/ecmascript/test-bi-proxy-finalizer-1.js
<reponame>sthagen/svaarala-duktape<filename>tests/ecmascript/test-bi-proxy-finalizer-1.js /*=== test 1, step 1 fin1 test 1, step 2 test 1, step 3 test 1, step 4 test 2, step 1 test 2, step 2 test 2, step 3 test 2, step 4 test 3, step 1 fin3 test 3, step 2 test 3, step 3 test 3, step 4 ===*/ function test() { /* Base case: normal object finalization. */ var O = {}; Duktape.fin(O, function () { print('fin1'); }); print('test 1, step 1'); O = null; print('test 1, step 2'); Duktape.gc(); print('test 1, step 3'); Duktape.gc(); print('test 1, step 4'); /* Proxy finalization, finalizer set on Proxy. Under the hood * uses duk_set_finalizer() on the proxy. This now has the behavior * where: * 1) the _Finalizer is set on the target, but * 2) the "have finalizer" flag is set on the Proxy * * As a result the finalizer doesn't run at all. */ var P = (function () { return new Proxy({}, {}); })(); Duktape.fin(P, function () { print('fin2'); }); print('test 2, step 1'); P = null; print('test 2, step 2'); Duktape.gc(); print('test 2, step 3'); Duktape.gc(); print('test 2, step 4'); /* Proxy finalization, finalizer set on target explicitly. */ var T = {}; Duktape.fin(T, function () { print('fin3'); }); var P = (function () { return new Proxy(T, {}); })(); T = null; print('test 3, step 1'); P = null; print('test 3, step 2'); Duktape.gc(); print('test 3, step 3'); Duktape.gc(); print('test 3, step 4'); } try { test(); } catch (e) { print(e.stack || e); }
carlosviveros/Soluciones
ejercicios/liquidacion_sueldos.py
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython Realizar un programa que efectúe la liquidación de sueldos basado en los siguientes datos: nombre del empleado, cantidad de días trabajados (cada día trabajando contempla 8 horas diarias), cantidad de horas extras (tienen un valor del 50% más con respecto a la hora normal), y el valor de la hora normal. Imprimir: el nombre del empleado y el neto a cobrar, considerando que el descuento a realizarse sobre el sueldo bruto es de 17%. """ HORAS = 8 empleado = input("Ingrese el nombre del empleado: ") dias = int(input("Ingrese la cantidad de días trabajados: ")) extras = int(input("Ingrese la cantidad de horas extras: ")) valor = int(input("Ingrese el valor de la hora normal: ")) neto = (dias * HORAS * valor) + (extras * valor * 1.5) descuento = neto * 0.17 total = neto - descuento print("Sueldo neto a cobrar: ", total)
greenhillee/mod-circulation
src/main/java/org/folio/circulation/domain/MoveRequestProcessAdapter.java
package org.folio.circulation.domain; import java.util.concurrent.CompletableFuture; import org.folio.circulation.infrastructure.storage.inventory.ItemRepository; import org.folio.circulation.infrastructure.storage.loans.LoanRepository; import org.folio.circulation.infrastructure.storage.requests.RequestQueueRepository; import org.folio.circulation.infrastructure.storage.requests.RequestRepository; import org.folio.circulation.support.Result; public class MoveRequestProcessAdapter { private final ItemRepository itemRepository; private final LoanRepository loanRepository; private final RequestRepository requestRepository; private final RequestQueueRepository requestQueueRepository; public MoveRequestProcessAdapter(ItemRepository itemRepository, LoanRepository loanRepository, RequestRepository requestRepository, RequestQueueRepository requestQueueRepository) { this.itemRepository = itemRepository; this.loanRepository = loanRepository; this.requestRepository = requestRepository; this.requestQueueRepository = requestQueueRepository; } CompletableFuture<Result<RequestAndRelatedRecords>> findDestinationItem( RequestAndRelatedRecords requestAndRelatedRecords) { return itemRepository.fetchById(requestAndRelatedRecords.getDestinationItemId()) .thenApply(r -> r.map(requestAndRelatedRecords::withItem)) .thenComposeAsync(r -> r.after(this::findLoanForItem)); } private CompletableFuture<Result<RequestAndRelatedRecords>> findLoanForItem( RequestAndRelatedRecords requestAndRelatedRecords) { return loanRepository.findOpenLoanForRequest(requestAndRelatedRecords.getRequest()) .thenApply(r -> r.map(requestAndRelatedRecords::withLoan)); } CompletableFuture<Result<RequestAndRelatedRecords>> getDestinationRequestQueue( RequestAndRelatedRecords requestAndRelatedRecords) { return requestQueueRepository.get(requestAndRelatedRecords.getDestinationItemId()) .thenApply(result -> result.map(requestAndRelatedRecords::withRequestQueue)); } CompletableFuture<Result<RequestAndRelatedRecords>> findSourceItem( RequestAndRelatedRecords requestAndRelatedRecords) { return itemRepository.fetchById(requestAndRelatedRecords.getSourceItemId()) .thenApply(result -> result.map(requestAndRelatedRecords::withItem)) .thenComposeAsync(r -> r.after(this::findLoanForItem)); } CompletableFuture<Result<RequestAndRelatedRecords>> getSourceRequestQueue( RequestAndRelatedRecords requestAndRelatedRecords) { return requestQueueRepository.get(requestAndRelatedRecords.getSourceItemId()) .thenApply(result -> result.map(requestAndRelatedRecords::withRequestQueue)); } CompletableFuture<Result<RequestAndRelatedRecords>> getRequest( RequestAndRelatedRecords requestAndRelatedRecords) { return requestRepository.getById(requestAndRelatedRecords.getRequest().getId()) .thenApply(r -> r.map(requestAndRelatedRecords::withRequest)); } }
77loopin/ray
rllib/env/atari_wrappers.py
from ray.rllib.env.wrappers.atari_wrappers import is_atari, \ get_wrapper_by_cls, MonitorEnv, NoopResetEnv, ClipRewardEnv, \ FireResetEnv, EpisodicLifeEnv, MaxAndSkipEnv, WarpFrame, FrameStack, \ FrameStackTrajectoryView, ScaledFloatFrame, wrap_deepmind from ray.rllib.utils.deprecation import deprecation_warning deprecation_warning( old="ray.rllib.env.atari_wrappers....", new="ray.rllib.env.wrappers.atari_wrappers....", error=False, ) is_atari = is_atari get_wrapper_by_cls = get_wrapper_by_cls MonitorEnv = MonitorEnv NoopResetEnv = NoopResetEnv ClipRewardEnv = ClipRewardEnv FireResetEnv = FireResetEnv EpisodicLifeEnv = EpisodicLifeEnv MaxAndSkipEnv = MaxAndSkipEnv WarpFrame = WarpFrame FrameStack = FrameStack FrameStackTrajectoryView = FrameStackTrajectoryView ScaledFloatFrame = ScaledFloatFrame wrap_deepmind = wrap_deepmind
tangdehao/flutter_aliyun_video
android/src/main/kotlin/com/sm9i/aliyun_video/aliyun/base/widget/beauty/skin/BeautyDefaultSkinSettingView.java
package com.sm9i.aliyun_video.aliyun.base.widget.beauty.skin; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import com.sm9i.aliyun_video.R; import com.sm9i.aliyun_video.aliyun.base.widget.AlivcPopupView; import com.sm9i.aliyun_video.aliyun.base.widget.beauty.enums.BeautyLevel; import com.sm9i.aliyun_video.aliyun.base.widget.beauty.enums.BeautyMode; import com.sm9i.aliyun_video.aliyun.base.widget.beauty.listener.OnBeautySkinItemSeletedListener; import com.sm9i.aliyun_video.aliyun.base.widget.beauty.listener.OnViewClickListener; import java.util.Map; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; public class BeautyDefaultSkinSettingView extends LinearLayout { private Context mContext; private RadioGroup mRgSkinGroup; private ImageView mBtBeautyDetail; private BeautyLevel beautyLevel = BeautyLevel.BEAUTY_LEVEL_THREE; private int skinPosition = 3; private BeautyMode beautyMode; private AlivcPopupView alivcPopupView; private Map<String, Integer> beautyMap; public BeautyDefaultSkinSettingView(Context context) { super(context); mContext = context; initView(); } public BeautyDefaultSkinSettingView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; initView(); } public BeautyDefaultSkinSettingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; initView(); } public void setDefaultSelect(Map<String, Integer> map) { this.beautyMap = map; if (map == null) { return; } skinPosition = map.get("skin") == null ? 3 : map.get("skin"); normalCheck(skinPosition); } private void normalCheck(int position) { int normalId; switch (position) { case 0: normalId = R.id.beauty0; break; case 1: normalId = R.id.beauty1; break; case 2: normalId = R.id.beauty2; break; case 3: normalId = R.id.beauty3; break; case 4: normalId = R.id.beauty4; break; case 5: normalId = R.id.beauty5; break; default: normalId = R.id.beauty3; break; } mRgSkinGroup.check(normalId); } private void initView() { LayoutInflater.from(mContext).inflate(R.layout.alivc_beauty_default, this); mRgSkinGroup = findViewById(R.id.beauty_normal_group); mBtBeautyDetail = findViewById(R.id.iv_beauty_detail); alivcPopupView = new AlivcPopupView(mContext); TextView textView = new TextView(getContext()); textView.setLayoutParams(new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)); textView.setPadding(10, 0, 10, 0); textView.setText(getResources().getString(R.string.alivc_base_tips_fine_tuning)); textView.setTextColor(ContextCompat.getColor(getContext(), R.color.alivc_common_font_white)); alivcPopupView.setContentView(textView); mBtBeautyDetail.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mSettingClickListener != null) { mSettingClickListener.onClick(); } } }); mRgSkinGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { checkedPosition(checkedId); if (mListener != null) { mListener.onItemSelected(skinPosition); } } }); } /** * 单位转换: dp -> px * * @param dp * @return */ public static int dp2px(Context context, int dp) { return (int) (getDensity(context) * dp + 0.5); } public static float getDensity(Context context) { return context.getResources().getDisplayMetrics().density; } private void checkedPosition(int checkedId) { if (checkedId == R.id.beauty0 /*|| checkedId == R.id.beauty_advanced_0*/) { skinPosition = 0; beautyLevel = BeautyLevel.BEAUTY_LEVEL_ZERO; } else if (checkedId == R.id.beauty1 /*|| checkedId == R.id.beauty_advanced_1*/) { skinPosition = 1; beautyLevel = BeautyLevel.BEAUTY_LEVEL_ONE; } else if (checkedId == R.id.beauty2 /*|| checkedId == R.id.beauty_advanced_2*/) { skinPosition = 2; beautyLevel = BeautyLevel.BEAUTY_LEVEL_TWO; } else if (checkedId == R.id.beauty3/* || checkedId == R.id.beauty_advanced_3*/) { skinPosition = 3; beautyLevel = BeautyLevel.BEAUTY_LEVEL_THREE; } else if (checkedId == R.id.beauty4 /*|| checkedId == R.id.beauty_advanced_4*/) { skinPosition = 4; beautyLevel = BeautyLevel.BEAUTY_LEVEL_FOUR; } else if (checkedId == R.id.beauty5 /*|| checkedId == R.id.beauty_advanced_5*/) { skinPosition = 5; beautyLevel = BeautyLevel.BEAUTY_LEVEL_FIVE; } } /** * 详情按钮点击监听 */ private OnViewClickListener mSettingClickListener; public void setSettingClickListener(OnViewClickListener listener) { mSettingClickListener = listener; } /** * item选择监听 */ private OnBeautySkinItemSeletedListener mListener; public void setItemSelectedListener(OnBeautySkinItemSeletedListener listener) { mListener = listener; if (beautyMode == BeautyMode.SKIN) { checkedPosition(skinPosition); } } /** * 显示详情按钮 */ public void showDetailBtn() { mBtBeautyDetail.setVisibility(VISIBLE); } /** * 显示详情提示 */ public void showDetailTips() { alivcPopupView.show(mBtBeautyDetail); } /** * 隐藏详情按钮 */ public void hideDetailBtn() { // 不要使用GONE, 否则会引起整体高度变化 mBtBeautyDetail.setVisibility(INVISIBLE); } public void setBeautyMode(BeautyMode beautyMode, boolean isBeautyFace) { this.beautyMode = beautyMode; mRgSkinGroup.setVisibility(VISIBLE); } }
zzzzzzzs/FlinkRealTimeProjectAnalysis
gmall2020-mock/gmall2020-mock-log/src/main/java/com/atgugu/gmall2020/mock/log/bean/AppAction.java
<gh_stars>0 package com.atgugu.gmall2020.mock.log.bean; import com.atgugu.gmall2020.mock.log.config.AppConfig; import com.atgugu.gmall2020.mock.log.enums.ItemType; import com.atgugu.gmall2020.mock.log.enums.PageId; import com.atgugu.gmall2020.mock.log.enums.ActionId; import com.atguigu.gmall2020.mock.db.util.RandomNum; import com.atguigu.gmall2020.mock.db.util.RandomOptionGroup; import lombok.*; import java.util.ArrayList; import java.util.List; @Data public class AppAction { public AppAction( ActionId action_id,ItemType item_type,String item ){ this.action_id=action_id; this.item_type=item_type; this.item=item; } ActionId action_id; ItemType item_type; String item ; String extend1; String extend2; Long ts; public static List<AppAction> buildList(AppPage appPage,Long startTs,Integer duringTime){ List<AppAction> actionList=new ArrayList(); Boolean ifFavor= RandomOptionGroup.builder().add(true ,AppConfig.if_favor_rate).add(false,100-AppConfig.if_favor_rate).build().getRandBoolValue(); Boolean ifCart= RandomOptionGroup.builder().add(true ,AppConfig.if_cart_rate).add(false,100-AppConfig.if_cart_rate).build().getRandBoolValue(); Boolean ifCartAddNum=RandomOptionGroup.builder().add(true ,AppConfig.if_cart_add_num_rate).add(false,100-AppConfig.if_cart_add_num_rate).build().getRandBoolValue(); Boolean ifCartMinusNum=RandomOptionGroup.builder().add(true ,AppConfig.if_cart_minus_num_rate).add(false,100-AppConfig.if_cart_minus_num_rate).build().getRandBoolValue(); Boolean ifCartRm=RandomOptionGroup.builder().add(true ,AppConfig.if_cart_rm_rate).add(false,100-AppConfig.if_cart_rm_rate).build().getRandBoolValue(); Boolean ifGetCouponRm=RandomOptionGroup.builder().add(true ,AppConfig.if_get_coupon).add(false,100-AppConfig.if_get_coupon).build().getRandBoolValue(); if(appPage.page_id== PageId.good_detail){ if(ifFavor){ AppAction favorAction = new AppAction(ActionId.favor_add, appPage.item_type, appPage.item); actionList.add(favorAction); } if(ifCart){ AppAction cartAction = new AppAction(ActionId.cart_add, appPage.item_type, appPage.item); actionList.add(cartAction); } if(ifGetCouponRm){ int couponId = RandomNum.getRandInt(1, AppConfig.max_coupon_id); AppAction couponAction = new AppAction(ActionId.get_coupon, ItemType.coupon_id, String.valueOf(couponId)); actionList.add(couponAction); } } else if(appPage.page_id==PageId.cart){ if(ifCartAddNum){ int skuId = RandomNum.getRandInt(1, AppConfig.max_sku_id); AppAction favorAction = new AppAction(ActionId.cart_add_num, ItemType.sku_id, skuId+""); actionList.add(favorAction); } if(ifCartMinusNum){ int skuId = RandomNum.getRandInt(1, AppConfig.max_sku_id); AppAction favorAction = new AppAction(ActionId.cart_minus_num, ItemType.sku_id, skuId+""); actionList.add(favorAction); } if(ifCartRm){ int skuId = RandomNum.getRandInt(1, AppConfig.max_sku_id); AppAction favorAction = new AppAction(ActionId.cart_remove, ItemType.sku_id, skuId+""); actionList.add(favorAction); } } else if(appPage.page_id==PageId.trade){ Boolean ifAddAddress=RandomOptionGroup.builder().add(true ,AppConfig.if_add_address).add(false,100-AppConfig.if_add_address).build().getRandBoolValue(); if(ifAddAddress){ AppAction appAction = new AppAction(ActionId.trade_add_address, null, null); actionList.add(appAction); } } else if(appPage.page_id==PageId.favor){ Boolean ifFavorCancel=RandomOptionGroup.builder().add(true ,AppConfig.if_favor_cancel_rate).add(false,100-AppConfig.if_favor_cancel_rate).build().getRandBoolValue(); int skuId = RandomNum.getRandInt(1, AppConfig.max_sku_id); for (int i = 0; i < 3; i++) { if(ifFavorCancel){ AppAction appAction = new AppAction(ActionId.favor_canel, ItemType.sku_id, skuId+i+""); actionList.add(appAction); } } } int size = actionList.size(); long avgActionTime = duringTime / (size+1); for (int i = 1; i <= actionList.size(); i++) { AppAction appAction = actionList.get(i-1); appAction.setTs(startTs+i*avgActionTime); } return actionList; } }
trevorgowing/project-log-server
src/test/java/com/trevorgowing/projectlog/log/risk/RiskRetrieverTests.java
<reponame>trevorgowing/project-log-server package com.trevorgowing.projectlog.log.risk; import static com.trevorgowing.projectlog.log.risk.IdentifiedRiskDTOBuilder.anIdentifiedRiskDTO; import static com.trevorgowing.projectlog.log.risk.RiskBuilder.aRisk; import static com.trevorgowing.projectlog.log.risk.RiskNotFoundException.identifiedRiskNotFoundException; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import com.trevorgowing.projectlog.common.types.AbstractTests; import com.trevorgowing.projectlog.log.LogDTO; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; public class RiskRetrieverTests extends AbstractTests { @Mock private RiskRepository riskRepository; @InjectMocks private RiskRetriever riskRetriever; @Test(expected = RiskNotFoundException.class) public void testFindRiskWithNonExistentRisk_shouldThrowRiskNotFoundException() { // Set up expectations when(riskRepository.findById(1L)).thenThrow(identifiedRiskNotFoundException(1L)); // Exercise SUT riskRetriever.findRisk(1L); } @Test public void testFindRiskWithExistingRisk_shouldReturnRisk() { // Set up fixture Risk expectedRisk = aRisk().id(1L).build(); // Set up expectations when(riskRepository.findById(1L)).thenReturn(Optional.of(expectedRisk)); // Exercise SUT Risk actualRisk = riskRetriever.findRisk(1L); // Verify behaviour assertThat(actualRisk, is(expectedRisk)); } @Test public void testGetLogDTOs_shouldDelegateToRiskRepositoryAndReturnLogDTOs() { // Set up fixture List<IdentifiedRiskDTO> identifiedRiskDTOs = asList( anIdentifiedRiskDTO().id(1).summary("Risk One").build(), anIdentifiedRiskDTO().id(2).summary("Risk Two").build()); List<LogDTO> expectedLogDTOs = new ArrayList<>(identifiedRiskDTOs); // Set up expectations when(riskRepository.findIdentifiedRiskDTOs()).thenReturn(identifiedRiskDTOs); // Exercise SUT List<LogDTO> actualLogDTOs = riskRetriever.getLogDTOs(); // Verify behaviour assertThat(actualLogDTOs, is(expectedLogDTOs)); } @Test(expected = RiskNotFoundException.class) public void testGetLogDTOByIdWithNoMatchingRisk_shouldThrowIdentifiedRiskNotFoundException() { // Set up expectations when(riskRepository.findIdentifiedRiskDTOById(1L)).thenReturn(null); // Exercise SUT riskRetriever.getLogDTOById(1L); } @Test public void testGetLogDTOByIdWithMatchingRisk_shouldDelegateToIssueRepositoryAndReturnIdentifiedIssueDTO() { // Set up fixture IdentifiedRiskDTO expectedIdentifiedRiskDTO = anIdentifiedRiskDTO().id(1L).build(); // Set up expectations when(riskRepository.findIdentifiedRiskDTOById(1L)).thenReturn(expectedIdentifiedRiskDTO); // Exercise SUT LogDTO actualLogDTO = riskRetriever.getLogDTOById(1L); // Verify behaviour assertThat(actualLogDTO, is(expectedIdentifiedRiskDTO)); } @Test public void testGetIdentifiedRiskDTOs_shouldDelegateToRiskRepositoryAndReturnIdentifiedRiskDTOs() { // Set up fixture List<IdentifiedRiskDTO> expectedIdentifiedRiskDTOs = asList( anIdentifiedRiskDTO().id(1).summary("Risk One").build(), anIdentifiedRiskDTO().id(2).summary("Risk Two").build()); // Set up expectations when(riskRepository.findIdentifiedRiskDTOs()).thenReturn(expectedIdentifiedRiskDTOs); // Exercise SUT List<IdentifiedRiskDTO> actualIdentifiedRiskDTOs = riskRetriever.getIdentifiedRiskDTOs(); // Verify behaviour assertThat(actualIdentifiedRiskDTOs, is(expectedIdentifiedRiskDTOs)); } }
pk65/DynaTableMvp
src/main/java/com/google/gwt/sample/dynatablemvp/shared/DiagTools.java
<reponame>pk65/DynaTableMvp package com.google.gwt.sample.dynatablemvp.shared; import java.util.Iterator; import java.util.Set; import javax.validation.ConstraintViolation; public class DiagTools { private static final transient String[] DAYS = new String[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" }; public static String getDescription(int zeroBasedDayOfWeek, int startMinutes, int endMinutes) { return DAYS[zeroBasedDayOfWeek] + " " + getHrsMins(startMinutes) + "-" + getHrsMins(endMinutes); } private static String getHrsMins(int mins) { int hrs = mins / 60; if (hrs > 12) { hrs -= 12; } int remainder = mins % 60; return hrs + ":" + (remainder < 10 ? "0" + remainder : String.valueOf(remainder)); } public static String getViolationText(String message, Set<ConstraintViolation<?>> errors) { StringBuilder buffer = new StringBuilder(message); Iterator<ConstraintViolation<?>> iter = errors.iterator(); while (iter.hasNext()) { buffer.append("\r\n"); buffer.append(iter.next().getMessage()); } return buffer.toString(); } }