language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,136
2.53125
3
[]
no_license
/* * 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 paw.timetable.model; import java.sql.Time; import javax.persistence.Entity; /** * * @author Arek */ @Entity public class SubjectWithNames extends Subject{ private String className; private String subjectName; public SubjectWithNames() { } public SubjectWithNames(String className, String subjectName, int id, Time start, Time end, int dayOfWeek, int nameId, int classId) { super(id, start, end, dayOfWeek, nameId, classId); this.className = className; this.subjectName = subjectName; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } }
Java
UTF-8
1,625
2.484375
2
[]
no_license
package com.base.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.base.entity.SimplePage; /** * Mapper的基础接口 * @author wille * */ public interface BaseCrudMapper<ModelType> { /** * 插入语句接口 * @param entity 对象 * @return */ int insert(ModelType entity); /** * 根据主键查询对象 * @param entity 对象 * @return 返回一个对象或者null */ ModelType selectByPrimaryKey(ModelType entity); /** * 删除对象 * @param entity 传入主键 * @return */ int deleteByPrimaryKey(ModelType entity); /** * 更新对象资料 * @param entity 必须存在主键 * @return */ int updateByPrimaryKey(ModelType entity); /** * 查询对象集合,不分页方法(建议限制条数) * @param entity 对象信息 * @param paramMap 其他参数集合 * @return */ List<ModelType> selectByParams( @Param("model") ModelType entity, @Param("params") Map<String, Object> paramMap); /** * 获取条数 * @param entity 对象信息, (不一定要用到,可以传空) * @param paramMap 其他参数, (不一定要用到,可以传空) * @return */ int selectCount( @Param("model") ModelType entity, @Param("params") Map<String, Object> paramMap); /** * 查询对象集合,分页方法 * @param page 分页对象 * @param paramMap 其他参数 * @param orderBy 排序 * @return */ List<ModelType> selectByPage( @Param("page") SimplePage page, @Param("params") Map<String, Object> paramMap, @Param("orderByField") String orderByField); }
SQL
UTF-8
218
3.5
4
[]
no_license
Select E.FirstName, E.LastName, I.InvoiceId From Employee E Join Customer C Join Invoice I where EmployeeId = C.SupportRepId And C.CustomerId = I.CustomerId And Title = "Sales Support Agent" Order By E.LastName
Java
UTF-8
11,246
2.578125
3
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
import helper.RobotBuilder; import model.*; import model.robotTypes.BaseRobot; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.Random; @RunWith(Parameterized.class) public class BaseRobotTest { final int max = 10; final int min = -10; private final int rounds; private final BaseRobot baseRobot; public BaseRobot creatTestBaseRobot(int arenaWidth, int arenaHeight, boolean isTorus, double engineR, double engineL, double engineDistance, double diameters, double poseX, double poseY, double poseRotation) { Arena arena = Arena.getInstance(arenaWidth, arenaHeight, isTorus); BaseRobot baseRobot = new RobotBuilder() .arena(arena) .diameters(diameters) .engineDistance(engineDistance) .powerTransmission(0) .random(new Random()) .engineLeft(engineL) .engineRight(engineR) .timeToSimulate(0) .minSpeed(min) .maxSpeed(max) .ticsPerSimulatedSecond(10) .pose(new Pose(poseX, poseY, poseRotation)) .buildDefault(); arena.addEntity(baseRobot); return baseRobot; } public BaseRobotTest(double engineRight, double engineLeft, int rounds) { this.rounds = rounds; baseRobot = creatTestBaseRobot(1000, 1000, false, engineRight, engineLeft, 1, 5, 10, 10, 0); if (baseRobot.getPaused()) baseRobot.togglePause(); } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {0, 1, 1}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}, {1, 0, 1000}, {0, 1, 1000}, {1, 0.9, 1}, {0.9, 1, 1}, {.1, 0, 1}, {.1, .1, 1000}, {0, .1, 1}, {.1, 0, 1000}, {0, .1, 1000}, {.5, 0, 1000}, {7, 4, 1000}, {2, 9, 1000}, {0, .5, 1000}, {-1, -1, 1000}, {-11, -1, 100}, {-1, 0, 1000}, {10, 10, 100}, {-10, -10, 100}, {11, 11, 100}, {-11, -11, 100}, {5, 5, 100}, {-5, -5, 100}, }); } private void setNext() { baseRobot.alterMovingVector(); baseRobot.setNextPosition(); } /** * Tests if the robot will stand on the correct position with given distance after driving * Also checks if when driven backwards position is correct */ @Test public void testDriveStraight() { double max = Math.max(baseRobot.getEngineL(), baseRobot.getEngineR()); baseRobot.setEngines(max, max); double speed = baseRobot.getTrajectoryMagnitude(); double speedAtStart = 0; Position position; if (speed != 0) { if (max > 0) { position = baseRobot.getPose().getPositionInDirection(rounds); for (int i = 0; i < rounds / speed; i++) { setNext(); if (baseRobot.getAccelerationInPercent() * baseRobot.getTrajectoryMagnitude() * i <= baseRobot.getTrajectoryMagnitude()) { speedAtStart += baseRobot.getTrajectoryMagnitude() - baseRobot.getAccelerationInPercent() * baseRobot.getTrajectoryMagnitude() * i; } } } else { position = baseRobot.getPose().getPositionInDirection(-rounds); for (int i = 0; i > rounds / speed; i--) { setNext(); if (baseRobot.getAccelerationInPercent() * baseRobot.getTrajectoryMagnitude() * i >= baseRobot.getTrajectoryMagnitude()) { speedAtStart += baseRobot.getTrajectoryMagnitude() - baseRobot.getAccelerationInPercent() * baseRobot.getTrajectoryMagnitude() * i; } } } if (0 > max) speedAtStart = -speedAtStart; speedAtStart += rounds * baseRobot.getFriction(); Assert.assertEquals(baseRobot.getPose().getX(), position.getX(), speedAtStart); Assert.assertEquals(baseRobot.getPose().getY(), position.getY(), speedAtStart); } } /** * Tests if the robot will stay on the same position after driving in circles */ @Test public void testDriveCircle() { double degree = baseRobot.angularVelocity(); Position position = baseRobot.getPose().clone(); for (double i = 0; i < rounds * 2 * Math.PI && i > rounds * 2 * Math.PI; i += degree) { setNext(); } Assert.assertTrue(Math.round(baseRobot.getPose().getX()) == Math.round(position.getX()) && Math.round(baseRobot.getPose().getY()) == Math.round(position.getY())); } /** * Tests if the distance between the destination and the robot gets less * if getTrajectoryMagnitude is negative it will test if the robot increased its distance */ @Test public void testDriveToPosition() { double max = Math.max(baseRobot.getEngineL(), baseRobot.getEngineR()); if (max != 0) { Position position = new Position(500, 500); double speed = baseRobot.getTrajectoryMagnitude(); double distance = position.getEuclideanDistance(baseRobot.getPose()); for (int i = 0; i < rounds / speed; i++) { baseRobot.driveToPosition(position, 1, max); setNext(); } if (max > 0) Assert.assertTrue(distance > position.getEuclideanDistance(baseRobot.getPose())); else Assert.assertTrue(distance <= position.getEuclideanDistance(baseRobot.getPose())); } } /** * Tests if the distance between the destination and the robot gets less * if getTrajectoryMagnitude is negative it will test if the robot increased its distance */ @Test public void testDriveToPosition2() { double max = Math.max(baseRobot.getEngineL(), baseRobot.getEngineR()); if (max != 0) { Position position = new Position(500, 500); double speed = baseRobot.getTrajectoryMagnitude(); double distance = position.getEuclideanDistance(baseRobot.getPose()); for (int i = 0; i < rounds / speed; i++) { baseRobot.driveToPosition(position); setNext(); } if (max > 0) Assert.assertTrue(distance > position.getEuclideanDistance(baseRobot.getPose())); else Assert.assertTrue(distance <= position.getEuclideanDistance(baseRobot.getPose())); } } /** * Tests if the move random will change the position */ @Test public void testMoveRandom() { double speed = baseRobot.getTrajectoryMagnitude(); Pose clone = baseRobot.getPose().clone(); if (speed != 0) { if (rounds / speed > 0) { for (int i = 0; i < rounds / speed; i++) { setNext(); } } else { for (int i = 0; i > rounds / speed; i--) { setNext(); } } Assert.assertFalse(clone.equals(baseRobot.getPose())); } else Assert.assertTrue(clone.equals(baseRobot.getPose())); } /** * Tests the increase Speed */ @Test public void testIncreaseSpeed() { double engineL = baseRobot.getEngineL(); double engineR = baseRobot.getEngineR(); baseRobot.increaseSpeed(2); if (engineL <= min) Assert.assertEquals(baseRobot.getEngineL(), min + 2, 0.0); else if (engineL >= max || engineL + 1 >= max) Assert.assertEquals(baseRobot.getEngineL(), max, 0.0); else Assert.assertEquals(baseRobot.getEngineL(), engineL + 2, 0.0); if (engineR <= min) { Assert.assertEquals(baseRobot.getEngineR(), min + 2, 0.0); } else if (engineR >= max || engineR + 1 >= max) Assert.assertEquals(baseRobot.getEngineR(), max, 0.0); else Assert.assertEquals(baseRobot.getEngineR(), engineR + 2, 0.0); } /** * Tests the increase Speed */ @Test public void testDecreaseSpeed() { double engineL = baseRobot.getEngineL(); double engineR = baseRobot.getEngineR(); baseRobot.setEngines(engineL, engineR); baseRobot.increaseSpeed(-3); if (engineL <= min || engineL - 3 <= min) Assert.assertEquals(baseRobot.getEngineL(), min, 0.0); else if (engineL >= max) Assert.assertEquals(baseRobot.getEngineL(), max - 3, 0.0); else Assert.assertEquals(baseRobot.getEngineL(), engineL - 3, 0.0); if (engineR <= min || engineR - 3 <= min) { Assert.assertEquals(baseRobot.getEngineR(), min, 0.0); } else if (engineR >= max) Assert.assertEquals(baseRobot.getEngineR(), max - 3, 0.0); else Assert.assertEquals(baseRobot.getEngineR(), engineR - 3, 0.0); } @Test public void testSetEngines() { double engineL = baseRobot.getEngineL(); double engineR = baseRobot.getEngineR(); baseRobot.setEngines(engineR, engineL); if (engineR <= min) Assert.assertEquals(baseRobot.getEngineL(), min, 0.0); else if (engineR >= max) Assert.assertEquals(baseRobot.getEngineL(), max, 0.0); else Assert.assertEquals(baseRobot.getEngineL(), engineR, 0.0); if (engineL <= min) { Assert.assertEquals(baseRobot.getEngineR(), min, 0.0); } else if (engineL >= max) Assert.assertEquals(baseRobot.getEngineR(), max, 0.0); else Assert.assertEquals(baseRobot.getEngineR(), engineL, 0.0); } @Test public void testCmPerSecond() { Assert.assertEquals(baseRobot.cmPerSecond(), baseRobot.getMovingVec().get().getLength() * 10, 0); } @Test public void testTurn() { double resultingDegree = baseRobot.getPose().getRotation() + Math.toRadians(10); resultingDegree %= (2 * Math.PI); //decreasing speed because rotation speed is to high baseRobot.setEngines(baseRobot.getEngineL() * 0.01, baseRobot.getEngineL() * 0.001); if (baseRobot.getEngineL() == baseRobot.getEngineR()) { baseRobot.setEngines(0.01, .001); } int i = 0; while (!baseRobot.turn(10)) { Assert.assertNotEquals(baseRobot.getPose().getRotation(), resultingDegree); baseRobot.getPose().incRotation(baseRobot.angularVelocity()); } Assert.assertEquals(baseRobot.getPose().getRotation(), resultingDegree, Math.toRadians(1)); } }
C
UTF-8
4,166
2.625
3
[]
no_license
#include <stdint.h> #include <stddef.h> #include <unistd.h> /* POSIX Header files */ #include <pthread.h> #include <ti/drivers/I2C.h> #include "board.h" #include "i2c_api.h" /***************************************************************************** * LOCAL FUNCTION PROTOTYPES */ /***************************************************************************** * LOCAL VARIABLES */ static I2C_Handle i2c; static I2C_Params i2cParams; static I2C_Transaction i2cTransaction; static pthread_mutex_t i2cMutex; /***************************************************************************** * @brief Init i2c module * * * @return 1 - Initialization failed * 0 - Initialization success ******************************************************************************/ int i2c_init(void) { int retc; retc = pthread_mutex_init(&i2cMutex, NULL); if (retc != 0) { /* pthread_mutex_init() failed */ while (1) {} } // Init here I2C I2C_init(); /* Create I2C for usage */ I2C_Params_init(&i2cParams); i2cParams.bitRate = I2C_400kHz; i2c = I2C_open(Board_I2C0, &i2cParams); if (i2c == NULL) { //Display_printf(display, 0, 0, "Error Initializing I2C\n"); return -1; } else { //Display_printf(display, 0, 0, "I2C Initialized!\n"); return 0; } } /***************************************************************************** * @brief Write data to i2c Slave * * * * @return 1 - Initialization failed * 0 - Initialization success ******************************************************************************/ void i2c_write(uint8_t device_addr, uint8_t reg, uint8_t value) { uint8_t txBuffer[2] = {reg, value}; i2c_write_buf(device_addr, txBuffer, 2); } // Read data from uint8_t i2c_read(uint8_t device_addr, uint8_t reg) { pthread_mutex_lock(&i2cMutex); uint8_t txBuffer[1]; uint8_t rxBuffer[1]; txBuffer[0] = reg; i2cTransaction.slaveAddress = device_addr; i2cTransaction.writeBuf = txBuffer; i2cTransaction.writeCount = 1; i2cTransaction.readBuf = rxBuffer; i2cTransaction.readCount = 1; if (I2C_transfer(i2c, &i2cTransaction)) { pthread_mutex_unlock(&i2cMutex); return rxBuffer[0]; } pthread_mutex_unlock(&i2cMutex); return 0xFF; } // This function write 16 bit command to Slave void i2c_write_u16_cmd(uint8_t device_addr, uint16_t reg) { pthread_mutex_lock(&i2cMutex); uint8_t txBuffer[2]; txBuffer[0] = reg>>8; txBuffer[1] = reg&0xFF; i2cTransaction.slaveAddress = device_addr; i2cTransaction.writeBuf = txBuffer; i2cTransaction.writeCount = 2; i2cTransaction.readBuf = NULL; i2cTransaction.readCount = 0; if (I2C_transfer(i2c, &i2cTransaction)) { //temperature = (rxBuffer[0] << 6) | (rxBuffer[1] >> 2); pthread_mutex_unlock(&i2cMutex); return ; } else { pthread_mutex_unlock(&i2cMutex); return ; } } // This function read data buffer from Slave uint8_t i2c_write_buf(uint8_t device_addr, uint8_t *txBuffer, uint32_t writeBufferLen) { pthread_mutex_lock(&i2cMutex); i2cTransaction.slaveAddress = device_addr; i2cTransaction.writeBuf = txBuffer; i2cTransaction.writeCount = writeBufferLen; i2cTransaction.readBuf = NULL; i2cTransaction.readCount = 0; if (I2C_transfer(i2c, &i2cTransaction)) { pthread_mutex_unlock(&i2cMutex); //Success return 0; } pthread_mutex_unlock(&i2cMutex); return 0xFF; } // This function read data buffer from Slave uint8_t i2c_read_buf(uint8_t device_addr, uint8_t *rxBuffer, uint32_t readBufferLen) { pthread_mutex_lock(&i2cMutex); i2cTransaction.slaveAddress = device_addr; i2cTransaction.writeBuf = NULL; i2cTransaction.writeCount = 0; i2cTransaction.readBuf = rxBuffer; i2cTransaction.readCount = readBufferLen; if (I2C_transfer(i2c, &i2cTransaction)) { pthread_mutex_unlock(&i2cMutex); //Success return 0; } pthread_mutex_unlock(&i2cMutex); return 0xFF; }
Java
UTF-8
1,370
1.921875
2
[]
no_license
package com.atguigu.atcrowdfunding.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.atguigu.atcrowdfunding.bean.TMenu; import com.atguigu.atcrowdfunding.service.TMenuService; @Controller public class TMenuController { @Autowired TMenuService menuService; @ResponseBody @RequestMapping("/menu/doDelete") public String doDelete(Integer id) { menuService.deleteTMenu(id); return "ok"; } @ResponseBody @RequestMapping("/menu/doUpdate") public String doUpdate(TMenu menu) { menuService.updateTMenu(menu); return "ok"; } @ResponseBody @RequestMapping("/menu/getMenuById") public TMenu getMenuById(Integer id) { TMenu menu = menuService.getMenuById(id); return menu; } @ResponseBody @RequestMapping("/menu/doAdd") public String doAdd(TMenu menu) { menuService.saveTMenu(menu); return "ok"; } @ResponseBody @RequestMapping("/menu/loadTree") public List<TMenu> loadTree() { List<TMenu> list = menuService.listMenuAllTree(); return list; } @RequestMapping("/menu/index") public String index() { return "menu/index"; } }
Markdown
UTF-8
28,309
2.78125
3
[]
no_license
# Helpful Tech Resources _Disclaimer: Please don't get stuck in 'tutorial hell'. Try to execute what you learned in a project or task of your own and then move on to the next interesting thing.<br>_ Over the last few months I spent a lot of time on social media, collecting all kinds of interesting, educational, and helpful resources. It was nearing the 100 links so I thought I would share them with the world, so here you go :) <br> Feel free to contact me on:<br> [![Twitter](https://img.shields.io/badge/lovelacecoding-%231DA1F2.svg?style=for-the-badge&logo=Twitter&logoColor=white)](https://www.twitter.com/lovelacecoding) [![Instagram](https://img.shields.io/badge/lovelacecoding-%23E4405F.svg?style=for-the-badge&logo=Instagram&logoColor=white)](https://www.instagram.com/lovelacecoding)<br> Also don't forget to give this repository a star ⭐ if you like it to keep up with changes. Use these resources yourself or share them with people that it could be helpful to. Thank you! ## Comments and Index Not all of these resources are free. **Paid**: you have to pay for the product or for a subscription. **Freemium**: the resource is partly free, partly paid * [Interactive Coding Courses](#interactive-coding-courses) * [Coding Challenges](#coding-challenges) * [Coding Project Inspiration](#coding-project-inspiration) * [Coding - What To Learn Next](#coding---what-to-learn-next) * [Blog Platforms](#blog-platforms) * [Video Course Platforms](#video-course-platforms) * [Helpful GitHub Repositories](#helpful-github-repositories) * [UI / UX](#ui--ux) * [Systm Administration & Networks](#system-administration--networks) * [DevOps](#devops) * [NoCode & Serverless](#nocode--serverless) * [Security & Hacking](#security--hacking) * [APIs](#apis) * [Studying](#studying) * [Career](#career) * [Cool Discord Communities](#cool-discord-communities) ## Interactive Coding Courses | Name | Languages | Notes | |--------------------|:---------------------------------:|----------| | [FreeCodeCamp](https://www.freecodecamp.org/) | <div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)</div> | | | [The Odin Project](https://www.theodinproject.com/) | <div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Ruby](https://img.shields.io/badge/ruby-%23CC342D.svg?style=for-the-badge&logo=ruby&logoColor=white)</div> | Focused on Web Development | | [DataCamp](https://www.datacamp.com/) |<div align="center">![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)![R](https://img.shields.io/badge/r-%23276DC3.svg?style=for-the-badge&logo=r&logoColor=white)</div> | **Freemium** - Focused on Machine Learning and Data Science | | [Kaggle](https://www.kaggle.com/learn) |<div align="center">![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)![SQL](https://img.shields.io/badge/SQL-00000F?style=for-the-badge&logo=sql&logoColor=white)</div> | Focused on Machine Learning | | [CodeAcademy](https://www.codecademy.com/) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)</div> | **Freemium** - Has more languages than listed | | [SoloLearn](https://www.sololearn.com) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)</div> | **Freemium** - Has more languages than listed | | [Educative](https://www.educative.io/) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)</div> | **Paid** - Has more languages than listed | | [Treehouse](https://teamtreehouse.com/) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)</div> | **Paid** | | [App Academy Open](https://www.appacademy.io/course/app-academy-open) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![Ruby](https://img.shields.io/badge/ruby-%23CC342D.svg?style=for-the-badge&logo=ruby&logoColor=white)</div> | | | [GA Dash](https://dash.generalassemb.ly/) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)</div> | | | [Khan Academy](https://bit.ly/2XAyDEv) |<div align="center">![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)</div> | | | [MongoDB University](https://university.mongodb.com/)|<div align="center">![MongoDB](https://img.shields.io/badge/MongoDB-%234ea94b.svg?style=for-the-badge&logo=mongodb&logoColor=white)</div> | Focused on NoSQL | ## Coding Challenges Coding challenges can be really fun. It can also help you to understand the logic behind the code you're writing better and can help you with getting through tech interviews | Name | Notes | |-------------------|---------------------------------------------------------------------------| | [Leetcode](https://leetcode.com/) | **Freemium** - Focused on code challenges used in big tech company interviews | | [Exercism](https://exercism.org/) | Including free mentorship | | [CodinGame](https://www.codingame.com/start) | | | [Coderbyte](https://coderbyte.com/) | | | [CodeWars](https://www.codewars.com/) | | | [Project Eulers](https://projecteuler.net/) | Focused on math related coding challenges | | [Front-end mentors](https://www.frontendmentor.io/) | Focused on frontend challenges by making projects | ## Coding Project Inspiration It's important to actually use what you learnt. Here are some long GitHub repositories to get some inspiration for your next project. | Name | Notes | |-----------------------------------------------------------------------------------------|----------------------------------------------| | [App Ideas](https://github.com/florinpop17/app-ideas) | By [Florin Pop](https://www.florin-pop.com/) | | [Project Megalist](https://github.com/karan/Projects) | By [Karan Goel](https://goel.io/) | | [Open Source Ideas](https://github.com/open-source-ideas/ideas) | | | [Project Based Learning](https://github.com/practical-tutorials/project-based-learning) | | ## Coding - What to Learn Next | Name | Notes | |-----------------------------------------------------------------------------|----------------------------------------------------------------------------| | [Bento](https://bento.io/) | Has multiple language tracks that help you find the best quality resources | | [Developer Roadmap](https://roadmap.sh/) | Community made flowcharts for developers | | [Hackr.io](https://hackr.io/) | Focused on finding the best courses and tutorials | | [The Missing Semester of Your CS Education](https://missing.csail.mit.edu/) | Focused on the aspects of being a developer that you may have missed | ## Blog Platforms People learn from people. Write your own blogposts to teach and inspire other or find likeminded people that write posts about topics you're interested in. | Name | Notes | |------------------------------------|-------------------------------------| | [Hashnode](https://hashnode.com/) | Focused on developers | | [Medium](https://medium.com/) | | | [DEV](https://dev.to/) | Has a podcast and video section too | | [Tumblr](https://www.tumblr.com/) | | | [Blogger](https://www.blogger.com) | | ## Video Course Platforms Do you learn best by watching videos? Find some really great courses, paid or free, on these platforms (or create your own). | Name | Notes | |------------------------------------------------------------|----------| | [Pluralsight](https://www.pluralsight.com/) | Paid | | [Coursera](https://www.coursera.org/) | Freemium | | [Udemy](https://www.udemy.com/) | Freemium | | [YouTube](https://www.youtube.com/) | | | [Microsoft Learn](https://docs.microsoft.com/en-us/learn/) | | | [Skillshare](https://www.skillshare.com/) | Paid | | [Fireship.io](https://fireship.io/) | Freemium | ## Helpful GitHub Repositories | Name | Notes | |-------------------------------------------------------------------------------------|----------------------------------------------------------------------------------| | [Awesome](https://github.com/sindresorhus/awesome) | Awesome lists about all kind of interesting tech topics | | [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) | In depth bookseries about JavaScript - By [Kyle Simpson](https://me.getify.com/) | | [Open Source Society University](https://github.com/ossu/computer-science) | Path to self-taught education in Computer Science | | [Free Programming Books](https://github.com/EbookFoundation/free-programming-books) | Freely available programming books in alot of languages | | [Free Certifications](https://github.com/cloudcommunity/free-certifications) | Curated list of free courses & certificates | | [30 Seconds of Code](https://github.com/30-seconds/30-seconds-of-code) | Short coding snippets for your development needs | ## UI / UX | Name | Notes | |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------| | [Hack Design](https://hackdesign.org/) | Recieve a design lesson in your inbox every week by a design pro | | [Figma - Learn Design](https://www.figma.com/resources/learn-design/) | Kick start your design education with lessons by Figma | | [Learn UX](https://learnux.io/) | UI/UX video courses | | [Coursera - UI/UX Design Specialization](https://www.coursera.org/specializations/ui-ux-design) | Allround video course about UI/UX design | | [Awesome Design](https://github.com/gztchan/awesome-design) | List with helpful design resources | | [unDraw](https://undraw.co/) | Open Source and free illustrations for your projects | | [Free Design Resources](https://twitter.com/hey_Ololade/status/1440220472554098695?t=kMHFFC6z0_WklLDoO-VdlA&s=19) | Huge list of free design resources - By [Bello Ololade](https://twitter.com/hey_Ololade) | ## System Administration & Networks | Name | Notes | |---------------------------------------------------------------------------------------------------|----------------------------| | [Powershell Course](https://docs.microsoft.com/en-us/learn/modules/introduction-to-powershell/) | | | [Windows Server Courses](https://bit.ly/3EqU6jh) | | | [Linux Unhatched](https://www.netacad.com/courses/os-it/ndg-linux-unhatched) | | | [Linux Essentials](https://www.netacad.com/courses/os-it/ndg-linux-essentials) | | | [Introduction to Networks](https://www.netacad.com/courses/networking/ccna-introduction-networks) | Paid | | [CMD Challenge](https://cmdchallenge.com/) | Challenge your bash skills | ## DevOps | Name | Notes | |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------| | [Docker Curriculum](https://docker-curriculum.com/) | | | [Docker and VS Code Tutorial](https://docs.microsoft.com/en-us/visualstudio/docker/tutorials/docker-tutorial) | | | [Awesome Docker](https://github.com/veggiemonk/awesome-docker) | Curated resource list all about Docker | | [Docker Cheatsheet](https://www.docker.com/sites/default/files/d8/2019-09/docker-cheat-sheet.pdf) | PDF file | | [Learn Kuburnetes](https://kubernetes.io/docs/tutorials/kubernetes-basics/) | | | [Digital Ocean-Intro to Kuburnetes](https://do.co/2XDoJ50) | | | [CI/CD With Azure DevOps](https://docs.microsoft.com/en-us/learn/modules/implement-ci-cd-azure-devops/) | | | [CI/CD With GitHub Actions](https://docs.microsoft.com/en-us/azure/app-service/deploy-github-actions) | | | [Get Started With Azure](https://medium.com/bb-tutorials-and-thoughts/how-to-get-started-with-azure-87ffd3bcfb7a) | | | [Awesome Azure Learning](https://github.com/ddneves/awesome-azure-learning) | Curated resource list all about learning Azure | | [Get Started With AWS](https://aws.amazon.com/getting-started/) | | | [Awesome AWS](https://github.com/donnemartin/awesome-aws) | Curated resource list all about AWS | ## NoCode & Serverless | Name | Notes | |----------------------------------------------------------------------------------------|----------------------------------------------------------| | [Wordpress No-Code Tutorials](https://wpnocode.com/) | | | [Webflow](https://webflow.com/) | | | [Awesome NoCode/LowCode](https://github.com/kairichard/awesome-nocode-lowcode) | Curated resource list all about NoCode & LowCode | | [Azure Functions University](https://github.com/marcduiker/azure-functions-university) | By [Marc Duiker](https://twitter.com/marcduiker) | | [The Serverless Framework](https://github.com/serverless/serverless) | | | [Awesome Serverless](https://github.com/anaibol/awesome-serverless) | Curated resource list all about serverless technology | ## Security & Hacking | Name | Notes | |-----------------------------------------------------------------------------------------------------------|---------------------------------------------| | [Hacker101](https://www.hacker101.com/) | CTF challenges and video courses | | [CoHackers](https://cohackers.co//) | Find a mentor in hacking | | [TryHackMe](https://tryhackme.com/) | All kinds of courses on different levels | | [Hack The Box](https://www.hackthebox.eu/) | Virtual Machine challenges | | [Introduction to Cybersecurity](https://www.netacad.com/courses/cybersecurity/introduction-cybersecurity) | Course (with certification) by Cisco | | [Awesome Security](https://github.com/sbilly/awesome-security) | A curated resources list all about security | ## APIs Looking for an API to use in your next project? Try one of these resources | Name | Notes | |-----------------------------------------------------------|-------| | [RapidAPI Hub](https://rapidapi.com/hub) | | | [Public APIs](https://github.com/public-apis/public-apis) | | | [API list](https://apilist.fun/) | | | [Awesome APIs](https://github.com/TonnyL/Awesome_APIs) | | ## Studying | Name | Notes | |-----------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------| | [25 Studying Tips](https://www.mydegreeguide.com/how-to-study-tips/) | Scientifically proven tips to help you with effectively studying | | [Crash Course - Study Skills](https://thecrashcourse.com/courses/studyskills) | Video Course all about studying | | [What is The Pomodoro Technique](https://todoist.com/nl/productivity-methods/pomodoro-technique) | How to study in small parts | | [Pomodoro Timer](https://pomofocus.io/) | | | [The Best Note-Taking Methods](https://medium.goodnotes.com/the-best-note-taking-methods-for-college-students-451f412e264e) | | | [Cornell Note Taking](https://medium.goodnotes.com/study-with-ease-the-best-way-to-take-notes-2749a3e8297b) | | ## Career | Name | Notes | |--------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------| | [Break Into Tech (without coding)](https://www.breakinto.tech/) | Focused on all kinds of information on how to get a tech job without being a developer | | [Developer Portfolio Inspiration](https://github.com/emmabostian/developer-portfolios) | Over 100 examples of developer portfolios - By [Emma Bostian](https://twitter.com/emmabostian) | | [Make your GitHub Page stand out](https://www.eddiejaoude.io/course-github-profile-landing) | Video course about how to make your GitHub page look amazing - By [Eddie Jaoude](https://www.eddiejaoude.io) | | [Get a Job Using LinkedIn](https://www.youtube.com/playlist?list=PL54X5yR8qizsMpvTCqUIEFMeEp-chvcxk) | YouTube Playlist full of tips on how to make your LinkedIn page better - By [Danny Thompson](https://twitter.com/DThompsonDev) | | [Open Source Internship Programs](https://github.com/deepanshu1422/List-Of-Open-Source-Internships-Programs) | A curated list of all open source internship programs | | [Summer 2022 Internships](https://github.com/pittcsc/Summer2022-Internships) | A list of summer 2022 internship programs in the USA | | [The Forage](https://www.theforage.com/) | Take part of a virtual work experience program and get hired | | [Tech Interview Handbook](https://techinterviewhandbook.org/) | | | [Coding Interview University](https://github.com/jwasham/coding-interview-university) | By [John Washam](https://startupnextdoor.com/) | | [Awesome Interview Questions](https://github.com/DopplerHQ/awesome-interview-questions) | Links to frequently asked questions on tech interviews | | [Toastmasters](https://www.toastmasters.org/) | Join a toastmasters group anywhere in the world to get better at public speaking ## Cool Discord Communities | Name | Notes | |--------------------------------------------------------------|-----------------------------------------------------------| | [The Programmer Hangout](https://theprogrammershangout.com/) | Geared towards all kind of developers | | [Devcord](https://devcord.com/) | Geared towards web developers | | [The Coding Den](https://discord.com/invite/code) | Geared towards developers that have questions / need help | | [Commit Your Code!](https://bit.ly/30YfIop) | Geared towards developers (+ career advice) | | [EddieHub](https://discord.com/invite/jZQs6Wus) | Geared towards developers interested in open source | | [4C](https://github.com/pittcsc/Summer2022-Internships) | geared towards people that create (tech) content online |
Ruby
UTF-8
155
3.21875
3
[]
no_license
# Date started: 7/28/12 # Problem: 1 # Description sum = 0 1000.times do |i| if i % 5 == 0 || i % 3 == 0 sum += i end end puts sum
Python
UTF-8
3,078
2.9375
3
[]
no_license
import os from test.compiler_test_case import CompilerTestCase COMPILER_DIR = '/'.join(os.getcwd().split('/')[:-2]) class TestCrucial(CompilerTestCase): def test_program0(self): self.assertOutputEquals( self.getCodeFromFile('program0.imp'), '1\n0\n0\n0\n0\n0\n1\n0\n0\n0\n0\n1\n0\n0\n0\n1\n0\n0\n1\n0\n1', stdin='1345601\n' ) def test_program1(self): self.assertOutputEquals( self.getCodeFromFile('program1.imp'), '2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n53\n59\n61\n67\n71\n73\n79\n83\n89\n97', ) def test_program2(self): self.assertOutputEquals( self.getCodeFromFile('program2.imp'), '857\n1\n14405693\n1', stdin='12345678901\n' ) def test_1_numbers(self): code = self.getCodeFromFile('1-numbers.imp') output = self.compileAndRunWithStdin(code, '20\n') self.assertEqual( ''.join(output.split('> ')), '1\n2\n10\n100\n10000\n1234567890\n35\n15\n999\n555555555\n7777\n999\n11\n707\n7777' ) def test_2_fib(self): self.assertOutputEquals( self.getCodeFromFile('2-fib.imp'), '121393', stdin='1\n' ) def test_3_fib_factorial(self): self.assertOutputEquals( self.getCodeFromFile('3-fib-factorial.imp'), '2432902008176640000\n17711', stdin='20\n' ) def test_4_factorial(self): self.assertOutputEquals( self.getCodeFromFile('4-factorial.imp'), '2432902008176640000', stdin='20\n' ) def test_5_tab(self): self.assertOutputEquals( self.getCodeFromFile('5-tab.imp'), '0\n23\n44\n63\n80\n95\n108\n119\n128\n135\n140\n143\n144\n143\n140\n135\n128\n119\n108\n95\n80\n63\n44' '\n23\n0', ) def test_6_mod_mult(self): self.assertOutputEquals( self.getCodeFromFile('6-mod-mult.imp'), '? > 674106858', stdin='1234567890 1234567890987654321 987654321\n' ) def test_7_loopiii(self): self.assertOutputEquals( self.getCodeFromFile('7-loopiii.imp'), '? > 31000\n40900\n2222010', stdin='0\n0\n0\n' ) self.assertOutputEquals( self.getCodeFromFile('7-loopiii.imp'), '? > 31001\n40900\n2222012', stdin='1\n0\n2\n' ) def test_8_for(self): self.assertOutputEquals( self.getCodeFromFile('8-for.imp'), '? > 507\n4379\n0', stdin='12\n23\n34\n' ) def test_9_sort(self): code = self.getCodeFromFile('9-sort.imp') output = self.compileAndRun(code) self.assertEqual( output, '5\n2\n10\n4\n20\n8\n17\n16\n11\n9\n22\n18\n21\n13\n19\n3\n15\n6\n7\n12\n14\n1\n1234567890\n1\n2\n3\n4\n5' '\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22' )
SQL
UTF-8
6,225
2.71875
3
[]
no_license
--CATEGORY insert into category values(10,'일반메뉴'); insert into category values(20,'추천메뉴'); insert into category values(30,'버거/세트'); insert into category values(40,'스낵/사이드'); insert into category values(50,'음료'); insert into category values(60,'해피밀'); insert into category values(11,'아침메뉴'); insert into category values(70,'아침추천메뉴'); insert into category values(80,'아침버거/세트'); insert into category values(90,'아침스낵/사이드'); --FOOD INSERT INTO FOOD VALUES (301,'빅맥',5300,'301.png','난류,우유,대두,밀,쇠고기',3.8,583,30); INSERT INTO FOOD VALUES (302,'맥스파이시 상하이버거',5300,'302.png','난류,우유,대두,밀,쇠고기',3.8,494,30); INSERT INTO FOOD VALUES (303,'1955버거',6400,'303.png', '난류, 우유, 대두, 밀, 돼지고기, 토마토, 쇠고기', 3.8, 536,30); INSERT INTO FOOD VALUES (304,'맥치킨 모짜렐라',5500,'304.png', '난류, 우유, 대두, 밀, 토마토, 닭고기', 3.8, 686,30); INSERT INTO FOOD VALUES (305,'맥치킨',4000,'305.png', '난류, 대두, 밀, 닭고기', 3.8, 483,30); INSERT INTO FOOD VALUES (306,'더블 불고기 버거',5100,'306.png','난류, 우유, 대두, 밀, 돼지고기, 조개, 굴',3.8,677,30); INSERT INTO FOOD VALUES (307,'에그 불고기 버거',3900,'307.png','난류, 대두, 밀, 돼지고기, 조개, 굴', 3.8, 514,30); INSERT INTO FOOD VALUES (308,'불고기 버거',2900,'308.png','난류, 대두, 밀, 돼지고기, 조개, 굴',3.8,430,30); INSERT INTO FOOD VALUES (309,'슈비 버거',6200,'309.png', '난류, 우유, 대두, 밀, 토마토, 새우, 쇠고기, 굴',3.8,563,30); INSERT INTO FOOD VALUES (310,'베이컨 토마토 디럭스',6200,'310.png', '난류, 우유, 대두, 밀, 돼지고기, 토마토, 쇠고기',3.8,545,30); INSERT INTO FOOD VALUES (311,'더블 쿼터파운더 치즈',7700,'311.png', '우유, 대두, 밀, 토마토, 쇠고기',3.8,770,30); INSERT INTO FOOD VALUES (312,'쿼터파운더 치즈',5900,'312.png', '우유, 대두, 밀, 토마토, 쇠고기',3.8,535,30); INSERT INTO FOOD VALUES (313,'치즈버거',3000,'313.png', '우유, 대두, 밀, 토마토, 쇠고기',3.8,317,30); INSERT INTO FOOD VALUES (314,'더블 치즈버거',5100,'314.png', '우유, 대두, 밀, 토마토, 쇠고기',3.8,478,30); INSERT INTO FOOD VALUES (315,'햄버거',2700,'315.png', '대두, 밀, 토마토, 쇠고기',3.8,265,30); INSERT INTO FOOD VALUES(401,'케이준 비프 스낵랩',2900,'401.png', '난류, 대두, 밀, 쇠고기, 굴',3.8,292,40); INSERT INTO FOOD VALUES(402,'상하이 치킨 스낵랩',2900,'402.png', '난류, 대두, 밀, 돼지고기, 닭고기',3.8,283,40); INSERT INTO FOOD VALUES(403,'골든 모짜렐라 치즈스틱 4조각',4700,'403.png', '우유, 대두, 밀',3.8,324,40); INSERT INTO FOOD VALUES(404,'골든 모짜렐라 치즈스틱 2조각',2900,'404.png', '우유, 대두, 밀',3.8,162,40); INSERT INTO FOOD VALUES(405,'맥너겟 10조각',5200,'405.png', '대두, 밀, 닭고기',3.8,427,40); INSERT INTO FOOD VALUES(406,'맥너겟 6조각',3700,'406.png', '대두, 밀, 닭고기',3.8,256,40); INSERT INTO FOOD VALUES(407,'맥너겟 4조각',2500,'407.png', '대두, 밀, 닭고기',3.8,171,40); INSERT INTO FOOD VALUES(408,'맥스파이시 치킨텐더 4조각',5600,'408.png', '대두, 밀, 닭고기',3.8,383,40); INSERT INTO FOOD VALUES(409,'맥스파이시 치킨텐더 2조각',3200,'409.png', '대두, 밀, 닭고기',3.8,191,40); INSERT INTO FOOD VALUES(410,'후렌치 후라이',2400,'410.png', '대두',3.8,332,40); INSERT INTO FOOD VALUES(411,'애플 파이',1900,'411.png', '밀',3.8,236,40); INSERT INTO FOOD VALUES(412,'스트링 치즈',2300,'412.png', '우유',3.8,50,40); INSERT INTO FOOD VALUES(413,'디핑소스 추가구매 - 스위트 앤 샤워 소스',200,'413.png', '대두, 밀, 아황산류, 굴',3.8,40,40); INSERT INTO FOOD VALUES(414,'디핑소스 추가구매 - 스위트 칠리 소스',200,'414.png', '토마토',3.8,55,40); INSERT INTO FOOD VALUES(415,'디핑소스 추가구매 - 케이준 소스',200,'415.png', '난류, 대두',3.8,75,40); INSERT INTO FOOD VALUES(501,'카페라떼',3400,'501.png', '우유',3.8,149,50); INSERT INTO FOOD VALUES(502,'카푸치노',3400,'502.png', '우유',3.8,93,50); INSERT INTO FOOD VALUES(503,'아메리카노',2900,'503.png', '-',3.8,12,50); INSERT INTO FOOD VALUES(504,'드립 커피',2200,'504.png', '-',3.8,10,50); INSERT INTO FOOD VALUES(505,'아이스 카페라떼 (시럽없음)',3400,'505.png', '우유',3.8,108,50); INSERT INTO FOOD VALUES(506,'아이스 아메리카노 (시럽없음)',2900,'506.png', '-',3.8,9,50); INSERT INTO FOOD VALUES(507,'아이스 드립 커피 (시럽없음)',1700,'507.png', '-',3.8,10,50); INSERT INTO FOOD VALUES(508,'디카페인 카페라떼',3500,'508.png', '우유',3.8,150,50); INSERT INTO FOOD VALUES(509,'디카페인 카푸치노',3500,'509.png', '우유',3.8,149,50); INSERT INTO FOOD VALUES(510,'디카페인 아메리카노',3000,'510.png', '-',3.8,12,50); INSERT INTO FOOD VALUES(511,'디카페인 에스프레소',2300,'511.png', '-',3.8,8,50); INSERT INTO FOOD VALUES(512,'디카페인 아이스 카페라떼 (시럽없음)',3500,'512.png', '우유',3.8,114,50); INSERT INTO FOOD VALUES(513,'디카페인 아이스 아메리카노 (시럽없음)',3000,'513.png', '-',3.8,8,50); INSERT INTO FOOD VALUES(531,'딸기 칠러',3400,'531.png', '-',3.8,209,50); INSERT INTO FOOD VALUES(532,'배 칠러',3400,'532.png', '-',3.8,256,50); INSERT INTO FOOD VALUES(533,'바닐라 쉐이크',3200,'533.png', '우유',3.8,344,50); INSERT INTO FOOD VALUES(534,'딸기 쉐이크',3200,'534.png', '우유',3.8,350,50); INSERT INTO FOOD VALUES(535,'초코 쉐이크',3200,'535.png', '우유',3.8,344,50); INSERT INTO FOOD VALUES(551,'코카-콜라',2100,'551.png', '-',3.8,143,50); INSERT INTO FOOD VALUES(552,'코카-콜라 제로',2100,'552.png', '-',3.8,0,50); INSERT INTO FOOD VALUES(553,'스프라이트',2100,'553.png', '-',3.8,149,50); INSERT INTO FOOD VALUES(554,'환타',2100,'554.png', '-',3.8,136,50); INSERT INTO FOOD VALUES(570,'우유',2200,'570.png', '우유',3.8,null,50); INSERT INTO FOOD VALUES(580,'생수',1900,'580.png', '-',3.8,null,50); commit;
Java
UTF-8
2,114
2.59375
3
[]
no_license
package dev.mvvasilev.dto; import com.fasterxml.jackson.annotation.JsonFormat; import java.time.LocalDate; import java.util.Objects; import java.util.Set; /** * @author Miroslav Vasilev */ public class UserDTO { private Long id; private String firstName; private String lastName; private String email; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private LocalDate dateOfBirth; private Set<AddressDTO> addresses; public UserDTO() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(LocalDate dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Set<AddressDTO> getAddresses() { return addresses; } public void setAddresses(Set<AddressDTO> addresses) { this.addresses = addresses; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserDTO userDTO = (UserDTO) o; return Objects.equals(id, userDTO.id) && Objects.equals(firstName, userDTO.firstName) && Objects.equals(lastName, userDTO.lastName) && Objects.equals(email, userDTO.email) && Objects.equals(dateOfBirth, userDTO.dateOfBirth) && Objects.equals(addresses, userDTO.addresses); } @Override public int hashCode() { return Objects.hash(id, firstName, lastName, email, dateOfBirth, addresses); } }
C
UTF-8
1,850
3.0625
3
[]
no_license
#include "threadpool.h" #include <stdlib.h> void* worker_job(void* args) { ThreadPool* tp = args; while(1) { pthread_testcancel(); ThreadPoolTask* task = dequeue(tp->task_queue); if (task != NULL) { (*task->job)(task->data); free(task); } else { pthread_mutex_lock(&tp->task_mutex); tp->free_workers += 1; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); pthread_cond_wait(&tp->task_cond, &tp->task_mutex); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_mutex_unlock(&tp->task_mutex); } } } ThreadPool* threadpool_create(int worker_count) { ThreadPool* tp = malloc(sizeof(ThreadPool)); tp->worker_count = worker_count; pthread_mutex_init(&tp->task_mutex, NULL); pthread_cond_init(&tp->task_cond, NULL); tp->free_workers = 0; tp->task_queue = queue_create(); tp->worker = malloc(sizeof(pthread_t) * worker_count); for (int i = 0; i < worker_count; i++) { pthread_create(&tp->worker[i], NULL, &worker_job, tp); } return tp; } void threadpool_add_task(ThreadPool* tp, void (*job)(void*), void* data) { ThreadPoolTask* task = malloc(sizeof(ThreadPoolTask)); task->job = job; task->data = data; enqueue(tp->task_queue, task); pthread_mutex_lock(&tp->task_mutex); if (tp->free_workers > 0) { tp->free_workers -= 1; pthread_cond_signal(&tp->task_cond); } pthread_mutex_unlock(&tp->task_mutex); } void threadpool_destroy(ThreadPool* tp) { for (int i = 0; i < tp->worker_count; i++) { pthread_cancel(tp->worker[i]); } pthread_mutex_lock(&tp->task_mutex); pthread_cond_broadcast(&tp->task_cond); pthread_mutex_unlock(&tp->task_mutex); for (int i = 0; i < tp->worker_count; i++) { pthread_join(tp->worker[i], NULL); } free(tp->worker); pthread_mutex_destroy(&tp->task_mutex); pthread_cond_destroy(&tp->task_cond); queue_destroy(tp->task_queue); free(tp); }
Java
UTF-8
6,654
2.328125
2
[]
no_license
package com.example.ato.kinectcount01_android; import android.graphics.Bitmap; import android.graphics.Rect; import android.view.View; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.view.Display; import android.view.WindowManager; /** * Created by Ato on 2017-06-28. */ public class StreamView extends View { private Paint paintSkeleton; private Paint paintThreshold; private Paint paintText; private Path path; private int[] x; private int[] y; private int threshold; private int workoutType = 3; //2는 null private int height; private int width; public Bitmap depthBitmap; private Rect dst; public StreamView(Context context) { super(context); paintSkeleton = new Paint(); paintSkeleton.setColor(Color.RED); paintSkeleton.setStrokeWidth(10f); paintSkeleton.setStyle(Paint.Style.STROKE); paintThreshold = new Paint(); paintThreshold.setColor(Color.CYAN); paintThreshold.setStrokeWidth(7f); paintText = new Paint(); paintText.setColor(Color.CYAN); paintText.setTextSize(200); path = new Path(); x = new int[20]; y = new int[20]; depthBitmap = Bitmap.createBitmap(Var._DepthWidth, Var._DepthHeight, Bitmap.Config.ARGB_8888); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(depthBitmap,null,dst,null); path.rewind(); //Draw head and torso path.moveTo(x[Var._Head],y[Var._Head]); path.lineTo(x[Var._ShoulderCenter],y[Var._ShoulderCenter]); path.lineTo(x[Var._ShoulderLeft],y[Var._ShoulderLeft]); path.lineTo(x[Var._Spine],y[Var._Spine]); path.lineTo(x[Var._ShoulderRight],y[Var._ShoulderRight]); path.lineTo(x[Var._ShoulderCenter],y[Var._ShoulderCenter]); path.lineTo(x[Var._HipCenter],y[Var._HipCenter]); path.moveTo(x[Var._HipLeft],y[Var._HipLeft]); path.lineTo(x[Var._HipRight],y[Var._HipRight]); //Draw left leg path.moveTo(x[Var._HipCenter],y[Var._HipCenter]); path.lineTo(x[Var._HipLeft],y[Var._HipLeft]); path.lineTo(x[Var._KneeLeft],y[Var._KneeLeft]); path.lineTo(x[Var._AnkleLeft],y[Var._AnkleLeft]); path.lineTo(x[Var._FootLeft],y[Var._FootLeft]); //Draw right leg path.moveTo(x[Var._HipCenter],y[Var._HipCenter]); path.lineTo(x[Var._HipRight],y[Var._HipRight]); path.lineTo(x[Var._KneeRight],y[Var._KneeRight]); path.lineTo(x[Var._AnkleRight],y[Var._AnkleRight]); path.lineTo(x[Var._FootRight],y[Var._FootRight]); //Draw left arm path.moveTo(x[Var._ShoulderLeft],y[Var._ShoulderLeft]); path.lineTo(x[Var._ElbowLeft],y[Var._ElbowLeft]); path.lineTo(x[Var._WristLeft],y[Var._WristLeft]); path.lineTo(x[Var._HandLeft],y[Var._HandLeft]); //Draw right arm path.moveTo(x[Var._ShoulderRight],y[Var._ShoulderRight]); path.lineTo(x[Var._ElbowRight],y[Var._ElbowRight]); path.lineTo(x[Var._WristRight],y[Var._WristRight]); path.lineTo(x[Var._HandRight],y[Var._HandRight]); canvas.drawPath(path,paintSkeleton); // 카운트 쓰레시홀드 canvas.drawLine(0,threshold,width,threshold,paintThreshold); // 운동 종류 switch (workoutType) { case 0: canvas.drawText("Squat", 10, 150, paintText); break; case 1: canvas.drawText("Biceps", 10, 150, paintText); canvas.drawText("Curl", 10, 320, paintText); break; case 2: canvas.drawText("Shoulder", 10, 150, paintText); canvas.drawText("Press", 10, 320, paintText); break; default: break; } } @Override protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) { // 뷰의 현재 사이즈 height = yNew; width = xNew; dst = new Rect(0,0,width,height); super.onSizeChanged(xNew, yNew, xOld, yOld); } // 데이터를 받아 뎁스 도트 이미지를 만들고 스켈레톤 관절 좌표를 업데이트 // 쓰레시홀드 라인과 운동 종류 업데이트 public void useData(byte[] data) { //뎁스 이미지 int xIndex; int yIndex; int pixelData; for (int j = 0; j < Var._DepthWidth*Var._DepthHeight/8; j++){ xIndex = j*8 % Var._DepthWidth; yIndex = j*8 / Var._DepthWidth; pixelData = ((data[Var._DepthOffset + j] & 0x01)) * 0xFF; depthBitmap.setPixel(xIndex, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x02) >> 1) * 0xFF; depthBitmap.setPixel(xIndex+1, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x04) >> 2) * 0xFF; depthBitmap.setPixel(xIndex+2, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x08) >> 3) * 0xFF; depthBitmap.setPixel(xIndex+3, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x10) >> 4) * 0xFF; depthBitmap.setPixel(xIndex+4, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x20) >> 5) * 0xFF; depthBitmap.setPixel(xIndex+5, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x40) >> 6) * 0xFF; depthBitmap.setPixel(xIndex+6, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); pixelData = ((data[Var._DepthOffset + j] & 0x80) >> 7) * 0xFF; depthBitmap.setPixel(xIndex+7, yIndex, Color.argb(0xFF, pixelData, pixelData, pixelData)); } //스켈레톤 for(int i=0;i<20;i++) { x[i] = data[Var._SkelOffset + 2*i]; y[i] = data[Var._SkelOffset + 2*i+1]; // x 와 y 위치를 뷰 크기에 맞춤 x[i] = x[i] * width / Var._DepthWidth; y[i] = y[i] * height / Var._DepthHeight; } threshold = (data[Var._CountOffset] & 0x7F) * height / Var._DepthHeight; workoutType = data[0] & 0x7F; } }
Markdown
UTF-8
9,537
3.171875
3
[ "CC0-1.0" ]
permissive
# Héritage multiple ## Complément - niveau avancé ### Avertissement - toutes les classes concernées sont *new-style* Toutes les classes considérées dans ce complément sont supposées *new-style*. Pour les classes classiques, le mécanisme d'héritage multiple est plus rudimentaire, vous en trouverez le détail dans la référence au blog de Guido van Rossum (voir dernière section). Il est, à nouveau, très fortement **conseillé d'utiliser des classes *new- style*** si vous écrivez du nouveau code, car c'est la seule sorte de classe qui reste disponible en python3. ### Rappels L'héritage en python consiste principalement en l'algorithme de recherche d'un attribut d'une instance; celui-ci regarde : 1. d'abord dans l'instance, 1. ensuite dans la classe, 1. ensuite dans les super-classes. ### Le problème Les deux premiers points ne posent pas de problème de définition, puisque l'objet lui-même et sa classe sont **définis de manière unique**. Par contre, lorsqu'on utilise l'héritage multiple, on peut imaginer trouver l'attribut recherché dans **plusieurs superclasses**. Il est donc important de préciser, dans le cas où plusieurs superclasses possèdent l'attribut recherché, quel est celui qui doit être retenu. ### Ordre sur les superclasses Le problème revient donc à définir un **ordre** sur l'ensemble des **super- classes**. On parle bien, naturellement, de **toutes** les super-classes, pas seulement celles dont on hérite directement - en termes savants on dirait qu'on s'intéresse à la fermeture transitive de la relation d'héritage ou à l'arbre de recouvrement du graphe d'héritage. Après quelques errements (décrits dans la première référence de la dernière section, "Pour en savoir plus"), l'algorithme qui a été choisi pour déterminer l'ordre des superclasses, qui est en service depuis la version 2.3, est connu sous le nom de **linéarisation C3**. Cet algorithme n'est pas propre à python, comme vous pourrez le lire dans les références citées dans la dernière section. Nous ne décrirons pas ici l'algorithme lui-même dans le détail&nbsp;; par contre nous allons&nbsp;: * dans un premier temps résumer **les raisons** qui ont guidé ce choix, en décrivant les bonnes propriétés que l'on attend, ainsi que les **limitations** qui en découlent; * puis voir l'ordre obtenu sur quelques exemples concrets de hiérarchies de classes. Vous trouverez dans les références (voir ci-dessous la dernière section, "Pour en savoir plus") des liens vers des documents plus techniques si vous souhaitez creuser le sujet. ### Les bonnes propriétés attendues Il y a un certain nombre de bonnes propriétés que l'on attend de cet algorithme. ##### Priorité au spécifique Lorsqu'une classe A hérite d'une classe B, on s'attend à ce que les méthodes définies sur A, qui sont en principe plus spécifiques, soient utilisées de préférence à celles définies sur B. ##### Priorité à gauche Lorsqu'on utilise l'héritage multiple, on mentionne les classes mères dans un certain ordre, qui n'est pas anodin. Les classes mentionnées en premier sont bien entendu celles desquelles on veut hériter en priorité. ##### De manière un peu plus formelle Pour reformuler les deux points ci-dessus d'une manière un peu plus formelle&nbsp;: * on se donne un objet *o* de la classe *O* * on considère l'ensemble $\cal{S}$ des superclasses de *O* (qui contient *O*), * et on cherche à construire la MRO (Method Resolution Order), c'est-à-dire la liste $\cal{MRO}$ ordonnée des éléments de $\cal{S}$ dans lesquelles chercher les attributs de *o*. Les deux règles ci-dessus s'écrivent alors comme ceci&nbsp;: * $\forall A,B \in \cal{S}$, A hérite de B $\Rightarrow$ A est avant B dans $\cal{MRO}$ * $\forall B,C,D \in \cal{S}$, B hérite de C puis de D $\Rightarrow$ B est avant C qui est avant D dans $\cal{MRO}$ La formule "B hérite de C puis de D" est à prendre ici au sens large; B peut hériter de plus de deux classes, tout ce qui est demandé est que C apparaisse avant D dans la liste des classes mères. ##### Limitations : toutes les hiérarchies ne peuvent pas être traitées L'algorithme C3 permet de calculer un ordre sur $\cal{S}$ qui respecte toutes ces contraintes, lorsqu'il en existe un. En effet, dans certains cas on ne peut pas trouver un tel ordre. Nous en verrons un exemple vers la fin de ce document&nbsp;; comme vous le verrez on peut exhiber de tels exemples qui restent relativement simples. Cependant, dans la pratique, il est relativement rare de tomber sur de tels cas pathologiques&nbsp;; et lorsque cela se produit c'est en général le signe d'erreurs de conception plus profondes. ### Un exemple très simple On se donne la hiérarchie suivante. class LeftTop(object): def attribut(self): return "attribut(LeftTop)" class LeftMiddle(LeftTop): pass class Left(LeftMiddle): pass class Middle(object): pass class Right(object): def attribut(self): return "attribut(Right)" class Class(Left, Middle, Right): pass instance = Class() qui donne en version dessinée, avec les deux points représentant les deux définitions de la méthode `attribut`: <img src="media/heritage-multiple01.png" height="40"> Les deux règles, telles que nous les avons énoncées en premier lieu (priorité à gauche, priorité au spécifique) sont un peu contradictoires ici. En fait, c'est la méthode de `LeftTop` qui est héritée dans `Class`, comme on le voit ici&nbsp;: print instance.attribut() == "attribut(LeftTop)" **Exercice** Remarquez qu'ici `Right` a elle-même un héritage très simple. À titre d'exercice, modifiez le code ci-dessus pour remplacer dans l'héritage de `Right` la classe `object` par `LeftMiddle`; de quelle classe d'après vous est- ce que `Class` hérite `attribut` dans cette configuration ? ##### Si cela ne vous convient pas C'est une évidence, mais cela va peut-être mieux en le rappelant&nbsp;: si la méthode que vous obtenez "gratuitement" avec l'héritage n'est pas celle qui vous convient, vous avez naturellement toujours la possibilité de la redéfinir, et ainsi d'en **choisir** une autre. Ainsi dans notre exemple si on préfère la méthode implémentée dans `Right`, on définira plutôt la classe `Class` comme ceci&nbsp;: class Class(Left, Middle, Right): def attribut(*args, **kwds): return Right.attribut(*args, **kwds) instance2 = Class() instance2.attribut() Ou encore bien entendu, si dans votre contexte vous devez appelez **les deux** méthodes dont vous pourriez hériter et les combiner, vous pouvez le faire aussi, par exemple comme ceci&nbsp;: class Class(Left, Middle, Right): def attribut(*args, **kwds): return LeftTop.attribut(*args, **kwds) + " ** " + Right.attribut(*args, **kwds) instance3 = Class() instance3.attribut() ### Un exemple un peu plus compliqué Voici un exemple tiré de la deuxième référence (voir ci-dessous la dernière section, "Pour en savoir plus"). O = object class F(O): pass class E(O): pass class D(O): pass class C(D, F): pass class B(E, D): pass class A(B, C): pass Cette hiérarchie nous donne, en partant de A, l'ordre suivant 6 --- Level 3 | O | / --- \ / | \ / | \ / | \ --- --- --- Level 2 2 | E | 4 | D | | F | 5 --- --- --- \ / \ / \ / \ / \ / \ / --- --- Level 1 1 | B | | C | 3 --- --- \ / \ / --- Level 0 0 | A | --- Que l'on peut calculer, sous l'interpréteur python, avec la méthode `mro` sur la classe de départ&nbsp;: A.mro() ### Un exemple qui ne peut pas être traité Voici enfin un exemple de hiérarchie pour laquelle on ne **peut pas trouver d'ordre** qui respecte les bonnes propriétés que l'on a vues tout à l'heure, et qui pour cette raison sera **rejetée par l'interpréteur python**. D'abord en version dessinée <img src="media/heritage-multiple02.png"> # en version code class X(object): pass class Y(object): pass class XY(X, Y): pass class YX(Y, X): pass # on essaie de créer une sous-classe de XY et YX try: class Class(XY,YX): pass # mais ce n'est pas possible except Exception as e: print "On ne peut pas créer Class" print e ### Pour en savoir plus 1. Un [blog de Guido Van Rossum](http://python-history.blogspot.fr/2010/06 /method-resolution-order.html ) qui retrace l'historique des différents essais qui ont été faits avant de converger sur le modèle actuel. 1. Un [article technique](https://www.python.org/download/releases/2.3/mro/) qui décrit le fonctionnement de l'algorithme de calcul de la MRO, et donne des exemples. 1. L'[article de wikipedia](http://en.wikipedia.org/wiki/C3_linearization) sur l'algorithme C3.
Markdown
UTF-8
977
3.453125
3
[ "MIT" ]
permissive
# Internalization - Say Trait Is it possible to add translation abilities to any applicatio object using specialized trait `Spiral\Translator\Traits\TranslatorTrait`. ## Usage We can add the translator trait to the controller: ```php namespace App\Controller; use Spiral\Translator\Traits\TranslatorTrait; class HomeController { use TranslatorTrait; public function index() { return $this->say("hello world!"); } } ``` > Run 'i18n:index' to index the string invocation. ## Class messages In cases where message is defined by logic and can not be indexed use constants and/or properties to declare class messages, every string wrapped with `[[]]` will be automatically indexed. ```php class HomeController { use TranslatorTrait; protected const MESSAGES = [ 'error' => '[[An error]]', 'success' => '[[Success]]' ]; public function index() { echo $this->say(self::MESSAGES['error']); } } ```
Java
UTF-8
708
3.28125
3
[ "MIT" ]
permissive
public class OOEnsaio4 { public static void main(String[] args) { Horario h1 = new Horario(); h1.horas = 21; h1.minutos = 26; System.out.println(h1.horas); // 21 System.out.println(h1.horas == 21); // 21 Horario h2 = h1; h1.horas = 22; System.out.println(h2.horas); h2.minutos = 30; int x = 5; int y = x; x = 7; System.out.println(y); Horario teste = new Horario(); teste.horas = 21; teste.minutos = 45; meiodia(teste); System.out.println(teste.horas); // 21? System.out.println(teste.minutos); // 45? } static void meiodia(Horario h) { h.horas = 12; h.minutos = 0; } } class Horario { int horas, minutos; }
Java
UTF-8
3,111
1.976563
2
[ "LicenseRef-scancode-unknown-license-reference", "MulanPSL-1.0", "LicenseRef-scancode-mulanpsl-1.0-en" ]
permissive
package cn.iocoder.mall.managementweb.manager.product; import cn.iocoder.common.framework.vo.CommonResult; import cn.iocoder.common.framework.vo.PageResult; import cn.iocoder.mall.managementweb.controller.product.vo.spu.ProductSpuCreateReqVO; import cn.iocoder.mall.managementweb.controller.product.vo.spu.ProductSpuPageReqVO; import cn.iocoder.mall.managementweb.controller.product.vo.spu.ProductSpuRespVO; import cn.iocoder.mall.managementweb.controller.product.vo.spu.ProductSpuUpdateReqVO; import cn.iocoder.mall.managementweb.convert.product.ProductSpuConvert; import cn.iocoder.mall.productservice.rpc.spu.ProductSpuFeign; import cn.iocoder.mall.productservice.rpc.spu.dto.ProductSpuRespDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 商品 SPU Manager */ @Service public class ProductSpuManager { @Autowired private ProductSpuFeign productSpuFeign; /** * 创建商品 SPU * * @param createVO 创建商品 SPU VO * @return 商品 SPU */ public Integer createProductSpu(ProductSpuCreateReqVO createVO) { CommonResult<Integer> createProductSpuResult = productSpuFeign.createProductSpu(ProductSpuConvert.INSTANCE.convert(createVO)); createProductSpuResult.checkError(); return createProductSpuResult.getData(); } /** * 更新商品 SPU * * @param updateVO 更新商品 SPU VO */ public void updateProductSpu(ProductSpuUpdateReqVO updateVO) { CommonResult<Boolean> updateProductSpuResult = productSpuFeign.updateProductSpu(ProductSpuConvert.INSTANCE.convert(updateVO)); updateProductSpuResult.checkError(); } /** * 获得商品 SPU * * @param productSpuId 商品 SPU编号 * @return 商品 SPU */ public ProductSpuRespVO getProductSpu(Integer productSpuId) { CommonResult<ProductSpuRespDTO> getProductSpuResult = productSpuFeign.getProductSpu(productSpuId); getProductSpuResult.checkError(); return ProductSpuConvert.INSTANCE.convert(getProductSpuResult.getData()); } /** * 获得商品 SPU列表 * * @param productSpuIds 商品 SPU编号列表 * @return 商品 SPU列表 */ public List<ProductSpuRespVO> listProductSpus(List<Integer> productSpuIds) { CommonResult<List<ProductSpuRespDTO>> listProductSpuResult = productSpuFeign.listProductSpus(productSpuIds); listProductSpuResult.checkError(); return ProductSpuConvert.INSTANCE.convertList(listProductSpuResult.getData()); } /** * 获得商品 SPU分页 * * @param pageVO 商品 SPU分页查询 * @return 商品 SPU分页结果 */ public PageResult<ProductSpuRespVO> pageProductSpu(ProductSpuPageReqVO pageVO) { CommonResult<PageResult<ProductSpuRespDTO>> pageProductSpuResult = productSpuFeign.pageProductSpu(ProductSpuConvert.INSTANCE.convert(pageVO)); pageProductSpuResult.checkError(); return ProductSpuConvert.INSTANCE.convertPage(pageProductSpuResult.getData()); } }
Python
UTF-8
546
2.890625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import yake # In[2]: f=open("1.txt", "r") text = str(f.read()) language = "en" max_ngram_size = 3 deduplication_thresold = 0.9 deduplication_algo = 'seqm' windowSize = 1 numOfKeywords = 20 custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_thresold, dedupFunc=deduplication_algo, windowsSize=windowSize, top=numOfKeywords, features=None) keywords = custom_kw_extractor.extract_keywords(text) for kw in keywords: print(kw) # In[ ]:
Markdown
UTF-8
4,381
2.78125
3
[ "MIT" ]
permissive
<!-- README.md is generated from README.Rmd. Please edit that file --> # State Space Modelling in R <a href='https://DylanB95.github.io/statespacer'><img src='man/figures/logo.png' align="right" height="138.5" style="float:right; height:138.5px;"/></a> <!-- badges: start --> [![Travis build status](https://travis-ci.com/DylanB95/statespacer.svg?branch=master)](https://travis-ci.com/DylanB95/statespacer) [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://www.tidyverse.org/lifecycle/#stable) [![CRAN status](https://www.r-pkg.org/badges/version/statespacer)](https://CRAN.R-project.org/package=statespacer) <!-- badges: end --> ## Overview statespacer is a package for state space modelling and forecasting in R. It provides functions that make estimating models in State Space form a breeze. This package implements state-of-the-art algorithms developed by various time series practitioners such as J. Durbin and S.J. Koopman. Details about the algorithms can be found in their book, “Time Series Analysis by State Space Methods”. If you are new to statespacer, check out `vignette("intro", "statespacer")` for a quick start to the statespacer package! Also check out the references for the following functions: - `statespacer()` for fitting State Space models. - `predict.statespacer()` for producing forecasts and out-of-sample simulations using fitted State Space models. - `SimSmoother()` for drawing random samples of the hidden state of a State Space model conditional on the data. ## State Space Components This package supports numerous state space components: - The Local Level - The Local Level + Slope - Smoothing Splines - Trigonometric Seasonality, BSM - (Business) Cycles - Explanatory Variables - Explanatory Variables with time-varying coefficients - Explanatory Variables in the Local Level - Explanatory Variables in the Local Level + Slope - ARIMA - SARIMA - Moreover, you can specify a component yourself! These components can be used for both univariate, and multivariate models. The components can be combined in order to get more extensive models. Moreover, the user can control the format of the variance - covariance matrices of each of the components. This way, one could specify the components to be deterministic instead of stochastic. In the multivariate case, one could impose rank restrictions on the variance - covariance matrices such that commonalities in the components are estimated, like common levels, common slopes, etc. ## Fitting Procedure The package employs a univariate treatment, and an exact initialisation for diffuse elements, to estimate the state parameters and compute the loglikelihood. Collapsing large observation vectors is supported as well. Moreover, missing observations are readily dealt with by putting the models in State Space form! ## Installation You can install statespacer from CRAN with: ``` r install.packages("statespacer") ``` ### Development version To get a bug fix or to use a feature from the development version, you can install the development version of statespacer from GitHub. ``` r # install.packages("devtools") devtools::install_github("DylanB95/statespacer") ``` ## Usage ``` r library(statespacer) library(datasets) y <- matrix(Nile) fit <- statespacer(y = y, local_level_ind = TRUE, initial = 0.5*log(var(y))) plot(1871:1970, fit$function_call$y, type = 'p', ylim = c(500, 1400), xlab = NA, ylab = NA, sub = "The smoothed level with 90% confidence intervals, and the observed data points") lines(1871:1970, fit$smoothed$level, type = 'l') lines(1871:1970, fit$smoothed$level + qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]), type = 'l', col = 'gray' ) lines(1871:1970, fit$smoothed$level - qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]), type = 'l', col = 'gray' ) ``` <img src="man/figures/README-unnamed-chunk-4-1.png" width="100%" /> ## Getting help If you encounter a clear bug, please file an issue with a minimal reproducible example on [GitHub](https://github.com/DylanB95/statespacer/issues). ------------------------------------------------------------------------ Please note that the ‘statespacer’ project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By contributing to this project, you agree to abide by its terms.
C
UTF-8
31,130
2.84375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> struct Process{ int processId; float arrivalTime; float runTime; int priority; }; struct Report{ int timeSlice[115]; float avgTurnAround; float avgWaiting; float avgResponse; float throughPut; }; //make processes struct Process* makeProcesses(struct Process* myList,int num); //print Process's Infor void myPrint(struct Process* myProcess,int arrayLength); //print report void printReport(struct Report* myReport,int length); //first come first serve void firstComefirstServe(struct Process* myProcess, int arrayLenth); //shortest job first void shortestFirst(struct Process* myProcess, int arrayLength); //sort array of process according to arrival time void sort(struct Process* unsortList,struct Process* sortedList, int arrayLength); //report Processing struct Report* reportProcessing(struct Process* sorted, int arrayLength); //highest priority first - non preemtive with aging void highestPriorFirstNonPrewAging(struct Process* myProcess,int arrayLength); //highest priority first - non preemtive without aging void highestPriorFirstNonPre(struct Process* myProcess,int arrayLength); //highest priority first - preemtive without aging void highestPriorFirstPre(struct Process* myProcess,int arrayLength); //highest priority first - preemtive with aging void highestPriorFirstPrewAging(struct Process* myProcess,int arrayLength); //return priority of a process. int getPriority(struct Process* processList,int length,int id); int main() { struct Process myProcessList[25]; myProcessList[0].processId = 65; myProcessList[0].arrivalTime = 0.12; myProcessList[0].runTime = 2.4; myProcessList[0].priority = 3; myProcessList[1].processId = 66; myProcessList[1].arrivalTime = 7.44; myProcessList[1].runTime = 2.8; myProcessList[1].priority = 2; myProcessList[2].processId = 67; myProcessList[2].arrivalTime = 25.53; myProcessList[2].runTime = 9.9; myProcessList[2].priority = 3; myProcessList[3].processId = 68; myProcessList[3].arrivalTime = 93.43; myProcessList[3].runTime = 1.8; myProcessList[3].priority = 1; myProcessList[4].processId = 69; myProcessList[4].arrivalTime = 3.49; myProcessList[4].runTime = 0.1; myProcessList[4].priority = 2; myProcessList[5].processId = 70; myProcessList[5].arrivalTime = 48.59; myProcessList[5].runTime = 2.8; myProcessList[5].priority = 2; myProcessList[6].processId = 71; myProcessList[6].arrivalTime = 9.15; myProcessList[6].runTime = 4.5; myProcessList[6].priority = 1; myProcessList[7].processId = 72; myProcessList[7].arrivalTime = 97.33; myProcessList[7].runTime = 6.7; myProcessList[7].priority = 3; myProcessList[8].processId = 73 ; myProcessList[8].arrivalTime = 56.33; myProcessList[8].runTime = 0.5; myProcessList[8].priority = 2; myProcessList[9].processId =74 ; myProcessList[9].arrivalTime =6.84 ; myProcessList[9].runTime = 3.0; myProcessList[9].priority = 3; myProcessList[10].processId = 75 ; myProcessList[10].arrivalTime = 7.47; myProcessList[10].runTime = 0.2; myProcessList[10].priority = 1; myProcessList[11].processId = 76 ; myProcessList[11].arrivalTime = 56.73; myProcessList[11].runTime = 5.2; myProcessList[11].priority = 2; myProcessList[12].processId = 77 ; myProcessList[12].arrivalTime = 72.06; myProcessList[12].runTime = 3.9; myProcessList[12].priority = 1; myProcessList[13].processId =78 ; myProcessList[13].arrivalTime = 2.65; myProcessList[13].runTime = 9.1; myProcessList[13].priority = 3; myProcessList[14].processId = 79 ; myProcessList[14].arrivalTime = 86.14; myProcessList[14].runTime = 5.5; myProcessList[14].priority = 2; myProcessList[15].processId = 80 ; myProcessList[15].arrivalTime = 62.82; myProcessList[15].runTime = 3.8; myProcessList[15].priority = 4; myProcessList[16].processId = 81 ; myProcessList[16].arrivalTime = 23.13 ; myProcessList[16].runTime = 5.3; myProcessList[16].priority = 2; myProcessList[17].processId = 82 ; myProcessList[17].arrivalTime = 89.74; myProcessList[17].runTime = 3.8; myProcessList[17].priority = 2; myProcessList[18].processId = 83 ; myProcessList[18].arrivalTime = 74.43; myProcessList[18].runTime = 3.6; myProcessList[18].priority = 2; myProcessList[19].processId = 84 ; myProcessList[19].arrivalTime = 21.91; myProcessList[19].runTime = 0.8; myProcessList[19].priority = 1; myProcessList[20].processId = 85 ; myProcessList[20].arrivalTime = 67.49; myProcessList[20].runTime = 4.4; myProcessList[20].priority =1 ; myProcessList[21].processId = 86; myProcessList[21].arrivalTime = 3.37; myProcessList[21].runTime = 6.7; myProcessList[21].priority = 1; myProcessList[22].processId = 87 ; myProcessList[22].arrivalTime = 74.28; myProcessList[22].runTime = 8.6; myProcessList[22].priority = 3; myProcessList[23].processId = 88 ; myProcessList[23].arrivalTime = 75.61; myProcessList[23].runTime = 4.4; myProcessList[23].priority = 2; myProcessList[24].processId = 89 ; myProcessList[24].arrivalTime = 14.30; myProcessList[24].runTime = 5.1; myProcessList[24].priority = 1; //akeProcesses(myProcessList,5); // myPrint(myProcessList,25); //firstComefirstServe(myProcessList,25); //shortestFirst(myProcessList,25); //highestPriorFirstNonPrewAging(myProcessList,25); //highestPriorFirstNonPre(myProcessList,25); highestPriorFirstPre(myProcessList,25); printf("-----\n\n"); highestPriorFirstPrewAging(myProcessList,25); return 0; } struct Process* makeProcesses(struct Process* myList,int num){ srand(1); int i = 0; int j=65; for(i = 0;i < num; i++){ myList[i].processId = j; j=j+1; myList[i].arrivalTime = (float)rand()/(float)(RAND_MAX/100);; myList[i].runTime = (float)rand()/(float)(RAND_MAX/10); + 0.1 ; myList[i].priority = rand()%4+1; } return myList; } void firstComefirstServe(struct Process* myProcess, int arrayLength){ struct Process sorted[arrayLength]; sort(myProcess,sorted,arrayLength); struct Report* myReport =reportProcessing(sorted,arrayLength); printf("First Come First Serve Analysis \n"); printf("-------------------------------\n"); printReport(myReport,115); printf("-------------------------------\n"); } void shortestFirst(struct Process* myProcess, int arrayLength){ int i = 0; int nextProcess; struct Process tempArray[arrayLength]; //sort temp array to shortest arrival time. sort(myProcess,tempArray,arrayLength); // myPrint(tempArray,arrayLength); struct Process finalSorted[arrayLength]; int counter = 0; float currentTime = tempArray[0].arrivalTime; //loop through until all processes are completed while(counter < arrayLength){ nextProcess = -99; //find the next shortest job up to current time. for(i = 0; i < arrayLength; i++){ if((tempArray[i].processId != -99) && (tempArray[i].arrivalTime <= currentTime)){ //set temp to be the first qualify candidate. if(nextProcess == -99){ nextProcess = i; } //if current process has shorter run time than nextProcess then set nextProcess to be current. if(tempArray[i].runTime < tempArray[nextProcess].runTime){ nextProcess = i; } } } //add run time of process to timeslice currentTime += (int)ceilf(tempArray[nextProcess].runTime); //add process to final sorted array. finalSorted[counter++] = tempArray[nextProcess]; //mark process as done. tempArray[nextProcess].processId = -99; } struct Report* myReport = reportProcessing(finalSorted,arrayLength); printf("\nShortest Job First Analysis \n"); printf("-----------------------------\n"); printReport(myReport,115); printf("-----------------------------\n"); } void highestPriorFirstNonPrewAging(struct Process* myProcess,int arrayLength){ int i = 0; float tempAge= 0.0; int nextProcess; struct Process tempArray[arrayLength]; //sort temp array to shortest arrival time. sort(myProcess,tempArray,arrayLength); myPrint(tempArray,arrayLength); float priorityQueue [4][4]; memset(priorityQueue, 0.0, sizeof priorityQueue); struct Process finalSorted[arrayLength]; float aging [arrayLength]; memset(aging, 0, sizeof aging); int counter = 0; float currentTime = tempArray[0].arrivalTime; //loop through until all processes are completed while(counter < arrayLength){ nextProcess = -99; if(currentTime >99){ printf("end here %f",currentTime); break; } //find the next shortest job up to current time. for(i = 0; i < arrayLength; i++){ if(tempArray[i].processId != -99){ if(tempArray[i].arrivalTime <= currentTime){ //set temp to be the first qualify candidate. if(nextProcess == -99){ nextProcess = i; } aging[i]= currentTime- tempArray[i].arrivalTime - (aging[i]); // printf("Process %c priority: %d has wait time of %f\n",tempArray[i].processId,tempArray[i].priority,aging[i]); while(aging[i] > 5){ // printf("Process %c priority increase 1\n",tempArray[i].processId); tempArray[i].priority--; aging[i] -=5; } // printf("NOW Process %c has priority: %d and wait time %f\n",tempArray[i].processId,tempArray[i].priority,aging[i]); //if current process has higher than nextProcess then set nextProcess to be current. if(tempArray[i].priority < tempArray[nextProcess].priority){ nextProcess = i; } } } } // add turn around time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][0] +=(currentTime - tempArray[nextProcess].arrivalTime); // add wait time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][1] +=(currentTime - tempArray[nextProcess].arrivalTime + tempArray[nextProcess].runTime); // add respond time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][2] +=(currentTime - tempArray[nextProcess].arrivalTime + tempArray[nextProcess].runTime); // add throughput // printf("before priority %d, number %f\n ", getPriority(myProcess,arrayLength,tempArray[nextProcess].processId),priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]); priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]++; // printf("after priority %d, number %f \n", getPriority(myProcess,arrayLength,tempArray[nextProcess].processId), // priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]); // priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]++; // add to visited // printf("Current time is %f\n", currentTime); // printf("Highest priority is process is %c - priority:%d\n", tempArray[nextProcess].processId,tempArray[nextProcess].priority); //add to visited currentTime = (int)ceilf(tempArray[nextProcess].runTime + currentTime); //add to final sort array. finalSorted[counter++] = tempArray[nextProcess]; //mark process as done. printf("\n***process %c is done.\n", tempArray[nextProcess].processId); tempArray[nextProcess].processId = -99; } for(i = 0; i < 4;i++){ printf("Priority Queue %d:\n",i+1); printf("Turn around time: %f\n",priorityQueue[i][0]/=priorityQueue[i][3]); printf("Wait around time: %f\n",priorityQueue[i][1]/=priorityQueue[i][3]); printf("Respond around time: %f\n",priorityQueue[i][2]/=priorityQueue[i][3]); printf("Throughtput : %f\n",priorityQueue[i][3]); printf("-----------------\n"); } struct Report* avgReport = reportProcessing(finalSorted,arrayLength); printf("\nHighest Priority First (Non Preemptive) w/ Aging Analysis \n"); printf("-----------------------------\n"); printReport(avgReport,115); printf("-----------------------------\n"); } void highestPriorFirstNonPre(struct Process* myProcess,int arrayLength){ int i = 0; float tempAge= 0.0; int nextProcess; struct Process tempArray[arrayLength]; //sort temp array to shortest arrival time. sort(myProcess,tempArray,arrayLength); myPrint(tempArray,arrayLength); float priorityQueue [4][4]; memset(priorityQueue, 0.0, sizeof priorityQueue); struct Process finalSorted[arrayLength]; int counter = 0; float currentTime = tempArray[0].arrivalTime; //loop through until all processes are completed while(counter < arrayLength){ nextProcess = -99; if(currentTime >99){ break; } //find the next shortest job up to current time. for(i = 0; i < arrayLength; i++){ if(tempArray[i].processId != -99){ if(tempArray[i].arrivalTime <= currentTime){ //set temp to be the first qualify candidate. if(nextProcess == -99){ nextProcess = i; } // printf("NOW Process %c has priority: %d and wait time %f\n",tempArray[i].processId,tempArray[i].priority,aging[i]); //if current process has higher than nextProcess then set nextProcess to be current. if(tempArray[i].priority < tempArray[nextProcess].priority){ nextProcess = i; } } } } // add turn around time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][0] +=(currentTime - tempArray[nextProcess].arrivalTime); // add wait time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][1] +=(currentTime - tempArray[nextProcess].arrivalTime + tempArray[nextProcess].runTime); // add respond time priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][2] +=(currentTime - tempArray[nextProcess].arrivalTime + tempArray[nextProcess].runTime); // add throughput // printf("before priority %d, number %f\n ", getPriority(myProcess,arrayLength,tempArray[nextProcess].processId),priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]); priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]++; // printf("after priority %d, number %f \n", getPriority(myProcess,arrayLength,tempArray[nextProcess].processId), // priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]); // priorityQueue[getPriority(myProcess,arrayLength,tempArray[nextProcess].processId)-1][3]++; // add to visited // printf("Current time is %f\n", currentTime); // printf("Highest priority is process is %c - priority:%d\n", tempArray[nextProcess].processId,tempArray[nextProcess].priority); //add to visited currentTime = (int)ceilf(tempArray[nextProcess].runTime + currentTime); // finalSorted[counter++] = tempArray[nextProcess]; //mark process as done. printf("\n***process %c is done.\n", tempArray[nextProcess].processId); tempArray[nextProcess].processId = -99; } for(i = 0; i < 4;i++){ priorityQueue[i][0] /= priorityQueue[i][3]; priorityQueue[i][1] /= priorityQueue[i][3]; priorityQueue[i][2] /= priorityQueue[i][3]; priorityQueue[i][3] /= currentTime; } for(i = 0; i < 4;i++){ printf("Priority Queue %d:\n",i+1); printf("Turn around time: %f\n",priorityQueue[i][0]); printf("Wait around time: %f\n",priorityQueue[i][1]); printf("Respond around time: %f\n",priorityQueue[i][2]); printf("Throughtput : %f\n",priorityQueue[i][3]); printf("-----------------\n"); } struct Report* avgReport = reportProcessing(finalSorted,arrayLength); printf("\nHighest Priority First (Non Preemptive) w/out Aging Analysis \n"); printf("-----------------------------\n"); printReport(avgReport,115); printf("-----------------------------\n"); } //end highest priority non preemptive without aging void highestPriorFirstPre(struct Process* myProcess,int arrayLength){ struct Process tempArray[arrayLength]; //sort temp array to shortest arrival time. sort(myProcess,tempArray,arrayLength); myPrint(tempArray,arrayLength); //quantum array stores process of each quantum being worked on. int currentTime[1000] ; memset(currentTime, -1, sizeof currentTime); float startTime[arrayLength]; memset(startTime, 0.0, sizeof startTime); float priorityQueue[4][4]; memset(priorityQueue, 0.0, sizeof priorityQueue); int i,j; i = 0; tempArray[0].arrivalTime = floorf(tempArray[0].arrivalTime); tempArray[0].runTime = tempArray[0].runTime + tempArray[0].arrivalTime; float avgWaitTime = 0.0; float avgTurnAround = 0.0; float avgRespond = 0.0; float tempEndTime = 0.0; float tempWaitTime = 0.0; float tempTurnAround = 0.0; float tempRespond = 0.0; float avgThroughput = 0.0; int lastEmpty = 0; while((i< 100) || (lastEmpty == 0)){ for(j = 0;j < arrayLength;j++){ if((tempArray[j].arrivalTime <= i) && (tempArray[j].runTime > 0)){ //set it for the first time. if(currentTime[i] == -1){ currentTime[i] = j; } //if current has higher priority then set current = highest. if(tempArray[j].priority < tempArray[currentTime[i]].priority){ currentTime[i] = j; } } } if(currentTime[i] != -1){ lastEmpty = 0; // printf("%d Process %c Runtime Now:%f\n",i,tempArray[currentTime[i]].processId,tempArray[currentTime[i]].runTime); tempArray[currentTime[i]].runTime--; if(tempArray[currentTime[i]].runTime <= 0){ if(currentTime[i-1] == 95){ startTime[currentTime[i]] = tempArray[currentTime[i]].arrivalTime; } else{ startTime[currentTime[i]] =i; } tempEndTime = i+ tempArray[currentTime[i]].runTime+1; tempWaitTime = tempEndTime - tempArray[currentTime[i]].arrivalTime -tempArray[currentTime[i]].runTime; tempTurnAround = tempEndTime - tempArray[currentTime[i]].arrivalTime; tempRespond = startTime[currentTime[i]] - tempArray[currentTime[i]].arrivalTime; //add turn around. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][0] += tempTurnAround; //add waiting time. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][1] += tempWaitTime; //add respond time priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][2] +=tempRespond; //add throughput. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][3]++; } // printf("Process %c Runtime After:%f\n\n",tempArray[currentTime[i]].processId,tempArray[currentTime[i]].runTime); } else{ currentTime[i] = 95; lastEmpty = 1; } i++; } /** for(j = 0; j < 115;j++){ printf("%d.%c \n", j,tempArray[currentTime[j]].processId); } **/ for(j = 0; j < 4;j++){ avgTurnAround += priorityQueue[j][0]; priorityQueue[j][0] /= priorityQueue[j][3]; avgWaitTime += priorityQueue[j][1]; priorityQueue[j][1] /= priorityQueue[j][3]; avgRespond += priorityQueue[j][2]; priorityQueue[j][2] /= priorityQueue[j][3]; avgThroughput += priorityQueue[j][3]; priorityQueue[j][3] /=i ; } avgTurnAround /= avgThroughput; avgWaitTime /= avgThroughput; avgRespond /= avgThroughput; avgThroughput /= i; printf("Average Turn Around Time: %.2f\n", avgTurnAround); printf("Average Turn Waiting Time: %.2f\n", avgWaitTime); printf("Average Turn Response Time: %f\n", avgRespond); printf("Throughput: %f\n", avgThroughput); for(j = 0; j < 4;j++){ printf("Priority Queue %d:\n",j+1); printf("Turn around time: %f\n",priorityQueue[j][0]); printf("Wait around time: %f\n",priorityQueue[j][1]); printf("Respond around time: %f\n",priorityQueue[j][2]); printf("Throughtput : %f\n",priorityQueue[j][3]); printf("-----------------\n"); } } void highestPriorFirstPrewAging(struct Process* myProcess,int arrayLength){ struct Process tempArray[arrayLength]; //sort temp array to shortest arrival time. sort(myProcess,tempArray,arrayLength); myPrint(tempArray,arrayLength); //quantum array stores process of each quantum being worked on. int currentTime[1000] ; memset(currentTime, -1, sizeof currentTime); float startTime[arrayLength]; memset(startTime, 0.0, sizeof startTime); float priorityQueue[4][4]; memset(priorityQueue, 0.0, sizeof priorityQueue); int i,j; i = 0; tempArray[0].arrivalTime = floorf(tempArray[0].arrivalTime); tempArray[0].runTime = tempArray[0].runTime + tempArray[0].arrivalTime; float avgWaitTime = 0.0; float avgTurnAround = 0.0; float avgRespond = 0.0; float tempEndTime = 0.0; float tempWaitTime = 0.0; float tempTurnAround = 0.0; float tempRespond = 0.0; float avgThroughput = 0.0; int lastEmpty = 0; float aging [arrayLength]; memset(aging, 0, sizeof aging); while((i< 100) || (lastEmpty == 0)){ for(j = 0;j < arrayLength;j++){ if((tempArray[j].arrivalTime <= i) && (tempArray[j].runTime > 0)){ aging[j]++; //set it for the first time. if(currentTime[i] == -1){ currentTime[i] = j; } //if current has higher priority then set current = highest. if(tempArray[j].priority < tempArray[currentTime[i]].priority){ aging[currentTime[i]]--; currentTime[i] = j; } } } for(j = 0; j < arrayLength;j++){ if(aging[j]>4){ tempArray[j].priority++; aging[j] = 0; } } if(currentTime[i] != -1){ lastEmpty = 0; // printf("%d Process %c Runtime Now:%f\n",i,tempArray[currentTime[i]].processId,tempArray[currentTime[i]].runTime); tempArray[currentTime[i]].runTime--; if(tempArray[currentTime[i]].runTime <= 0){ if(currentTime[i-1] == 95){ startTime[currentTime[i]] = tempArray[currentTime[i]].arrivalTime; } else{ startTime[currentTime[i]] =i; } tempEndTime = i+ tempArray[currentTime[i]].runTime+1; tempWaitTime = tempEndTime - tempArray[currentTime[i]].arrivalTime -tempArray[currentTime[i]].runTime; tempTurnAround = tempEndTime - tempArray[currentTime[i]].arrivalTime; tempRespond = startTime[currentTime[i]] - tempArray[currentTime[i]].arrivalTime; //add turn around. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][0] += tempTurnAround; //add waiting time. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][1] += tempWaitTime; //add respond time priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][2] +=tempRespond; //add throughput. priorityQueue[getPriority(myProcess,arrayLength,tempArray[currentTime[i]].processId)-1][3]++; } // printf("Process %c Runtime After:%f\n\n",tempArray[currentTime[i]].processId,tempArray[currentTime[i]].runTime); } else{ currentTime[i] = 95; lastEmpty = 1; } i++; } /** for(j = 0; j < 115;j++){ printf("%d.%c \n", j,tempArray[currentTime[j]].processId); } **/ for(j = 0; j < 4;j++){ avgTurnAround += priorityQueue[j][0]; priorityQueue[j][0] /= priorityQueue[j][3]; avgWaitTime += priorityQueue[j][1]; priorityQueue[j][1] /= priorityQueue[j][3]; avgRespond += priorityQueue[j][2]; priorityQueue[j][2] /= priorityQueue[j][3]; avgThroughput += priorityQueue[j][3]; priorityQueue[j][3] /=i ; } avgTurnAround /= avgThroughput; avgWaitTime /= avgThroughput; avgRespond /= avgThroughput; avgThroughput /= i; printf("Average Turn Around Time: %.2f\n", avgTurnAround); printf("Average Turn Waiting Time: %.2f\n", avgWaitTime); printf("Average Turn Response Time: %f\n", avgRespond); printf("Throughput: %f\n", avgThroughput); for(j = 0; j < 4;j++){ printf("Priority Queue %d:\n",j+1); printf("Turn around time: %f\n",priorityQueue[j][0]); printf("Wait around time: %f\n",priorityQueue[j][1]); printf("Respond around time: %f\n",priorityQueue[j][2]); printf("Throughtput : %f\n",priorityQueue[j][3]); printf("-----------------\n"); } } struct Report* reportProcessing(struct Process* sorted, int arrayLength){ struct Report* myReport = malloc(sizeof(struct Report)); myReport->avgWaiting =0.0; myReport->avgTurnAround = 0.0; myReport->avgResponse = 0.0; myReport->throughPut = 0.0; int Time = 99; float timeCounter = 0; timeCounter = sorted[0].arrivalTime; int timeSlideCounter = 0; int i = 0; for(i = 0; i < arrayLength; i++){ float currentWaitTime = 0; //only add to wait time if current time quantum is greater than arrival time. if(timeCounter > sorted[i].arrivalTime){ currentWaitTime = timeCounter - sorted[i].arrivalTime; myReport->avgWaiting += currentWaitTime; } // if current time is less than next arrival time then set current time to arrival time. else{ timeCounter = sorted[i].arrivalTime; } if(timeCounter > Time){ break; } timeCounter += ceilf(sorted[i].runTime); myReport->avgTurnAround += currentWaitTime + sorted[i].runTime; myReport->avgResponse += currentWaitTime; int m = 0; m = (int)timeCounter - timeSlideCounter; while( m > 0) { myReport->timeSlice[timeSlideCounter++] = sorted[i].processId; m--; } } myReport->avgResponse = (myReport->avgResponse/(i)); myReport->avgWaiting = (myReport->avgWaiting/(i)); myReport->avgTurnAround = (myReport->avgTurnAround/(i)); myReport->throughPut = i/timeCounter; return myReport; } void printReport(struct Report* myReport,int length){ printf("Average Turn Around Time: %.2f\n", myReport->avgTurnAround); printf("Average Turn Waiting Time: %.2f\n", myReport->avgWaiting); printf("Average Turn Response Time: %f\n", myReport->avgResponse); int i = 0; printf("Time Slide: \n"); for(i = 0; i < length; i++){ if(i % 5 == 0 && i != 0){ printf("-"); } printf("%c",(char)(myReport->timeSlice[i])); } printf("\nThroughput: %f\n", myReport->throughPut); } void myPrint(struct Process* myArray,int arrayLength){ printf("%s%15s%15s%18s\n", "Process ID", "Arrival Time","Run Time", "Priority"); int j = 0; for (j = 0; j < arrayLength; j++){ printf("%c%20.2f%18.2f%15d\n", (char)(myArray[j].processId), myArray[j].arrivalTime, myArray[j].runTime, myArray[j].priority); } } void sort(struct Process* unsortList,struct Process* sortedList, int arrayLength){ int i = 0; //copy to new array. for (i = 0; i < arrayLength; i++){ sortedList[i] = unsortList[i]; } int j = 0; //sort array according to arrival time. for(i = 0; i < arrayLength; i++){ for (j = 0; j < arrayLength - 1 -i; j++){ if (sortedList[j].arrivalTime > sortedList[j+1].arrivalTime){ struct Process temp = sortedList[j]; sortedList[j] = sortedList[j+1]; sortedList[j+1] = temp; } } } } int getPriority(struct Process* processList,int length,int id){ int i,result = 1000; for(i = 0;i < length;i++){ if(processList[i].processId == id){ result = processList[i].priority; break; } } return result; }
Markdown
UTF-8
7,106
3.625
4
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
# Understanding Firebase Authentication Before we dive into the logic of implementing authentication, it's first important to understand the Firebase API, and how it handles authentication with the various options we have. As we're also working in React, we'll cover how Firebase's asynchronous API fits in with Reacts lifecycle methods. Luckily [react-native-firebase](https://rnfirebase.io) follows the Firebase web SDK API making this a breeze! ## Enabling authentication We need to tell Firebase that we plan on using authentication and also enable a couple of the many login providers which Firebase supports. Head over to the [Firebase console](https://console.firebase.google.com/u/0/) and select the project you're using. Find the Authentication section and you'll be prompted with a number of options. To get started, we want to select the "SIGN-IN METHOD" tab. You'll see we have a number of options here, however for the purposes of this Codorial we'll be using "Email/Password" and "Facebook" as our providers. Go ahead and enable these: ![Enabled Providers](assets/auth-providers.jpg) > If you don't have a Facebook app, simply enter dummy values. We'll cover this later on. ## Listening to the users authentication state The Firebase API provides a simple yet powerful listener, which triggers when some event changes with the user. This can be as obvious the user signing out or as subtle as the user validating their email address. Whatever the event, it triggers the same method: `onAuthStateChanged`. ```js import firebase from 'react-native-firebase'; firebase.auth().onAuthStateChanged(user => { console.log(user); }); ``` The callback for the `onAuthStateChanged` method returns a single parameter, commonly referred to as `user`. The concept here is simple; * the method is first called once Firebase responds, then any time user state changes thereafter. * if a user is "signed in", our parameter will be a [`User`](https://firebase.google.com/docs/reference/js/firebase.User) `class`, containing all sorts of information we know about the user, from their e-mail address to any social provider IDs they may have signed in through. * if the user signed out, the parameter will be `null` value. > The `user` class provides a `.toJSON()` method to serialize the users details if required. ### Handling authentication state when the app closes A common question we get is how to handle the users authenticated state when the app closes/restarts so they don't have to keep logging in each time they open the app. Luckily this is all handled through Firebase so you don't have to worry about a thing - they'll only be signed out if they choose to, or the app is uninstalled. ## Creating a new account Creating a new account on Firebase is very easy. Another method called `createUserAndRetrieveDataWithEmailAndPassword` is available which does exactly what it says on the tin! This is an asynchronous promise which will throw an exception if something is wrong (such as email taken, or password too short). Creating a user will also sign them in at the same time. ```js import firebase from 'react-native-firebase'; firebase .auth() .createUserAndRetrieveDataWithEmailAndPassword( 'jim.bob@gmail.com', 'supersecret!' ) .then(user => { console.log('New User', user); }) .catch(error => { console.error('Woops, something went wrong!', error); }); ``` What's great about this is we don't need to know about the user within the `.then`, as any `onAuthStateChanged` listener would get triggered with our new users details - how awesome is that. ## Signing into an existing account Unsurprisingly, Firebase offers a method called `signInAndRetrieveDataWithEmailAndPassword`, which follows the exact same flow as `createUserAndRetrieveDataWithEmailAndPassword`: ```js import firebase from 'react-native-firebase'; firebase .auth() .signInAndRetrieveDataWithEmailAndPassword( 'jim.bob@gmail.com', 'supersecret!' ) .then(user => { console.log('Existing User', user); }) .catch(error => { console.error('Woops, something went wrong!', error); }); ``` ## Using with React Firebase on it's own is super simple, however when using in a React environment there's some gotchas you need to be mindful of. ### Handling state changes For any React component to update, a state or prop change needs to occur. As our Firebase auth methods are asynchronous we cannot rely on the data being available on component mount. To solve this issue, we can make use of state: ```jsx import React, { Component } from 'react'; import { View, Text } from 'react-native'; import firebase from 'react-native-firebase'; class App extends React.Component { constructor() { super(); this.state = { loading: false, user: null, }; } componentDidMount() { firebase.auth().onAuthStateChanged(user => { if (user) { this.setState({ user: user.toJSON(), // serialize the user class loading: false, }); } else { this.setState({ loading: false, }); } }); } render() { const { loading, user } = this.state; // Firebase hasn't responded yet if (loading) return null; // Firebase has responded, but no user exists if (!user) { return ( <View> <Text>Not signed in</Text> </View> ); } // Firebase has responded, and a user exists return ( <View> <Text>User signed in! {user.email}</Text> </View> ); } } ``` ### Subscribing/Un-subscribing from listeners When subscribing to a new listener, such as `onAuthStateChanged`, a new reference to it is made in memory which has no knowledge of the React environment. If a component within your app mounts and subscribes, the method will still trigger even if your component unmounted. If this happens and you're updating state, you'll get a yellow box warning. To get around this, Firebase returns an unsubscribe function to every subscriber method, which when calls removes the subscription from memory. This can be easily implemented using React lifecycle methods and class properties: ```jsx import React, { Component } from 'react'; import { View, Text } from 'react-native'; import firebase from 'react-native-firebase'; class App extends React.Component { constructor() { super(); this.unsubscribe = null; // Set a empty class method this.state = { loading: true, user: null, }; } componentDidMount() { // Assign the class method to the unsubscriber response this.unsubscribe = firebase.auth().onAuthStateChanged((user) => { // handle state changes }); } componentWillUnmount() { // Call the unsubscriber if it has been set if (this.unsubscribe) { this.unsubscribe(); } } ``` ## Further reading The above examples just scratch the surface of whats available with Firebase auth. Firebase itself provides some in-depth documentation on authentication and the many different implementation paths you can follow.
Java
UTF-8
4,078
2.015625
2
[ "Apache-2.0" ]
permissive
/* First created by JCasGen Tue Mar 03 14:57:59 CET 2009 */ package cybion.annotator_utils.jcas.cas; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.cas.TOP_Type; /** * Updated by JCasGen Wed Mar 11 08:02:23 CET 2009 * XML source: * @generated */ public class Entity extends TOP { /** @generated * @ordered */ public final static int typeIndexID = JCasRegistry.register(Entity.class); /** @generated * @ordered */ public final static int type = typeIndexID; /** @generated */ public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected Entity() {} /** Internal - constructor used by generator * @generated */ public Entity(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated */ public Entity(JCas jcas) { super(jcas); readObject(); } /** <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> @generated modifiable */ private void readObject() {} //*--------------* //* Feature: occurrencies /** getter for occurrencies - gets * @generated */ public FSArray getOccurencies() { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_occurrencies == null) jcasType.jcas.throwFeatMissing("occurrencies", "cybion.annotator_utils.jcas.cas.Entity"); return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies)));} /** setter for occurrencies - sets * @generated */ public void setOccurencies(FSArray v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_occurrencies == null) jcasType.jcas.throwFeatMissing("occurrencies", "cybion.annotator_utils.jcas.cas.Entity"); jcasType.ll_cas.ll_setRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies, jcasType.ll_cas.ll_getFSRef(v));} /** indexed getter for occurrencies - gets an indexed value - * @generated */ public TOP getOccurencies(int i) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_occurrencies == null) jcasType.jcas.throwFeatMissing("occurrencies", "cybion.annotator_utils.jcas.cas.Entity"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies), i); return (TOP)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies), i)));} /** indexed setter for occurrencies - sets an indexed value - * @generated */ public void setOccurencies(int i, TOP v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_occurrencies == null) jcasType.jcas.throwFeatMissing("occurrencies", "cybion.annotator_utils.jcas.cas.Entity"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_occurrencies), i, jcasType.ll_cas.ll_getFSRef(v));} //*--------------* //* Feature: text /** getter for text - gets * @generated */ public String getText() { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_text == null) jcasType.jcas.throwFeatMissing("text", "cybion.annotator_utils.jcas.cas.Entity"); return jcasType.ll_cas.ll_getStringValue(addr, ((Entity_Type)jcasType).casFeatCode_text);} /** setter for text - sets * @generated */ public void setText(String v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_text == null) jcasType.jcas.throwFeatMissing("text", "cybion.annotator_utils.jcas.cas.Entity"); jcasType.ll_cas.ll_setStringValue(addr, ((Entity_Type)jcasType).casFeatCode_text, v);} }
Python
UTF-8
4,220
3.46875
3
[]
no_license
#!/usr/bin/env python """ Takes a config file as input from STDIN with the following line format: MM HH ANY_NAME With any number of lines, and minute/hour can also be replaced by an '*'. Requires current time in HH:MM format as command line argument. Prints the next execution time for each job in a new line.""" import sys import traceback class Time: """ represents a specific time at a day, but can also contain wildcard * as hour or/and minute.""" def __init__(self, hour, minute): if not (minute == "*" or int(minute) < 60): raise ValueError("Minute doesn't have the right format") if not (hour == "*" or int(hour) < 24): raise ValueError("Hour doesn't have the right format") self.minute = int(minute) if minute != "*" else minute self.hour = int(hour) if hour != "*" else hour class CronJob: """ one object represents one job (one line of a config file)""" def __init__(self, minute, hour, name): self.time = Time(hour, minute) self.name = name def __str__(self): return f"{self.time.minute} {self.time.hour} {self.name}" def __repr__(self): return f"{self.time.minute} {self.time.hour} {self.name}" def parse_cron_config(config_lines): """ parse input lines to read cron job config file. returns a list of CronJobs""" cron_lines = [] for line in config_lines: try: minute, hour, name = line.strip().split(" ")[0:3] cron_new = CronJob(minute, hour, name) cron_lines.append(cron_new) except ValueError: # traceback.print_exc() print(f"Error: Invalid config file. Line [{config_lines.index(line)}] does not have the required format:") print(f"\t{line.strip()}") return [] return cron_lines def find_job_runtime(job_t1, t2): """ returns the next runtime for job_t1. main challenge is to replace wildcards ('*') in job, otherwise it's trivial. """ t1_hour_fixed = job_t1.hour t1_minute_fixed = job_t1.minute ## replace wildcards ## TWO WILDCARDS if job_t1.minute == "*" and job_t1.hour == "*": ## trivial case with two wildcards t1_hour_fixed = t2.hour t1_minute_fixed = t2.minute ## HOUR WILDCARD only elif job_t1.hour == "*" and job_t1.minute != "*": if t2.minute <= job_t1.minute: ## still in this hour t1_hour_fixed = t2.hour else: ## next hour, mind day change t1_hour_fixed = (t2.hour + 1) % 24 ## MINUTE WILDCARD only elif job_t1.hour != "*" and job_t1.minute == "*": if t2.hour == job_t1.hour: ## same hour, so now t1_minute_fixed = t2.minute else: ## not this hour, so :00 t1_minute_fixed = 0 return Time(t1_hour_fixed, t1_minute_fixed) def get_next_runtime(job, current_time): """ formats the time when the given job runs next, given the current_time.""" run_time = find_job_runtime(job.time, current_time) day = "today" if run_time.hour < current_time.hour or \ (run_time.hour == current_time.hour and run_time.minute < current_time.minute): day = "tomorrow" return f"{run_time.hour}:{run_time.minute:0>2} {day} - {job.name}" def get_upcoming_runtimes(cron_jobs, current_time): """ prints the next runtime for each job, given the current_time.""" assert type(current_time) is Time assert all(type(job) is CronJob for job in cron_jobs) ## get runtime for each single job next_runtimes = [get_next_runtime(job, current_time) for job in cron_jobs] return next_runtimes def parse_current_time(time_input): try: input_arg = time_input hour, minute = input_arg.split(":") input_time = Time(hour, minute) return input_time except IndexError: print("Error: requires a command line argument") return except ValueError: print("Error: argument has wrong time format (requires HH:MM)") return def main(): ## read from STDIN stdin_lines = sys.stdin.readlines() ## and parse config file cron_jobs = parse_cron_config(stdin_lines) # print("found the following jobs:") # [print(f"\t{c}") for c in cron_jobs] # if len(cron_jobs) == 0: # print("Error: found no cron jobs in config file") # return ## read time from command line argument input_time = parse_current_time(sys.argv[1]) ## check which jobs run when next upcoming = get_upcoming_runtimes(cron_jobs, input_time) print("\n".join(upcoming)) if __name__ == '__main__': main()
Java
UTF-8
3,598
2.390625
2
[]
no_license
package com.example.yanglin.arcface.models; import java.util.List; /** * Created by yanglin on 18-3-21. */ public class Record { /** * code : 1 * msg : 成功 * data : {"datas":[{"count":1,"type":0,"created_at":"2018-04-12T22:23:43.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:23:48.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:23:52.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:41.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:46.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:51.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:55.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:59.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:26:03.000Z"}],"pageNo":1,"pageSize":10,"total":9} */ private int code; private String msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * datas : [{"count":1,"type":0,"created_at":"2018-04-12T22:23:43.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:23:48.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:23:52.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:41.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:46.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:51.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:55.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:25:59.000Z"},{"count":1,"type":0,"created_at":"2018-04-12T22:26:03.000Z"}] * pageNo : 1 * pageSize : 10 * total : 9 */ private int pageNo; private int pageSize; private int total; private List<DatasBean> datas; public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<DatasBean> getDatas() { return datas; } public void setDatas(List<DatasBean> datas) { this.datas = datas; } public static class DatasBean { /** * count : 1 * type : 0 * created_at : 2018-04-12T22:23:43.000Z */ private int count; private int type; private String created_at; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } } } }
Java
UTF-8
869
1.875
2
[]
no_license
package com.ccsoft.yunqudao.ui.house; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; public class MyLocationListener implements BDLocationListener { public static String addr; public static String city; public static String city_code; @Override public void onReceiveLocation(BDLocation location) { // addr = location.getAddrStr(); //获取详细地址信息 // String country = location.getCountry(); //获取国家 // String province = location.getProvince(); //获取省份 // city = location.getCity(); //获取城市 // String district = location.getDistrict(); //获取区县 // String street = location.getStreet(); // city_code = location.getCityCode(); // Log.e("cccccw",city+" "+city_code); } }
Markdown
UTF-8
1,207
2.671875
3
[]
no_license
# order_imbalance ## Project Overview The aim of this project is to study the effect of order imbalance on the price of Bitcoin. ## Files 1. data_collect.py This notebook reads 55 dump files of format xbtusd.dump*, applies some data cleaning process and then exports it to a single CSV with required data. Data is exported to first_sum_55h.csv. 1. order_imbalance.py This file logs the incoming data to two files: * one file contains orderbook and trade data as received from websocket(without parsing) * another file contains prices and sizes for top 10 orders in the order book for both sides 2. data_analysis.ipynb Reads df_join.csv at the start of the notebook. Studying simple correlation between price change and input features. 3. order_imbalance.ipynb This notebook shows that features we selected were highly skewed. So, we could not make any statistical conclusion from it. ## Output The `id` and `price` have same relation for both side of `orderBookL2`: when `id` increases, `price` decreases: Here is sample data from **orderBook.dump** when `action = partial` showing the inverse relation between `price` and `id` for both side of orderbook: ![alt text](img/price_id_rel.jpg)
C#
UTF-8
2,358
3.6875
4
[]
no_license
using System; using System.Text; using Algorithms_DS.Stacks; using System.Collections.Generic; namespace Algorithms_DS.Queues { public class ArrayQueue { private int[] items; private int count; private int rear; private int front; public ArrayQueue(int capacity) { items = new int[capacity]; } public void Enqueue(int item) { if(items.Length == count) throw new ArgumentOutOfRangeException(); items[rear] = item; rear = (rear + 1) % items.Length; count++; } public int Dequeue() { if(count == front) throw new ArgumentOutOfRangeException(); var item = items[front]; items[front] = 0; front = (front + 1) % items.Length; count--; return item; } public bool IsEmtpy() { return count == 0; } public int[] Reverse() { Stack st = new Stack(10); int index = count; while(!IsEmtpy()) st.Push(Dequeue()); while(!st.IsEmpty()) Enqueue(st.Pop()); return null; } public void ReverseOrderOfFirstKElements(int k) { if(k>count) throw new InvalidOperationException(); //Method 1 // for(int i=0; i<k-1;i++) // { // int temp = items[k-i-1]; // items[k-i-1] = items[i]; // items[i] = temp; // } //Method 2 Stack<int> st = new Stack<int>(); for(int i=0;i<k;i++) st.Push(Dequeue()); while(st.Count >0) Enqueue(st.Pop()); for(int i=0;i<items.Length-k;i++) Enqueue(Dequeue()); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("["); for(int i=0;i<items.Length;i++) { sb.Append(items[i]); if(i+1!=items.Length) sb.Append(","); } sb.Append("]"); return sb.ToString(); } } }
Markdown
UTF-8
7,615
2.640625
3
[]
no_license
--- title: Typological Dating Notes on Antoniniani author: Samuel Brew --- | Coin | Date | Emperor | Mint | RIC Reference | | :------: | :-----: | :-------------: | :-----: | :----------------------: | | 1 | 293 | Maximian | Cyzicus | RIC V Diocletian 607 | | 2 | 293-295 | Diocletian | Antioch | RIC V Diocletian 322 | | 3 | 270-275 | Aurelian | Cyzicus | RIC V Aurelian 356 | | 4 (P61) | 238-239 | Gordian III | Antioch | RIC IV Gordian III 177A | | 5 (2509) | 247 | Otacilia Severa | Roma | RIC IV Philip I 125C | | 6 (2512) | 250 | Decius | Roma | RIC IV Trajan Decius 21B | ## Initial Listing - First coin - Emperor: Maximianus - Obverse: IMP CMA MAXIMIANVS AVG - Reverse: CONCORDIA MILITVM/A/XXI - Date: 293 - Mint: Cyzicus - Second coin (Radiatus) - Emperor: Diocletianus - Obverse: ??? - Reverse: CONCORDIA MILITVM/XXMIV - Date: 320 - Mint: Antioch - Third coin - Emperor: Aurelianus - Obverse: IMP C AVRELIANVS AVG - Reverse: CONCORDIA MILITVM/XXIV - Date: 356 - Mint: ??? - Fourth coin (P61) - Emperor: Constantinus II Junior (Constantine II) - Obverse: AVG C?E S... - Reverse: ...QVINTAS AVG - Date: 321-322 - Mint: Trier - Fifth coin (2509) - Emperor: ??? - Obverse: ...AVG - Reverse: ??? - Date: ??? - Mint: ??? - Sixth coin (2512) - Emperor: Crispus? - Obverse: ...DE CIUS AVG - Reverse: ??? - Date: ??? - Mint: ??? - Fourth coin dating (WRONG!) - Ruler determined from https://www.tesorillo.com/aes/_anv/constantinus2_i.htm - Reverse identified from https://www.tesorillo.com/aes/195/195i.htm, reverse type is 195 with *ubertas* standing left holding balance and cornucopia - Mint mark given as TR at above source, confirmed to be Treveri mint from https://www.tesorillo.com/aes/_cec/cecas1.htm (wrong, Trier) - This emperor is Flavius Claudius Constantinus according to https://www.tesorillo.com/aes/_rev/constantinus2_i.htm - That's Constantine II according to https://en.wikipedia.org/wiki/Constantine_II_(emperor) - Ruled from 337-340, made Caesar in 317 (just after birth) - Then I have an RIC page: https://www.wildwinds.com/coins/ric/constantine_II/t.html - Just noticed the RIC reference to RIC VII Trier 335 on https://www.tesorillo.com/aes/195/195i.htm, but apparently not listed in RIC! - Mint definitely at Trier than Treveri - First coin dating - Find in page 'CONCORDIA MILITVM' at https://www.wildwinds.com/coins/ric/maximianus/t.html, looking for anything with mintmark XXI and correct obverse legend - Noting that the coin actually has Δ in lower centre - RIC V 607, D then (definite) - Cyzicus mint - 293 - Determining mint at https://www.tesorillo.com/aes/_cec/cecas1.htm - Apparently XXI is mark of value, so mint unknown then for coin this early? - http://numismatics.org/ocre/id/ric.5.dio.607 -- RIC V Diocletian 607 - Fifth coin dating - Possibly RIC 75bMule (https://www.wildwinds.com/coins/ric/otacilia_severa/t.html) - Ruling out RIC 119a because the obverse legend appears to be different - Very likely RIC 125c, has identical obverse/reverse lettering, perfect legends too () - Ruling out RIC 128a because different posture of figure on reverse - Calling it as RIC 125c! - https://www.vcoins.com/en/stores/numiscorner/239/product/coin_otacilia_severa_antoninianus_247_roma__billon_ric125c/1482589/Default.aspx seems to confirm typology - Date 247 - Mint Roma - https://department.monm.edu/classics/coins/data/id/ota/ota007.jpg image confirms typology - Calling date and mint! - http://numismatics.org/ocre/id/ric.4.ph_i.125C -- RIC IV Philip I 125C - Sixth coin dating - Know it's using sharp (sun ray?) crown, hence looking for that on https://wildwinds.com/coins/ric/trajan_decius/t.html - https://wildwinds.com/coins/sear5/s9378.html has very close obverse, now know lettering (IMP C M Q TRAIANVS DECIVS AVG) - Looks like the reverse has Pannoniae (https://wildwinds.com/coins/ric/trajan_decius/RIC_0021a.jpg) - Based on https://wildwinds.com/coins/sear5/s9378.html I also want the radiate crown - That one is very similar but I don't think it's correct, minor discrepancies on reverse (RIC 21b for reference though) - Searching for IMP C M Q TRAIANVS DECIVS AVG, radiate seems to yield one of the above to be correct (24 results) - List of possible (correct lettering, radiate crown, Pannoniae): RIC 21b, RIC 25 - Ruling out 25 because the right figure on the reverse golds a torch - Ruling out 21b because the right figures don't match completely (possible though) - https://www.vcoins.com/en/stores/victors_imperial_coins/208/product/trajan_decius_pannoniae_from_rome/1361541/Default.aspx is very similar, again 21b, but reverse not quite right, maybe a variant? - Doesn't have the staff-like object at the base of right figure, so maybe mine is 21b - https://www.vcoins.com/en/stores/aeternitas_numismatics/2/product/trajan_decius_ar_antoninianus_efef_pannoniae_excellent_coin/544997/Default.aspx does have that, but more generic Pannoniae - Probably 21b -- date range 249-251 - http://numismatics.org/ocre/id/ric.4.tr_d.21B description of 21b matches, therefore calling it as RIC 21b - Lists mint as Roma - http://numismatics.org/ocre/id/ric.4.tr_d.21B -- RIC IV Trajan Decius 21B - Fourth coin (take 2) - I now know that the emperor is Gordian III from Dr. Dearn's identification - Looking for it in https://wildwinds.com/coins/ric/gordian_III/t.html - Sir read obverse as IMP CAES M ANT GORDIANVS AVG, searching for that (and radiate) 'IMP CAES M ANT GORDIANVS AVG, radiate' - Sir has identified reverse as Aequitas (only 15 results, using that instead) - Possibly: RIC 34, RIC 177 (not certain that's radiate though) - All others are PIVS or the like - RIC 177 tentatively ruled out, different eye style, despite identical reverse - RIC 34 has very wrong nose style - Either could be it, but RIC 34 is 240 CE and RIC 177 is TODO - RIC 177a fits perfectly, though maybe with a slightly different facial expression on the eyes (possible new RIC variant!) https://wildwinds.com/coins/ric/gordian_III/RIC_0177a.jpg - Chose that over RIC 177 or 177a.1 due to the more accurate representation of the radiate crown - Date for 177a given on Wildwinds as 238-239 CE, confirmed by http://numismatics.org/ocre/id/ric.4.gor_iii.177 - Mint also given as Antioch from both sources - http://numismatics.org/ocre/id/ric.4.gor_iii.177A -- RIC IV Gordian III 177A - Second coin - Didn't initially date, information already given, should clarify though! - Using given RIC V Diocletian 322 (that last digit is in question...) - http://numismatics.org/ocre/id/ric.5.dio.322 matches perfectly! - Permits Z in reverse field, as this one has - Mint: Antioch - 293-295 AD - Examples available, they match too (http://numismatics.org/ocre/id/ric.5.dio.322#examples) - That also confirms it to be an antoninianus, in contradiction to given statement - http://numismatics.org/ocre/id/ric.5.dio.322 -- RIC V Diocletian 322 - Third coin - Stuffed up, 356 is RIC reference, not date! - Wildwinds Aurelian doesn't have it - URl playing around on Numismatic.org! http://numismatics.org/ocre/id/ric.5.aur.356 - 5 year date range, which is bad (270-275), I'll try to narrow that down - Searching for that date range on Wildwinds at https://www.wildwinds.com/coins/ric/aurelian/t.html yields nothing - No other sources found unfortunately, not a common coin perhaps - Mint is Cyzicus - http://numismatics.org/ocre/id/ric.5.aur.356 -- RIC V Aurelian 356
Java
UTF-8
417
2.421875
2
[]
no_license
package factories; import java.util.ArrayList; import nl.tomsanders.game.engine.util.Vector; import game.Level; import game.objects.GameObject; public abstract class AmmoFactory { protected Level level; public abstract ArrayList<GameObject> create(Vector position, ArrayList<Vector> arrayList); public Level getLevel() { return this.level; } public void setLevel(Level level) { this.level = level; } }
C#
UTF-8
7,148
3.171875
3
[]
no_license
using System; using System.Collections.Generic; namespace BoatClub.Model { internal class MemberRegistry { public List<Member> GetMemberList() { var memberList = XML.GetMemberListFromXMLFile(); return memberList; } public void SaveMemberList(List<Member> memberList) { XML.SaveMemberListToXMLFile(memberList); } public void SaveMember(string name, string personalNumber) { var memberList = GetMemberList(); var member = new Member(name, personalNumber, GetNextMemberId()); memberList.Add(member); SaveMemberList(memberList); } public void AddBoat(string memberId, string boatType, string lengthInMetres) { var boat = CreateBoat(boatType, lengthInMetres); var memberList = GetMemberList(); var found = false; foreach (var member in memberList) { if (member.MemberId == memberId) { member.Boats.Add(boat); found = true; break; } } if (!found) { throw new Exception("No member with that id."); } SaveMemberList(memberList); } private Boat CreateBoat(string boatTypeInput, string lengthInMetresInput) { if (Enum.IsDefined(typeof(BoatType), boatTypeInput)) { double lengthInMetres; var boatType = (BoatType)Enum.Parse(typeof(BoatType), boatTypeInput); double.TryParse(lengthInMetresInput, out lengthInMetres); var boat = new Boat(boatType, lengthInMetres); return boat; } var listOfValidBoatTypes = ""; var boatTypes = Enum.GetNames(typeof(BoatType)); for (int i = 0; i < boatTypes.Length; i++) { listOfValidBoatTypes += boatTypes[i]; if (i < boatTypes.Length - 1) { listOfValidBoatTypes += ", "; } } throw new Exception($"You have entered an invalid type of boat. \nVaild boat types: {listOfValidBoatTypes}"); } public string GetNextMemberId() { int id; var memberList = GetMemberList(); if (memberList.Count == 0) return "1"; var lastId = memberList[memberList.Count - 1].MemberId; int.TryParse(lastId, out id); id++; return id.ToString(); } public Member GetMemberById(string id) { Member memberToGet = null; var memberList = GetMemberList(); foreach (var member in memberList) { if (member.MemberId == id) { memberToGet = member; break; } } if (memberToGet == null) { throw new Exception($"Member with id: {id} does not exist."); } return memberToGet; } public Member DeleteMemberById(string id) { var memberList = GetMemberList(); Member deletedMember = null; var updatedMemberList = new List<Member>(); foreach (var member in memberList) { if (member.MemberId == id) { deletedMember = member; continue; } updatedMemberList.Add(member); } if (deletedMember == null) { throw new Exception($"Member with id {id} could not be deleted. Not found."); } SaveMemberList(updatedMemberList); return deletedMember; } public void UpdateMember(string memberId, string newName, string newPersonalNumber) { var memberList = GetMemberList(); Member memberToBeFound = null; foreach (var member in memberList) { if (member.MemberId == memberId) { memberToBeFound = member; member.Name = newName; member.PersonalNumber = newPersonalNumber; break; } } if (memberToBeFound == null) { throw new Exception($"Member with id {memberId} does not exist."); } SaveMemberList(memberList); } public string DeleteMember(string memberId) { return $"Successfully deleted member with id: {memberId}"; } public void AddBoat(string memberId, Boat boat) { var memberList = GetMemberList(); var found = false; foreach (var member in memberList) { if (member.MemberId == memberId) { member.Boats.Add(boat); found = true; break; } } if (!found) { throw new Exception("No member with that id."); } SaveMemberList(memberList); } public void UpdateBoat(string memberId, int boatIndex, string boatTypeInput, float length) { var memberList = GetMemberList(); foreach (var member in memberList) { if (member.MemberId == memberId) { var boat = member.Boats[boatIndex - 1]; var boatType = (BoatType) Enum.Parse(typeof(BoatType), boatTypeInput); boat.BoatType = boatType; boat.BoatLength = length; } } SaveMemberList(memberList); } public void DeleteBoat(string memberId, int boatIndex) { var memberList = GetMemberList(); Member memberToBeFound = null; foreach (var member in memberList) { if (member.MemberId == memberId) { memberToBeFound = member; if (boatIndex < 1 || boatIndex > member.Boats.Count) { throw new Exception($"Boat index {boatIndex} is out of range."); } member.Boats.RemoveAt(boatIndex - 1); } } if (memberToBeFound == null) { throw new Exception($"Could not remove boat. Member with id {memberId} was not found."); } SaveMemberList(memberList); } } }
Markdown
UTF-8
2,336
2.984375
3
[]
no_license
+++ date = "2009-01-15T02:31:00-07:00" draft = false title = "On App Store Download Statistics" url = "/blog/2009/01/15/on-app-store-download-statistics/" +++ It seems that nobody wants to release statistics about how their apps are doing on the iTunes App Store, yet a lot of people want to know how well various apps are doing. I've seen [a](http://www.taptaptap.com/blog/final-numbers-for-july/) [couple](http://www.taptaptap.com/blog/the-easy-way-to-get-into-the-iphone-app-game-buy-a-proven-app/) [of](http://venturebeat.com/2008/12/27/a-christmas-ifart-explosion-nearly-40000-downloads-and-30000-net/) [examples](http://blog.wired.com/gadgets/2008/09/indie-developer.html) of income and download numbers, but I'd still like to see more. So, I'm putting my money where my mouth is and publishing the download statistics for my first app, [Prayer Book](https://arashpayan.com/projects/#prayer-book). For some background about the app, you may want to check out my [earlier post](https://arashpayan.com/blog/2008/10/02/prayer-book-for-iphone-and-ipod-touch/). After submitting Prayer Book to Apple on September 24th, they approved it for sale on October 2nd. It was immediately placed on the App Store, but it was never at the top of the recently released apps list, because I had set the release date to be September 24th. It wasn't until 3 months later that I learned that your order in the App Store has nothing to do with the date Apple approves your app. ![Prayer Book Monthly Download Stats](/blog-files/prayerbookmonthlystats.png) Up until the writing this post, there have been 9,448 downloads of Prayer Book, with an average of 91 downloads a day. Not bad I think. December was a particularly interesting month, so I'll share some more detailed numbers there. ![Prayer Book December Downloads](/blog-files/prayerbookdecemberdownloads-300x196.jpg) December was shaping up to be a pretty regular month, and then on the 22nd, there was a spike to 118 downloads, then a drop, and then another spike that lasted from the 25th-29th. I only have data up to the 13th of January included in the monthly table above, but that's already further ahead in downloads than the same time in December (941 downloads from December 1-13). Granted, December will probably still be better than January because of the Christmas activity.
PHP
UTF-8
636
2.796875
3
[]
no_license
<?php $server = "localhost"; $user = "root"; $pass = "123mudar"; $database = "teste"; //conexão com mysqli @$mysqli = new mysqli($server,$user,$pass,$database); //Error if (mysqli_connect_errno()) { echo "Failed to connect (".$mysqli->connect_errno.") ".$mysqli->connect_error; exit; } $stmt = $mysqli->stmt_init(); $stmt->prepare("select name, email from user where id = ? and name = ?"); $stmt->bind_param("is",$_GET["id"],$_GET["name"]); $stmt->execute(); $stmt->bind_result($name,$email); $stmt->fetch(); echo "Name: ".$name."<br/>"; echo "Email: ".$email."<hr/>"; // if ($query = $mysqli->query($sql)) { // // } ?>
C#
UTF-8
2,120
2.609375
3
[]
no_license
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Dictcreator.Core.Fetchers { public class TranslateFetcherReverso : DataFetcher { private string _siteUrl = "https://context.reverso.net/translation/english-russian/"; private string _xPathQuery = "//div[@id='translations-content']//*[contains(@class, 'translation')]"; public override CellType CellExlType => CellType.STRING; public override string ServiceName => "Reverso"; protected override ColumnName ColName => ColumnName.TRANSLATE; public override string GetResult(string word) { var result = GetResultAsync(word); string resultString = result.Result; return resultString; } private async Task<string> GetResultAsync(string word) { string result = ""; var htmlDoc = new HtmlDocument(); var client = new HttpClient(); try { var response = await client.GetStringAsync(_siteUrl + word); htmlDoc.LoadHtml(response); HtmlAgilityPack.HtmlNodeCollection translateList = htmlDoc.DocumentNode.SelectNodes(_xPathQuery); if (translateList != null && translateList.Count > 0) { List<string> translateWordList = new List<string>(); foreach (var item in translateList) { var wordStr = Regex.Replace(item.InnerText, "\n", "").Trim(); if (wordStr != String.Empty) translateWordList.Add(wordStr); } result = string.Join(", ", translateWordList); } } catch (HttpRequestException e) { //404 nothing do } return result; } } }
Java
UTF-8
2,303
2.546875
3
[]
no_license
package propertiessheet; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Callback; import org.controlsfx.control.PropertySheet; import org.controlsfx.property.BeanPropertyUtils; import org.controlsfx.property.editor.DefaultPropertyEditorFactory; import org.controlsfx.property.editor.Editors; import org.controlsfx.property.editor.PropertyEditor; import java.util.ArrayList; import java.util.List; public class PropertiesSheetTest extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Person bean = new Person(); bean.addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, Object oldValue, Object newValue) { System.err.println(newValue); } }); ObservableList<PropertySheet.Item> properties = BeanPropertyUtils.getProperties(bean); PropertySheet propertySheet = new PropertySheet(properties); propertySheet.setSearchBoxVisible(false); propertySheet.setModeSwitcherVisible(false); DefaultPropertyEditorFactory defaultPropertyEditorFactory = new DefaultPropertyEditorFactory(); propertySheet.setPropertyEditorFactory(new Callback<PropertySheet.Item, PropertyEditor<?>>() { @Override public PropertyEditor<?> call(PropertySheet.Item param) { if(param.getName().equals("age")){ // List<Integer> ageList = new ArrayList<>(); // ageList.add(3); // ageList.add(5); // ageList.add(10); // return Editors.createChoiceEditor(param,ageList); return Editors.createNumericEditor(param); } return defaultPropertyEditorFactory.call(param); } }); VBox vBox = new VBox(propertySheet); Scene scene = new Scene(vBox); primaryStage.setScene(scene); primaryStage.show(); } }
C++
UTF-8
538
2.75
3
[]
no_license
#include<vector> class EuropeanCallOption{ public: //constructor EuropeanCallOption( int nInt_, double strike_, double spot_, double vol_, double r_, double expiry_, double barier_ ); //destructor ~EuropeanCallOption(){}; //methods void generatePath(); void printPath(); double getEuropeanCallPrice(int nReps); double getLastPrice(); //members std::vector<double> thisPath; int nInt; double strike; double spot; double vol; double r; double expiry; double barier; };
Java
UTF-8
1,581
2.234375
2
[ "LicenseRef-scancode-generic-cla", "MIT", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents; import com.azure.search.documents.models.IndexAction; /** * This interface represents callback hooks that are triggered when {@link IndexAction IndexActions} are added, succeed, * fail, or are removed from the document indexing batch while using a {@link SearchBatchClient} or {@link * SearchBatchAsyncClient}. */ public interface IndexingHook { /** * Callback hook for when a document indexing action has been added to a batch queued. * * @param action The {@link IndexAction} that has been added to a batch queue. */ void actionAdded(IndexAction<?> action); /** * Callback hook for when a document indexing action has successfully completed indexing. * * @param action The {@link IndexAction} that successfully completed indexing. */ void actionSuccess(IndexAction<?> action); /** * Callback hook for when a document indexing action has failed to index and isn't retryable. * * @param action The {@link IndexAction} that failed to index and isn't retryable. */ void actionError(IndexAction<?> action); /** * Callback hook for when a document indexing has been removed from a batching queue. * <p> * Actions are removed from the batch queue when they either succeed or fail indexing. * * @param action The {@link IndexAction} that has been removed from a batch queue. */ void actionRemoved(IndexAction<?> action); }
C
UTF-8
476
2.890625
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include "positional_actual.h" #include "ast_helper.h" positional_actual *create_positional_actual(char *identifier) { positional_actual *result = malloc(sizeof(positional_actual)); result->identifier = identifier; return result; } void print_positional_actual(positional_actual *positional_actual, int indent) { print_indent(indent); printf("positional_actual(identifier=%s)\n", positional_actual->identifier); }
Java
UTF-8
2,644
2.125
2
[]
no_license
package com.lanrenyou.interceptor; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.lanrenyou.config.AppConfigs; import com.lanrenyou.user.model.UserInfo; import com.lanrenyou.util.HtmlFilterUtil; import com.lanrenyou.util.ServletUtil; import com.lanrenyou.util.StringUtil; import com.lanrenyou.util.UrlEncoderUtil; import com.lanrenyou.util.constants.LRYConstant; public class LoginCheckInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(LoginCheckInterceptor.class); protected static final int DEFAULT_PORT = 80; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UserInfo userInfo = (UserInfo)request.getAttribute(LRYConstant.LOGIN_USER); if (null == userInfo) { if ((request.getHeader("X-Requested-With") != null) && (request.getHeader("X-Requested-With").equals("XMLHttpRequest"))) { return false; } String currentUrl = getForwardUrl(request); logger.debug("user does not login"); response.sendRedirect("http://" + AppConfigs.getInstance().get("domains.www") + "/login?redir=" + UrlEncoderUtil.encodeByUtf8(currentUrl)); return false; } Cookie mailCookie = ServletUtil.getCookie(request, LRYConstant.AUTH_EMAIL_COOKIE_KEY); if ((mailCookie == null) || (StringUtil.isBlank(mailCookie.getValue())) || mailCookie.getValue().equals(userInfo.getEmail())) { ServletUtil.writeCookie(response, LRYConstant.AUTH_EMAIL_COOKIE_KEY, userInfo.getEmail(), AppConfigs.getInstance().get("domains.www"), -1); } return true; } protected String getForwardUrl(HttpServletRequest request) { int port = request.getServerPort(); String servletPath = request.getServletPath(); if ((servletPath == null) || ("/".equals(servletPath))) { servletPath = ""; } StringBuilder stringBuilder = new StringBuilder(request.getScheme()).append("://").append(request.getServerName()).append(port == 80 ? "" : new StringBuilder().append(":").append(port).toString()).append(request.getContextPath()).append(servletPath).append(request.getPathInfo()); if ((request.getQueryString() != null) && (!request.getQueryString().isEmpty())) { stringBuilder.append("?").append(HtmlFilterUtil.filterHeaderValue(request.getQueryString())); } return stringBuilder.toString(); } }
Java
UTF-8
3,278
2.015625
2
[]
no_license
package com.ku.dku.controller; import javax.annotation.RegEx; import javax.mail.Session; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.ku.dku.bean.LoginRequest; import com.ku.dku.bean.LoginResponse; import com.ku.dku.entity.MsFile; import com.ku.dku.entity.TxStudent; import com.ku.dku.repository.TxStudentRepository; import com.ku.dku.service.FileService; import com.ku.dku.service.LoginService; @RestController @RequestMapping(value = "/demo") public class LoginController { @Autowired private LoginService loginService; @Autowired private TxStudentRepository studentRepository; @Autowired private FileService fileService; @RequestMapping(value = "/check") public String loginSes(HttpServletRequest request) { JSONObject obj = new JSONObject(); obj.put("username", request.getSession().getAttribute("username")); return obj.toString(); } @CrossOrigin(origins = "http://192.168.43.126:8080") @RequestMapping(value = "/login",method = RequestMethod.POST) public @ResponseBody LoginResponse login(@RequestBody LoginRequest request, HttpServletRequest req ) { LoginResponse response = new LoginResponse(); try { TxStudent txStudent = new TxStudent(); txStudent.setStudentUsername(request.getStudentUsername()); txStudent.setStudentPassword(request.getStudentPassword()); boolean login = loginService.login(txStudent,request.getLoginFrom()); String getData = txStudent.getStudentUsername(); if (login) { TxStudent getTxStudent = studentRepository.findByStudentUsername(getData); req.getSession().setAttribute("username", getTxStudent.getStudentUsername()); req.getSession().setAttribute("studentFname", getTxStudent.getStudentFname()); req.getSession().setAttribute("studentLname", getTxStudent.getStudentLname()); req.getSession().setAttribute("studentId",getTxStudent.getStudentId()); System.out.println(req.getSession().getAttribute("username")); System.out.println("Hello"); response.setStudentIdResponse(getTxStudent.getStudentId()); response.setStudentFnameResponse(getTxStudent.getStudentFname()); response.setStudentLnameResponse(getTxStudent.getStudentLname()); response.setStudentPhoneResponse(getTxStudent.getStudentPhone()); response.setStudentRoomResponse(getTxStudent.getStudentRoom()); response.setStatusResponse("success"); //getFiles MsFile files = fileService.getFile(getTxStudent.getStudentId()); // response.setFileData(files.getFileData()); response.setFileType(files.getFileType()); response.setFileName(files.getFileName()); } else { response.setStatusResponse("failed"); } } catch (Exception e) { e.printStackTrace(); response.setStatusResponse("longin failed"); } return response; } }
Java
UTF-8
636
2.5
2
[]
no_license
package Thread.provideconsume.method2; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * @Desc: 描述 * @Author: Heyyw * @CreateDate: 2019/3/28 14:47 * @UpdateAuthor: * @UpdateDate: * @UpdateRemark: 更新说明 * @Version: 1.0 */ public class product { public static void main(String[] args) { BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10); new Thread(new provide(queue)).start(); new Thread(new consume(queue)).start(); new Thread(new consume(queue)).start(); new Thread(new consume(queue)).start(); } }
Python
UTF-8
12,093
2.59375
3
[]
no_license
import threat import state pawn_start_keys = [ 52, 53, 54, 55, 56, 57, 58, 59, 82, 98, 114, 130, 146, 162, 178, 194, 93, 109, 125, 141, 157, 173, 189, 205, 228, 229, 230, 231, 232, 233, 234, 235 ] castle_ext_keys = { 129 : { 97 : 0, 161 : 1}, 248 : { 250 : 0, 246 : 1}, 39 : { 37 : 0, 41 : 1}, 158 : { 190 : 0, 126 : 1} } castle_req_keys = { 129 : { 97 : 81, 161 : 193}, 248 : { 250 : 151, 246 : 244}, 39 : { 37 : 36, 41 : 43}, 158 : { 190 : 206, 126 : 94} } castle_rep_keys = { 129 : { 97 : 113, 161 : 145}, 248 : { 250 : 249, 246 : 247}, 39 : { 37 : 38, 41 : 40}, 158 : { 190 : 174, 126 : 142} } valid_promotion_codes = [1, 2, 3, 4] promotion_keys = [ [81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94], [43, 59, 75, 91, 107, 123, 139, 155, 171, 187, 203, 219, 235, 251], [193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206], [36, 52, 68, 84, 100, 116, 132, 148, 164, 180, 196, 212, 228, 244] ] def undo(history): """ Returns The Last Position Data """ pos = history.pop() return [pos, history] def get_moves(board, move, castle_rights, enpassants): """ Gets A List Of Avaliable Moves """ ret = [] for key, square in enumerate(board): if square != 0 and square[0] == move: if pawn_start_square(key) and square[1] == 0: if move == 0: directone = key + (threat.directions[0] * 2) directtwo = key + threat.directions[0] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) if board[directone] == 0: temp_board = board[:] temp_board[directone] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directone]) elif move == 1: directone = key + (threat.directions[3] * 2) directtwo = key + threat.directions[3] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) if board[directone] == 0: temp_board = board[:] temp_board[directone] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directone]) elif move == 2: directone = key + (threat.directions[1] * 2) directtwo = key + threat.directions[1] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) if board[directone] == 0: temp_board = board[:] temp_board[directone] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directone]) else: directone = key + (threat.directions[2] * 2) directtwo = key + threat.directions[2] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) if board[directone] == 0: temp_board = board[:] temp_board[directone] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directone]) elif square[1] == 0: if move == 0: directtwo = key + threat.directions[0] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) elif move == 1: directtwo = key + threat.directions[3] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) elif move == 2: directtwo = key + threat.directions[1] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) else: directtwo = key + threat.directions[2] if board[directtwo] == 0: temp_board = board[:] temp_board[directtwo] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) == 0: ret.append([key, directtwo]) if square[1] == 5 and state.in_check(board, move) == 0: if castle_rights[move][0] == True: if move == 0: local_a = 249 local_b = 250 elif move == 1: local_a = 113 local_b = 97 elif move == 2: local_a = 38 local_b = 37 else: local_a = 174 local_b = 190 if board[local_a] == 0 and board[local_b] == 0: allow = True for key_check, square_check in enumerate(board): if square_check != 0 and not(is_not_opposite_color(move, square_check[0])): if threat.is_threat(key_check, local_a, board) or threat.is_threat(key_check, local_b, board): allow = False if allow == True: ret.append([key, local_b]) if castle_rights[move][1] == True: if move == 0: local_a = 247 local_b = 246 local_c = 245 elif move == 1: local_a = 145 local_b = 161 local_c = 177 elif move == 2: local_a = 40 local_b = 41 local_c = 42 else: local_a = 142 local_b = 126 local_c = 110 if board[local_a] == 0 and board[local_b] == 0: allow = True for key_check, square_check in enumerate(board): if square_check != 0 and not(is_not_opposite_color(move, square_check[0])): if threat.is_threat(key_check, local_a, board) or threat.is_threat(key_check, local_b, board) or threat.is_threat(key_check, local_c, board): allow = False if allow == True: ret.append([key, local_b]) for key_check, square_check in enumerate(board): if threat.is_threat(key, key_check, board): if square_check == 0: if square[1] == 0: for enpassant_key, enpassant_check in enumerate(enpassants): if key_check == enpassant_check and not(is_not_opposite_color(enpassant_key, move)): if move == 0: hasOpposingPawnKey = key + threat.directions[0] elif move == 1: hasOpposingPawnKey = key + threat.directions[3] elif move == 2: hasOpposingPawnKey = key + threat.directions[1] else: hasOpposingPawnKey = key + threat.directions[2] accessKey = board[hasOpposingPawnKey] if accessKey != 0 and accessKey[0] == enpassant_key and accessKey[1] == 0: ret.append([key, key_check]) continue if square_check != 0: if is_not_opposite_color(square[0], square_check[0]): continue skipSection = False if square[1] == 5: for threat_key_check in threat.valid_keys: if board[threat_key_check] == 0: continue check_opposite = board[threat_key_check] if not(is_not_opposite_color(square[0], check_opposite[0])): if threat.is_threat(threat_key_check, key_check, board): skipSection = True if skipSection == False: temp_board = board[:] temp_board[key_check] = temp_board[key] temp_board[key] = 0 if state.in_check(temp_board, move) != 0: continue ret.append([key, key_check]) return ret def is_not_opposite_color(color_one, color_two): """ Checks If The Colors Are Opposite """ if color_one == 0 and color_two == 0 or color_one == 0 and color_two == 2: return True if color_one == 1 and color_two == 1 or color_one == 1 and color_two == 3: return True if color_one == 2 and color_two == 2 or color_one == 2 and color_two == 0: return True if color_one == 3 and color_two == 3 or color_one == 3 and color_two == 1: return True return False def pawn_start_square(key): """ Checks If The Pawn Is On Starting Square """ if key in pawn_start_keys: return True return False def next_move(color): """ Get The Next Color To Move """ return (color + 1) % 4 def is_promotion_key(key, move): """ Checks An promotion Key """ if key in promotion_keys[move]: return True return False def valid_promotion(code): """ Checks An promotion Code """ if code in valid_promotion_codes: return True return False
C#
UTF-8
1,605
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class Fee { HospitalEntities e = new HospitalEntities(); public List<FeeTable> AllCharges() { var query = from FeeTable in e.FeeTables select FeeTable; List<FeeTable> userList = query.ToList(); return userList; } public List<string> listOfAllServices() { var query = from FeeTable in e.FeeTables select FeeTable; List<string> list = new List<string>(); foreach (var v in query) { list.Add(v.FeeName); } return list; } public bool changeCharge(string type, int amount) { var v=from FeeTable in e.FeeTables select FeeTable; FeeTable f = e.FeeTables.FirstOrDefault(fee=>fee.FeeName==type); f.Charge=amount; e.SaveChanges(); return true; } public bool Addtype(string type, int amount) { FeeTable fee = new FeeTable(); fee.FeeName = type; fee.Charge = amount; e.FeeTables.Add(fee); e.SaveChanges(); return true; } public bool DeleteType(string s) { FeeTable fee = e.FeeTables.FirstOrDefault(f=>f.FeeName==s); e.FeeTables.Remove(fee); e.SaveChanges(); return true; } } }
Ruby
UTF-8
839
3.46875
3
[]
no_license
require 'pry' require './lib/card' require './lib/guess' require './lib/deck' class Round attr_reader :deck, :guesses def initialize(deck) @deck = deck @guesses = [] @deck_index = 0 end def current_card @deck.cards[@deck_index] end def record_guess(guess) response = guess[:value] + " of " + guess[:suit] guess = Guess.new(response, current_card) @deck_index += 1 @guesses << guess end def number_correct correct_guesses = 0 @guesses.find_all do |guess| guess_card = guess.response.split(' ') if guess_card[0] == guess.card.value && guess_card[-1] == guess.card.suit correct_guesses += 1 end end correct_guesses end def percent_correct percent = (number_correct.to_f / @guesses.count) * 100 percent.to_i end end
Shell
UTF-8
4,747
4
4
[ "MIT" ]
permissive
#!/bin/sh command=$1 shift current_dir=$(pwd) script_path="${BASH_SOURCE[0]}" script_dir="${script_path:0:${#script_path}-5}" script_dir_pwd="$( cd "$script_dir" && pwd )" chmod +x "$script_path" if [ "$command" == "help" ] || [ "$command" == "" ]; then echo "usage: golem <command> [<args>] commands are: do exec command on vm (synced folder to cwd) run exec command on vm in golem root folder summon wake the golem halt halt the golem suspend suspend the golem reload reload the golem destroy destroy the golem expose forward ports from vm to host (parameters: vmport localport) clean clear all synced folders status display golem status ssh ssh into golem machine global-alias create global 'golem' alias where display golem location " exit fi cd "$script_dir_pwd" if [ $(pwd) == $current_dir ]; then at_golem_dir=true fi if [ "$command" == "where" ]; then echo "$script_path" exit $? fi if [ "$command" == "global-alias" ]; then bin_dir="/usr/local/bin" if [ -d "$bin_dir" ]; then echo "$script_dir_pwd/golem \$*" > "$bin_dir/golem" chmod +x "$bin_dir/golem" if [ $? == 0 ]; then echo "'golem' global alias created" fi else if [ -d "c:\\windows" ]; then # yes this is nasty, so is windows CLI sh ./utils/windows-elevate.sh "echo \"\"@$script_path %*\"\" > \"\"${SYSTEMROOT}\golem.cmd\"\"" else echo "WARNING: unable to set global alias on current system" fi fi exit $? fi if [ "$command" == "up" ] || [ "$command" == "summon" ]; then echo "Summoning the Golem!" vagrant up if [ $? == 0 ]; then vagrant ssh -c "cat /vagrant/resources/banner.erb" fi exit $? fi if [ "$command" == "halt" ]; then vagrant halt exit $? fi if [ "$command" == "suspend" ]; then vagrant suspend exit $? fi if [ "$command" == "reload" ]; then vagrant reload exit $? fi if [ "$command" == "destroy" ] || [ "$command" == "die" ]; then vagrant destroy exit $? fi if [ "$command" == "clean" ]; then if [ -e "./synced_folders" ]; then echo "removing all synced folders" echo "(they get created automatically when using 'golem do')" rm ./synced_folders echo "removing all forwarded ports" echo "(they get created automatically when using 'golem expose')" rm ./forwarded_ports vagrant reload else echo "no synced folders found, done." fi exit $? fi if [ "$command" == "status" ]; then vagrant status exit $? fi if [ "$command" == "ssh" ]; then vagrant ssh exit $? fi if [ "$command" == "run" ]; then vagrant ssh -c "cd /vagrant && $*" exit $? fi if [ "$command" == "expose" ]; then vmport="$1" localport="$2" # remove duplicates if [ -e ./forwarded_ports ]; then if grep -q "$vmport => $localport" ./forwarded_ports; then echo "port forward already existing" exit $? fi if grep -q "$vmport =>" ./forwarded_ports; then echo 'removing existing forward' cat ./forwarded_ports | grep "$vmport =>" cat ./forwarded_ports | grep -v "$vmport =>" > ./forwarded_ports.tmp mv ./forwarded_ports.tmp ./forwarded_ports fi if grep -q " => $localport" ./forwarded_ports; then echo 'removing existing forward' cat ./forwarded_ports | grep " => $localport" cat ./forwarded_ports | grep -v " => $localport" > ./forwarded_ports.tmp mv ./forwarded_ports.tmp ./forwarded_ports fi fi echo "exposing golem http port $vmport to local $localport" echo " $vmport => $localport" >> ./forwarded_ports echo "reload to apply changes" exit $? fi if [ "$command" == "do" ]; then guest_dir='/vagrant' if ! [ $at_golem_dir ]; then synced_folder=$(grep -x "^ $current_dir => .*$" ./synced_folders) if ! [ -n "$synced_folder" ]; then guest_dir="/host/${current_dir//[\/:\\]/_}" echo "syncing $current_dir as $guest_dir..." echo " $current_dir => $guest_dir" >> ./synced_folders # reload to make vagrant created the new folder vagrant reload else guest_dir=$(echo "$synced_folder" | sed -E "s/^ .* => (.*)$/\\1/") fi fi if ! [ -n "$*" ]; then export LC_INITIALDIR=" $guest_dir" vagrant ssh -- -o SendEnv=LC_INITIALDIR else vagrant ssh -c "cd $guest_dir && $*" fi exit $? fi echo "'$command' is not a golem command. See 'golem help'"
C++
UTF-8
422
2.703125
3
[]
no_license
#ifndef _RADSCORPION_H_ #define _RADSCORPION_H_ #include <iostream> #include <string> #include "Character.hpp" class RadScorpion : public Enemy { private: int _hp; std::string _type; public: RadScorpion(/* args */); RadScorpion(RadScorpion const &src); ~RadScorpion(); RadScorpion &operator=(RadScorpion const &rhs); virtual void takeDamage(int damage); }; #endif
Java
GB18030
870
2.15625
2
[]
no_license
package com.li.ssm_dwr01.entity; /** * Ϣ * @author * */ public class Message { //Ϣ private String msgText; // private String toUserId; //id private String fromUserId; // private String fromUserName; public String getMsgText() { return msgText; } public void setMsgText(String msgText) { this.msgText = msgText; } public String getToUserId() { return toUserId; } public void setToUserId(String toUserId) { this.toUserId = toUserId; } public String getFromUserId() { return fromUserId; } public void setFromUserId(String fromUserId) { this.fromUserId = fromUserId; } public String getFromUserName() { return fromUserName; } public void setFromUserName(String fromUserName) { this.fromUserName = fromUserName; } }
C
ISO-8859-1
6,958
3.421875
3
[]
no_license
//Projeto de c questo 11.15 do livro //Dupla: diomedes/ Moises #include <stdio.h> #include <stdlib.h> void exibe(void); //prototipo de func que exibe texo digitado void cria(FILE *); //prototipo de func que cria arquivo void adiciona(FILE *); //prototipo de func que adiciona dados no fim do arquivo void ler(void); //prototipo de func que ler arquivo void subistitui(FILE *); //prototipo de func que ler arquivo int main(){ char c; int i = 0, opcao = 0; FILE *cptr; do{ printf ("Escolha uma opcao:\n 1. Ler da entrada padrao e escrever na saida padrao;\n"); printf(" 2.criar um arquivo\n 3. Adicionar dados, em sequencia, no arquivo projeto\n 4. Ler o arquivo projeto\n" " 5. Substituir todo o conteudo do arquivo projeto\n 6. Sair.\n\n"); scanf("%d",&opcao); switch (opcao){ case 1: exibe(); //chama a funcao que le cada caracter e mostra tudo na tela. break; case 2: cria(cptr);//chama a funcao que cria o arquivo de nome projeto. break; case 3: adiciona(cptr); //chama a funcao que adiciona dados no final do arquivo de nome projeto. break; case 4: ler(); //chama a funcao que le o arquivo de nome projeto. break; case 5: subistitui(cptr); //chama a funcao que subistitui os dados do arquivo de nome projeto. break; case 6: printf("saindo\n\n"); break; default: puts("Opcao invalida:"); }//fecha switch printf("Digite 6. Para encerrar o programa\n 7. Para um novo acesso:\n\n"); scanf("%d",&opcao); }while(opcao != 6); system("pause"); return 0; } void exibe(FILE *fptr){ char c, sentence[80]; int i = 0; puts("Digite uma linha de texto:"); while (( c = getchar())!='\n') sentence[i++] = c; sentence[i] = '\0'; /* insere NULL no final da string */ puts("\nA linha digitada foi:"); retorn (sentence); /* char c; char nome[10000]; int conta; float saldo; int i; puts("Digite o texo apenas para exibicao na tela:"); scanf("%c",&c); while (( c = getchar())!='\n'){ if(c != '\n') nome[i++] = c; nome[i] = '\0';// insere NULL no final da string }//fecha o while scanf("%d%f",&conta,&saldo); puts("\nO texto digitado foi:"); printf("Nome: %s\n",nome); //imprime o texto digitado. printf("conta no: %d\nsaldo: %.2f",conta,saldo); printf("\n"); */ } //fim func exibe void cria(FILE *fptr){ struct dadosCliente { int numConta; char sobrenome[15]; char primNome[10]; float saldo; }; FILE *gravaPtr; struct dadosCliente cliente; char arquivo[50]; int conta; printf("informe o arquivo:\n"); scanf("%s",&arquivo); printf("informe a conta:\n"); scanf("%d",&conta); if ((gravaPtr = fopen(arquivo, "rb+")) == NULL) printf("Arquivo nao pode ser aberto.\n"); else { printf("Digite o numero da conta (1 a 10, 0 para encerrar dados)\n? "); scanf("%d", &cliente.numConta); while (cliente.numConta != 0) { printf("Digite sobrenome, primeiro nome e saldo\n? "); scanf("%s %s %f", &cliente.sobrenome, &cliente.primNome, &cliente.saldo); fseek(gravaPtr, (cliente.numConta - 1)*sizeof(struct dadosCliente), SEEK_SET); fwrite(&cliente,sizeof(struct dadosCliente), 1, gravaPtr); printf("Digite o numero da conta\n? "); scanf("%d", &cliente.numConta); } } fclose(gravaPtr); /* if ((gravaptr = fopen("projeto3.dat", "w")) == NULL) printf("Arquivo nao pode ser criado"); else{ puts("Digite o texo para criar o arquivo de nome projeto3:"); printf("?"); scanf("%s",&texto); while(!feof(stdin)){ fprintf(gravaptr, "%s\n",texto); scanf("%s",&texto); } fclose(gravaptr); } printf("\n\n"); */ }//fim func cria void adiciona(FILE *fptr){ char texto[10000]; FILE *adptr; if ((adptr = fopen("projeto3.dat", "a")) == NULL) printf("Arquivo nao pode ser aberto"); else{ puts("Digite o texo para adicionar ao arquivo de nome projeto3:" " em seguida entre com EOF (ctrl+z) para encerrar entradas de dados" ); scanf("%s",&texto); while(!feof(stdin)){ fprintf(adptr, "%s\n",texto); scanf("%s",&texto); } fclose(adptr); } printf("\n\n"); }//fim func adiciona void ler(void){ char texto[10000]; FILE *leptr; if ((leptr = fopen("projeto3.dat", "r")) == NULL) printf("Arquivo nao pode ser aberto"); else{ puts("Este eh o conteudo do arquivo projeto3:"); fscanf(leptr, "%s",&texto); while(!feof(leptr)){ printf("\n%p",ftell(leptr)); fprintf(leptr,"%s",texto); fscanf(leptr, "%s",&texto); } fclose(leptr); } printf("\n\n"); }//fim func ler void subistitui(FILE *fptr){ char texto[10000]; FILE *subptr; if ((subptr = fopen("projeto3.dat", "w")) == NULL) printf("Arquivo nao pode ser criado"); else{ puts("Digite o texo para subistituir os adados do arquivo de nome projeto3:" " em seguida entre com EOF (ctrl+z) para encerrar entradas de dados" ); printf("?"); fscanf(subptr,"%s",texto); while(!feof(stdin)){ fprintf(subptr, "%s\n",texto); //scanf("%s",&texto); fscanf(subptr,"%s",texto); } fclose(subptr); } printf("\n\n"); }//fim func subistitui
C
UTF-8
2,577
3.25
3
[]
no_license
#include "test_utils.h" #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> bool test_bool(bool cond, char *testname) { printf("TEST - %s : %s%s%s\n", testname, cond ? GREEN : RED, cond ? PASSED : FAILED, NOCOLOUR); return cond; } bool test_uint8(uint8_t expected, uint8_t got, char *testname) { bool passed = expected == got; printf("TEST - %s : %s%s%s\n", testname, passed ? GREEN : RED, passed ? PASSED : FAILED, NOCOLOUR); if (!passed) { printf("\texpected : %d (0x%02x)\n", expected, expected); printf("\tgot : %d (0x%02x)\n", got, got); } return passed; } bool test_uint16(uint16_t expected, uint16_t got, char *testname) { bool passed = expected == got; printf("TEST - %s : %s%s%s\n", testname, passed ? GREEN : RED, passed ? PASSED : FAILED, NOCOLOUR); if (!passed) { printf("\texpected : %d (0x%04x)\n", expected, expected); printf("\tgot : %d (0x%04x)\n", got, got); } return passed; } bool test_uint32(uint32_t expected, uint32_t got, char *testname) { bool passed = expected == got; printf("TEST - %s : %s%s%s\n", testname, passed ? GREEN : RED, passed ? PASSED : FAILED, NOCOLOUR); if (!passed) { printf("\texpected : %d (0x%08x)\n", expected, expected); printf("\tgot : %d (0x%08x)\n", got, got); } return passed; } bool test_string(char *expected, char *got, char *testname) { bool passed = expected == NULL ? got == NULL : strcmp(expected, got) == 0; printf("TEST - %s : %s%s%s\n", testname, passed ? GREEN : RED, passed ? PASSED : FAILED, NOCOLOUR); if (!passed) { printf("\texpected : %s\n", expected); printf("\tgot : %s\n", got); } return passed; } bool test_uint8_array(uint8_t *expected, uint8_t *got, size_t length, char *testname) { bool passed = true; for (int i = 0; i < length; i++) { passed = passed && (expected[i] == got[i]); } printf("TEST - %s : %s%s%s\n", testname, passed ? GREEN : RED, passed ? PASSED : FAILED, NOCOLOUR); if (!passed) { printf("\texpected : "); print_uint8_array(expected, length); printf("\n"); printf("\tgot : "); print_uint8_array(got, length); printf("\n"); } return passed; } void print_uint8_array(uint8_t *array, size_t length) { for (int i = 0; i < length; i++) { printf("%02x ", array[i]); } } void track_test(bool test, int *passing, int *total) { (*total)++; if (test) { (*passing)++; } }
Markdown
UTF-8
500
2.546875
3
[]
no_license
# Generics :pushpin: > :construction: **TODO:** > - Was sind Generics und wozu? We funktionieren sie? > - Information zur Laufzeit nicht vorhanden > - Implementation am Beispiel der verketteten Liste > - ... <!-- Dieses HTML-Snippet sollte am Ende jeder Seite stehen! --> <div class="top-link"> <a href="#" title="Zum Anfang scrollen!">Top :balloon:</a> <br/> <a href="https://dh-cologne.github.io/java-wegweiser#inhalt-book" title="Zurück zur Übersicht!">Inhalt :book:</a> </div>
Java
UTF-8
3,614
1.898438
2
[]
no_license
package com.sensebling.ope.core.service.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.sensebling.common.controller.HttpReqtRespContext; import com.sensebling.common.service.impl.BasicsSvcImpl; import com.sensebling.common.util.DateUtil; import com.sensebling.common.util.Pager; import com.sensebling.common.util.QueryParameter; import com.sensebling.common.util.Result; import com.sensebling.common.util.StringUtil; import com.sensebling.ope.core.entity.OpeCoreModel; import com.sensebling.ope.core.entity.OpeCoreProduct; import com.sensebling.ope.core.entity.OpeCoreProductModelLog; import com.sensebling.ope.core.service.OpeCoreModelSvc; import com.sensebling.ope.core.service.OpeCoreProductModelLogSvc; import com.sensebling.ope.core.service.OpeCoreProductSvc; @Service public class OpeCoreProductSvcImpl extends BasicsSvcImpl<OpeCoreProduct> implements OpeCoreProductSvc{ @Resource private OpeCoreModelSvc opeCoreModelSvc; @Resource private OpeCoreProductModelLogSvc opeCoreProductModelLogSvc; @Override public Pager getProductPager(QueryParameter qp) { StringBuffer sb = new StringBuffer("select * from (select a.*,b.code modelcode,b.name modelname from ope_core_product a left join ope_core_model b on b.id=a.modelid) where "); sb.append(qp.transformationCondition(null)+qp.getOrderStr(null)); return baseDao.querySQLPageEntity(sb.toString(), qp.getPager().getPageSize(), qp.getPager().getPageIndex(), OpeCoreProduct.class.getName()); } @Override public boolean checkCode(String code, String id) { String sql = "select 1 from ope_core_product where code=?"; List<Object> param = new ArrayList<Object>(); param.add(code); if(StringUtil.notBlank(id)) { sql += " and id!=?"; param.add(id); } List<OpeCoreProduct> list = baseDao.findBySQLEntity(sql, param, OpeCoreProduct.class.getName()); if(list==null || list.size()==0) { return true; } return false; } @Override public Result updateModel(String id, String modelid) { Result r = new Result(); OpeCoreProduct product = get(id); if(product != null) { OpeCoreModel model = opeCoreModelSvc.get(modelid); if(model != null) { if(modelid.equals(product.getModelid())) { r.success(); }else { if("1".equals(model.getStatus())) { String sql = "update ope_core_product set modelid=? where id=?"; baseDao.executeSQL(sql, modelid, id); OpeCoreProductModelLog log = new OpeCoreProductModelLog(); log.setAddtime(DateUtil.getStringDate()); log.setAdduser(HttpReqtRespContext.getUser().getId()); log.setModelid(modelid); log.setProductid(id); opeCoreProductModelLogSvc.save(log); r.success(); }else { r.setError("当前模型已禁用"); } } }else { r.setError("模型不存在"); } }else { r.setError("产品不存在"); } return r; } @Override public Result delProduct(String id) { Result r = new Result(); OpeCoreProduct product = get(id); if(product != null) { String sql = "select count(1) num from ope_apply_baseinfo a where a.productid=?"; List<Map<String,Object>> list = baseDao.queryBySql_listMap(sql, id); if(Integer.parseInt(list.get(0).get("NUM").toString()) == 0) { baseDao.executeSQL("delete from ope_core_product where id=?", id); baseDao.executeSQL("delete from ope_core_product_model_log where productid=?", id); r.success(); }else { r.setError("当前产品已被使用,不能删除"); } } return r; } }
Markdown
UTF-8
474
2.59375
3
[]
no_license
Postchi is a platform for admins of social media pages, news agencies, fanpages, etc. whom want to share their news and posts in all their accounts in social media (Twitter, Instagram, Telegram, their Wordpress website, etc.). But copying files and changing apps may be bothering. So what about using one place to write posts, adjust them to your social media limits, editing photos or videos and adding watermarks to them, and everything you want as an admin of a channel.
JavaScript
UTF-8
4,885
2.828125
3
[]
no_license
/* eslint-disable no-unused-expressions */ /* eslint-disable no-useless-constructor */ import React from 'react' import './Mainpage.css' class Mainpage extends React.Component { // Constructor, initialize state and bind functions constructor() { super(); this.state = { input : {}, errors: {} }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.validate = this.validate.bind(this); } //Setting path after clicking on login after validation nextPath(path) { this.props.history.push(path); } // Updating state on every change in input field handleChange(event){ let input = this.state.input; input[event.target.name] = event.target.value; this.setState({ input }); this.valid = this.validate(); } // Handling Submit and clearing error if validation is successful handleSubmit(event) { event.preventDefault(); if(this.validate){ let input = {}; input["email"]=""; input["password"]=""; this.setState({input:input}); } } // this function validate email and password and update state.error accordingly validate(){ let input = this.state.input; let errors = {}; let isValid = true; if(!input["email"]){ isValid = false; errors["email"] = "Please enter email address"; } if(typeof input["email"] !== "undefined") { var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); if (!pattern.test(input["email"])) { isValid = false; errors["email"] = "Please enter valid email address."; } } if(!input["password"]) { isValid = false; errors["password"] = "Please enter your password"; } if(typeof input["password"] !== "undefined"){ isValid = false; if( input["password"].length < 8 ){ errors["password"] = "Password must be at least 8 characters"; }else{ const re = new RegExp(/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/); const isOk = re.test(input["password"]); if(!isOk){ errors["password"] = "Password must contain a capital letter, a small letter, a special character and a number."; }else{ errors["password"] = ""; isValid = true; } } } this.setState({ errors : errors }) return isValid; } render(){ return ( <div className="Login container"> <div className='m-5'> <h1>ADCURATIO</h1> </div> <form onSubmit={this.handleSubmit}> <div className="form-group shadow p-5 login-form"> <h3 className="text-center mb-4">LOGIN</h3> <div className='mb-3'> <label className="form-label">E-mail</label> <input className="form-control" type="text" placeholder="Enter email" name="email" value={this.state.input.email} onChange={this.handleChange} id="email" autoFocus /> <div className='text-danger'>{this.state.errors.email}</div> </div> <div className='mb-3'> <label className="form-label">Password</label> <input className="form-control" type="password" placeholder="Password" name="password" value = {this.state.input.password} onChange={this.handleChange} /> <div className="text-danger">{this.state.errors.password}</div> </div> <div className='mb-3 mt-4'> <button type="submit" className="form-control btn btn-success" onClick={() => {if(this.valid)this.nextPath('/user')} } >Login</button> </div> </div> </form> <div className='float-right m-5'> <p className="font-italic" > - by Rishabh Gupta</p> </div> </div> ) } } export default Mainpage;
Python
UTF-8
4,253
2.8125
3
[]
no_license
"""First experiment. 1D data.""" # Guilhere Franca <guifranca@gmail.com> # Johns Hopkins University, Neurodata import numpy as np import multiprocessing as mp import energy.data as data import energy.eclust as eclust import energy.initialization as initialization import run_clustering import plot def sample_normal(m1, m2, s1, s2, n1, n2): return data.univariate_normal([m1, m2], [s1, s2], [n1, n2]) def sample_lognormal(m1, m2, s1, s2, n1, n2): return data.univariate_lognormal([m1, m2], [s1, s2], [n1, n2]) class Clustering1D: def __init__(self): # parameters for distributions self.m1 = 0 self.m2 = 5 self.s1 = 1 self.s2 = 2 self.distr = 'normal' # should be normal or lognormal self.numpoints = range(50, 100, 20) self.experiments = 100 # number of experiments (Markov samples) def get_sample(self, n): n1, n2 = np.random.multinomial(n, [0.5, 0.5]) if self.distr == 'normal': X, z = sample_normal(self.m1, self.m2, self.s1, self.s2, n1, n2) elif self.distr == 'lognormal': X, z = sample_lognormal(self.m1, self.m2, self.s1, self.s2, n1, n2) else: raise ValueError("Clustering 1D, unknown distribution to sample.") return X, z def run(self): k = 2 ncols = 3 + 1 # number of clustering methods + 1 table = np.zeros((self.experiments*len(self.numpoints), ncols)) count = 0 for i, n in enumerate(self.numpoints): for ne in range(self.experiments): X, z = self.get_sample(n) Y = np.array([[x] for x in X]) #G = eclust.kernel_matrix(Y, lambda x, y: np.linalg.norm(x-y)) table[count, 0] = n table[count, 1] = run_clustering.energy1D(X, z) table[count, 2] = run_clustering.kmeans(k, Y, z, run_times=5) table[count, 3] = run_clustering.gmm(k, Y, z, run_times=5) #table[count, 4] = run_clustering.energy_hartigan(k, X, G, z, # init="k-means++", run_times=3) #table[count, 4] = run_clustering.energy_hartigan(k, Y, G, z, # init="spectral") count += 1 return table ############################################################################### ## the functions below need to be customized according ## to the experiment def make_plot(*data_files): table = [] for f in data_files: t = np.loadtxt(f, delimiter=',') t[:,0] = np.array([int(D) for D in t[:,0]]) table.append(t) table = np.concatenate(table) ## customize plot below ## p = plot.ErrorBar() p.xlabel = r'$\#$ points' p.legends = [r'$\mathcal{E}^{1D}$-clustering', r'$k$-means', 'GMM'] p.colors = ['b', 'r', 'g'] p.lines = ['-', '-', '-'] #p.output = './experiments_figs/1D_normal.pdf' p.output = './experiments_figs/1D_lognormal.pdf' p.bayes = 0.88 p.xlim = [10,800] #p.loc = (0.55,0.45) p.make_plot(table) def gen_data(fname): ## choose the range for each worker ## n_array = [range(10,400,20), range(400,700,20), range(700,760,20), range(760,820,20)] jobs = [] for i, n in enumerate(n_array): p = mp.Process(target=worker, args=(n, fname%i)) jobs.append(p) p.start() def worker(numpoints, fname): """Used for multiprocessing. i is the index of the file, each process will generate its own output file. """ e = Clustering1D() ## Need to change these parameters below by hand according to ## the experiment e.m1 = 1.5 e.m2 = 0 e.s1 = 0.3 e.s2 = 1.5 #e.distr = 'normal' e.distr = 'lognormal' e.experiments = 100 e.numpoints = numpoints table = e.run() np.savetxt(fname, table, delimiter=',') ############################################################################### if __name__ == '__main__': #fname = './experiments_data/experiment_1D_normal_%i.csv' fname = './experiments_data/experiment_1D_lognormal_%i.csv' #gen_data(fname) make_plot(fname%0, fname%1, fname%2, fname%3)
Shell
UTF-8
4,440
3.15625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #* * #* This file is part of the program and library * #* SCIP --- Solving Constraint Integer Programs * #* * #* Copyright (c) 2002-2023 Zuse Institute Berlin (ZIB) * #* * #* 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. * #* * #* You should have received a copy of the Apache-2.0 license * #* along with SCIP; see the file LICENSE. If not visit scipopt.org. * #* * #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ### resets and fills a batch file TMPFILE to run CBC with ### sets correct limits, reads in settings, and controls ### display of the solving process # environment variables passed as arguments INSTANCE="${1}" # instance name to solve SCIPPATH="${2}" # - path to working directory for test (usually, the check subdirectory) TMPFILE="${3}" # - the batch file to control XPRESS SETNAME="${4}" # - specified basename of settings-file, or 'default' SETFILE="${5}" # - instance/settings specific set-file THREADS="${6}" # - the number of LP solver threads to use SETCUTOFF="${7}" # - should optimal instance value be used as objective limit (0 or 1)? FEASTOL="${8}" # - feasibility tolerance, or 'default' TIMELIMIT="${9}" # - time limit for the solver MEMLIMIT="${10}" # - memory limit for the solver NODELIMIT="${11}" # - node limit for the solver LPS="${12}" # - LP solver to use DISPFREQ="${13}" # - display frequency for chronological output table REOPT="${14}" # - true if we use reoptimization, i.e., using a difflist file instead if an instance file OPTCOMMAND="${15}" # - command that should per executed after reading the instance, e.g. optimize, presolve or count CLIENTTMPDIR="${16}" # - directory for temporary files SOLBASENAME="${17}" # - base name for solution file VISUALIZE="${18}" # - true, if the branch-and-bound search should be visualized SOLUFILE="${19}" # - solu file, only necessary if ${SETCUTOFF} is 1 EMPHBENCHMARK="${20}" # - use set emphasis benchmark # new environment variables after running this script # -None # updated environment variables after running this script # EXECNAME # init an empty list of command line settings to be used by gurobi_cl CLSETTINGSLIST="" #append feasibility tolerance in case of non-default values if test "${FEASTOL}" != "default" then CLSETTINGSLIST="${CLSETTINGSLIST} FeasibilityTol=${FEASTOL} IntFeasTol=${FEASTOL}" fi CLSETTINGSLIST="${CLSETTINGSLIST} TimeLimit=${TIMELIMIT} NodeLimit=${NODELIMIT} DisplayInterval=${DISPFREQ} MIPGap=0.0 Threads=${THREADS} Crossover=0 Method=2" # parse settings from settings file via awk if test "${SETNAME}" != "default" then echo $(pwd) CLSETTINGSLIST="$(awk 'BEGIN { finalstr=""} {finalstr=finalstr " "$1"="$2} END {print finalstr}' ${SETTINGS}) ${CLSETTINGSLIST}" fi #have a look if Gurobi is invoked with the settings you are asking for echo "Gurobi will be invoked with arguments: ${CLSETTINGSLIST}" EXECNAME="${EXECNAME} ${CLSETTINGSLIST} ${INSTANCE}"
Python
UTF-8
611
3.03125
3
[]
no_license
from abc import ABC, abstractmethod class Collector(ABC): """Abstract class for data collector.""" def __init__(self, es): self._es = es self._url = None self._index_name = None def collect(self): """Loads data, normalizes it and dumps.""" return self._dump(self._normalize(self._load())) @abstractmethod def _load(self): """Loads data from response.""" @abstractmethod def _normalize(self, loaded): """Normalizes loaded data.""" @abstractmethod def _dump(self, normalized): """Dumps data to elastic."""
Java
UTF-8
1,063
2.71875
3
[]
no_license
package View; import Model.PlayingField; import javafx.scene.image.Image; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.Pane; public class FieldView extends Pane { private GameObjectView objects; private PlayingField playingfield; private BackgroundImage background = new BackgroundImage(new Image("Media/72850_screenshots_2015-03-14_00017.jpg"), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); public FieldView(PlayingField playingfield) { this.playingfield = playingfield; objects = new GameObjectView(playingfield); setBackground(new Background(background)); setPrefSize(500, 500); getChildren().add(objects); } public void Draw() { // hier worden alle objecten getekend. if(!playingfield.objectsIsEmpty()) { objects.drawObjects(); } } }
Java
UTF-8
1,050
3.9375
4
[]
no_license
package Oops; // Realworld example class Account{ int acc_no; String name; float amount; void insert (int a, String n, float amt){ acc_no = a; name = n; amount = amt; } void deposit(float amt){ amount = amount + amt; System.out.println(amt+" deposited"); } void withdraw(float amt){ if(amount < amt){ System.out.println("Insufficient balance"); }else{ amount = amount - amt; System.out.println(amt+" withdrawn"); } } void checkBalance(){ System.out.println("Balance is: "+amount); } void display(){ System.out.println(acc_no + " " + name + " " + amount); } } public class TestAccount { public static void main(String args[]){ Account a1 = new Account(); a1.insert(123456, "Debesh Nayak", 75000); a1.display(); a1.checkBalance(); a1.deposit(4000); a1.checkBalance(); a1.withdraw(10000); a1.checkBalance(); } }
Markdown
UTF-8
16,377
2.53125
3
[ "MIT" ]
permissive
--- title: "ICLR 2020" permalink: /notes/iclr2020/ author_profile: true math: true --- ## [Variational Template Machine for Data-to-Text Generation](http://www.openreview.net/pdf?id=HkejNgBtPB) * A graphical model for generating text <span>$y$</span> from structured data <span>$x$</span> * Similar to a variational autoencoder, but adds latent variables that represent a template <span>$z$</span> and content <span>$c$</span> * Continuous latent variables generate diverse output * Reconstruction loss for output given data and template * Template preserving loss: template variable can reconstruct the text <figure> <img src="/assets/images/variational-template-machine.png" style="border-width: 15px 45px 15px 45px"> <figcaption> The graphical model of a Variational Template Machine. <a href="http://www.openreview.net/pdf?id=HkejNgBtPB">Ye et al.</a> </figcaption> </figure> ### [Variational Inference](https://fabiandablander.com/r/Variational-Inference.html) * Approximation for Bayesian inference with graphical models * Computing posterior probabilities is hard because of the integration required to compute the evidence probability * Approximates the posterior distribution using a variational posterior from a family of distributions * Computing the KL divergence between the approximate and exact posterior would be equally hard, since it depends on the evidence probability * Minimizing KL divergence is equal to minimizing the negative evidence lower bound (ELBO) * ELBO is log evidence subtracted from the KL divergence * The optimization problem is not as hard as integration ## [Meta-Learning with Warped Gradient Descent](http://www.openreview.net/pdf?id=rkeiQlBFPB) * Model consists of task layers and warp layers * Task layers are updated using a normal loss * Meta-learn warp-layers that modify the loss surface to be smoother * Novelty: non-linear warp layers avoid dependence on the trajectory or the initialization, depending only on the task parameter updates at the current position of the search space ### Meta-Learning * Learning some parameters of the optimizer such as initialization * Optimize for the final model accuracy as a function of the initialization * When using gradient descent, the objective is differentiable * Backpropagate through all training steps back into the initialization * Vanishing / exploding gradients when the loss surface is very flat or steep * Costly—usually scales to a handful of training steps only ## [Transformer-XH](http://www.openreview.net/pdf?id=r1eIiCNYwS) * Adaptation of Transformer for structured text * For example, multi-evidence reasoning: answer questions, following words that are linked to Wikipedia * Extra hop attention attends to the first token of another sequence (representative of the entire sequence) ## [Deep Double Descent](http://www.openreview.net/pdf?id=B1g5sA4twr) * Bigger model means lower training loss * At some point test error starts to increase, but with large enough models decreases again * Occurs across various architectures (CNNs, ResNets, Transformers), data domains (NLP, vision), and optimizer (SGD, Adam) * Also occurs when increasing training time * In some cases increasing training data can hurt performance * Effective model complexity takes training time into account ## [Towards Stabilizing Batch Statistics in Backward Propagation of Batch Normalization](http://www.openreview.net/pdf?id=SkgGjRVKDS) * Unstable mean and variance estimation with too small batch sizes * Batch renormalization (BRN): corrects batch mean and variance by moving average * Moving average batch normalization: moving average of variance mean reduction + weight centralization ## [Compressive Transformer for Long-Range Sequence Modelling](https://openreview.net/pdf?id=SylKikSYDH) * Train a language model on segments similar to Transformer-XL * When moving to the next segment, the oldest N activations in the memory are compressed using a compressing function ### Related Work * Lightweight and Dynamic Convolution: depth-wise separable convolution that runs in linear time * Transformer-XL: train a language model on segments, but include activations from the previous segment in “extended context” * Sparse Transformer: sparse attention masks * Adaptive Attention Span: different attention heads can have longer or shorter spans of attention ## [A Closer Look at Deep Policy Gradients](https://openreview.net/pdf?id=ryxdEkHtPS) * Policy gradient methods: optimize policy parameters to maximize the expected reward * Variance reduction using baseline—separate the quality of the action from the quality of the state * A canonical choice of baseline function is the value function * Surrogate objective is a simplification of reward maximization used by modern policy gradient algorithms (policy is divided by the old policy, [Schulman et al. 2015](https://arxiv.org/abs/1502.05477)) * Measure of gradient variance: mean pairwise correlation (similarity) between gradient samples * Visualization of optimization landscapes with different number of samples per estimate ## [Laurent Dinh: Invertible Models and Normalizing Flows](https://iclr.cc/virtual_2020/speaker_4.html) * A model finds a representation <span>$h = f(x)$</span> of a datapoint <span>$x$</span> (in practice, an image) * Generative models (VAE, GAN) can produce an image <span>$x$</span> from its representation <span>$h$</span> * GANs cannot encode images into the latent space * VAEs support only approximate inference of latent variables from an image * *Normalizing flow* is a sequence of invertible transformations * Reversible generative models can encode an image into a latent space, making it possible to interpolate between two images ### [NICE](https://arxiv.org/pdf/1410.8516.pdf) * Finds a representation such that <span>$p(h)$</span> factorizes as <span>$\prod p(h_d)$</span>, where <span>$h_d$</span> are independent latent variables (arguably a “good” representation) * Prior distribution <span>$p(h_d)$</span> is Gaussian or logistic * Training: maximize the likelihood of the data using a “change of variables” formula * <span>$f(x)$</span> has to be invertible—achieved by splitting <span>$x$</span> into <span>$x_1$</span> and <span>$x_2$</span> and using a transformation that transforms them into <span>$x_1$</span> and <span>$x_2 + m(x_1)$</span> respectively * Sampling images: sample from <span>$p(h)$</span> and use the inverse of <span>$f(x)$</span> ## [A Probabilistic Formulation of Unsupervised Text Style Transfer](http://www.openreview.net/pdf?id=HJlA0C4tPS) * Change text style, keeping the semantic meaning unchanged * Machine translation, sentiment transfer (positive ↔ negative) * Unsupervised (only a nonparallel corpus) * Previous work on text style transfer: autoencoding loss + adversarial loss using a language model as a discriminator * Previous work on machine translation: cycle structures for unsupervised machine translation * Novelty: probabilistic formulation of the above heuristic training strategies * Translations of language A are “latent sequences” of language B and vice versa * We want to utilize a language model prior within each language * Train using variational inference <figure> <img src="/assets/images/unsupervised-text-style-transfer.png"> <figcaption> A graphical model for text style transfer. <a href="http://www.openreview.net/pdf?id=HJlA0C4tPS">He et al.</a> </figcaption> </figure> ## [Estimating Gradients for Discrete Random Variables by Sampling without Replacement](http://www.openreview.net/pdf?id=rklEj2EFvB) * Strategies for obtaining gradients for discrete outputs: smoothening the outputs (relaxation), or sampling (REINFORCE) * REINFORCE: move the gradient inside the expectation and estimate it using a sample * With multiple samples one can use the average as a baseline * Sampling without replacement can be done efficiently by taking the top <span>$k$</span> of Gumbel variables * Probability for sampling an unordered sample can be calculated as a sum over all possible permutations * The estimator is changed to work with an unordered set ## [Reformer](http://www.openreview.net/pdf?id=rkgNKkHtvB) * Memory efficiency: reversible residual layers, chunked FF and attention layers * Time complexity: attention within buckets created using locality sensitive hashing ## [A Theoretical Analysis of the Number of Shots in Few-Shot Learning](http://www.openreview.net/pdf?id=HkgB2TNYPS) * Prototypical networks cannot handle different numbers of shots between classes * Performance drops when there’s a mismatch in the number of shots between meta-training and testing * Trade-off between minimizing intra-class variance and maximizing inter-class variance is different when clustering a different number of embeddings * Proposes an embedding space transformation ### [Prototypical Networks](https://arxiv.org/abs/1703.05175) * Aggregate experiences from learning other tasks to learn a few-shot task * Form prototypes of each class as the average embedding of the labeled “support” examples * Class likelihoods from the distances from the embedding of the current example to the prototypes <figure> <img src="/assets/images/prototypical-networks.png"> <figcaption> Prototypical networks in the few-shot (left) and zero-shot (right) scenarios. <a href="https://arxiv.org/abs/1703.05175">Snell et al.</a> </figcaption> </figure> ## [Mixed Precision DNNs](http://www.openreview.net/pdf?id=Hyx0slrFvH) * Fixed-point representation for the weights and activations, with a different bitwidth for each layer * A quantizer DNN is learned using gradient-based methods * Which parameters (bitwidth, step size, minimum value, maximum value) to use for parameterization of uniform and power-of-two quantizations? * The gradients with regard to the quantizer parameters are bounded and decoupled when choosing step size and maximum value, or minimum value and maximum value * How to learn the parameters? * A penalty term is added to the loss to enforce size constraints for the weights and activations ## [Training Binary Neural Networks with Real-to-Binary Convolutions](http://www.openreview.net/pdf?id=BJg4NgBKvH) * Binary convolution can be implemented using fast xnor and pop-count operations * Per-channel scaling is used to produce real-valued outputs * Teacher-student with a real-valued teacher ## [On Mutual Information Maximization for Representation Learning](http://www.openreview.net/pdf?id=rkxoh24FPH) * Unsupervised learning based on information theoretic concepts * InfoMax principle: a good representation should have high mutual information with the input * MMI alone is not sufficient for representation learning, but modern methods work well in practice * Multi-view approach: maximize mutual information between different views of the same input * For example: split an image in half, encode both parts independently, and compare the mutual information between the parts * If the representation encodes high-level features of the image, mutual information will be high; if it encodes noise, mutual information will be low ## [A Mutual Information Maximization Perspective of Language Representation Learning](http://www.openreview.net/pdf?id=Syx79eBKwr) * Many language tasks can be formulated as maximizing an objective function that is a lower bound on mutual information between different parts of the text sequence * BERT (masked LM): word and corrupted word context, or sentence and following sentence * Skip-gram (word2vec): word and word context * InfoWorld (proposed by the authors): sentence and n-gram, both encoded using Transformer ### [Mutual Information Neural Estimation](https://arxiv.org/abs/1801.04062) * Mutual information: the amount the uncertainty about <span>$X$</span> is reduced by knowing the value of <span>$Z$</span> * Maximizing mutual information directly is infeasible * The mutual information between <span>$X$</span> and <span>$Z$</span> can be expressed as the KL divergence between the joint probability distribution and the product of the marginal distributions: <span>$I(X;Z) = D_{KL}(P_{XZ} \parallel P_X P_Z)$</span> * <span>$E_P[f(x)] - \log E_Q[e^{f(x)}]$</span>, where <span>$f(x)$</span> is any real-valued function for which the expectations are finite, is always less than or equal to the KL divergence between <span>$P$</span> and <span>$Q$</span> * Donsker-Varadhan representation for KL divergence: supremum of this lower bound is equal to the KL divergence * In theory, any function can be represented with a neural network ⇒ we can train a neural network <span>$f(x)$</span> to maximize the lower bound ### [InfoNCE](https://arxiv.org/abs/1807.03748) * Maximize mutual information between target <span>$x$</span> and context <span>$c$</span> * One positive sample from <span>$p(x \mid c)$</span> and <span>$N-1$</span> negative samples from <span>$p(x)$</span> * Loss based on noise contrastive estimation ## [ALBERT](https://openreview.net/pdf?id=H1eA7AEtvS) * Small “sandwich” layer reduce the number of embedding parameters * By default shares all parameters between layers * Additional next-sentence prediction loss * Dropout removed * More data ## [Incorporating BERT into Neural Machine Translation](http://www.openreview.net/pdf?id=Hyl7ygStwB) * Initialize weights of NMT encoder from BERT (degradation) * Initialize encoder and decoder weights with cross-lingual BERT trained on a multilingual corpus (small improvement) * Create embeddings using BERT (significant improvement) * BERT-fused NMT: additional attention to BERT (whose parameters are fixed) in each layer * Drop-net trick: with certain probability perform a regularization step—use only BERT-encoder attention or self-attention * SOTA results in semi-supervised NMT ## [Mixout](http://www.openreview.net/pdf?id=HkgaETNtDB) * Weight decay towards previous model parameters prevents catastrophic forgetting on the pretrained task * Mixout sets parameters from a randomly selected neuron to those of the pretrained model during fine-tuning * Corresponds to adaptive weight decay towards the pretrained model ## [Network Deconvolution](http://www.openreview.net/pdf?id=rkeu30EtvS) * There is a lot of correlation between nearby pixels, even when an image is not blurred * Correlation in data causes gradient descent to take more steps * Correlation between dimensions can be removed with a coordinate transform * Calculate the correlation at every layer and apply inverse filtering * Results in a sparse representation ## [A Signal Propagation Perspective for Pruning Neural Networks at Initialization](http://www.openreview.net/pdf?id=HJeTo2VFwH) * By repeatedly training and pruning connections, model size can be reduced * Even randomly initialized networks can be pruned prior to training, based on connection sensitivity * It is unclear why pruning the initialization is effective * Scaling of the initialization can have a critical impact ## [Monotonic Multihead Attention](http://www.openreview.net/pdf?id=Hyg96gBKPS) * Simultaneous translation: start translating before reading the full input * Monotonic attention: stepwise probability for decision whether to read a source token or write a target token * State of the art: [Monotonic Infinite Loopback Attention](https://www.aclweb.org/anthology/P19-1126/) (based on LSTM) * Novelty: Transformer with multihead monotonic attention * Independent stepwise probabilities for different heads * A source token is read if the fastest head decides to read * A target token is written if all the heads finish reading * Implemented in [Fairseq](https://github.com/pytorch/fairseq/blob/master/examples/simultaneous_translation/README.md) ## [Revisiting Self-Training for Neural Sequence Generation](http://www.openreview.net/pdf?id=SJgdnAVKDH) * Self-training: train a teacher model using labeled data and a student model using the predictions of the teacher on unlabeled data * Fine-tune the student model on the labeled data * Helps on machine translation (100k parallel, 3.8M monolingual samples) * Beam search, when decoding the unlabeled data, contributes a bit to the gain (compared to sampling from the teacher's output distribution) * Dropout, while training on the pseudo-data, accounts for most of the gain
Markdown
UTF-8
2,554
2.765625
3
[ "MIT" ]
permissive
# 5. Creating modules UNDER DEVELOPMENT! ### What you will learn ```@contents Pages = ["chapter5.md"] ``` With modules we can build applications. A [module](https://docs.julialang.org/en/v1/manual/modules/index.html) is a demarcated unit, with its own namespace. You create a module with the package manages command `generate`, as we did during step 5 in the activity of the [previous chapter](https://www.appligate.nl/BAWJ/chapter4/#Create-the-base-folder-AppliInvoicing-1). The command created tho next: - Project.toml - src/AppliInvoicing.jl ## AppliAR.jl ``` module AppliAR #1 greet() = print("Hello World!") #2 export create, process, retrieve_unpaid_invoices, read_bank_statements \#3 include("./infrastructure/infrastructure.jl") #4 end # module ``` \#1 The module block with its name. \#2 Initial the only statements, can be removed. \#3 The functions that other programs can use. \#4 The path to our model. ## Exports Exports are the interface to the module. Here you mention the function from the API and infrastructure layers. I don't export elements from the domain; one can use the import statement when a reference is necessary. ## Dependencies The file Project.toml contains the base information of the module and the dependencies. ``` name = "AppliInvoicing" uuid = "3941c6da-33b5-11ea-2884-afa98fed5e3b" authors = ["Rob Bontekoe <rbontekoe@appligate.nl>"] version = "0.2.0" [deps] AppliGeneralLedger = "153ef306-36d1-11ea-1f0d-e3f38f84e10d" AppliSales = "a1ddd20a-2e39-11ea-38f9-6b919ef027c3" CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" SQLite = "0aa819cd-b072-5ff4-a722-6bc24af294d9" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" ``` Initial is the section [deps] empty. Dependencies are automatically if you [activate](https://www.simonwenkel.com/2018/10/06/a-brief-introduction-to-package-management-with-julia.html) the project mode with: `] activate ./` and add a package. Use `update` in this mode to receive the latest package versions. Use `remove` to delete a package from the list. Use `gc` to remove unnecessary stuff. ## GitHub In [chapter 4](https://www.appligate.nl/BAWJ/chapter4/#Create-a-repository-on-GitHub-1) you learned how to create a Julia package at GitHub. ## Download a package To add a package that is not registered at Julialang, you use command `add` followed by the (git) package name , e.g. `add https://github.com/rbontekoe/AppliGeneralLedger.jl`.
Markdown
UTF-8
1,057
3.203125
3
[]
no_license
# Movies search app This is the final project of GeekHubs Academy Bootcamp. It's an app that provides a list of popular, top-rated and upcoming films, and allows users to search for movies and save them in a list. ## Technologies - ReactJS - SCSS - Redux Toolkit - npm - Axios / Custom API ## Description ![](src/media/animation.gif) This app has the following functionalities: 1. Display popular, top-rated and upcoming movies in separate carousels 2. Search for movies by names 3. Add movies to list and remove them When the app loads it sends the ajax request to [The Movie Database](https://www.themoviedb.org/) and so that the above mentioned carousels render. When user types in in the search bar the app sends request on each new entry. ## Problems that I faced during the development When I implemented the redux I discoved that the lists of carousels were the same. In order to fix this bug, I had to restructure Home and MoviesCarousel components, as well as refactoring the function that was sending the ajax request to the api.
C
UTF-8
2,486
3.984375
4
[]
no_license
// includes #include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> #include <stdlib.h> // funcs declaration char letter_shifting(int key, char c, bool uppercase); // main func int main(int argc, string argv[]) { // Checks if there are only two inputs (including filename) if (argc != 2) { // Prints error message if argc is not 2 printf("Usage: %s key\n", argv[0]); return 1; } // Checks if argument is purely digits int checker = 0; for (int i = 0, arg_len = strlen(argv[1]); i < arg_len; i++) { // isdigit returns integers > 0 for digits if (isdigit(argv[1][i]) == 0) { checker++; break; } } if (checker != 0) { printf("Usage: %s key\n", argv[0]); return 1; } else { // Converts string to int int key = atoi(argv[1]); // Prompts user for plaintext string plaintext = get_string("plaintext: "); // Prints ciphertext printf("ciphertext: "); for (int i = 0, text_len = strlen(plaintext); i < text_len; i++) { // Checks if char is lowercase if (islower(plaintext[i]) != 0) { printf("%c", letter_shifting(key, plaintext[i], 0)); } // Checks if char is uppercase else if (isupper(plaintext[i]) != 0) { printf("%c", letter_shifting(key, plaintext[i], 1)); } // Else prints the char itself else { printf("%c", plaintext[i]); } } printf("\n"); } } char letter_shifting(int key, char c, bool uppercase) { // Initiate int variables int shifted, uppernum = 65, lowernum = 97; if (uppercase == 1) { // Shifts uppercase char to 0 shifted = c - uppernum; // Add key and reduce mod 26 shifted = (shifted + key) % 26; // Shifts char back to 65 shifted += uppernum; return shifted; } else if (uppercase == 0) { // Shifts lowercase char to 0 shifted = c - lowernum; // Add key and reduce mod 26 shifted = (shifted + key) % 26; // Shifts char back to 97 shifted += lowernum; return shifted; } else { // Throw an error and exits program printf("Error!"); return 1; } }
JavaScript
UTF-8
951
3.765625
4
[]
no_license
/** * */ // 01_function.js function add(a,b){ return a+b; } console.log('2+3=' + add(2,3)); console.log('java + script =' + add('java', 'script')); console.log(add()); console.log(add(2)); console.log(add(2, 3)); console.log(add(2, 3, 4, 5)); // sumAll() function sumAll(){ var sum =0; for(var i in arguments){ // var i=0;i<arguments.length;i++ sum += arguments[i]; } return sum; } console.log(sumAll(1,2,3,4,5)); // 06_arguments2.js function total(){ var s =0; if(typeof(arguments[0]) == 'string'){ s = ""; } for(var i =0;i<arguments.length;i++){ s += arguments[i]; } return s; } console.log(total(1,2,3)); console.log(total('니들이', '게맛을', '알어?')); // 07_callby.js function byvalue(a){ a = 9999; } function byref(a){ a[0] = 9999; } var int = 1000; var ar = [1000, 2000, 3000]; byvalue(int); console.log('int='+int+', ar[0] = ' + ar[0]); byref(ar); console.log('int='+int+', ar[0] = ' + ar[0]);
Python
UTF-8
384
3.015625
3
[ "MIT" ]
permissive
def train_test_split(X, train_size=0.7, val_size=0.3): n = len(X) if train_size + val_size > 1.0: raise ValueError('train_size + val_size must be smaller than 1.0') train_df = X[0: int(n * train_size)] val_df = X[int(n * train_size): int(n * (train_size + val_size))] test_df = X[int(n * (train_size + val_size)):] return train_df, val_df, test_df
C
UTF-8
2,831
3.359375
3
[]
no_license
#include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> long double c_conv(int in_channel, long int o_channel, int kernel_size, int stride); int main() { int in_channel = 3; int o_channel = 1; int kernel_size = 3; int stride = 1; clock_t start; clock_t end; long double operations = 0.0; for(int i = 0; i < 11; i++){ o_channel = pow(2,i); start = clock(); operations = c_conv(in_channel, o_channel, kernel_size, stride); end = clock(); printf("i = %d, o_channel = %d, number_of_operations = %Lf, computation_time = %lf \n", i, o_channel, operations, (double)(end - start) / CLOCKS_PER_SEC); } return 0; } long double c_conv(int in_channel, long int o_channel, int kernel_size, int stride){ //file handle FILE *myFile; myFile = fopen("testimage1.txt", "r"); //filesize int m = 720+2; int n = 1280+2; //create image array with padding margins float **img_padded = (float**)malloc(m*sizeof(float*)); for (int i = 0; i < m; i++) img_padded[i] = (float*)malloc(n*sizeof(float)); //read txt into img_padded for(int i = 0; i < m; i++){ for(int j = 0; j < n ; j++){ fscanf(myFile, "%f", &img_padded[i][j] ); } } fclose(myFile); //create output image array float ***img_output = (float***)malloc(o_channel*sizeof(float**)); for (int i = 0; i < o_channel; i++) img_output[i] = (float**)malloc((m-2)*sizeof(float*)); for (int i = 0; i < o_channel; i++) for (int j = 0; j < (m-2); j++) img_output[i][j] = (float*)malloc((n-2)*sizeof(float)); //generate kernel array float ***kernelArr = (float***)malloc(o_channel*sizeof(float**)); for (int i = 0; i < o_channel; i++) kernelArr[i] = (float**)malloc(kernel_size*sizeof(float*)); for (int i = 0; i < o_channel; i++) for (int j = 0; j < kernel_size; j++) kernelArr[i][j] = (float*)malloc(kernel_size*sizeof(float)); //generate random kernel value for convolution for(int i = 0; i < o_channel; i++) for(int j = 0; j < kernel_size; j++) for(int k = 0; k < kernel_size; k++){ kernelArr[i][j][k] = (float)(rand()%20-10.0)/10.0; } long double operation_count = 0; for(int i = 1; i < m-1; i++){ for(int j = 1; j < n-1; j++){ //(i,j) pixel in the source image for(int q = 0; q < o_channel; q++){ // use kernelArr[q] for convolution float** kernel = kernelArr[q]; float tmpSum = 0.0; //loop the 3*3 window for(int k = 0; k < kernel_size; k++){ for(int p =0; p < kernel_size; p++){ tmpSum = tmpSum + kernel[k][p] * img_padded[i-1+k][j-1+p]; operation_count = operation_count + 2; } } operation_count-- ; img_output[q][i-1][j-1] = tmpSum; } } } return operation_count; }
PHP
UTF-8
8,556
2.921875
3
[]
no_license
<?php //========================== //CUSTOMIZING THE REST API / CREATING OUR OWN CUSTOM URL ROUTES to have more control //CREATING CUSTOM REST API " READ " ENDPOINT //========================= add_action('rest_api_init', 'universityRegisterSearch'); //To register a new custom Rest API route function universityRegisterSearch() { //1st argument = namespace [the "wp" in -> /wp-json/wp/v2/posts)] v2 is also part of the namespace, the version of our api route //2nd argument = route [the "posts"] //3rd argument = array that describes how we want to manage this field register_rest_route('university/v1', 'search', array( //university/v1/search/... 'methods' => WP_REST_SERVER::READABLE, //means = 'GET', but just in case if some web hosts don't know what GET is 'callback' => 'universitySearchResults' //calls this function, and passes along $data about the current request that someone is sending /* callback is just a function that we want to run when a request is sent to one of these routes */ )); } //To create our own custom JSON function universitySearchResults($data) { //WP automatically converts PHP into JSON data!!!! (don't need to write JSON syntax) //Main query to REST API custom URL $mainQuery = new WP_Query(array( 'post_type' => array('post', 'page', 'program', 'professor', 'event', 'institution'), 's' => sanitize_text_field($data['term']) //s = search |$data = array that WordPress puts together and within this is the term someone searched for )); // return $professors->posts; //LOOPS through the professor object and posts array automatically (and outputs 10 by default) //Since we don't use 90% of the JSON data we get back, we are populating the JSON with only the data we want !! //POPULATING this array with certain post types $results = array( 'generalInfo' => array(), 'professors' => array(), 'programs' => array(), 'events' => array(), 'institutions' => array() ); //CREATING CUSTOM JSON - Main query for all data - NO RELATIONSHIPS YET (Look next fx) //CLASSIC WORDPRESS LOOP (while) while($mainQuery->have_posts()) { //Loop length = number of professors $mainQuery->the_post(); if (get_post_type() == 'post' OR get_post_type() == 'page') { array_push($results['generalInfo'], array( //Output the combined array of objects in JSON 'postType' => get_post_type(), 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'author' => get_the_author(), )); } if (get_post_type() == 'professor') { array_push($results['professors'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'image' => get_the_post_thumbnail_url(0, 'professorLandscape') )); } if (get_post_type() == 'program') { //IF SEARCHING FOR PROGRAM, ADD RELATIONSHIP WITH INSTITUTIONS $relatedInstitutions = get_field('related_institution'); if ($relatedInstitutions) { foreach ($relatedInstitutions as $institution) { array_push($results['institutions'], array( 'title' => get_the_title($institution), 'permalink' => get_the_permalink($institution) )); } } array_push($results['programs'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'id' => get_the_ID() )); } if (get_post_type() == 'event') { $eventDate = new DateTime(get_field('event_date')); //Creating new object that uses DateTime class as a blueprint $description = null; if (has_excerpt()) { //If the post has handmade custom excerpt $description = get_the_excerpt(); //Display it } else { $description = wp_trim_words(get_the_content(), 18); //first 18 words } array_push($results['events'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'month' => $eventDate->format('M'), 'day' => $eventDate->format('d'), 'description' => $description )); } if (get_post_type() == 'institution') { array_push($results['institutions'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink() )); } } //CUSTOM QUERY - If there are any PROFESSORS that are related to PROGRAMS (search for programs) if ($results['programs']) { //CREATING array to pass it to $programRelationshipQuery $programsMetaQuery = array('relation' => 'OR'); foreach($results['programs'] as $item) { array_push($programsMetaQuery, array( 'key' => 'related_programs', 'compare' => 'LIKE', 'value' => '"' . $item['id'] . '"' )); } //Custom Query for the relationships between post types [Programs and professors, Programs and events] $programRelationshipQuery = new WP_Query(array( 'post_type' => array('professor', 'event'), 'meta_query' => $programsMetaQuery /* array( BETTER CODE ABOVE (SO WE CAN HAVE AS MANY RELATED PROGRAMS AS NEEDED) 'relation' => 'OR', //by default, WP wants to consider all of the arrays, so we set relation to OR array( 'key' => 'related_programs', 'compare' => 'LIKE', 'value' => '"' . $results['programs'][0]['id'] . '"' ) ) */ )); while ($programRelationshipQuery->have_posts()) { $programRelationshipQuery->the_post(); if (get_post_type() == 'event') { $eventDate = new DateTime(get_field('event_date')); //Creating new object that uses DateTime class as a blueprint $description = null; if (has_excerpt()) { //If the post has handmade custom excerpt $description = get_the_excerpt(); //Display it } else { $description = wp_trim_words(get_the_content(), 18); //first 18 words } array_push($results['events'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'month' => $eventDate->format('M'), 'day' => $eventDate->format('d'), 'description' => $description )); } if (get_post_type() == 'professor') { array_push($results['professors'], array( //Output the combined array of objects in JSON 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'image' => get_the_post_thumbnail_url(0, 'professorLandscape') //0 = default thumbnail )); } } $results['professors'] = array_values(array_unique($results['professors'], SORT_REGULAR)); //REMOVING DUPLICATE SEARCH RESULTS (cause both main query and relationship query can output professors) (array_values removes the indexes array_unique creates in JSON) $results['events'] = array_values(array_unique($results['events'], SORT_REGULAR)); } return $results; //Return the associative array with JSON data } ?>
Markdown
UTF-8
1,195
2.640625
3
[]
no_license
# Week 3: Tuesday ### Challenges ##### Core Challenges - [Student Roster DB from Schema](https://github.com/mantises-2014/student-roster-db-from-schema-challenge) - [University DB Schema](https://github.com/mantises-2014/university-course-database-design-challenge) - [Address Book DB from Schema](https://github.com/mantises-2014/address-book-db-from-schema-challenge) ##### Stretch Challenges - [Many to Many Schema to Database](https://github.com/mantises-2014/many-to-many-schema-to-database-challenge) - [Congress Database 1](https://github.com/mantises-2014/congress-database-1-from-csv-to-sqlite-with-ruby-challenge) - [Congress Database 2](https://github.com/mantises-2014/congress-database-2-scrub-and-analyze-with-ruby-challenge) - [Family Tree Database Design](https://github.com/mantises-2014/family-tree-database-design-challenge) ### Lecture Topics - no lectures schedules ### Additonal Resources - [Executing SQL using Ruby example](https://gist.github.com/alycit/340e49a09146231abca5) - [Ruby and SQLite demystified](https://gist.github.com/brickthorn/feefe99fc571324368aa) - [Wikipedia on Object-relational mapping](http://en.wikipedia.org/wiki/Object-relational_mapping)
JavaScript
UTF-8
884
2.5625
3
[ "Apache-2.0" ]
permissive
var strategoCols = [0,1,2,3,4,5,6,7,8,9] var strategoRows = [0,1,2,3,4,5,6,7,8,9] $(document).ready(function () { var strategoGame = new Vue({ el:'#stratego-game' }) }) Vue.component('stratego-field', { template:` <div class="gameboard__container" id="board"> <table> <tr v-for="r in rows"> <td class="cell" v-for="c in cols" v-bind:id="'row' + r + 'col' + c"><span><img v-bind:class="'piece ' + 'row' + r + 'col' + c" alt="" src="" /></span></td> </tr> </table> </div> `, data: function () { return { cols: strategoCols, rows: strategoRows } }, }); Vue.component('stratego-info', { template:` <div class="info__container"> <p class="info__turn" id="infoPlayer"></p> </div> `, });
Markdown
UTF-8
1,118
2.875
3
[ "MIT" ]
permissive
# Ropa de Piedra ## Paquete ```zenscript import mods.terrafirmacraft.StoneKnapping;PiedraKnapping; ``` ## Adicional ```zenscript StoneKnapping.addRecipe(String registryName, IItemStack[] salida, String[] rocks, String... patrón) ``` ## Eliminar ```zenscript StoneKnapping.removeRecipe(ItemStack output); StoneKnapping.removeRecipe(String registryName); ``` ## Ejemplos ```zenscript // Da una azadada de piedra en todas las rocas". StoneKnapping.addRecipe("testrecipe", [<minecraft:stone_hoe>], ["all"], " ", "XXXX "); // Otorga una azada de piedra sólo en esquisto, arcilla, sal, caliza. StoneKnapping.addRecipe("testrecipe2", [<minecraft:stone_hoe>], ["shale", "claystone", "rocksalt", "caliza"], " ", "XXXX "); // Otorga una azada de piedra en piedra arcillada, y un pico en piedra caliza. StoneKnapping.addRecipe("testrecipe3", [<minecraft:stone_hoe>, <minecraft:stone_pickaxe>], ["claystone", "limestone"], " ", "XXXX "); // Otorga una azada de piedra sólo en basalto y cerveza. StoneKnapping.addRecipe("testrecipe4", [<minecraft:stone_hoe>, <minecraft:stone_hoe>], ["basalt", "chert"], " ", "XXX "); ```
Java
UTF-8
1,777
1.640625
2
[]
no_license
package com.tencent.mm.plugin.radar.ui; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import b.i; import com.tencent.mm.plugin.radar.b.e$e; import com.tencent.mm.plugin.radar.ui.RadarViewController.c; import java.util.LinkedList; final class RadarViewController$f implements OnClickListener { final /* synthetic */ RadarViewController mmN; RadarViewController$f(RadarViewController radarViewController) { this.mmN = radarViewController; } public final void onClick(View view) { if (this.mmN.getRadarStatus() == e$e.SEARCHING || this.mmN.getRadarStatus() == e$e.SEARCH_RETRUN) { Context context = this.mmN.getContext(); if (context == null) { throw new i("null cannot be cast to non-null type android.app.Activity"); } ((Activity) context).finish(); return; } RadarViewController radarViewController = this.mmN; c d = RadarViewController.d(this.mmN); LinkedList linkedList = new LinkedList(); int length = ((Object[]) d.mmP).length; for (int i = 0; i < length; i++) { Object obj = d.mmP[i]; if (obj != null) { linkedList.add(obj); } } if (RadarViewController.a(radarViewController, linkedList)) { RadarViewController.f(this.mmN).bpO(); RadarViewController.f(this.mmN).setVisibility(0); RadarViewController.c(this.mmN).bps(); RadarViewController.a(this.mmN, e$e.SEARCH_RETRUN); } else { RadarViewController.a(this.mmN, e$e.SEARCHING); } RadarViewController.d(this.mmN).bpx(); } }
Python
UTF-8
1,160
3.1875
3
[]
no_license
def nevilleInter(points, x): """ :param points: a list of points ie ((0,1),(1,2)) etc.. :param x: the x in question of what the value is at this x :return: the value y at the given x """ if len(points) < 2: return "Invalid points" p = [[0 for j in range(len(points))] for y in range(len(points))] for i in range(len(points)): p[i][i] = points[i][1] if i + 1 < len(points): if points[i + 1][0] <= points[i][0]: return "Invalid points" i = 0 j = 1 t = j while True: print("P{0},{1}=(({2} - x{1}) * p{0}{3} - ({2} -x{0}) * p{4}{1}/ (x{0} - x{1})=".format(i,j,x,j-1,i+1),end="") p[i][j] = ((x - points[j][0]) * p[i][j - 1] - (x - points[i][0]) * p[i + 1][j]) / ( points[i][0] - points[j][0]) print(p[i][j]) if i == 0 and j == len(points) - 1: break if j == len(points) - 1: i = 0 j = t + 1 t = j else: i += 1 j += 1 return p[0][-1] print(nevilleInter(((8.1, 16.9446), (8.3, 17.56492), (8.6, 18.50515), (8.7, 18.82091)),8.5))
C#
UTF-8
1,391
2.703125
3
[]
no_license
using System.Collections.Generic; using System.Drawing; using Localization; using RembyClipper2.Config; using RembyClipper2.DrawingTool.Figures; namespace RembyClipper2.DrawingTool.FigureCreator { /// <summary> /// Text figure builder /// </summary> public class TextCreator : FigureCreator { #region Overrides of FigureCreator /// <summary> /// This method performs to create text figure /// </summary> /// <param name="point">point of the left upper corner</param> /// <param name="borderColor">color of the border</param> /// <param name="fillColor">fill color of the figure</param> /// <param name="surface">working surface</param> /// <returns>Created figure</returns> public override IFigure CreateFigure(Point point, Color borderColor, Color fillColor, IDrawingSurface surface, byte opacity) { TextFigure figure = new TextFigure(point, surface); //figure.BorderColor = borderColor; //figure.FillColor = fillColor; figure.Name = LanguageMgr.LM.GetText(Labels.Text); figure.Text = LanguageMgr.LM.GetText(Labels.TextFigureText); figure.Font = AppConfig.Instance.FigureFont; figure.FontColor = AppConfig.Instance.FigureFontColor; return figure; } #endregion } }
Java
UTF-8
1,056
1.804688
2
[]
no_license
package com.guiji.botsentence.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.guiji.botsentence.dao.entity.BotSentenceAddition; import com.guiji.botsentence.dao.entity.BotSentenceBranch; import com.guiji.botsentence.dao.entity.BotSentenceBranchExample; import com.guiji.botsentence.util.BotSentenceUtil; import com.guiji.botsentence.vo.BotSentenceIntentVO; import com.guiji.common.exception.CommonException; /** * * @ClassName: IBotSentenceKeyWordsValidateService * @Description: 关键词校验相关服务类 * @author: 张朋 * @date 2019年1月11日 下午4:36:02 * @version V1.0 */ public interface IBotSentenceKeyWordsValidateService { public void validateBusinessAskKeywords(List<BotSentenceIntentVO> list, String processId, List<Long> ignoreIntentIds); public void validateIntents(String processId, Long intentId); public void validateBusinessAskKeywords2(List<BotSentenceIntentVO> list, String processId, List<Long> ignoreIntentIds); }
Markdown
UTF-8
1,147
2.890625
3
[]
no_license
# 메모리 주소와 접근 - 메모리 한 바이트(8비트)에 주소 한 개가 들어가도록 설계했다. - 인텔 32비트에서는 주소값을 32비트로 저장할 수 있다. - 32비트에서는 최대로 4GB의 공간을 사용할 수 있다. - 2^32 x 1 bypte = 2^2 x 2^30 x 1byte = 4GB - 1 KB = 1024 byte = 2^10 byte - 1 MB = 1024 KB = 2^20 byte - 1 GB = 1024 MB = 2^10 MB = 2^30 byte - 어셈블리어의 메모리 접근 - 어셈블리어에서 메모리에 주소를 지정하고 그 주소 안에 있는 데이터를 지정할 때 - 대괄호를 쓰고 그 안에 주소를 넣는다. : [주소] - example - 402000번지에 접근해서 데이터 넣기 : mov [402000], AL - CL에 402000번지의 데이터를 넣기 : mov CL, [402000] - `주의해야 할 것` - mov mem1, mem2 XXXX!!! - 해결방법 - 메모리 1의 값을 레지스터에 먼저 옮기고 레지스터 값을 다시 메모리 2로 옮긴다. - mov mem1, reg - mov reg, mem2
C#
UTF-8
907
2.734375
3
[ "Apache-2.0" ]
permissive
using System.Web.Routing; namespace MvcContrib.Routing { /// <summary> /// Helper class for switching the default route handler to the debug route handler. /// </summary> public static class RouteDebugger { /// <summary> /// Iterates over each route in the route collection and replaces the default route handler with a DebugRouteHandler. /// </summary> /// <param name="routes">The route table</param> public static void RewriteRoutesForTesting(RouteCollection routes) { using (routes.GetReadLock()) { bool foundDebugRoute = false; foreach (var routeBase in routes) { var route = routeBase as Route; if (route != null) { route.RouteHandler = new DebugRouteHandler(); } if (route == DebugRoute.Singleton) foundDebugRoute = true; } if (!foundDebugRoute) { routes.Add(DebugRoute.Singleton); } } } } }
Python
UTF-8
1,379
2.921875
3
[ "BSD-2-Clause" ]
permissive
# -*- python -*- # # This file is part of biokit software # # Copyright (c) 2014- # # File author(s): Thomas Cokelaer <cokelaer@ebi.ac.uk> # # Distributed under the GPLv3 License. # See accompanying file LICENSE.txt or copy at # http://www.gnu.org/licenses/gpl-3.0.html # # website: https://github.com/biokit # ############################################################################## from easydev import check_param_in_list class Py2R(object): """Simple class to convert Python object to R objects as strings""" @staticmethod def from_bool(self, value): check_param_in_list(value, [True, False]) if value is True: return "T" if value is False: return "F" def from_dict(self, value): return('list(' + ','.join(['%s=%s' % (self.Str4R(a[0]), self.Str4R(a[1])) for a in value.items()]) + ')') def Str4R(self, obj): """convert a Python basic object into an R object in the form of string.""" #return str_func.get(type(obj), OtherStr)(obj) # for objects known by PypeR if type(obj) in str_func: return(str_func[type(obj)](obj)) # for objects derived from basic data types for tp in base_tps: if isinstance(obj, tp): return(str_func[tp](obj)) # for any other objects return(OtherStr(obj))
Markdown
UTF-8
2,210
3.28125
3
[]
no_license
--- title: Cuestionario - Sobrecarga sidebar_label: Cuestionario slug: /clases/sobrecarga/apuntes/cuestionario hide_table_of_contents: true hide_title: false author: authorURL: --- 1. ¿Qué significa sobrecargar un método o constructor? 2. ¿Qué debe cambiar para que la sobrecarga de un método o constructor sea válida? 3. ¿La sobrecarga se resuelve en tiempo de ejecución o en tiempo de compilación? 4. ¿Cómo se distingue a qué sobrecarga llamar? 5. ¿Se tiene en cuenta el nombre o identificador de los parámetros de entrada para una sobrecarga? 6. ¿Se tiene en cuenta el modificador de visibilidad para una sobrecarga? 7. ¿Se tiene en cuenta el tipo de retorno para una sobrecarga? 8. ¿Los métodos pueden tener el mismo nombre que otros elementos de una misma clase? (atributos, propiedades, etc). 9. Mencione dos razones por las cuales se sobrecargan los métodos. 10. ¿Los métodos estáticos pueden ser sobrecargados? 11. ¿Agregar el modificador “static” sin cambiar los parámetros de entrada es una sobrecarga válida? 12. ¿Agregar un modificador “out” o “ref” en la firma del método sin cambiar nada más es una sobrecarga válida? 13. ¿Cambiar el tipo de retorno sin cambiar los parámetros de entrada es una sobrecarga válida? 14. ¿Se pueden sobrecargar los constructores estáticos? ¿Por qué? 15. ¿Se puede llamar a un constructor estático con el operador “this()”? 16. ¿Se puede llamar a constructores de otras clases con el operador “this()”? 17. ¿Se puede sobrecargar un constructor privado? 18. ¿Qué es un operador? 19. ¿En qué se diferencian un operador unario y un operador binario? De un ejemplo de cada uno. 20. ¿Qué varía en la sintaxis de la sobrecarga de operadores unarios y binarios? 21. ¿Se pueden sobrecargar los operadores de operación y asignación (+=, -=,=, /=)? ¿Por qué? 22. ¿Cuál es la diferencia entre un operador de conversión implícito y uno explícito? (En finalidad, declaración y aplicación) 23. Los operadores de casteo “(T)x” no se pueden sobrecargar. ¿Cuál es la alternativa? 24. ¿Cuál es la diferencia entre castear (casting), convertir (converting) y parsear (parsing)?
C#
UTF-8
3,741
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; /* Still not clear what interactables will do, probably there will be different * types, so that will need to be taken care of. */ namespace MapFeatures.Interactables { public class InteractableManager : MapFeatureManager<InteractableDTO> { List<InteractableDTO> currentInteractables = new List<InteractableDTO>(); List<InteractableDTO> interactablesToDelete = new List<InteractableDTO>(); List<InteractableDTO> interactablesToCreate = new List<InteractableDTO>(); public override bool Create(InteractableDTO dto) { // TODO: some checking that this location is free to place on. GameObject interactable = InteractableGenerator.GenerateInteractable(dto); // Update currentinteractables for next UpdateFeatures call. if (interactable == null) { Debug.Log("Generated interactable is null!"); return false; } currentInteractables.Add(dto); return true; } public override bool Delete(InteractableDTO dto) { if (currentInteractables.Contains(dto)) { if (!currentInteractables.Remove(dto)) { return false; } GameObject objectToDestroy = GameObject.Find("interactable_" + dto.type + "_" + dto.location.x + "_" + dto.location.y); Destroy(objectToDestroy); return true; } Debug.Log("dto not found in currentInteractables!"); return false; } public override string MapFeatureId(string id) { return string.Format("Interactable{0}", id); } public override string MapFeatureTag() { return "Interactable"; } /* Receives a InteractableDTO array and handles it appropriately. */ public override bool UpdateFeatures(InteractableDTO[] dtoArray) { CreateInteractables(dtoArray); DeleteInteractables(dtoArray); return true; } private bool CreateInteractables(InteractableDTO[] dtoArray) { // We need a list for mutable sizing of the data structure. List<InteractableDTO> newInteractables = dtoArray.OfType<InteractableDTO>().ToList(); // Clear old contents. interactablesToCreate.Clear(); // Find elements that exist in provided array that doesn't exist // in current world interactables. interactablesToCreate = (List<InteractableDTO>) newInteractables.Except(currentInteractables).ToList(); foreach (InteractableDTO interactable in interactablesToCreate) { Create(interactable); } return true; } private bool DeleteInteractables(InteractableDTO[] dtoArray) { // We need a list for mutable sizing of the data structure. List<InteractableDTO> newInteractables = dtoArray.OfType<InteractableDTO>().ToList(); // Clear old contents. interactablesToDelete.Clear(); // We find elements that exist in currentInteractables but not dtoArray // (ie. newInteractables). interactablesToDelete = (List<InteractableDTO>) currentInteractables.Except(newInteractables).ToList(); foreach (InteractableDTO interactable in interactablesToDelete) { Delete(interactable); } return true; } } }
C#
UTF-8
4,345
3.140625
3
[]
no_license
/// Usage examples /// /// Lets imagine we need a simple progress bar to handle 'health' of the tree we need to cut off /// We need to create new empty script that inherits from SceneLineProgressBar /// with itself as generic argument public class HealthExampleTreeProgressBar : SceneLineProgressBar<HealthExampleTreeProgressBar> { } /// Add this script to your progress bar and fill all properties /// All properties have tooltips for best understanding what they representing /// Next we create our tree to handle his 'health' using our new progress bar public class ExampleTree { private float maxHealth; private float currentHealth; InitialData<HealthExampleTreeProgressBar> healthInitData; UpdateData<HealthExampleTreeProgressBar> healthUpdateData; private void OnEnable() { HealthExampleTreeProgressBar.OnProgressFinished += delegate { FallDown(); } ; } private void FallDown() { //Fall } private void Start() { InitializeHealthBar(); } public void InitializeHealthBar() { currentHealth = maxHealth; // All of this properties also have explanations in IProgressBar.cs // so if you want you can go to realization and study the work of progress bars deeper // to initialize progress you simply need to set up InitialData of HealthExampleTreeProgressBar // and send it using InitializeProgress event healthInitData.MinValue = 0; healthInitData.MaxValue = maxHealth; healthInitData.CurrentValue = maxHealth; HealthExampleTreeProgressBar.InitializeProgress(healthInitData); } public void ApplyDamage(float amount) { currentHealth -= amount; UpdateHealthBar(); } private void UpdateHealthBar() { // On all changes of actual value of some progress // you need to send this changes to appropriate progress bar healthUpdateData.CurrentValue = currentHealth; HealthExampleTreeProgressBar.UpdateProgress(healthUpdateData); } } /// There is similar controller to scene where we need to cut a few of trees public class StageExampleTreeProgressBar : SceneStageProgressBar<StageExampleTreeProgressBar> { } public class ExampleTreeController { private int felledTreesCountToWin; private int felledTreesCount; InitialData<StageExampleTreeProgressBar> stageInitData; UpdateData<StageExampleTreeProgressBar> stageUpdateData; private void OnEnable() { // as you can see, when we cut one of our trees, we create a new // which initializes the HealthExampleTreeProgressBar again HealthExampleTreeProgressBar.OnProgressFinished += delegate { InstantiateNewTree(); }; StageExampleTreeProgressBar.OnProgressFinished += delegate { FinishGame(); }; } private void Start() { InitializeStageBar(); } private void InitializeStageBar() { stageInitData.MinValue = 0; stageInitData.MaxValue = felledTreesCountToWin; stageInitData.CurrentValue = 0; StageExampleTreeProgressBar.InitializeProgress(stageInitData); } private void InstantiateNewTree() { felledTreesCount++; ExampleTree nextTree = new ExampleTree(); nextTree.InitializeHealthBar(); UpdateStageProgress(); } private void UpdateStageProgress() { stageUpdateData.CurrentValue = felledTreesCount; StageExampleTreeProgressBar.UpdateProgress(stageUpdateData); } private void FinishGame() { //Finish } } /// With GameObject progress bar logic is the same as with others public class ExampleGOLineProgressBar : GOLineProgressBar { } public class ExampleGOWithHealth { public ExampleGOLineProgressBar healthBar; private float currentHP; private float maxHP; private void OnEnable() { healthBar.OnProgressFinished += Death; } private void Death() { //Death } private void Start() { InitializeHealthBar(); } private void InitializeHealthBar() { healthBar.Initialize(0, maxHP, currentHP); } private void ApplyDamage(float damage) { currentHP -= damage; healthBar.UpdateCurrentProgress(currentHP); } }
C#
UTF-8
433
2.65625
3
[]
no_license
using CommandLine; namespace CommandLineParserExample { [Verb("concatenate", HelpText = "Concatenates two strings")] public sealed class ConcatenateStringOptions { [Option('s', "string1", HelpText = "The first string", Required = true)] public string Text1 { get; set; } [Option('t', "string2", HelpText = "The second string", Required = true)] public string Text2 { get; set; } } }
JavaScript
UTF-8
12,048
3.046875
3
[ "MIT" ]
permissive
// Build a Pie Chart for top 10 designations by number of jobs function buildPieChart(jobsByState) { jobsByState = jobsByState.slice(0,10); var x_data = jobsByState.map(row => row.State); var y_data = jobsByState.map(row => row.Jobs_Count); colors = ["#3e95cd", "violet","tomato","OliveDrab ","#8e5ea2","orange","#e8c3b9", "#3cba9f","purple","#c45850","grey"] new Chart(document.getElementById("pie-chart"), { type: 'pie', data: { labels: x_data, datasets: [{ label: x_data, backgroundColor: colors, data: y_data }] }, options: { title: { display: true, text: 'States with highest number of jobs', fontSize: 25 }, legend: { display: true, position: 'right', labels: { fontSize: 14, padding: 10, fontFamily: 'Arial' } } } }); } d3.json("/piechart").then((data) => { buildPieChart(data); }); // function buildBarChart(jobsByCompany) { // jobsByCompany = jobsByCompany.slice(0,20); // // Build a Bar Chart for top 10 Companies for data jobs // // need to use slice() to grab the top 10 sample_values, // var trace1 = { // y: jobsByCompany.map(row => row.Company), // x: jobsByCompany.map(row => row.Jobs_Count), // type: "bar", // orientation: "h", // width: .5 // }; // // Create the data array for the plot // var data = [trace1]; // // Define the plot layout // var layout = { // title: "Companies with maximum Data Analytics Jobs postings", // xaxis: { title: "No. of Jobs"}, // yaxis: { title: "Companies", autorange: "reversed"}, // margin: { // pad: -30, // l: -50 // }, // marker: {autocolorscale: true} // }; // // Plot the chart to a div tag with id "bar-plot" // Plotly.newPlot("bar-plot", data, layout); // } // d3.json("/company").then((data) => { // buildBarChart(data); // }); // Step 1: Set up our chart //= ================================ var svgWidth = 960; var svgHeight = 500; var margin = { top: 20, right: 40, bottom: 100, left: 100 }; var width = svgWidth - margin.left - margin.right; var height = svgHeight - margin.top - margin.bottom; // Step 2: Create an SVG wrapper, // append an SVG group that will hold our chart, // and shift the latter by left and top margins. // ================================= var svg = d3.select("#bar-plot") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // Initial Params var chosenXAxis = "State"; var chosenYAxis = 1; // function used for updating x-scale var upon click on axis label function xScale(jobsData, chosenXAxis) { // create scales var xBandScale = d3.scaleBand() .domain(jobsData[chosenXAxis][0]) .range([0, width]) .padding(0.1); return xBandScale; } function yScale(jobsData, chosenXAxis, chosenYAxis) { // create scales var yLinearScale = d3.scaleLinear() .domain([d3.min(jobsData[chosenXAxis][chosenYAxis]), d3.max(jobsData[chosenXAxis][chosenYAxis])]) .range([height, 0]); return yLinearScale; } // function used for updating xAxis var upon click on axis label function renderXAxes(newXScale, xAxis) { var bottomAxis = d3.axisBottom(newXScale); xAxis.transition() .duration(1000) .call(bottomAxis); return xAxis; } function renderYAxes(newYScale, yAxis) { var leftAxis = d3.axisLeft(newYScale); yAxis.transition() .duration(1000) .call(leftAxis); return yAxis; } // function used for updating circles group with a transition to // new circles function renderBarsX(barsGroup, newXScale, chosenXAxis) { barsGroup.transition() .duration(1000) .attr("x", d => newXScale(d[chosenXAxis][0])) .attr("transform", "rotate(-90)"); return barsGroup; } function renderBarsY(barsGroup, newYScale, chosenXAxis, chosenYAxis) { barsGroup.transition() .duration(1000) .attr("y", d => newYScale(d[chosenXAxis][chosenYAxis])); return barsGroup; } // function to update the text in circles (state abbr) function updateBarTextX(chosenXAxis, newXScale, textGroup) { textGroup.transition() .duration(1000) .attr("x", d => newXScale(d[chosenXAxis][0])); return textGroup; } function updateBarTextY(chosenYAxis, newYScale, textGroup) { textGroup.transition() .duration(1000) .attr("y", d => newYScale(d[chosenXAxis][chosenYAxis])+5); return textGroup; } // function used for updating circles group with new tooltip function updateToolTip(chosenXAxis, chosenYAxis, textGroup) { if (chosenXAxis === "State") { var labelX = "State: "; } else if (chosenXAxis === "City") { var labelX = "City: "; } else { var labelX = "Company: " } if (chosenYAxis === 2) { var labelY = "No. of jobs: "; } else { var labelY = "Avg Salary: " } var toolTip = d3.tip() .attr("class", "tooltip") .offset([80, -60]) .html(function(d) { return (`<br>${labelX} <br>${labelY}`); }); textGroup.call(toolTip); textGroup.on("mouseover", function(data) { toolTip.show(data); }) // onmouseout event .on("mouseout", function(data, index) { toolTip.hide(data); }); return textGroup; } // Step 3: // Import data from the donuts.csv file // ================================= d3.json("/d3chart").then((jobsData) => { console.log(jobsData[chosenXAxis]); console.log(jobsData[chosenXAxis][chosenYAxis]); // Step 4: Parse the data // ================================= // Format the data // jobsData.forEach(function(data) { // data[1] = +data[1]; // data[2] = +data[2]; // }); // Step 5: Create Scales //= ============================================ // xLinearScale function above csv import var xBandScale = xScale(jobsData, chosenXAxis); var yLinearScale = yScale(jobsData, chosenXAxis, chosenYAxis); // Step 6: Create Axes // ============================================= var bottomAxis = d3.axisBottom(xBandScale); var leftAxis = d3.axisLeft(yLinearScale); // append x axis var xAxis = chartGroup.append("g") .classed("x-axis", true) .attr("transform", `translate(0, ${height})`) .call(bottomAxis); // append y axis var yAxis = chartGroup.append("g") .classed("y-axis", true) .call(leftAxis); var node = chartGroup.selectAll(".node") .data(jobsData) .enter() .append("g") .classed("node", true); // append initial circles var barsGroup = node .append("rect") .attr("class", "bar") .attr("x", jobsData[chosenXAxis][0]) .attr("y", yLinearScale(jobsData[chosenXAxis][chosenYAxis])) .attr("width", xBandScale.bandwidth()) .attr("height", d => height - yLinearScale(d[chosenXAxis][chosenYAxis])); ; var textGroup = node .append("text") .classed("stateText",true) .attr("x", d => xBandScale(d[chosenXAxis][0])) .attr("y", d => yLinearScale(d[chosenXAxis][chosenYAxis])+5) .text(d => d[chosenXAxis][0]); // Create group for 3 x- axis labels var labelsGroupX = chartGroup.append("g") .attr("transform", `translate(${width / 2}, ${height + 20})`); var stateLabel = labelsGroupX.append("text") .attr("x", 0) .attr("y", 20) .attr("value", "State") // value to grab for event listener .classed("active", true) .text("States"); var cityLabel = labelsGroupX.append("text") .attr("x", 0) .attr("y", 40) .attr("value", "City") // value to grab for event listener .classed("inactive", true) .text("Cities"); var companyLabel = labelsGroupX.append("text") .attr("x", 0) .attr("y", 60) .attr("value", "Company") // value to grab for event listener .classed("inactive", true) .text("Companies"); // Create group for 3 y- axis labels var labelsGroupY = chartGroup.append("g") .attr("transform", "rotate(-90)"); var jobcountLabel = labelsGroupY.append("text") .attr("x", -160) .attr("y", -40) .attr("value", 2) // value to grab for event listener .classed("active", true) .text("Number of Jobs"); var salaryLabel = labelsGroupY.append("text") .attr("x", -160) .attr("y", -60) .attr("value", 1) // value to grab for event listener .classed("inactive", true) .text("Avg Salary $ (K)"); // updateToolTip function above csv import // var textGroup = updateToolTip(chosenXAxis, chosenYAxis, textGroup); // x axis labels event listener labelsGroupX.selectAll("text") .on("click", function() { // get value of selection var value = d3.select(this).attr("value"); console.log(value); if (value !== chosenXAxis) { // replaces chosenXAxis with value chosenXAxis = value; // functions here found above csv import // updates x scale for new data xLinearScale = xScale(jobsData, chosenXAxis); // updates x axis with transition xAxis = renderXAxes(xLinearScale, xAxis); // updates circles with new x values barsGroup = renderBarsX(barsGroup, xLinearScale, chosenXAxis); //updates text with new info textGroup = updateBarTextX(chosenXAxis, xLinearScale, textGroup); // updates tooltips with new info // textGroup = updateToolTip(chosenXAxis, chosenYAxis, textGroup); // changes classes to change bold text if (chosenXAxis === "State") { stateLabel .classed("active", true) .classed("inactive", false); cityLabel .classed("active", false) .classed("inactive", true); companyLabel .classed("active", false) .classed("inactive", true); } else if (chosenXAxis === "City") { stateLabel .classed("active", false) .classed("inactive", true); cityLabel .classed("active", true) .classed("inactive", false); companyLabel .classed("active", false) .classed("inactive", true); } else { stateLabel .classed("active", false) .classed("inactive", true); cityLabel .classed("active", false) .classed("inactive", true); companyLabel .classed("active", true) .classed("inactive", false); } } }); labelsGroupY.selectAll("text") .on("click", function() { // get value of selection var value = d3.select(this).attr("value"); console.log(value); if (value !== chosenYAxis) { chosenYAxis = value; // functions here found above csv import // updates x scale for new data yLinearScale = yScale(jobsData, chosenXAxis, chosenYAxis); // updates x axis with transition yAxis = renderYAxes(yLinearScale, yAxis); // updates circles with new x values barsGroup = renderBarsY(barsGroup, yLinearScale, chosenXAxis, chosenYAxis); //updates text with new info textGroup = updateBarTextY(chosenYAxis, yLinearScale, textGroup); //updates tooltips with new info textGroup = updateToolTip(chosenXAxis, chosenYAxis, textGroup); // changes classes to change bold text if (chosenYAxis === 2) { jobcountLabel .classed("active", true) .classed("inactive", false); salaryLabel .classed("active", false) .classed("inactive", true); } else { jobcountLabel .classed("active", false) .classed("inactive", true); salaryLabel .classed("active", false) .classed("inactive", true); } } }); });
Swift
UTF-8
663
2.5625
3
[]
no_license
// // CustomImageScrollviewCell.swift // shortNewIOS // // Created by SSd on 12/20/16. // Copyright © 2016 SSd. All rights reserved. // import UIKit class CustomImageScrollviewCell: CustomImage { var mScrollView : UIScrollView? init(frame: CGRect, scrollView : UIScrollView) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if self.point(inside: point, with: event){ return mScrollView } return self } }
Python
UTF-8
5,719
2.59375
3
[ "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-3-Clause-Open-MPI", "LicenseRef-scancode-free-unknown", "Libtool-exception", "GCC-exception-3.1", "LicenseRef-scancode-mit-old-style", "OFL-1.1", "JSON", "LGPL-2.1-only", "LGPL-2.0-or-later", "ICU", "Li...
permissive
import h5py import json from nndct_shared.nndct_graph.base_tensor import Tensor def save_graph(nndct_graph, hdf5_path='graph.hdf5'): GraphHDF5Saver(nndct_graph).save(hdf5_path) class GraphHDF5Saver(): def __init__(self, nndct_graph): self.graph = nndct_graph def get_node_config(self, node): node_info = dict() node_info['idx'] = node.idx node_info['name'] = node.name node_info['dtype'] = str(node.dtype) for idx, tensor in enumerate(node.in_tensors): node_info['in_tensors{}.name'.format(idx)] = tensor.name node_info['in_tensors{}.shape'.format(idx)] = tensor.shape node_info['in_tensors{}.dtype'.format(idx)] = tensor.dtype for idx, tensor in enumerate(node.out_tensors): node_info['out_tensors{}.name'.format(idx)] = tensor.name node_info['out_tensors{}.shape'.format(idx)] = tensor.shape node_info['out_tensors{}.dtype'.format(idx)] = tensor.dtype for attr_enum, attr in node.op.attrs.items(): if isinstance(attr.value, Tensor): continue elif isinstance(attr.value, (tuple, list)): has_tensor = False for val in attr.value: if isinstance(val, Tensor): has_tensor = True break if not has_tensor: node_info['Attr.{}'.format(attr_enum.name)] = attr.value else: node_info['Attr.{}'.format(attr_enum.name)] = attr.value return node_info def get_model_config(self): model_config = {'name': self.graph.name} model_config['layers'] = list() for node in self.graph.nodes: node_info = dict() node_info['class_name'] = node.op_type node_info['name'] = node.name node_info['inbound_nodes'] = [[[i, 0, 0, {}] for i in node.in_nodes]] node_info['config'] = self.get_node_config(node) model_config['layers'].append(node_info) return model_config def save(self, hdf5_path): config = self.get_model_config() model_config = {'class_name': 'Functional', 'config': config} metadata = dict(model_config=model_config) f = h5py.File(hdf5_path, mode='w') try: for k, v in metadata.items(): if isinstance(v, (dict, list, tuple)): f.attrs[k] = json.dumps(v).encode('utf8') else: f.attrs[k] = v f.flush() finally: f.close() class GraphConvertToCFG(): # Visualizing network structure with multiple inputs is not supported. def __init__(self, nndct_graph, cfg_savepath='test.cfg'): self.graph = nndct_graph self.cfg_path = cfg_savepath self.content = [] def read_node(self, node): self.content.append('name={}'.format(node.name)) self.content.append('scope_name={}'.format(node.scope_name)) self.content.append('idx={}'.format(str(node.idx))) self.content.append('dtype={}'.format(node.dtype)) self.content.append('in_nodes={}'.format(str(node.in_nodes))) self.content.append('out_nodes={}'.format(str(node.out_nodes))) for idx, tensor in enumerate(node.in_tensors): self.content.append('in_tensors{}.name={}'.format(str(idx), tensor.name)) self.content.append('in_tensors{}.shape={}'.format( str(idx), str(tensor.shape))) self.content.append('in_tensors{}.dtype={}'.format( str(idx), str(tensor.dtype))) for idx, tensor in enumerate(node.out_tensors): self.content.append('out_tensors{}.name={}'.format(str(idx), tensor.name)) self.content.append('out_tensors{}.shape={}'.format( str(idx), str(tensor.shape))) self.content.append('out_tensors{}.dtype={}'.format( str(idx), str(tensor.dtype))) for name, attr in node.op.attrs.items(): self.content.append('op_{}={}'.format(name, attr.value)) def convert(self): # Traverse every node in graph sequentially once. And all input nodes of the current node must have been traversed before. index = 0 nodename_index = {} last_nodename = None is_first_layer = True for node in self.graph.nodes: nodename = node.name op_type = node.op.type if is_first_layer: self.content.append('height={}'.format(node.out_tensors[0].shape[1])) self.content.append('width={}'.format(node.out_tensors[0].shape[2])) self.content.append('channels={}'.format(node.out_tensors[0].shape[3])) self.read_node(node) is_first_layer = False last_nodename = nodename continue num_innodes = len(node.in_nodes) nodename_index[nodename] = index index += 1 if num_innodes == 0: self.content.append('[{}]'.format(op_type)) self.read_node(node) elif num_innodes == 1: in_nodename = node.in_nodes[0] if in_nodename == last_nodename: self.content.append('[{}]'.format(op_type)) self.read_node(node) else: self.content.append('[route]') self.content.append('layers={}'.format( str(nodename_index[in_nodename]))) nodename_index[nodename] = index index += 1 self.content.append('[{}]'.format(op_type)) self.read_node(node) else: self.content.append('[route]') str_layers = 'layers=' for i in range(len(node.in_nodes)): if i == 0: str_layers += str(nodename_index[node.in_nodes[i]]) else: str_layers += ',' + str(nodename_index[node.in_nodes[i]]) self.content.append(str_layers) self.content.append('op_type={}'.format(op_type)) self.read_node(node) last_nodename = nodename with open(self.cfg_path, 'w') as f: f.write('[net]' + '\n') f.writelines(line + '\n' for line in self.content)
C
UTF-8
1,662
2.875
3
[]
no_license
//这是TCP多进程版本的服务端 #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/socket.h> #include<arpa/inet.h> #include <sys/types.h> #include <sys/wait.h> #include<netinet/in.h> int Data_IO(int id) { int pid = -1; pid = fork(); if(pid<0)return -1; else if(pid==0) { //子进程 while(1) { char buff[1024] = {0}; int ret=read(id,buff,1023); if(ret<0) { perror("read error"); close(id); exit(-1); } printf("client say:%s",buff); send(id, "what\?\?!!", 8, 0); } } //父进程 int status; while(wait(&status)>0); close(id); return 0; } int main() { int sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(sockfd<0){ perror("socket error"); return -1; } struct sockaddr_in ser; ser.sin_family=AF_INET; ser.sin_port=htons(atoi("9000")); ser.sin_addr.s_addr=inet_addr("192.168.1.100"); socklen_t len=sizeof(struct sockaddr_in); if(bind(sockfd,(struct sockaddr*)&ser,len)<0){ perror("bind error"); return -1; } if(listen(sockfd,5)<0){ perror("listen error"); return -1; } while(1){ int new_sockfd; struct sockaddr_in cli; len=sizeof(cli); new_sockfd=accept(sockfd,(struct sockaddr*)&cli,&len); if(new_sockfd<0){ perror("accept error"); continue; } Data_IO(new_sockfd); } close(sockfd); return 0; }
C
UTF-8
1,410
2.546875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* cmd_parsing.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fhenrion <fhenrion@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/18 10:47:06 by fhenrion #+# #+# */ /* Updated: 2020/02/26 15:09:18 by fhenrion ### ########.fr */ /* */ /* ************************************************************************** */ #include "cmd_parsing.h" /* Commands parsing informations arrays */ static const char *cmd_str[CMD_TAB_LEN] = CMD_STR_TAB; static const size_t cmd_len[CMD_TAB_LEN] = CMD_LEN_TAB; static const t_cmd cmd[CMD_TAB_LEN] = CMD_TAB; /* Command parsing to index function */ t_cmd parse_cmd(t_net *client, char data[BUFF_SIZE]) { size_t index = 0; recv(client->sock, data, BUFF_SIZE, 0); while (index < CMD_TAB_LEN) { if (!strncmp(data, cmd_str[index], cmd_len[index])) return (cmd[index]); index++; } return (UNKNOWN); }
Java
UTF-8
2,198
2.171875
2
[]
no_license
package com.sprocketry.avro.security; import static org.junit.Assert.assertEquals; import org.apache.avro.AvroRuntimeException; import org.apache.avro.ipc.LocalTransceiver; import org.apache.avro.specific.SpecificRequestor; import org.apache.avro.specific.SpecificResponder; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.annotation.ExpectedException; public abstract class AbstractAuthenticationStrategyTest { @Autowired @Qualifier("testService") protected MockFoo testImpl; @Autowired protected AuthenticationPlugin serverPlugin; protected AuthenticationPlugin clientPlugin; protected Foo client; public AbstractAuthenticationStrategyTest() { super(); } @Test public void validcredentials() throws Exception { for (int x = 0; x < 5; x++) assertEquals(12345, client.foo(new Bar())); } @Test @ExpectedException(AvroRuntimeException.class) public void invalidCredentials() throws Exception { clientPlugin.setPassword("notcorrect"); assertEquals(12345, client.foo(new Bar())); } @Test @ExpectedException(AvroRuntimeException.class) public void invalidAuthorizationForCall() throws Exception { clientPlugin.setUsername("billy"); clientPlugin.setPassword("hasNoRoles"); assertEquals(12345, client.foo(new Bar())); } @Before public void testSecurityContext() throws Exception { SpecificResponder responder = new SpecificResponder(Foo.class, testImpl); responder.addRPCPlugin(serverPlugin); clientPlugin = new AuthenticationPlugin(); clientPlugin.setUsername("rredford"); clientPlugin.setPassword("afghanistanbananastand"); SpecificRequestor testRequestor = new SpecificRequestor(Foo.class, new LocalTransceiver( responder)); testRequestor.addRPCPlugin(clientPlugin); client = SpecificRequestor.getClient(Foo.class, testRequestor); } }
Markdown
UTF-8
428
2.53125
3
[]
no_license
## Springboard Projects by Earnest Long, Jr. Instead of creating a separate repo for each of my Springboard projects, I've decided to host them all in this repo together. Each folder contains a separate project, and each folder name describes the topic of the project therein. Exceptions are the "relax_challenge" and "ultimate_challenge" projects (mock data science take-home interviews) and "hospital_readmit" (Inferential Statistics).
C++
UTF-8
1,938
3.40625
3
[]
no_license
//symbol_table.hpp //classes : attr - a symbol table entry, Scope - A symbol table #include <vector> #include <iostream> #include <unordered_map> #include <string> #include <stack> using namespace std; //address offset int offset = 0; //string constants to print vector<string> strdata; class attr{ public: int val; //value of the variable int offset; //offset from the datasegment begin address - store in $8 register string type; //datatype int width; //size of the variable int reg; //register that has the current value of the variable attr(int val, int offset, string type, int width){ this->val = val; this->offset = offset; this->type = type; this->width = width; this->reg = -1; } void print(){ cout<<"( "; cout<<this->val<<", "; cout<<this->offset<<", "; cout<<this->type<<", "; cout<<this->width<<", "; cout<<this->reg<<" "; cout<<")\n"; } }; class Scope { public: unordered_map<string, attr*> table; Scope *prev; Scope(Scope *p){ prev = p; } void put(string s, attr *a){ table.insert({s,a}); } attr* get(string s){ for( Scope *scp = this; scp!=NULL; scp = scp->prev){ auto found = (scp->table).find(s); if(found!=table.end()) return found->second; } return NULL; } void print(){ for(auto iter = table.begin(); iter != table.end(); iter++){ cout<<iter->first<<" : "; iter->second->print(); } cout<<endl<<endl; } string printData(){ //print datasegment string code = ""; vector<int> data(offset/4); for(auto iter = table.begin(); iter != table.end(); iter++){ data[((iter->second)->offset)/4] = (iter->second)->val; } for(int i = 0;i<offset/4;i++){ code += to_string(data[i]) + " "; } for(int i = 0;i<strdata.size();i++){ code += strdata[i]; } strdata.clear(); return code; } }; //symbol table Scope* top = new Scope(NULL); //attributes attr* a;
Java
UTF-8
2,090
2.171875
2
[]
no_license
package com.zhaotai.uzao.ui.theme.adapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.zhaotai.uzao.R; import com.zhaotai.uzao.api.ApiConstants; import com.zhaotai.uzao.bean.ThemeModuleBean; import com.zhaotai.uzao.utils.GlideLoadImageUtil; import com.zhaotai.uzao.utils.StringUtil; /** * description: 主题设置页面模块 * author : ZP * date: 2018/1/22 0022. */ public class ThemeSettingModuleAdapter extends BaseQuickAdapter<ThemeModuleBean.ThemeContentModel, BaseViewHolder> { private static final String TYPE_SPU = "spu"; private static final String TYPE_MATERIAL = "material"; public ThemeSettingModuleAdapter() { super(R.layout.item_theme_module); } @Override protected void convert(BaseViewHolder helper, ThemeModuleBean.ThemeContentModel item) { // spu material String entityType = item.getEntityType(); if (StringUtil.isEmpty(entityType)) { TextView tvName = helper.getView(R.id.tv_module_name); ImageView ivPic = helper.getView(R.id.iv_module_pic); tvName.setSelected(false); helper.setText(R.id.tv_module_name, "添加"); Glide.with(mContext) .load(R.drawable.icon_add_module) .into(ivPic); } else { TextView tvName = helper.getView(R.id.tv_module_name); ImageView ivPic = helper.getView(R.id.iv_module_pic); tvName.setSelected(false); helper.setText(R.id.tv_module_name, item.getEntityName()); //设置图片 String picUrl; if (TYPE_MATERIAL.equals(entityType)) { picUrl = ApiConstants.UZAOCHINA_IMAGE_HOST + item.getEntityPic(); } else { picUrl = ApiConstants.UZAOCHINA_IMAGE_HOST + item.getEntityPic(); } GlideLoadImageUtil.load(mContext,picUrl,ivPic); } } }
Java
UTF-8
819
1.984375
2
[]
no_license
package com.hhh.product.service.impl; import com.hhh.product.dao.ProductCategoryDao; import com.hhh.product.entity.ProductCategory; import com.hhh.product.service.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author hhh * @date 2020/2/17 17:23 * @description */ @Service public class CategoryServiceImpl implements CategoryService { private final ProductCategoryDao categoryDao; @Autowired public CategoryServiceImpl(ProductCategoryDao categoryDao) { this.categoryDao = categoryDao; } @Override public List<ProductCategory> findProductCategoriesByCategoryTypeIn(List<Integer> categoryTypeList) { return categoryDao.findProductCategoriesByCategoryTypeIn(categoryTypeList); } }
Java
UTF-8
11,419
2.109375
2
[ "MIT" ]
permissive
package money.terra.terrawallet.test; import jdk.vm.ci.code.site.Call; import money.terra.terrawallet.TerraWalletSDK; import money.terra.terrawallet.WalletModel; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class TerraWalletTest { @Test public void addressValidTest() throws Exception { boolean valid1 = TerraWalletSDK.isValidAddress("terra14aqr0fwhsh334qpeu39wuzdt9hkw2pwvwnyvh6"); boolean valid2 = TerraWalletSDK.isValidAddress("terra14aqr0fwhsh334qpeu39wuzdt9hkw2pwvwny"); boolean valid3 = TerraWalletSDK.isValidAddress("terra14aqr0fwhsh334qpeu39wuzdt9hkw2paaanyvh6"); boolean valid4 = TerraWalletSDK.isValidAddress("terrb14aqr0fwhsh334qpeu39wuzdt9hkw2paaanyvh6"); Assert.assertEquals("valid1 ", true, valid1); Assert.assertEquals("valid2 ", false, valid2); Assert.assertEquals("valid3 ", false, valid3); Assert.assertEquals("valid4 ", false, valid4); } @Test public void walletGenerateAndRecoverTest() throws Exception { final int count = 100; ArrayList<String[]> wallets = new ArrayList(); // generate for (int i = 0; i < count; i++) { String[] wallet = TerraWalletSDK.getNewWallet(); String privateKey = wallet[0]; String publicKey = wallet[1]; String publicKey64 = wallet[2]; String address = wallet[3]; String mnemonic = wallet[4]; Assert.assertEquals("generated[" + i + "], privateKey is wrong.", 64, privateKey.length()); Assert.assertEquals("generated[" + i + "], publicKey32 is wrong." + publicKey, 66, publicKey.length()); Assert.assertEquals("generated[" + i + "], publicKey64 is wrong." + publicKey64, 130, publicKey64.length()); Assert.assertEquals("generated[" + i + "], mnemonic is wrong.", 24, mnemonic.split(" ").length); //success generating. wallets.add(wallet); } // recover from generated above. Assert.assertEquals("items generated not enough.", wallets.size(), count); for (int i = 0; i < wallets.size(); i++) { String mnemonic = wallets.get(i)[4]; String[] wallet = TerraWalletSDK.getNewWalletFromSeed(mnemonic, 330); String privateKey = wallet[0]; String publicKey = wallet[1]; //compressed public key. String publicKey64 = wallet[2]; //'un'compressed public key. String address = wallet[3]; //check privateKey(recovered and generated is equal) Assert.assertEquals("recovered[" + i + "], privateKey is wrong.", wallets.get(i)[0], privateKey); //check publicKey(recovered and generated is equal) Assert.assertEquals("recovered[" + i + "], publicKey is wrong.", wallets.get(i)[1], publicKey); //check address(recovered and generated is equal) Assert.assertEquals("recovered[" + i + "], address is wrong.", wallets.get(i)[3], address); } } @Test public void transferTest() { String[] wallet = TerraWalletSDK.getNewWalletFromSeed("airport fox tomorrow arm slab invest size bird eyebrow push swarm fork bone grant ketchup wear pepper manual apart brand thank trash advance burger", 330); String hexPrivateKey = wallet[0]; String hexPublicKey = wallet[1]; String address = wallet[3]; String chainId = "bombay-11"; String toAddress = "terra1y56xnxa2aaxtuc3rpntgxx0qchyzy2wp7dqgy3"; String transferBalance = "1000000"; //1 Luna JSONObject accountInfo = getAccountInfo(address); String accountNumber = accountInfo.getString("account_number"); String sequence = accountInfo.getString("sequence"); int luna = accountInfo.getInt("luna"); Assert.assertEquals("not enough luna balance.", true, (luna >= 1000)); Assert.assertEquals("account number is not valid.", true, (!accountNumber.equals(""))); Assert.assertEquals("sequence is not valid.", true, (!sequence.equals(""))); // JSONObject message = makeTransferMessage(address, toAddress, accountNumber, chainId, sequence, transferBalance); Assert.assertEquals("makeTransferMessage is wrong", true, !message.isEmpty()); JSONObject signed = null; try { signed = TerraWalletSDK.sign(message, sequence, accountNumber, chainId, hexPrivateKey, hexPublicKey); }catch(Exception e) { Assert.fail("signed message is wrong."); } JSONObject response = broadcast(signed); System.out.println("response : " + response.toString()); } @Test public void marketSwapTest() { String[] wallet = TerraWalletSDK.getNewWalletFromSeed("airport fox tomorrow arm slab invest size bird eyebrow push swarm fork bone grant ketchup wear pepper manual apart brand thank trash advance burger", 330); String hexPrivateKey = wallet[0]; String hexPublicKey = wallet[1]; String address = wallet[3]; String chainId = "bombay-11"; String toCurrency = "usdr"; //SDT String swapBalance = "1000000"; //1Luna JSONObject accountInfo = getAccountInfo(address); String accountNumber = accountInfo.getString("account_number"); String sequence = accountInfo.getString("sequence"); int luna = accountInfo.getInt("luna"); Assert.assertEquals("not enough luna balance.", true, (luna >= 1000)); Assert.assertEquals("account number is not valid.", true, (!accountNumber.equals(""))); Assert.assertEquals("sequence is not valid.", true, (!sequence.equals(""))); // JSONObject message = makeMarketSwapMessage(address, toCurrency, accountNumber, chainId, sequence, swapBalance); Assert.assertEquals("makeMarketSwapMessage is wrong", true, !message.isEmpty()); JSONObject signed = null; try { signed = TerraWalletSDK.sign(message, sequence, accountNumber, chainId, hexPrivateKey, hexPublicKey); }catch(Exception e) { Assert.fail("signed message is wrong."); } JSONObject response = broadcast(signed); System.out.println("response : " + response.toString()) ; } private JSONObject getAccountInfo(String address) { String accountNumber = ""; String sequence = ""; int luna = 0; try { JSONObject accountInfo = httpConnection("/auth/accounts/" + address, true); JSONObject value = accountInfo.getJSONObject("result").getJSONObject("value"); accountNumber = value.getString("account_number"); sequence = value.getString("sequence"); JSONObject balanceInfo = httpConnection("/bank/balances/" + address, true); JSONArray coins = balanceInfo.getJSONArray("result"); luna = 0; for (int i = 0; i < coins.length(); i++) { JSONObject coin = coins.getJSONObject(i); if (coin.getString("denom").equals("uluna")) { luna = Integer.parseInt(coin.getString("amount")); } } }catch(Exception e) { e.printStackTrace(); }finally { JSONObject result = new JSONObject(); result.put("account_number", accountNumber); result.put("sequence", sequence); result.put("luna", luna); return result; } } private JSONObject makeTransferMessage(String from, String to, String accountNumber, String chainId, String sequence, String transferBalance) { JSONObject requestJson = new JSONObject("{\"base_req\": {\"from\": \"" + from + "\",\"memo\": \"Sent via terra-wallet-java test\",\"chain_id\": \"" + chainId + "\",\"account_number\": \"" + accountNumber + "\",\"sequence\": \"" + sequence + "\",\"gas\": \"200000\",\"gas_adjustment\": \"1.2\",\"fees\": [{\"denom\": \"uluna\",\"amount\": \"50\"}],\"simulate\": false},\"coins\": [{\"denom\": \"uluna\",\"amount\": \"" + transferBalance + "\"}]}"); try { JSONObject response = httpConnection("/bank/accounts/" + to + "/transfers", false, requestJson); return response.getJSONObject("value"); }catch(Exception e) { return new JSONObject(); } } private JSONObject makeMarketSwapMessage(String from, String toCurrency, String accountNumber, String chainId, String sequence, String swapBalance){ JSONObject requestJson = new JSONObject("{\"base_req\": {\"from\": \"" + from + "\",\"memo\": \"Sent via terra-wallet-java test\",\"chain_id\": \"" + chainId + "\",\"account_number\": \"" + accountNumber + "\",\"sequence\": \"" + sequence + "\",\"gas\": \"200000\",\"gas_adjustment\": \"1.2\",\"fees\": [{\"denom\": \"uluna\",\"amount\": \"50\"}],\"simulate\": false},\"offer_coin\": {\"denom\": \"uluna\",\"amount\": \"" + swapBalance + "\"},\"ask_denom\": \"" + toCurrency + "\"}"); try { JSONObject response = httpConnection("/market/swap", false, requestJson); return response.getJSONObject("value"); }catch(Exception e) { return new JSONObject(); } } private JSONObject broadcast(JSONObject message) { return httpConnection("/txs", false, message); } public JSONObject httpConnection(String targetUrl, boolean isGet) { return httpConnection(targetUrl, isGet, null); } public JSONObject httpConnection(String targetUrl, boolean isGet, JSONObject params) { BufferedReader br = null; try { URL url = new URL("https://bombay-lcd.terra.dev" + targetUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod(isGet ? "GET" : "POST"); if (params != null) { conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); os.close(); } conn.connect(); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuffer sb = new StringBuffer(); String jsonData = ""; while ((jsonData = br.readLine()) != null) { sb.append(jsonData); } return new JSONObject(sb.toString()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } } return new JSONObject(); } }
PHP
UTF-8
1,236
2.640625
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Characteristic extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'charact_code_1c', 'name' ]; public $timestamps = false; /** * * @param object $xml * @return object */ public function createCharacteristic($xml) { return $this->create([ 'charact_code_1c' => $xml->code_1c, 'name' => $xml->name, ]); } /** * @param object $xml * @return object */ public function updateCharacteristic($xml) { return $this->update([ 'charact_code_1c' => $xml->code_1c, 'name' => $xml->name, ]); } /** * @param string $code * @return boolean */ public function IsIssetCharacteristics($code) { return $this->where('charact_code_1c', '=', $code)->first(); } public function getCharacteristicValue() { return $this->hasMany('App\Models\CharacteristicValue', 'code_1c_characteristic', 'charact_code_1c'); } }
Python
UTF-8
350
3.609375
4
[]
no_license
import time def timer(f): def tmp(*args, **kwargs): start_time = time.time() res = f(*args, **kwargs) # put function which will be decorated print(f'Function execution time: {time.time() - start_time}') return res return tmp @timer def func(x, y): # instead of func put tmp return x + y func(4, 89)
Java
UTF-8
2,348
2.34375
2
[]
no_license
package com.example.applicate; import com.example.applicate.catalog.Catalog; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; @SpringBootTest class ApplicateApplicationTests { @Test void contextLoads() { } @Test public void initialCatalogsCheck() { given().when() .get("/catalog/1") .then().assertThat() .body("supplier.id", equalTo(1)); given().when().get("/catalog/2").then().assertThat().body("supplier.id", equalTo(1)); given().when().get("/catalog/3").then().assertThat().body("supplier.id", equalTo(1)); given().when().get("/catalog/4").then().assertThat().body("supplier.id", equalTo(2)); } @Test public void addNewCatalog() { given().body(new Catalog("4", "Ashirwad Atta", "sample desc1", "brand1", "brand desc")) .contentType("application/json") .when().post("/catalog/{supplierid}", 2) .then().assertThat().statusCode(400); given().body(new Catalog("10", "Ashirwad Atta", "sample desc1", "brand1", "brand desc")) .contentType("application/json") .when().post("/catalog/{supplierid}", 10) .then().assertThat().statusCode(404); } @Test public void getSupplier(){ given().when().get("/supplier/1") .then().assertThat().body("id",equalTo(1)); given().when().get("/supplier/5") .then().assertThat().statusCode(404); } @Test public void getCatalogSKUNameFromSupplierId(){ given().when().get("/catalog/supplier/1") .then().assertThat().body("",hasItems("Haldiram Namkeen","Bingo 200 gm","Bingo 500 gm")); given().when().get("/catalog/supplier/2") .then().assertThat().body("",hasItems("Ashirwad Atta")); } @Test public void searchCatalogBySupplierNameAndSubstring(){ given().when().param("suppliername","supplierA").param("query","ing") .get("/catalog/search") .then() .assertThat().body("",hasItems("Bingo 200 gm","Bingo 500 gm")); } }
Python
UTF-8
490
4.03125
4
[]
no_license
from time import sleep def higher(*num): count = higherNumber = 0 print('Os valores digitados foram:') for number in num: print(f'{number} ', end='', flush=True) sleep(0.3) if higherNumber == 0: higherNumber = number elif number >= higherNumber: higherNumber = number count += 1 print(f'\nForam informados {count} valores') print(f'O maior número digitado foi {higherNumber}') higher(10, 5, 8, 4, 2)
TypeScript
UTF-8
40,344
3.65625
4
[ "MIT" ]
permissive
/** * Options for compressing data into a DEFLATE format */ export interface DeflateOptions { /** * The level of compression to use, ranging from 0-9. * * 0 will store the data without compression. * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. * The default level is 6. * * Typically, binary data benefits much more from higher values than text data. * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. * * For example, a 1 MB text file could: * - become 1.01 MB with level 0 in 1ms * - become 400 kB with level 1 in 10ms * - become 320 kB with level 9 in 100ms */ level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; /** * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. * * Note that this is exponential: while level 0 uses 4 kB, level 4 uses 64 kB, level 8 uses 1 MB, and level 12 uses 16 MB. * It is recommended not to lower the value below 4, since that tends to hurt performance. * In addition, values above 8 tend to help very little on most data and can even hurt performance. * * The default value is automatically determined based on the size of the input data. */ mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | undefined; } /** * Options for compressing data into a GZIP format */ export interface GzipOptions extends DeflateOptions { /** * When the file was last modified. Defaults to the current time. * Set this to 0 to avoid revealing a modification date entirely. */ mtime?: Date | string | number | undefined; /** * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file * with this name instead of the name of the compressed file. */ filename?: string | undefined; } /** * Options for compressing data into a Zlib format */ export type ZlibOptions = DeflateOptions; /** * Handler for data (de)compression streams * @param data The data output from the stream processor * @param final Whether this is the final block */ export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; /** * Handler for asynchronous data (de)compression streams * @param err Any error that occurred * @param data The data output from the stream processor * @param final Whether this is the final block */ export type AsyncFlateStreamHandler = (err: Error, data: Uint8Array, final: boolean) => void; /** * Callback for asynchronous (de)compression methods * @param err Any error that occurred * @param data The resulting data. Only present if `err` is null */ export type FlateCallback = (err: Error | string, data: Uint8Array) => void; interface AsyncOptions { /** * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in * unusable but will increase performance and reduce memory usage. */ consume?: boolean | undefined; } /** * Options for compressing data asynchronously into a DEFLATE format */ export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions {} /** * Options for decompressing DEFLATE data asynchronously */ export interface AsyncInflateOptions extends AsyncOptions { /** * The original size of the data. Currently, the asynchronous API disallows * writing into a buffer you provide; the best you can do is provide the * size in bytes and be given back a new typed array. */ size?: number | undefined; } /** * Options for compressing data asynchronously into a GZIP format */ export interface AsyncGzipOptions extends GzipOptions, AsyncOptions {} /** * Options for decompressing GZIP data asynchronously */ export type AsyncGunzipOptions = AsyncOptions; /** * Options for compressing data asynchronously into a Zlib format */ export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions {} /** * Options for decompressing Zlib data asynchronously */ export type AsyncUnzlibOptions = AsyncInflateOptions; /** * A terminable compression/decompression process */ export interface AsyncTerminable { /** * Terminates the worker thread immediately. The callback will not be called. */ (): void; } /** * Streaming DEFLATE compression */ export class Deflate { /** * Creates a DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: DeflateOptions, cb?: FlateStreamHandler); constructor(cb?: FlateStreamHandler); private o; private d; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private p; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming DEFLATE compression */ export class AsyncDeflate { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous DEFLATE stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with DEFLATE without any wrapper * @param data The data to compress * @param cb The function to be called upon compression completion */ export function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @returns The deflated version of the data */ export function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; /** * Streaming DEFLATE decompression */ export class Inflate { /** * Creates an inflation stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler); private s; private o; private p; private d; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private e; private c; /** * Pushes a chunk to be inflated * @param chunk The chunk to push * @param final Whether this is the final chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming DEFLATE decompression */ export class AsyncInflate { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous inflation stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); /** * Pushes a chunk to be inflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands DEFLATE data with no wrapper * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands DEFLATE data with no wrapper * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Expands DEFLATE data with no wrapper * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function inflateSync(data: Uint8Array, out?: Uint8Array): Uint8Array; /** * Streaming GZIP compression */ export class Gzip { private c; private l; private v; private o; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a GZIP stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: GzipOptions, cb?: FlateStreamHandler); /** * Creates a GZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: FlateStreamHandler); /** * Pushes a chunk to be GZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; private p; } /** * Asynchronous streaming GZIP compression */ export class AsyncGzip { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous GZIP stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous GZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); /** * Pushes a chunk to be GZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with GZIP * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with GZIP * @param data The data to compress * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the decompression */ export function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Compresses data with GZIP * @param data The data to compress * @param opts The compression options * @returns The gzipped version of the data */ export function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; /** * Streaming GZIP decompression */ export class Gunzip { private v; private p; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a GUNZIP stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler); /** * Pushes a chunk to be GUNZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming GZIP decompression */ export class AsyncGunzip { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous GUNZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb: AsyncFlateStreamHandler); /** * Pushes a chunk to be GUNZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands GZIP data * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands GZIP data * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Expands GZIP data * @param data The data to decompress * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory. * @returns The decompressed version of the data */ export function gunzipSync(data: Uint8Array, out?: Uint8Array): Uint8Array; /** * Streaming Zlib compression */ export class Zlib { private c; private v; private o; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a Zlib stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: ZlibOptions, cb?: FlateStreamHandler); /** * Creates a Zlib stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: FlateStreamHandler); /** * Pushes a chunk to be zlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; private p; } /** * Asynchronous streaming Zlib compression */ export class AsyncZlib { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous DEFLATE stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with Zlib * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion */ export function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with Zlib * @param data The data to compress * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Compress data with Zlib * @param data The data to compress * @param opts The compression options * @returns The zlib-compressed version of the data */ export function zlibSync(data: Uint8Array, opts: ZlibOptions): Uint8Array; /** * Streaming Zlib decompression */ export class Unzlib { private v; private p; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a Zlib decompression stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler); /** * Pushes a chunk to be unzlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming Zlib decompression */ export class AsyncUnzlib { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous Zlib decompression stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); /** * Pushes a chunk to be decompressed from Zlib * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands Zlib data * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function unzlib(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands Zlib data * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Expands Zlib data * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function unzlibSync(data: Uint8Array, out?: Uint8Array): Uint8Array; export { gzip as compress, AsyncGzip as AsyncCompress }; export { gzipSync as compressSync, Gzip as Compress }; /** * Streaming GZIP, Zlib, or raw DEFLATE decompression */ export class Decompress { private G; private I; private Z; /** * Creates a decompression stream * @param cb The callback to call whenever data is decompressed */ constructor(cb?: FlateStreamHandler); private s; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private p; /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression */ export class AsyncDecompress { private G; private I; private Z; /** * Creates an asynchronous decompression stream * @param cb The callback to call whenever data is decompressed */ constructor(cb?: AsyncFlateStreamHandler); /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; /** * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function decompressSync(data: Uint8Array, out?: Uint8Array): Uint8Array; /** * Attributes for files added to a ZIP archive object */ export interface ZipAttributes { /** * The operating system of origin for this file. The value is defined * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) * is MS/DOS, 3 is UNIX, 19 is macOS. */ os?: number | undefined; /** * The file's attributes. These are traditionally somewhat complicated * and platform-dependent, so using them is scarcely necessary. However, * here is a representation of what this is, bit by bit: * * `TTTTugtrwxrwxrwx0000000000ADVSHR` * * TTTT = file type (rarely useful) * * u = setuid, g = setgid, t = sticky * * rwx = user permissions, rwx = group permissions, rwx = other permissions * * 0000000000 = unused * * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only * * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0644 << 16 */ attrs?: number | undefined; /** * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an * integer between 0 and 65,535, inclusive. * * This field is incredibly rare and almost never needed except for compliance with * proprietary standards and software. */ extra?: Record<number, Uint8Array> | undefined; /** * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This * field is not read by consumer software. */ comment?: string | undefined; /** * When the file was last modified. Defaults to the current time. */ mtime?: GzipOptions['mtime'] | undefined; } /** * Options for creating a ZIP archive */ export interface ZipOptions extends DeflateOptions, ZipAttributes {} /** * Options for asynchronously creating a ZIP archive */ export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes {} /** * Options for asynchronously expanding a ZIP archive */ export type AsyncUnzipOptions = AsyncOptions; /** * A file that can be used to create a ZIP archive */ export type ZippableFile = Uint8Array | [Uint8Array, ZipOptions]; /** * A file that can be used to asynchronously create a ZIP archive */ export type AsyncZippableFile = Uint8Array | [Uint8Array, AsyncZipOptions]; /** * The complete directory structure of a ZIPpable archive */ export interface Zippable { [path: string]: Zippable | ZippableFile; } /** * The complete directory structure of an asynchronously ZIPpable archive */ export interface AsyncZippable { [path: string]: AsyncZippable | AsyncZippableFile; } /** * An unzipped archive. The full path of each file is used as the key, * and the file is the value */ export interface Unzipped { [path: string]: Uint8Array; } /** * Handler for string generation streams * @param data The string output from the stream processor * @param final Whether this is the final block */ export type StringStreamHandler = (data: string, final: boolean) => void; /** * Callback for asynchronous ZIP decompression * @param err Any error that occurred * @param data The decompressed ZIP archive */ export type UnzipCallback = (err: Error | string, data: Unzipped) => void; /** * Handler for streaming ZIP decompression * @param file The file that was found in the archive */ export type UnzipFileHandler = (file: UnzipFile) => void; /** * Streaming UTF-8 decoding */ export class DecodeUTF8 { private p; private t; /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is decoded */ constructor(cb?: StringStreamHandler); /** * Pushes a chunk to be decoded from UTF-8 binary * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; /** * The handler to call whenever data is available */ ondata: StringStreamHandler; } /** * Streaming UTF-8 encoding */ export class EncodeUTF8 { /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is encoded */ constructor(cb?: FlateStreamHandler); /** * Pushes a chunk to be encoded to UTF-8 * @param chunk The string data to push * @param final Whether this is the last chunk */ push(chunk: string, final?: boolean): void; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; } /** * Converts a string into a Uint8Array for use with compression/decompression methods * @param str The string to encode * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless decoding a binary string. * @returns The string encoded in UTF-8/Latin-1 binary */ export function strToU8(str: string, latin1?: boolean): Uint8Array; /** * Converts a Uint8Array to a string * @param dat The data to decode to string * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless encoding to binary string. * @returns The original UTF-8/Latin-1 string */ export function strFromU8(dat: Uint8Array, latin1?: boolean): string; /** * A stream that can be used to create a file in a ZIP archive */ export interface ZipInputFile extends ZipAttributes { /** * The filename to associate with the data provided to this stream. If you * want a file in a subdirectory, use forward slashes as a separator (e.g. * `directory/filename.ext`). This will still work on Windows. */ filename: string; /** * The size of the file in bytes. This attribute may be invalid after * the file is added to the ZIP archive; it must be correct only before the * stream completes. * * If you don't want to have to compute this yourself, consider extending the * ZipPassThrough class and overriding its process() method, or using one of * ZipDeflate or AsyncZipDeflate. */ size: number; /** * A CRC of the original file contents. This attribute may be invalid after * the file is added to the ZIP archive; it must be correct only before the * stream completes. * * If you don't want to have to generate this yourself, consider extending the * ZipPassThrough class and overriding its process() method, or using one of * ZipDeflate or AsyncZipDeflate. */ crc: number; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA */ compression: number; /** * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely * to be necessary. */ flag?: number | undefined; /** * The handler to be called when data is added. After passing this stream to * the ZIP file object, this handler will always be defined. To call it: * * `stream.ondata(error, chunk, final)` * * error = any error that occurred (null if there was no error) * * chunk = a Uint8Array of the data that was added (null if there was an * error) * * final = boolean, whether this is the final chunk in the stream */ ondata?: AsyncFlateStreamHandler | undefined; /** * A method called when the stream is no longer needed, for clean-up * purposes. This will not always be called after the stream completes, * so you may wish to call this.terminate() after the final chunk is * processed if you have clean-up logic. */ terminate?: AsyncTerminable | undefined; } /** * A pass-through stream to keep data uncompressed in a ZIP archive. */ export class ZipPassThrough implements ZipInputFile { filename: string; crc: number; size: number; compression: number; os?: number | undefined; attrs?: number | undefined; comment?: string | undefined; extra?: Record<number, Uint8Array> | undefined; mtime?: GzipOptions['mtime'] | undefined; ondata: AsyncFlateStreamHandler; private c; /** * Creates a pass-through stream that can be added to ZIP archives * @param filename The filename to associate with this data stream */ constructor(filename: string); /** * Processes a chunk and pushes to the output stream. You can override this * method in a subclass for custom behavior, but by default this passes * the data through. You must call this.ondata(err, chunk, final) at some * point in this method. * @param chunk The chunk to process * @param final Whether this is the last chunk */ protected process(chunk: Uint8Array, final: boolean): void; /** * Pushes a chunk to be added. If you are subclassing this with a custom * compression algorithm, note that you must push data from the source * file only, pre-compression. * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate * for better performance */ export class ZipDeflate implements ZipInputFile { filename: string; crc: number; size: number; compression: number; flag: 0 | 1 | 2 | 3; os?: number | undefined; attrs?: number | undefined; comment?: string | undefined; extra?: Record<number, Uint8Array> | undefined; mtime?: GzipOptions['mtime'] | undefined; ondata: AsyncFlateStreamHandler; private d; /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ constructor(filename: string, opts?: DeflateOptions); process(chunk: Uint8Array, final: boolean): void; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * Asynchronous streaming DEFLATE compression for ZIP archives */ export class AsyncZipDeflate implements ZipInputFile { filename: string; crc: number; size: number; compression: number; flag: 0 | 1 | 2 | 3; os?: number | undefined; attrs?: number | undefined; comment?: string | undefined; extra?: Record<number, Uint8Array> | undefined; mtime?: GzipOptions['mtime'] | undefined; ondata: AsyncFlateStreamHandler; private d; terminate: AsyncTerminable; /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ constructor(filename: string, opts?: DeflateOptions); process(chunk: Uint8Array, final: boolean): void; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): void; } /** * A zippable archive to which files can incrementally be added */ export class Zip { private u; private d; /** * Creates an empty ZIP archive to which files can be added * @param cb The callback to call whenever data for the generated ZIP archive * is available */ constructor(cb?: AsyncFlateStreamHandler); /** * Adds a file to the ZIP archive * @param file The file stream to add */ add(file: ZipInputFile): void; /** * Ends the process of adding files and prepares to emit the final chunks. * This *must* be called after adding all desired files for the resulting * ZIP file to work properly. */ end(): void; private e; /** * A method to terminate any internal workers used by the stream. Subsequent * calls to add() will fail. */ terminate(): void; /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; } /** * Asynchronously creates a ZIP file * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @param cb The callback to call with the generated ZIP archive * @returns A function that can be used to immediately terminate the compression */ export function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously creates a ZIP file * @param data The directory structure for the ZIP archive * @param cb The callback to call with the generated ZIP archive * @returns A function that can be used to immediately terminate the compression */ export function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; /** * Synchronously creates a ZIP file. Prefer using `zip` for better performance * with more than one file. * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @returns The generated ZIP archive */ export function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; /** * A decoder for files in ZIP streams */ export interface UnzipDecoder { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Pushes a chunk to be decompressed * @param data The data in this chunk. Do not consume (detach) this data. * @param final Whether this is the last chunk in the data stream */ push(data: Uint8Array, final: boolean): void; /** * A method to terminate any internal workers used by the stream. Subsequent * calls to push() should silently fail. */ terminate?: AsyncTerminable | undefined; } /** * A constructor for a decoder for unzip streams */ export interface UnzipDecoderConstructor { /** * Creates an instance of the decoder * @param filename The name of the file * @param size The compressed size of the file * @param originalSize The original size of the file */ new (filename: string, size?: number, originalSize?: number): UnzipDecoder; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA */ compression: number; } /** * Streaming file extraction from ZIP archives */ export interface UnzipFile { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * The name of the file */ name: string; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no * decompression stream available for this method, start() will throw. */ compression: number; /** * The compressed size of the file */ size?: number | undefined; /** * The original size of the file */ originalSize?: number | undefined; /** * Starts reading from the stream. Calling this function will always enable * this stream, but ocassionally the stream will be enabled even without * this being called. */ start(): void; /** * A method to terminate any internal workers used by the stream. ondata * will not be called any further. */ terminate: AsyncTerminable; } /** * Streaming pass-through decompression for ZIP archives */ export class UnzipPassThrough implements UnzipDecoder { static compression: number; ondata: AsyncFlateStreamHandler; push(data: Uint8Array, final: boolean): void; } /** * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for * better performance. */ export class UnzipInflate implements UnzipDecoder { static compression: number; private i; ondata: AsyncFlateStreamHandler; /** * Creates a DEFLATE decompression that can be used in ZIP archives */ constructor(); push(data: Uint8Array, final: boolean): void; } /** * Asynchronous streaming DEFLATE decompression for ZIP archives */ export class AsyncUnzipInflate implements UnzipDecoder { static compression: number; private i; ondata: AsyncFlateStreamHandler; terminate: AsyncTerminable; /** * Creates a DEFLATE decompression that can be used in ZIP archives */ constructor(_: string, sz?: number); push(data: Uint8Array, final: boolean): void; } /** * A ZIP archive decompression stream that emits files as they are discovered */ export class Unzip { private d; private c; private p; private k; private o; /** * Creates a ZIP decompression stream * @param cb The callback to call whenever a file in the ZIP archive is found */ constructor(cb?: UnzipFileHandler); /** * Pushes a chunk to be unzipped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean): any; /** * Registers a decoder with the stream, allowing for files compressed with * the compression type provided to be expanded correctly * @param decoder The decoder constructor */ register(decoder: UnzipDecoderConstructor): void; /** * The handler to call whenever a file is discovered */ onfile: UnzipFileHandler; } /** * Asynchronously decompresses a ZIP archive * @param data The raw compressed ZIP file * @param cb The callback to call with the decompressed files * @returns A function that can be used to immediately terminate the unzipping */ export function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; /** * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better * performance with more than one file. * @param data The raw compressed ZIP file * @returns The decompressed files */ export function unzipSync(data: Uint8Array): Unzipped;
JavaScript
UTF-8
1,859
2.75
3
[ "MIT" ]
permissive
let text=$("#text")[0]; let output=$("#output")[0]; text.ondragover=(e)=>{ e.preventDefault(); e.stopPropagation(); }; text.ondrop=(e)=>{ let file=e.dataTransfer.files[0]; let reader=new FileReader(); reader.readAsText(file); reader.onloadend=()=>{ text.value=reader.result; } e.preventDefault(); e.stopPropagation(); }; $("#convert")[0].onclick=()=>{ if(!text.value)return ; let list=text.value.replaceAll(/\n?\[re:.*\]\n\[ve:.*\]\n?/g,"").trim(); list=list.split("\n"); let time; let returnvalue=""; let lastindex=0; let timelist=[],tag=0; list.forEach((value,index)=>{ if(/(?<=\[)\d{2}:\d{2}\.\d{2}(?=\])/.test(value)){ let timetriple=value.match(/(?<=\[)\d{2}:\d{2}\.\d{2}(?=\])/)[0].split(/(:|\.)/).filter(el=>!/(:|\.)/.test(el)); timelist.push(timetriple.map((value)=>parseInt(value))); } }) console.log(timelist); list=list.map((value,index)=>{ if(/(?<=\[)\d{2}:\d{2}\.\d{2}(?=\])/.test(value)){ let timetriple; if(tag==timelist.length-1){ timetriple=timelist[tag]; timetriple[1]+=5; timetriple[0]+=timetriple[1]>=60?1:0; timetriple[1]-=timetriple[1]>=60?60:0; }else if(tag>0&&timelist[tag].toString()==timelist[tag-1].toString()){ timetriple=Array.from(timelist[tag+1]); timetriple[2]-=1; if(timetriple[2]<0){ timetriple[1]-=1; timetriple[2]+=100; } if(timetriple[1]<0){ timetriple[0]-=1; timetriple[1]+=60; } }else{ timetriple=timelist[tag]; } tag++; return `[${timetriple[0].toString().padStart(2,"0")}:${timetriple[1].toString().padStart(2,"0")}.${timetriple[2].toString().padStart(2,"0")}]${value.substr(10)}`; }else{ return value; }; }); returnvalue=list.join("\n"); output.innerText=returnvalue; new ClipboardJS(`#copy`,{ text:()=>returnvalue }); }
Markdown
UTF-8
971
3.046875
3
[ "MIT" ]
permissive
--- title: HARcURL license: LGPL License link: http://andydude.github.io/harcurl/ source: https://github.com/andydude/harcurl --- The HTTP archiving (HAR) file transfer tool. The harcurl tool accepts requests on stdin, and prints responses to stdout. The format of the request and response are both specified in the HAR-1.2 specification. Obviously, almost every property is optional on input, even though the HAR spec says it is required, since one of the jobs of harcurl is to fill in the rest of the data from the response. The only 2 properties that are required are method and url. The recommended usage is to build a JSON file either by hand, or by generating one with your favorite programming language, then feed that to harcurl on stdin. ```sh echo ' { "request" { "method": "GET", "url": "http://httpbin.org/get" } }' | harcurl ``` The simplest way to use harcurl is to call it with the shell command: ```sh harcurl < req.json > resp.json ```
Java
UTF-8
821
3.34375
3
[]
no_license
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); for(int t = 1; t <= tc; t++) { int N = sc.nextInt(); int K = sc.nextInt(); Vector<Integer> v = new Vector<>(); for(int i = 1; i <= N; i++) v.add(i); for(int i = 0; i < K; i++) { int num = sc.nextInt(); if(v.contains(num)) { int idx = v.indexOf(num); v.remove(idx); } } String res = ""; for(int i : v) res += i + " "; res = res.trim(); System.out.println("#" + t + " " + res); } } }
Java
UTF-8
1,833
2.5
2
[]
no_license
package com.mallon.cardatabase.domain.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Car { public Car() { super(); } public Car(String brand, String model, String colour, String registrationNumber, int year, int price, Owner owner) { super(); this.brand = brand; this.model = model; this.colour = colour; this.registrationNumber = registrationNumber; this.year = year; this.price = price; this.owner = owner; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public String getRegistrationNumber() { return registrationNumber; } public void setRegistrationNumber(String registrationNumber) { this.registrationNumber = registrationNumber; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; private String brand, model, colour, registrationNumber; private int year, price; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "owner") @JsonIgnore private Owner owner; //Getter and setter public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } }
Java
UTF-8
1,388
2.390625
2
[]
no_license
package foo.bar.day01.lab07; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by blvp on 06.04.15. */ public class BenchmarkBeanPostProccessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(final Object bean, String s) throws BeansException { Class<?> clazz = bean.getClass(); return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { if(bean.getClass().getMethod(method.getName(), method.getParameterTypes()).getAnnotation(Benchmark.class) != null){ Object result; long startTime = System.nanoTime(); result = method.invoke(bean); System.out.println("Invocation time: " + (System.nanoTime() - startTime)); return result; } return method.invoke(bean); } }); } @Override public Object postProcessAfterInitialization(Object o, String s) throws BeansException { return o; } }