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
Markdown
UTF-8
2,709
2.578125
3
[]
no_license
## Implementation Working Agreement ### GitHub #### Branching - `master` branch will act as Prod - `dev` branch will act as a staging area - all feature work must be merged to `dev` before `master` - `dev` branch must be fully integrated and tested before merged to `master` - All feature work will be coded up and tested on our individual branches, following the naming convention `dev-author` #### Code Review - Only pushed working, tested code - <em>Keep our branches clean!</em> - Create a Pull Request to `dev` for all completed and tested feature work - Pull Requests must be reviewed by at least one team member other than the author - All comments/concerns left by the reviewer must be addressed/mitigated by the author before the Pull Request can be merged ### Testing - <b><em>Test all the code!</em></b> - Use [`mocha`](https://www.npmjs.com/package/mocha) to test Javascript code - Whenever you fix a bug, write a regression test. A bug fixed without a regression test is almost certainly going to break again in the future. ### React - Follow the [React](https://facebook.github.io/react/docs/react-api.html) style guide ## Styleguide ### File Names `all-lower-case-with-dashes.js` ### Javascript ```javascript "use strict"; // use camelCase when naming objects, functions, and instances var camelCaseVariables = "always user var"; // and always use semi-colons // use PascalCase only when naming constructors or classes class User { constructor(options) { this.name = options.name; } } // capitalize acronyms var capitalizeAcronymns = "HTMLEscapeCharacters and HTTPSServer"; // place 1 space before the leading brace function spaceBeforeLeadingBrace() { console.log("test"); } // place 1 space before the opening parenthesis in control statements if (spaceBetweenOpeningParens) { jobWellDone(); } // no space between argument list and the function name function noSpaceBetweenFunctionAndArguments() {...} // no more than a single space between any two lines fruits.map({ endingBracketsOnSeparateLines: "use double quotes" }); var limitMethodLengthTo20Lines = function(space, after, commas) { var andLimitTabDepthToFiveTabs; }; // use expressive variable names... var goodVariableNames = [ "successReturnToOrRedirect", "onTaskDescriptionChange", ]; // ...and method headers calculateRadioFrequency() {} // use the literal syntax for object creation var obj = {}; var array = []; ``` ### CSS ```cs .all-lower-case-with-dashes { } ``` ### Miscellaneous - No `console.log()` statements in master or any Prod code - Limit line length to 100 characters - Use tabs & always use the correct indentation - Use a single space after the comment token - // comment
Shell
UTF-8
1,017
3.75
4
[]
no_license
#!/bin/bash if [[ $# -lt 3 ]] ; then echo "Usage: $(basename "$0") user hostname_or_ip_address ssh-port" exit 0 fi CONVERT="PLACEHOLDER URL" PREP="PLACEHOLDER URL" echo "Deleting $2 from known_hosts" ssh-keygen -R "[$2]:$3" echo "Sending SSH-key to $2" ssh-copy-id -f $1@$2 -p $3 echo "Installing CHR" ssh -p $3 -o ServerAliveInterval=10 -o ServerAliveCountMax=1 $1@$2 "wget $CONVERT -O ~/make-chr.sh && chmod +x ~/make-chr.sh && ~/make-chr.sh" echo "Now reboot VM using VDS control panel to boot into CHR" read -p "Then press Enter when rebooted" -n1 -s unameOut="$(uname -s)" case "${unameOut}" in Linux*) WAIT='w';; Darwin*) WAIT='i';; *) machine="w" #Like linux I guess esac while ! ping -c 1 -n -$WAIT 1 $2 &> /dev/null do printf "%c" "." done printf "\n%s\n" "$2 is back online" sleep 5 echo "Deleting $2 from known_hosts as key hash has changed" ssh-keygen -R "[$2]:$3" ssh -p $3 $1@$2 "/tool fetch output=file dst-path=prepare.rsc $PREP /import file=prepare.rsc "
Java
UTF-8
15,131
2.203125
2
[]
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 com.activedge.atm.message.persistence; import com.activedge.atm.message.data.MessageData; import com.activedge.atm.util.Util; import com.activedge.atm.web.common.BaseDAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Efe Akpofure * the data access persistence layer for the Message entity * @since 01 Dec 2016 */ public class MessageDAO extends BaseDAO { /** * creates Message Data * @param message - the message data to create * @return Message Data - created Message Data * @throws SQLException - if a database error occurs */ public MessageData createMessage(MessageData message) throws SQLException { long id = -1; String sql = "insert into atm_message values (?,?,?,?,?,?)"; // String updatesql = "update atm_entity set table_id = (table_id + 1) where table_name = ?"; Connection conn= null; try { //message.setSqlToUserId(Util.getDateFromString(message.getToUserId())); conn = getConnection(); id = this.findNextPtid("ATM_MESSAGE"); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setLong(1, id); stmt.setString(2, message.getFromUserId()); stmt.setString(3, message.getToUserId()); // stmt.setString(4, message.getSubject()); stmt.setString(4, message.getMessage()); // stmt.setDate(5, message.getSqlToUserId()); // stmt.setLong(6, message.getVersionId()); stmt.setString(5, message.getStatus()); stmt.setDate(6, message.getCreateDate()); message.setId(id); stmt.execute(); stmt.close(); conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error creating message " + message.getFromUserId() + " error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return message; } // /** * updates Message Data * @param message - the update message * @return MessageData the updated message * @throws SQLException - error if any */ public MessageData updateMessage(MessageData message) throws SQLException { String sql = "update ATM_MESSAGE set from_user_id = ?, to_user_id =?, message = ?, status = ? ," + "create_date = ? where id = ? "; // String updatesql = "update atm_entity set table_id = (table_id + 1) where table_name = ?"; Connection conn= null; try { //message.setSqlToUserId(Util.getDateFromString(message.getToUserId())); conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, message.getFromUserId()); stmt.setString(2, message.getToUserId()); // stmt.setString(3, message.getSubject()); stmt.setString(3, message.getMessage()); // stmt.setDate(4, message.getSqlToUserId()); stmt.setString(4, message.getStatus()); stmt.setDate(5, message.getCreateDate()); stmt.setLong(6, message.getId()); stmt.execute(); stmt.close(); conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error updating message " + message.getFromUserId() + " error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return message; } /** * delete a Message Data * @return * @throws Exception */ public MessageData deleteMessage(MessageData message) throws Exception { String sql = "delete from atm_message where id = ? "; // String updatesql = "update atm_entity set table_id = (table_id + 1) where table_name = ?"; Connection conn= null; try { conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setLong(1, message.getId()); stmt.execute(); stmt.close(); conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error deleting atm_message " + message.getFromUserId() + " error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return message; } /** * creates Message Data * @return * @throws Exception */ public MessageData viewMessage(MessageData pmessage) throws Exception { MessageData message = new MessageData(); //String sql = "select * from atm_message LEFT JOIN atm_user ON atm_message.from_user_id=atm_user.id where id = ? "; String sql = "select a.*, b.login_id from atm_message a, atm_user b where a.from_user_id = b.id and a.id = ?"; Connection conn= null; try { conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setLong(1, pmessage.getId()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { message.setId(rs.getLong("id")); message.setName(rs.getString("login_id")); message.setFromUserId(rs.getString("from_user_id")); message.setToUserId(rs.getString("to_user_id")); // message.setSubject(rs.getString("subject")); message.setMessage(rs.getString("message")); //message.setSqlToUserId(rs.getDate("to_user_id")); message.setCreateDate(rs.getDate("create_date")); // message.setVersionId(rs.getInt("version")); message.setStatus(rs.getString("status")); } stmt.close(); conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error updating message " + message.getFromUserId() + " error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return message; } /** * creates Message Data * @return * @throws java.sql.SQLException * @throws Exception */ public List findAllMessages() throws SQLException { List messages = new ArrayList(); //String sql = "select * from atm_message LEFT JOIN atm_user ON atm_message.from_user_id=atm_user.id"; String sql = "select a.*, b.login_id from atm_message a, atm_user b where a.from_user_id = b.id"; // String updatesql = "update atm_entity set table_id = (table_id + 1) where table_name = ?"; Connection conn= null; try { conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { MessageData message = new MessageData(); message.setId(rs.getLong("id")); message.setName(rs.getString("login_id")); message.setFromUserId(rs.getString("from_user_id")); message.setToUserId(rs.getString("to_user_id")); // message.setSubject(rs.getString("subject")); message.setMessage(rs.getString("message")); // message.setSqlToUserId(rs.getDate("to_user_id")); message.setCreateDate(rs.getDate("create_date")); // message.setVersionId(rs.getInt("version")); message.setStatus(rs.getString("status")); messages.add(message); // if (message.getSqlToUserId() != null) // message.setToUserId(Util.getStringFromDate(message.getSqlToUserId())); // messages.add(message); } rs.close(); stmt.close(); // conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error finding all messages error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return messages; } public List findMessagesByCriteria(MessageData searchCriteria) throws SQLException { List messages = new ArrayList(); //String sql = "select * from atm_message "; //String sql = "select * from atm_message LEFT JOIN atm_user ON atm_message.from_user_id=atm_user.id"; String sql = "select a.*, b.login_id from atm_message a, atm_user b where a.from_user_id = b.id "; String sSQLWhere = ""; if (searchCriteria.getFromUserId() != null && searchCriteria.getFromUserId().trim().length() > 0) { sSQLWhere = addWhereClause(sSQLWhere, " from_user_id = ? "); } if (searchCriteria.getToUserId() != null && searchCriteria.getToUserId().trim().length() > 0) { // sSQLWhere += " message_no = ? "; sSQLWhere = addWhereClause(sSQLWhere, " to_user_id = ? "); } /* if (searchCriteria.getSubject() != null && searchCriteria.getSubject().trim().length() > 0) { sSQLWhere = addWhereClause(sSQLWhere, " subject = ? "); // sSQLWhere += " name = ? "; } */ if (searchCriteria.getMessage() != null && searchCriteria.getMessage().trim().length() > 0) { sSQLWhere = addWhereClause(sSQLWhere, " message = ? "); // sSQLWhere += " name = ? "; } if (searchCriteria.getStatus() != null && searchCriteria.getStatus().trim().length() > 0) { sSQLWhere = addWhereClause(sSQLWhere, " status = ? "); // sSQLWhere += " name = ? "; } if (sSQLWhere != null && sSQLWhere.trim().length()> 0) sql += " AND a." + sSQLWhere; System.out.println("SQL " + sql); Connection conn= null; try { conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); int i =1; if (searchCriteria.getFromUserId() != null && searchCriteria.getFromUserId().trim().length() > 0) { // sSQLWhere += " message_no = ? "; stmt.setString(i++, searchCriteria.getFromUserId()); } if (searchCriteria.getToUserId() != null && searchCriteria.getToUserId().trim().length() > 0) { // sSQLWhere += " message_no = ? "; stmt.setString(i++, searchCriteria.getToUserId()); } /* if (searchCriteria.getSubject() != null && searchCriteria.getSubject().trim().length() > 0) { // sSQLWhere = addWhereClause(sSQLWhere, " name = ? "); stmt.setString(i++, searchCriteria.getSubject()); // sSQLWhere += " name = ? "; } */ if (searchCriteria.getMessage() != null && searchCriteria.getMessage().trim().length() > 0) { stmt.setString(i++, searchCriteria.getMessage()); } if (searchCriteria.getStatus() != null && searchCriteria.getStatus().trim().length() > 0) { stmt.setString(i++, searchCriteria.getStatus()); } ResultSet rs = stmt.executeQuery(); while (rs.next()) { MessageData message = new MessageData(); message.setId(rs.getLong("id")); message.setName(rs.getString("login_id")); message.setFromUserId(rs.getString("from_user_id")); message.setToUserId(rs.getString("to_user_id")); // message.setSubject(rs.getString("subject")); message.setMessage(rs.getString("message")); message.setStatus(rs.getString("status")); message.setCreateDate(rs.getDate("create_date")); messages.add(message); } rs.close(); stmt.close(); // conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("error finding all messages error msg " + ex.getMessage()); Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (Exception ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); throw new SQLException(ex.getMessage()); } finally { try { this.releaseConnection(conn); } catch (SQLException ex) { Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return messages; } }
C++
UTF-8
342
3.3125
3
[]
no_license
#include <iostream> using namespace std; string remDup(string str) { if(str.length() == 0) return ""; char ch = str[0]; string oth = remDup(str.substr(1)); if(ch == oth[0]) return oth; return (ch + oth); } int main() { cout << remDup("aaaaabbbbeeeddddccccc") << endl; return 0; }
Markdown
UTF-8
677
2.609375
3
[]
no_license
--- layout: post title: Codility - CountSemiprimes category: codility --- [RESULT](https://app.codility.com/demo/results/trainingQ6NJRH-F2X) ```java import java.util.*; class Solution { public int solution(int N) { String s = Integer.toBinaryString(N); int longestGap = 0; int gap = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '0') { gap++; } else { if (gap > longestGap) { longestGap = gap; } gap = 0; } } return longestGap; } } ```
SQL
UTF-8
7,082
2.9375
3
[]
no_license
/* SQLyog Ultimate v11.27 (32 bit) MySQL - 5.5.29 : Database - w951_db_zsbus_staffchannel ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`w951_db_zsbus_staffchannel` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `w951_db_zsbus_staffchannel`; /*Table structure for table `zsbus_staffchannel_branch` */ DROP TABLE IF EXISTS `zsbus_staffchannel_branch`; CREATE TABLE `zsbus_staffchannel_branch` ( `branch_id` varchar(32) NOT NULL COMMENT '部门ID', `branch_pid` varchar(32) DEFAULT NULL COMMENT '上级部门', `branch_no` varchar(10) DEFAULT NULL COMMENT '部门编号', `branch_name` varchar(20) DEFAULT NULL COMMENT '部门名称', `branch_manager` varchar(10) DEFAULT NULL COMMENT '部门主管', `branch_summary` varchar(100) DEFAULT NULL COMMENT '部门简介', `branch_phone` varchar(20) DEFAULT NULL COMMENT '部门电话', `branch_email` varchar(20) DEFAULT NULL COMMENT '部门邮箱', `branch_remark` varchar(100) DEFAULT NULL COMMENT '备注', `branch_createname` varchar(10) DEFAULT NULL COMMENT '创建人', `branch_createdate` datetime DEFAULT NULL COMMENT '创建日期', PRIMARY KEY (`branch_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `zsbus_staffchannel_branch` */ insert into `zsbus_staffchannel_branch`(`branch_id`,`branch_pid`,`branch_no`,`branch_name`,`branch_manager`,`branch_summary`,`branch_phone`,`branch_email`,`branch_remark`,`branch_createname`,`branch_createdate`) values ('402881e746416b410146416d283c0001','0','000','全部部门','CEO','','','','','admin','2014-05-28 14:03:31'); /*Table structure for table `zsbus_staffchannel_notice` */ DROP TABLE IF EXISTS `zsbus_staffchannel_notice`; CREATE TABLE `zsbus_staffchannel_notice` ( `notice_id` varchar(32) NOT NULL COMMENT '通知ID', `notice_title` varchar(50) DEFAULT NULL COMMENT '通知标题', `notice_content` text COMMENT '通知内容', `notice_createdate` datetime DEFAULT NULL COMMENT '创建时间', `notice_createname` varchar(20) DEFAULT NULL COMMENT '创建者', PRIMARY KEY (`notice_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `zsbus_staffchannel_notice` */ insert into `zsbus_staffchannel_notice`(`notice_id`,`notice_title`,`notice_content`,`notice_createdate`,`notice_createname`) values ('402881e7463735ba0146374e4356000e','关于端午节放假的通知','<h1 style=\"text-align:center\"><strong><span style=\"color:#FF0000\">关于端午节放假的通知</span></strong></h1>\r\n\r\n<p>&nbsp;&nbsp;&nbsp; 关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知.</p>\r\n\r\n<p>&nbsp;&nbsp;&nbsp; 关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知关于端午节放假的通知.</p>\r\n','2014-05-26 14:53:34','admin'); /*Table structure for table `zsbus_staffchannel_staff` */ DROP TABLE IF EXISTS `zsbus_staffchannel_staff`; CREATE TABLE `zsbus_staffchannel_staff` ( `staff_id` varchar(32) NOT NULL COMMENT '员工ID', `staff_no` varchar(20) DEFAULT NULL COMMENT '员工工号', `staff_password` varchar(20) DEFAULT NULL COMMENT '员工密码', `staff_name` varchar(20) DEFAULT NULL COMMENT '员工姓名', `staff_sex` int(1) DEFAULT NULL COMMENT '员工性别', `staff_birthdate` date DEFAULT NULL COMMENT '员工出生日期', `staff_age` int(11) DEFAULT NULL COMMENT '员工年龄', `staff_entrydate` date DEFAULT NULL COMMENT '员工入职日期', `staff_political` int(1) DEFAULT NULL COMMENT '员工政治面貌', `staff_marriage` int(1) DEFAULT NULL COMMENT '员工婚姻', `staff_departure` varchar(20) DEFAULT NULL COMMENT '员工祖籍', `staff_address` varchar(50) DEFAULT NULL COMMENT '员工住址', `staff_remark` varchar(100) DEFAULT NULL COMMENT '备注', `staff_createname` varchar(10) DEFAULT NULL COMMENT '创建人', `staff_createdate` datetime DEFAULT NULL COMMENT '创建日期', `staff_branch_id` varchar(32) DEFAULT NULL COMMENT '部门ID', PRIMARY KEY (`staff_id`), KEY `staff_branch_id` (`staff_branch_id`), CONSTRAINT `zsbus_staffchannel_staff_ibfk_1` FOREIGN KEY (`staff_branch_id`) REFERENCES `zsbus_staffchannel_branch` (`branch_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `zsbus_staffchannel_staff` */ /*Table structure for table `zsbus_staffchannel_system` */ DROP TABLE IF EXISTS `zsbus_staffchannel_system`; CREATE TABLE `zsbus_staffchannel_system` ( `system_id` varchar(32) NOT NULL COMMENT '制度ID', `system_title` varchar(50) DEFAULT NULL COMMENT '制度标题', `system_content` text COMMENT '制度内容', `system_createdate` datetime DEFAULT NULL COMMENT '创建时间', `system_createname` varchar(20) DEFAULT NULL COMMENT '创建者', PRIMARY KEY (`system_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `zsbus_staffchannel_system` */ insert into `zsbus_staffchannel_system`(`system_id`,`system_title`,`system_content`,`system_createdate`,`system_createname`) values ('402881e7463735ba01463750034b000f','关于考勤制度','<h1 style=\"text-align: center;\"><span style=\"color:#FF0000\"><strong>关于考勤制度</strong></span></h1>\r\n\r\n<p>&nbsp;&nbsp;&nbsp; 关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度。</p>\r\n\r\n<p>&nbsp;&nbsp;&nbsp; 关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度关于考勤制度。</p>\r\n','2014-05-26 14:55:29','admin'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
JavaScript
UTF-8
1,379
2.84375
3
[]
no_license
var csv = require('csv-parser') var fs = require('fs') var data = [] const parseStr = (str) => { if (!str) { return null; } let key = str; if (['\'', '\"'].includes(key[0])) { key = key.slice(1); } if (['\'', '\"'].includes(key[key.length - 1])) { key = key.slice(0, key.length - 1); } if (key.toLowerCase() === 'null') { return null; } if (key.toLowerCase() === 'undefined') { return null; } return key; } const parsed = fs.createWriteStream('./parsed_ratings.sql'); const cleaned = fs.createWriteStream('./cleaned_ratings.sql'); fs.createReadStream('./BX-Book-Ratings.csv') .pipe(csv()) .on('data', function (raw) { const keys = Object.keys(raw)[0].split(';'); const values = Object.values(raw)[0].split(';'); const row = keys.reduce((acc, curr, index) => { acc[parseStr(curr)] = parseStr(values[index]); return acc; }, {}) const formatted = { id: row['User-ID'] ? Number.parseInt(row['User-ID']) : null, isbn: row.ISBN, rating: row['Book-Rating'] ? Number.parseInt(row['Book-Rating']) : null, }; data.push(formatted) parsed.write(`insert into ratings (user_id, isbn, rating) values (${formatted.id}, '${formatted.isbn}', ${formatted.rating});\n`) }) .on('end', function () { // cleanData(data); });
Python
UTF-8
10,354
2.515625
3
[]
no_license
from PyQt4 import QtGui, QtCore import numpy as np from atom_pair import AtomPair from molecule import Molecule import output import molecular_scene import settings TOPB = 1 TOPRB = 2 RIGHTB = 3 BOTTOMRB = 4 BOTTOMB = 5 BOTTOMLB = 6 LEFTB = 7 TOPLB = 8 class Surface(QtGui.QGraphicsItem): def __init__(self, scene): super(Surface, self).__init__(scene=scene) self.size = None self.corner = None self.atom_types = None self.surface_atoms = {} self.selection_atoms = {} self.painting_status = None self.current_atom = 0 self.currently_painting = False @classmethod def create(cls, scene): surface = cls(scene) surface.size = QtCore.QSizeF( settings.layer_size[0] - settings.layer_size[0] % AtomPair.XSIZE, settings.layer_size[1] - settings.layer_size[1] % AtomPair.YSIZE) surface.corner = QtCore.QPointF(0, 0) surface.populate() return surface def matchSize(self, other): """Match the size of other surface.""" self.size = other.size self.corner = other.corner self.populate() def addAtom(self, x, y): """Add a hydrogen pair on to the surface at (x,y).""" if (x, y) not in self.surface_atoms: atom = AtomPair(x, y, self) self.surface_atoms[(x, y)] = atom def addDroppedItem(self, pos, dropped_item): """Add a item dropped in to the scene on to the surface.""" status_bar = self.scene().views()[0].window().statusBar() data_type = dropped_item.data(0, QtCore.Qt.UserRole) data = dropped_item.data(0, QtCore.Qt.UserRole + 1) if data_type == "BLOCK": new_item = data.insert(self) new_item.setPos(pos.x() - pos.x()%AtomPair.XSIZE, pos.y() - pos.y()%AtomPair.YSIZE) elif data_type == "MOLECULE": if self.scene().surface is self: new_item = Molecule(pos.x(), pos.y(), data, self) else: status_bar.showMessage("Molecules can only be added to the surface.", 3000) return if not new_item.resolveCollisions(): self.scene().removeItem(new_item) status_bar.showMessage("Item couldn't be added there.", 3000) elif data_type == "BLOCK": new_item.updateIndexing() def indexAtoms(self): """Add unindexed surface atoms to the index.""" for item in self.childItems(): if isinstance(item, AtomPair): if not (item.x(), item.y()) in self.surface_atoms: self.surface_atoms[item.x(), item.y()] = item def findAtomAt(self, pos): """Return the hydrogen at the given position.""" key = (pos.x() - pos.x()%AtomPair.XSIZE, pos.y() - pos.y()%AtomPair.YSIZE) if key in self.selection_atoms: return self.selection_atoms[key] elif key in self.surface_atoms: return self.surface_atoms[key] else: return None def removeFromIndex(self, rect): """Remove items inside the given rectangle from the selection index.""" xmin = rect.left() + AtomPair.XSIZE - rect.left() % AtomPair.XSIZE xmax = rect.right() - AtomPair.XSIZE ymin = rect.top() + AtomPair.YSIZE - rect.top() % AtomPair.YSIZE ymax = rect.bottom() - AtomPair.YSIZE for x in range(int(xmin), int(xmax), AtomPair.XSIZE): for y in range(int(ymin), int(ymax), AtomPair.YSIZE): del self.selection_atoms[(x, y)] def addToIndex(self, selection): """Add child items of selection to the index.""" for item in selection.childItems(): pos = item.scenePos() self.selection_atoms[(pos.x(), pos.y())] = item def boundingRect(self): """Return the bounding rectangle of the surface.""" return QtCore.QRectF(self.corner - QtCore.QPointF(2, 2), self.size + QtCore.QSizeF(4, 4)) def populate(self): """Fill the surface with hydrogen.""" y = self.top() while y < self.bottom(): x = self.left() while x < self.right(): self.addAtom(x, y) x += AtomPair.XSIZE y += AtomPair.YSIZE def populateVerticalLines(self, xmin, xmax): """Fill the vertical lines between xmin and xmax with hydrogen.""" for x in range(int(xmin), int(xmax) + AtomPair.XSIZE, AtomPair.XSIZE): y = self.top() while y < self.bottom(): self.addAtom(x, y) y += AtomPair.YSIZE def populateHorizontalLines(self, ymin, ymax): """Fill the horizontal lines between ymin and ymax with hydrogen.""" for y in range(int(ymin), int(ymax) + AtomPair.YSIZE, AtomPair.YSIZE): x = self.left() while x < self.right(): self.addAtom(x, y) x += AtomPair.XSIZE def resize(self, pos, border): """Resize the surface by moving given border to the given position.""" self.prepareGeometryChange() old_rect = QtCore.QRectF(self.corner, self.size) if border == LEFTB or border == BOTTOMLB or border == TOPLB: if pos.x() < self.right(): if pos.x() < self.left() - AtomPair.XSIZE: self.setLeft(pos.x() - pos.x() % AtomPair.XSIZE + AtomPair.XSIZE) self.populateVerticalLines(self.left(), old_rect.left()) elif pos.x() > self.left() + AtomPair.XSIZE: self.setLeft(pos.x() - pos.x() % AtomPair.XSIZE) if border == RIGHTB or border == BOTTOMRB or border == TOPRB: if pos.x() > self.left(): if pos.x() < self.right() - AtomPair.XSIZE: self.setRight(pos.x() - pos.x() % AtomPair.XSIZE + AtomPair.XSIZE) elif pos.x() > self.right() + AtomPair.XSIZE: self.setRight(pos.x() - pos.x() % AtomPair.XSIZE) self.populateVerticalLines(old_rect.right(), self.right()) if border == TOPB or border == TOPLB or border == TOPRB: if pos.y() < self.bottom(): if pos.y() < self.top() - AtomPair.YSIZE: self.setTop(pos.y() - pos.y() % AtomPair.YSIZE + AtomPair.YSIZE) self.populateHorizontalLines(self.top(), old_rect.top()) elif pos.y() > self.top() + AtomPair.YSIZE: self.setTop(pos.y() - pos.y() % AtomPair.YSIZE) if border == BOTTOMB or border == BOTTOMLB or border == BOTTOMRB: if pos.y() > self.top(): if pos.y() < self.bottom() - AtomPair.YSIZE: self.setBottom(pos.y() - pos.y() % AtomPair.YSIZE + AtomPair.YSIZE) elif pos.y() > self.bottom() + AtomPair.YSIZE: self.setBottom(pos.y() - pos.y() % AtomPair.YSIZE) self.populateHorizontalLines(old_rect.bottom(), self.bottom()) # Ignore the changes if contacts are outside of the new surface for item in self.childItems(): if not isinstance(item, AtomPair): if not item.onSurface(): self.size = old_rect.size() self.corner = old_rect.topLeft() return False def getOutput(self, result, options): """Get the output information of the surface and its child items.""" for item in self.childItems(): item.getOutput(result, options) return result def getSaveState(self): return SaveSurface(self) def reset(self): pass def addContextActions(self, menu): """Add item specific context actions in to the menu.""" pass def paint(self, painter, options, widget): """Draw the surface.""" painter.setPen(QtGui.QColor(0, 0, 0)) painter.setBrush(QtGui.QColor(48, 48, 122)) painter.drawRect(QtCore.QRectF(self.corner, self.size)) def width(self): """Return the width of the surface.""" return self.size.width() def height(self): """Return the height of the surface.""" return self.size.height() def left(self): """Return the x value of the left border.""" return self.corner.x() def right(self): """Return the x value of the right border.""" return self.corner.x() + self.size.width() def top(self): """Return the y value of the top border.""" return self.corner.y() def bottom(self): """Return the y value of the bottom border.""" return self.corner.y() + self.size.height() def setLeft(self, value): """Set the x value of the left border.""" old_left = self.left() self.corner.setX(value) self.size.setWidth(self.width() - value + old_left) def setRight(self, value): """Set the x value of the right border.""" old_right = self.right() self.size.setWidth(self.width() + value - old_right) def setTop(self, value): """Set the y value of the top border.""" old_top = self.top() self.corner.setY(value) self.size.setHeight(self.height() - value + old_top) def setBottom(self, value): """Set the y value of the bottom border.""" old_bottom = self.bottom() self.size.setHeight(self.height() + value - old_bottom) class SaveSurface(object): def __init__(self, surface): self.x = surface.corner.x() self.y = surface.corner.y() self.width = surface.width() self.height = surface.height() self.atom_types = surface.atom_types self.child_items = [] for child in surface.childItems(): self.child_items.append(child.getSaveState()) def load(self, scene): surface = Surface(scene) surface.corner = QtCore.QPointF(self.x, self.y) surface.size = QtCore.QSizeF(self.width, self.height) surface.atom_types = self.atom_types scene.surface = surface for child in self.child_items: child.load(surface) surface.indexAtoms() return surface
JavaScript
UTF-8
109
3.09375
3
[]
no_license
console.log('good morning'); var age = 23; const name = 'Dominik'; console.log(name); console.log(age);
C++
UTF-8
526
2.765625
3
[]
no_license
#include <iostream> #include <set> using namespace std; using P = pair<int, int>; int main() { int N, M; cin >> N >> M; set<P> requests; for (int i{}; i < M; ++i) { int a, b; cin >> a >> b; requests.insert(P{a, b}); } int ans{1}; P wp{1, N}; for (const auto &r : requests) { P p{max(wp.first, r.first), min(wp.second, r.second)}; if (p.first < p.second) { wp = p; } else { ++ans; wp = r; } } cout << ans << endl; return 0; }
C++
UTF-8
912
2.515625
3
[]
no_license
#include "enemy.h" #include "player.h" #include <QDebug> extern cGame *game; cEnemy::cEnemy() { setPixmap(QPixmap(":/images/enemy.png")); int random_position = rand() % 700; setPos(random_position, 0); QTimer *timer = new QTimer(); QObject::connect(timer,SIGNAL(timeout()),this,SLOT(move())); timer->start(50); } void cEnemy::move() { setPos(x(), y()+2); if (pos().y() > scene()->height()) { scene()->removeItem(this); delete this; qDebug() << "deleted!!"; } QList<QGraphicsItem *> colliding_enemies = collidingItems(); for (int i = 0, n = colliding_enemies.size(); i < n ; ++i) { if (typeid(*(colliding_enemies[i])) == typeid(cPlayer)) { game->health->setHealth(); scene()->removeItem(colliding_enemies[i]); delete colliding_enemies[i]; return; } } }
C
UTF-8
499
3.796875
4
[]
no_license
//A program to calculate x^n/n! where x is a float and n is an integer greater or equal to zero #include<stdio.h> #include<conio.h> void main() { int n,i,fact=1; float x,s,numr=1; printf("Enter a float x and an integer n:"); scanf("%f%d",&x,&n); if(n==0) fact = 1; else { for(i=1;i<=n;i++) { fact*=i; numr*=x; } } s = numr / fact; printf("The result is %f",s); getch(); }
TypeScript
UTF-8
1,984
2.53125
3
[]
no_license
import { Component, OnInit } from '@angular/core'; import { FormGroup , FormControl, Validators, FormArray } from '@angular/forms'; @Component({ selector: 'app-reactiveforms2', templateUrl: './reactiveforms2.component.html', styleUrls: ['./reactiveforms2.component.css'] }) export class Reactiveforms2Component implements OnInit { constructor() { } ngOnInit(): void { // console.log(this.studentForm); } createDepartmentForm(): FormGroup { return new FormGroup({ deptId : new FormControl(), deptName : new FormControl(), deptrole : new FormControl(), }) } studentForm = new FormGroup({ firstName : new FormControl("",[Validators.required]), lastName : new FormControl("",[Validators.required]), email : new FormControl("",[ Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]), address : new FormGroup({ street : new FormControl(), city : new FormControl(), state : new FormControl(), zipcode : new FormControl('789456',[ Validators.required, Validators.minLength(6), Validators.maxLength(6), Validators.pattern('^[0-9]+$') ]) }), department :new FormArray([this.createDepartmentForm()]), }) onSubmit(form){ console.log(form) console.log(form.value) } studForm = new FormGroup({ fullName : new FormControl("",Validators.required), phoneNumber : new FormControl("",Validators.required), address : new FormGroup({ street : new FormControl(""), city : new FormControl(""), zipCode : new FormControl("",[ Validators.required, Validators.maxLength(5), Validators.minLength(5) ]), }) }) onSUbmit(form){ if(form.valid){ alert('Form working'); console.log(form) console.log(form.value) } else alert('Invalid form data'); } }
C++
GB18030
7,727
2.546875
3
[]
no_license
#include "Stdafx.h" #include "Math.h" #include "Resource.h" #include "GoldControl.h" ////////////////////////////////////////////////////////////////////////// //궨 #define CELL_WIDTH 19 //Ԫ #define LESS_WIDTH 70 //С #define SPACE_WIDTH 12 //Ϯ #define BUTTON_WIDTH 0 // #define CONTROL_HEIGHT 50 //ؼ߶ ////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CGoldControl, CWnd) ON_WM_PAINT() ON_WM_LBUTTONUP() ON_WM_RBUTTONUP() ON_WM_SETCURSOR() END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////// //캯 CGoldControl::CGoldControl() { // m_nWidth=0; m_nCellCount=0; m_AppendWidth=0; //ñ m_lMaxGold=0L; memset(m_lGoldCell,0,sizeof(m_lGoldCell)); //Դ HINSTANCE hInstance=AfxGetInstanceHandle(); m_ImageLeft.SetLoadInfo(IDB_USERMONEY_LEFT,hInstance); m_ImageMid.SetLoadInfo(IDB_USERMONEY_MID,hInstance); m_ImageRight.SetLoadInfo(IDB_USERMONEY_RIGHT,hInstance); } // CGoldControl::~CGoldControl() { } //ȡ LONG CGoldControl::GetGold() { LONG lGold=0L; for (LONG i=0;i<CountArray(m_lGoldCell);i++) lGold+=m_lGoldCell[i]*(LONG)pow(10L,i); return lGold; } //ý void CGoldControl::SetGold(LONG lGold) { // if (lGold>m_lMaxGold) lGold=m_lMaxGold; memset(m_lGoldCell,0,sizeof(m_lGoldCell)); //ñ int nIndex=0; while (lGold>0L) { m_lGoldCell[nIndex++]=lGold%10L; lGold/=10L; } //ػ Invalidate(FALSE); return; } //ûע void CGoldControl::SetMaxGold(LONG lMaxGold) { //Чı if (m_lMaxGold==lMaxGold) return; //ñ m_lMaxGold=lMaxGold; if (m_lMaxGold>9999999L) m_lMaxGold=9999999L; memset(m_lGoldCell,0,sizeof(m_lGoldCell)); //㵥Ԫ m_nCellCount=0; while (lMaxGold>0L) { lMaxGold/=10L; m_nCellCount++; } m_nCellCount=__min(CountArray(m_lGoldCell),__max(m_nCellCount,1)); //ý m_AppendWidth=0; m_nWidth=(m_nCellCount+(m_nCellCount-1)/3)*CELL_WIDTH+SPACE_WIDTH*6+BUTTON_WIDTH; if (m_nWidth<LESS_WIDTH) { m_AppendWidth=LESS_WIDTH-m_nWidth; m_nWidth=LESS_WIDTH; } MoveWindow(m_BasicPoint.x-m_nWidth,m_BasicPoint.y-CONTROL_HEIGHT,m_nWidth,CONTROL_HEIGHT); //ػ Invalidate(FALSE); return; } //λ void CGoldControl::SetBasicPoint(int nXPos, int nYPos) { //ñ m_BasicPoint.x=nXPos; m_BasicPoint.y=nYPos; // RectifyControl(); return; } //ؼ void CGoldControl::RectifyControl() { MoveWindow(m_BasicPoint.x-m_nWidth,m_BasicPoint.y-CONTROL_HEIGHT,m_nWidth,CONTROL_HEIGHT); return; } //滭 void CGoldControl::DrawGoldCell(CDC * pDC, int nXPos, int nYPox, LONG lGold) { if (lGold<10L) { TCHAR szBuffer[12]; _snprintf(szBuffer,sizeof(szBuffer),TEXT("%d"),lGold); pDC->TextOut(nXPos,nYPox,szBuffer,lstrlen(szBuffer)); } else { LPCTSTR pszBuffer=TEXT(""); pDC->TextOut(nXPos,nYPox,pszBuffer,lstrlen(pszBuffer)); } return; } //ػ void CGoldControl::OnPaint() { CPaintDC dc(this); //ȡλ CRect ClientRect; GetClientRect(&ClientRect); //ͼ CDC BackFaceDC; CBitmap BufferBmp; BufferBmp.CreateCompatibleBitmap(&dc,ClientRect.Width(),ClientRect.Height()); BackFaceDC.CreateCompatibleDC(&dc); BackFaceDC.SelectObject(&BufferBmp); //Դ CImageHandle ImageMidHandle(&m_ImageMid); CImageHandle ImageLeftHandle(&m_ImageLeft); CImageHandle ImageRightHandle(&m_ImageRight); //滭 m_ImageLeft.BitBlt(BackFaceDC,0,0); m_ImageMid.StretchBlt(BackFaceDC,m_ImageLeft.GetWidth(),0,ClientRect.Width()-m_ImageLeft.GetWidth()-m_ImageRight.GetWidth(),m_ImageMid.GetHeight()); m_ImageRight.BitBlt(BackFaceDC,ClientRect.Width()-m_ImageRight.GetWidth(),0); //(-24,0,0,0,700,0,0,0,134,3,2,1,1,TEXT("_GB2312")); CFont GlodFont; GlodFont.CreateFont(-24,0,0,0,700,0,0,0,134,3,2,1,1,TEXT("")); CFont * pOldFont=BackFaceDC.SelectObject(&GlodFont); // DC BackFaceDC.SetBkMode(TRANSPARENT); BackFaceDC.SetTextColor(RGB(150,150,150)); //滭 int nXExcursion=ClientRect.Width()-SPACE_WIDTH*5-BUTTON_WIDTH; for (int i=0;i<m_nCellCount;i++) { //滭 if ((i!=0)&&(i%3)==0) { nXExcursion-=CELL_WIDTH; DrawGoldCell(&BackFaceDC,nXExcursion,0,10); } //滭 nXExcursion-=CELL_WIDTH; DrawGoldCell(&BackFaceDC,nXExcursion,7,m_lGoldCell[i]); } //Դ BackFaceDC.SelectObject(pOldFont); GlodFont.DeleteObject(); //ʾϢ TCHAR szBuffer[50]; sprintf(szBuffer,TEXT("ࣺ%ld"),m_lMaxGold); BackFaceDC.SetTextColor(RGB(200,200,200)); BackFaceDC.SelectObject(CSkinResourceManager::GetDefaultFont()); BackFaceDC.TextOut(10,31,szBuffer,lstrlen(szBuffer)); //滭 dc.BitBlt(0,0,ClientRect.Width(),ClientRect.Height(),&BackFaceDC,0,0,SRCCOPY); return; } //Ϣ void CGoldControl::OnLButtonUp(UINT nFlags, CPoint point) { // int nViewCellCount=(m_nCellCount-1)/3+m_nCellCount; //λù int nHeadWidth=SPACE_WIDTH+m_AppendWidth; if ((point.y<=2)||(point.y>=26)) return; if ((point.x<=nHeadWidth)||(point.x>=(CELL_WIDTH*nViewCellCount+nHeadWidth))) return; //ť int iCellPos=(nViewCellCount-(point.x-nHeadWidth)/CELL_WIDTH)-1; if ((iCellPos==3)||(iCellPos==7)) return; if (iCellPos>3) iCellPos=iCellPos-(iCellPos-1)/3; // ASSERT((iCellPos>=0)&&(iCellPos<CountArray(m_lGoldCell))); if (m_lGoldCell[iCellPos]!=9L) { LONG lAddGold=(LONG)pow(10L,iCellPos); if ((GetGold()+lAddGold)>m_lMaxGold) return; } //ñ m_lGoldCell[iCellPos]=(m_lGoldCell[iCellPos]+1)%10; //ػ Invalidate(FALSE); return; } //ҼϢ void CGoldControl::OnRButtonUp(UINT nFlags, CPoint point) { // int nViewCellCount=(m_nCellCount-1)/3+m_nCellCount; //λù int nHeadWidth=SPACE_WIDTH+m_AppendWidth; if ((point.y<=2)||(point.y>=26)) return; if ((point.x<=nHeadWidth)||(point.x>=(CELL_WIDTH*nViewCellCount+nHeadWidth))) return; //ť int iCellPos=(nViewCellCount-(point.x-nHeadWidth)/CELL_WIDTH)-1; if ((iCellPos==3)||(iCellPos==7)) return; if (iCellPos>3) iCellPos=iCellPos-(iCellPos-1)/3; // ASSERT((iCellPos>=0)&&(iCellPos<CountArray(m_lGoldCell))); if (m_lGoldCell[iCellPos]==0L) { LONG lAddGold=9L*(LONG)pow(10L,iCellPos); if ((GetGold()+lAddGold)>m_lMaxGold) return; } //ñ m_lGoldCell[iCellPos]=(m_lGoldCell[iCellPos]+9)%10; //ػ Invalidate(FALSE); return; } //ù BOOL CGoldControl::OnSetCursor(CWnd * pWnd, UINT nHitTest, UINT message) { //ȡ POINT point; GetCursorPos(&point); ScreenToClient(&point); //ù int nHeadWidth=SPACE_WIDTH+m_AppendWidth; int nViewCellCount=(m_nCellCount-1)/3+m_nCellCount; if ((point.y>2)&&(point.y<26)&&(point.x>nHeadWidth)&&(point.x<(CELL_WIDTH*nViewCellCount+nHeadWidth))) { int iCellPos=(m_nCellCount-(point.x-nHeadWidth)/CELL_WIDTH); if ((iCellPos!=3)&&(iCellPos!=7)) { SetCursor(LoadCursor(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDC_CARD_CUR))); return TRUE; } } return __super::OnSetCursor(pWnd, nHitTest, message); } //////////////////////////////////////////////////////////////////////////
Java
UTF-8
1,145
2.859375
3
[]
no_license
package entities; import java.util.ArrayList; import org.joda.time.LocalDateTime; public class Event { private String name; private String address; private String place; private ArrayList<LocalDateTime> times; private Venue venue; private EventType type; public Event (String name, String address, String place, ArrayList<LocalDateTime> times, EventType type) { this.name = name; this.address = address; this.place = place; this.times = times; this.type = type; } public Venue getVenue() { return venue; } public void setVenue(Venue venue) { this.venue = venue; } public String getTypeDescription () { if (type == EventType.THEATREDANCE) { return "Teatro-Danza"; } else return "Concierto"; } public ArrayList<LocalDateTime> getTimes() { return times; } public String getPlace() { return place; } public String getName() { return name; } public void setNombre(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Event(String name) { this.name = name; } }
Markdown
UTF-8
587
3.515625
4
[]
no_license
# Function description Complete the Diagonal Difference function in the editor below. It must return an integer representing the absolute diagonal difference. diagonalDifference takes the following parameter: * arr: an array of integers . # Input Format The first line contains a single integer, 'n' , the number of rows and columns in the matrix 'arr'. Each of the next 'n' lines describes a row, arr[i] , and consists of 'n' space-separated integers arr[i][j] . # Output Format Print the absolute difference between the sums of the matrix's two diagonals as a single integer.
Markdown
UTF-8
10,836
2.875
3
[]
no_license
# Date and time picker ## Data binding <hhl-live-editor title="" style="overflow:none" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato"></H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Data binding with undefined date <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker v-model="dato"/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Long Date By adding the property `long-date` you will get the week day name incluted <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker v-model="dato" long-date/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Show seconds By adding the property `show-seconds`. <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker v-model="dato" show-seconds/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Date Picker The property `type` control which type of picker to use.<br> You can select "datetime" (default) "date" or "time" <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" type="date"/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Time Picker The property `type` control which type of picker to use.<br> You can select "datetime" (default) "date" or "time" <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" type="time"/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Hide Icon By adding the property `hide-icon` you will remove the icon. <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" hide-icon/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Prevent closing. By adding the attribute `no-outside-click` you will prevent the popup to close when you click outside the popup. <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" no-outside-click/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Disabled By adding the attribute `disabled` you will disable the dateTime-picker <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" disabled/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Readonly By adding the attribute `readonly` it will be in readonly mode. <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" readonly/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Hint Text You can show a hint text at the bottom of the datepicker by adding `hint-start=""` and `hint-end=""` <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" hint-start="hint-start." hint-end="hint-end."/> </H_date-picker> <H_input readonly :model-value="formatDate(dato)" label="Value"></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; const { dateFormat } = fakeImport; const dato = ref(new Date()); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate } </script> '> </hhl-live-editor> <br> ## Validation Validation by adding `validator=""` <hhl-live-editor title="" htmlCode=' <template> <H_row> <H_date-picker label="Date" v-model="dato" :validator="[v.dateRequired]"/> </H_date-picker> <H_input :model-value="formatDate(dato)" label="Value" ></H_input> </H_row> </template> <script> // import { * as dateFormat } from "components/utils/dateFormat"; // import { validator } from "components/utils/validator"; const { dateFormat, validator } = fakeImport; const v = validator; const dato = ref(); function formatDate(date) { if (date) { return dateFormat.D_01_dec_2021_HHMMSSms(date); } else { return "undefined" } } return { dato, formatDate, v } </script> '> </hhl-live-editor> <br>
Java
UTF-8
3,992
3.03125
3
[]
no_license
package web.server; import http.packet.RequestHttpPacket; import http.packet.ResponseHttpPacket; import routing.Route; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.net.Socket; import java.net.SocketException; import java.util.Arrays; import java.util.List; public class Request implements Runnable { private final Socket s; private final BufferedReader socInput; private final DataOutputStream socOutput; private RequestHttpPacket requestHttpPacket; private ResponseHttpPacket responseHttpPacket; protected Request(Socket s) throws IOException { this.s = s; this.socInput = new BufferedReader(new InputStreamReader(s.getInputStream())); this.socOutput = new DataOutputStream(s.getOutputStream()); /** @param Socket --> Taking socket's class object corresponding to each request */ } public List<String> getPostData() { return requestHttpPacket.getRequestHttpBody(); /** @return --> It returns the Post's request body */ } public String getMethod() { return requestHttpPacket.getRequestMethod(); /** @return --> It returns the HTTP request method */ } private void invokeRouter(String path, String httpMethod) throws Exception { /** @param path --> Endpoint to which the request should be mapped * @param httpMethod --> HTTP request method * * */ //This method is calling the corresponding method of Router class which is written by the user String response = ""; Object router = RouterObject.getRouter(); Method[] methods = router.getClass().getDeclaredMethods(); for(Method method : methods) { //checking @Route annotation is present or not on a method and if present then checking the endpoint of request if (method.isAnnotationPresent(Route.class) && method.getAnnotation(Route.class).value().equals(path)) { //checking the request method is allowed or not if(Arrays.asList(method.getAnnotation(Route.class).method()).contains(httpMethod)) { method.setAccessible(true); response = method.invoke(router,this).toString();// calling the corresponding router's class method } else { response = "Not Allowed"; } break; } } //This method is initializing the response http packet responseHttpPacket = new ResponseHttpPacket(response,ResponseHttpPacket.ContentType.TEXT); } private void getRequest() { //This method is initializing the request http packet and calling the invokeRouter method try { requestHttpPacket = new RequestHttpPacket(socInput); String path = requestHttpPacket.getRequestHttpHeader().get(0).split(" ")[1]; invokeRouter(path,requestHttpPacket.getRequestMethod()); } catch (Exception e) { responseHttpPacket = new ResponseHttpPacket("Error",ResponseHttpPacket.ContentType.TEXT); } } private void sendResponse() throws IOException { //This method method is sending response http packet to the client socOutput.writeBytes(responseHttpPacket.toString()); socOutput.flush(); socOutput.close(); s.close(); } @Override public void run() { // This method is called for each request and send the response to the client for each corresponding request try { getRequest(); sendResponse(); } catch (SocketException ignored){} catch (Exception e) { e.printStackTrace(); } } }
C++
UTF-8
2,886
2.6875
3
[]
no_license
#ifndef Player_h #define Player_h #include <vector> #include <string> #include "Cards.h" #include "Map.h" #include "BidingFacility.h" #include "Army.h" #include "City.h" #include "GameObservers.h" #include "PlayerStrategies.h" #include "GameScore.h" class Strategy; class BidingFacility; class MainGameLoop; using namespace std; class Player : public GameObservers { public: //Constructors/Destructor Player(); Player(string, int, int, int, int, Strategy * str); ~Player(); //Getters string getName(); int* getPlayerNumber(); int* getPlayerCoins(); int* getDayOfBirth(); int* getMonthOfBirth(); int* getYearOfBirth(); double* getPlayerAge(); int* getArmyUnitsLeft(); vector<Card*> getCards(); vector<Node*> getCountries(); vector<City*> getCities(); vector<Map*> getContinents(); vector<Army*> getPlayerArmies(); BidingFacility* getBuildingFacility(); void playerBid(int coins); void toString(); MainGameLoop* getSubject(); int* lastPlayerScore; //Setters void setName(string); void setDayOfBirth(int); void setMonthOfBirth(int); void setYearOfBirth(int); void setPlayerAge(double); void setPlayerCoins(int); void setArmyUnitsLeft(int); void setPlayerBiddingFacility(BidingFacility* bf); void setPlayerScore(int); void setPlayerNumOfArmiesBasedOnSoldiers(int); void setSubject(MainGameLoop* subject, GameScore* gameScore); //Print info of player void printInfo(); //Implemented player methods void addCountry(Node*); void addContinent(Map*); void Bid(int); void BuyCard(int); bool PayCoin(int); void PlaceNewArmies(Node*); void MoveArmies(Node*, Node*); void BuildCity(Node*); void DestroyArmy(Node*, int); int getArmyCount(); int getCardCount(); int getPlayerScore(); int getArmyCountBasedOnSoldiers(); void setAsGreedyComputer(); void setAsModerateComputer(); bool isGreedyComputer(); bool isModerateComputer(); bool isHuman(); void setStrategy(Strategy *); void pickStrategy(); Strategy* getStrategy(); void update(int, int, int); void updatePhase(int, int); void updateGameStats(int); void resetScore(); private: Strategy* strategy; bool GreedyComputer; bool HumanPlayer; bool ModerateComputer; static int* objCounter; string playerName; int* playerNumber; int* dayOfBirth; int* monthOfBirth; int* yearOfBirth; double* playerAge; int* playerCoins; int* citiesLeft; int* armyUnitsLeft; vector<Node*> playerCountries; vector<Card*> playerCards; HandObject* playerHand; BidingFacility* playerBiddingFacility; vector<Army*> playerArmy; vector<City*> playerCities; vector<Map*> playerContinents; int* playerScore; int* playerNumOfArmiesBasedOnSoldiers; MainGameLoop* game; GameScore* score; }; #endif // Player_h
Python
UTF-8
1,848
2.890625
3
[]
no_license
from ai.oop.oop_inheritance import * # Car1 = Car("Gv70", 4, 2400) # Car1.carinfo() # parent = Parent("부모", "공무원") # print(parent.display()) # child01 = Child01("자식", "강사", 49) # child01.childinfo() # stu01 = StudentVO("은영", 25, "anyang", "2017") # print(stu01.stuinfo()) # teacher01 = TeacherVO("섭섭", 49, "seoul", "python") # print(teacher01.teachinfo()) # emp01 = ManagerVO("장호연", 29, "seoul", "hrd") # print(emp01.emptinfo()) # userDate = Mydate() # userDate.setYear() # print(userDate.getYear()) # hiding = HidingClass("홍길동", "교육팀", 100) # print(hiding.name) # print(hiding.dept) # print(hiding.num) # print(hiding.utype) # print(hiding.getDept()) # print(hiding.__getDept()) # 다형성 # stu01 = StudentVO("은영", 25, "anyang", "2017") # teacher01 = TeacherVO("섭섭", 49, "seoul", "python") # emp01 = ManagerVO("장호연", 29, "seoul", "hrd") # # perlist = [] # perlist.append(stu01) # perlist.append(teacher01) # perlist.append(emp01) # for obj in perlist: #version1 # if isinstance(obj, StudentVO): # print(obj.stuinfo()) # elif isinstance(obj, TeacherVO): # print(obj.teachinfo()) # else : # print(obj.emptinfo()) # for obj in perlist: #version2 # print(obj.perinfo()) # account = Account("441-2919-1234", 500000, 0.073) # account.accountInfo() # account.withDraw(600000) # account.deposit(200000) # account.accountinfo() # account.withDraw(600000) # account.accountinfo() # print("현재 잔액의 이자를 포함한 금액") # account.printInterestRate() account = FundAccount("441-2919-1234", 500000, 0.073, "F") account.accountInfo() account.withDraw(600000) account.deposit(200000) account.accountinfo() account.withDraw(600000) account.accountinfo() print("현재 잔액의 이자를 포함한 금액") account.printInterestRate()
Markdown
UTF-8
2,000
3.296875
3
[]
no_license
# Anime JS 라이브러리 사용 ## 타켓 요소 명시 - Anime.js 를 이용해 애니메이션을 제작하려면, `anime()` 함수를 호출하고 그 중에서도 애니메이션 하려는 타깃 엘리먼트와 프로퍼티를 명시할 key-value 쌍으로 함수를 오브젝트에 넘겨주어야 한다. ### CSS 선택자 ```javascript let blue = anime({ targets: ".blue", translateY: 200, }); let redBlue = anime({ targets: ".red, .blue", translateY: 200, }); let even = anime({ targets: ".square:nth-child(even)", translateY: 300, }); ``` ### DOM 노드 선택 ```javascript let special = anime({ targets: document.getElementById("special"), translateY: 200, }); var blue = anime({ targets: document.querySelector(".blue"), translateY: 200, }); ``` - DOM Node나 NodeList를 받은 함수는 Anime.js에서 `targets` key 값을 설정하는 데 사용할 수 있다. ### Object 선택 ```javascript var logEl = document.querySelector(".battery-log"); var battery = { charged: "0%", cycles: 120, }; anime({ targets: battery, charged: "100%", cycles: 130, round: 1, easing: "linear", update: function () { logEl.innerHTML = JSON.stringify(battery); }, }); ``` - 위 코드에서 스캔된 파일 수를 0~1000까지, 전염된 파일 수를 0~8까지 애니메이션 합니다. - 이런 식으로 숫자 값으로만 할 수 있으며 <span style="color:red">영어로 하면 에러가 </span>난다. - 또한 애니메이션이 진행되는 동안 모든 프레임에서 호출되는 update 키에 관한 콜백 함수를 사용했다. - 여기에서 스캔과 전염된 파일의 수를 업데이트 하는데 사용한 것이다. ### Array 선택 - 여러 요소들을 애니메이션 해야 할 때 배열로 명시합니다. ```javascript let multipleAnimation = anime({ targets: [document.querySelectorAll(".blue"), ".red, #special"], translateY: 250, }); ```
Python
UTF-8
2,450
2.734375
3
[ "MIT" ]
permissive
''' MIT License Copyright (c) [2018] Pedro Gil-Jiménez (pedro.gil@uah.es). Universidad de Alcalá. Spain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the TrATVid Software ''' import cv2 import numpy from .Node import RectangleNode from .Trajectory import Trajectory # Create a black image img = numpy.zeros((400,600,3), numpy.uint8) #Create some point nodes p1=RectangleNode(3, 60, 100, 60, 80) p2=RectangleNode(9, 200, 250, 70, 50) p3=RectangleNode(6, 150, 300, 90, 100) p4=RectangleNode(9, 250, 240, 60, 40) p5=RectangleNode(2, 50, 50, 30, 50) p6=RectangleNode(2, 50, 90, 30, 50) t1=Trajectory(p1) print(t1) 'Insert at the end of the list' t1.addNode(p2) print(t1) 'Insert in the middle of the list' t1.addNode(p3) print(t1) 'Replace the last element' t1.addNode(p4) print(t1) 'Insert at the beginning of the list' t1.addNode(p5) print(t1) 'Replace at the beginning og the list' t1.addNode(p6) print(t1) img[:]=(0, 0, 0) t1.drawNode(img) t1.drawPath(img) for i in range(-2,12): print(i) t1.selectNode(i) t1.drawNode(img) cv2.imshow('img', img) cv2.waitKey(0) t1.selectNode(5) t1.deleteNode() print(t1) t1.deleteNode() t1.deleteNode() t1.selectNode(10) t1.deleteNode() print(t1) t1.selectNode(1) t1.deleteNode() print(t1) t1.selectNode(3) t1.deleteNode() print(t1) t1.selectNode(9) t1.deleteNode() print(t1) t1.selectNode(2) t1.deleteNode() print(t1) t1.selectNode(5) t1.deleteNode() print(t1) t1.selectNode(6) t1.deleteNode() print(t1)
JavaScript
UTF-8
1,629
2.796875
3
[]
no_license
// components/popUp/popUp.js // js中使用component来注册组件 /** * json 解读 * component: 自定义组件声明 * usingComponent: {} 可选项用于应用别的组件 * */ Component({ /** * 在组件定义中启用多个slot支持 */ options: { multipleSlots: true }, /** * 组件的属性列表,组件的对外属性,是属性名到属性设置的映射表, * type: 表示属性类型 * value: 表示属性初始值 * observe: 表示属性值被更改时的响应函数 */ properties: { title: { type: String , value: '标题' }, cancelText: { type: String, value: '清除' }, confirmText: { type: String, value: '确认' } }, /** * 私有属性,组件的初始数据,和 properties 一同用于组件的的模板渲染 */ data: { isShow: true }, /** * 组件的方法列表 * 组件的方法,包括事件响应函数和任意的自定义方法 */ methods: { /** * 公有方法: * 隐藏: hidenPop * 显示: showPop */ hidenPop() { this.setData({ isShow: !this.data.isShow }) console.log(this.data.isShow) }, showPop() { this.setData({ isShow: !this.data.isShow }) }, /** * 私有方法 * 自定义组件触发时 需要使用triggerEvent方法,指定事件名、detail对象和事件选项 */ _cancelEvent() { this.triggerEvent("cancelEvent",this.data.isShow) }, _confirmEvent() { this.triggerEvent("confirmEvent") } } })
Markdown
UTF-8
8,462
2.6875
3
[ "MIT" ]
permissive
# Project 7 - Highway Driving Path Planning - Trajectory Generation [![Udacity - Self-Driving Car NanoDegree](https://s3.amazonaws.com/udacity-sdc/github/shield-carnd.svg)](http://www.udacity.com/drive) Overview --- In this project my goal is to safely navigate around a virtual highway with other traffic that is driving +-10 MPH of the 50 MPH speed limit. I will utilize the car's localization and sensor fusion data, there is also a sparse map list of waypoints around the highway. There are several parameters required to successfully pass the project. The car should try to go as close as possible to the 50 MPH speed limit, which means passing slower traffic when possible, note that other cars will try to change lanes too. The car should avoid hitting other cars at all cost as well as driving inside of the marked road lanes at all times, unless going from one lane to another. The car should be able to make one complete loop around the 6,946m (4.32 mile) highway. Since the car is trying to go 50 MPH, it should take a little over 5 minutes to complete 1 loop. Also the car should not experience total acceleration over 10 m/s^2 and jerk that is greater than 10 m/s^3, as this would affect passenger comfort. A detailed list of the projects requiremtns can be found in the project [Rubic](https://review.udacity.com/#!/rubrics/1971/view) ![McLaren](https://github.com/silverwhere/Self-Driving-Car-Nanodegree---Udacity/blob/main/Project%207%20-%20Highway%20Driving%20Path%20Planning/img/mclaren.jpg) [![YouTube](https://github.com/silverwhere/Self-Driving-Car-Nanodegree---Udacity/blob/main/Project%207%20-%20Highway%20Driving%20Path%20Planning/img/YouTube.png)](https://youtu.be/aiAuKvl1UZo) Simulator --- You can download the Term3 Simulator which contains the Path Planning Project from the [releases tab (https://github.com/udacity/self-driving-car-sim/releases/tag/T3_v1.2). To run the simulator on Mac/Linux, first make the binary file executable with the following command: ```shell sudo chmod u+x {simulator_file_name} ``` Dependencies --- * This project requires [C++](https://isocpp.org/) and the following C++ libraries installed: * spline.h * cmake >= 3.5 * All OSes: [click here for installation instructions](https://cmake.org/install/) * make >= 4.1 * Linux: make is installed by default on most Linux distros * Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/) * Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm) * gcc/g++ >= 5.4 * Linux: gcc / g++ is installed by default on most Linux distros * Mac: same deal as make - [install Xcode command line tools]((https://developer.apple.com/xcode/features/) * Windows: recommend using [MinGW](http://www.mingw.org/) * [uWebSockets](https://github.com/uWebSockets/uWebSockets) * Run either `install-mac.sh` or `install-ubuntu.sh`. * If you install from source, checkout to commit `e94b6e1`, i.e. ``` git clone https://github.com/uWebSockets/uWebSockets cd uWebSockets git checkout e94b6e1 `` Map & Localization Data Variables for Sensor Fusion and Localization --- The map of the highway is in `data/highway_map.txt` Each waypoint in the list contains `[x,y,s,dx,dy]` values. `x` and `y` are the waypoint's map coordinate position, the `s` value is the distance along the road to get to that waypoint in meters, the `dx` and `dy` values define the unit normal vector pointing outward of the highway loop. The highway's waypoints loop around so the frenet `s` value, distance along the road, goes from 0 to 6945.554. Here is the data provided from the Simulator to the C++ Program #### Main car's localization Data (No Noise) `x` The car's x position in map coordinates `y` The car's y position in map coordinates `s` The car's s position in frenet coordinates `d` The car's d position in frenet coordinates `yaw` The car's yaw angle in the map `speed` The car's speed in MPH #### Previous path data given to the Planner //Note: Return the previous list but with processed points removed, can be a nice tool to show how far along the path has processed since last time. `previous_path_x` The previous list of x points previously given to the simulator `previous_path_y` The previous list of y points previously given to the simulator #### Previous path's end s and d values `end_path_s` The previous list's last point's frenet s value `end_path_d` The previous list's last point's frenet d value #### Sensor Fusion Data, a list of all other car's attributes on the same side of the road. (No Noise) `sensor_fusion` A 2d vector of cars and then that car's [car's unique ID, car's x position in map coordinates, car's y position in map coordinates, car's x velocity in m/s, car's y velocity in m/s, car's s position in frenet coordinates, car's d position in frenet coordinates. Details --- The car uses a perfect controller and will visit every (x,y) point it recieves in the list every .02 seconds. The units for the (x,y) points are in meters and the spacing of the points determines the speed of the car. The vector going from a point to the next point in the list dictates the angle of the car. Acceleration both in the tangential and normal directions is measured along with the jerk, the rate of change of total Acceleration. The (x,y) point paths that the planner recieves should not have a total acceleration that goes over 10 m/s^2, also the jerk should not go over 50 m/s^3. (NOTE: As this is BETA, these requirements might change. Also currently jerk is over a .02 second interval, it would probably be better to average total acceleration over 1 second and measure jerk from that. There will be some latency between the simulator running and the path planner returning a path, with optimized code usually its not very long maybe just 1-3 time steps. During this delay the simulator will continue using points that it was last given, because of this its a good idea to store the last points you have used so you can have a smooth transition. previous_path_x, and previous_path_y can be helpful for this transition since they show the last points given to the simulator controller with the processed points already removed. You would either return a path that extends this previous path or make sure to create a new path that has a smooth transition with this last path. Results --- My path planner was able to correctly navigate the highway for greater than the requirement of 4.32 miles, being able to both maintain my lane and change lanes correctly, not over accelerate and maintain the desired target speed of 50 MPH. By utilizing a spline from `spline.h` I was able to effectively create a smooth trajectory when changing lanes, which minimized acceleration normal to the vehicle `AccN`. Further, by adding functional safety logic to my path planner I was able to utilize the localization of my vehicle and with sensor fusion the vehicles around me to determine if it was safe to change lanes safely or brake for vehicles ahead to avoid all collisions. While my estimates were conservative at 50 metres for a minimum safe distance for changing lanes; I believe if I was not restricted to acceleration `Acc` < 10 m/s^2 and `Jerk` < 10 m/s^3 I believe I could have lapped the track faster. Remarks --- The project was extremely interesting and I can certainly see my knowledge across the whole nanodegree converging into trajectory generation. As I review videos being performed by one company named [Cruise](https://www.getcruise.com/) I really have a strong understanding of path planning and also an great appreciation of all the details that have to be considered when planning a trajectory. Furthermore, of interest are edge cases, such as dynamic events such as temporary construction on routes utilizing localization data with provided maps. Probably a good reason to consider other alternatives such as SLAM to aid in these events. References --- A really helpful resource for doing this project and creating smooth trajectories was using http://kluge.in-chemnitz.de/opensource/spline/, the spline function is in a single hearder file is really easy to use. I utilized the spline.h library to help fit a smooth curve for my trajectory over a distance with `N` trajectory points evenly spaced to control my vehicles acceleration and velocity. ---
Python
UTF-8
334
4.0625
4
[]
no_license
'''Usando uma estrutura de iteração, codifique um algoritmo que leia 8 bits (um a um) e diga quantos 1s e 0s compõem o byte lido.''' cont = 1 s0 = 0 s1 = 0 while cont <= 8: num = int(input('Digite um bit 1 ou 0: ')) if num == 0: s0 += 1 else: s1 == 1 s1 += 1 cont += 1 print(s1) print(s0)
Python
UTF-8
3,903
2.65625
3
[ "MIT" ]
permissive
""" implement multiclass matrix factorization algorithms for CF data using Stochastic Gradient Descent according to Menon, A.K. and Elkan, C., 2010, December. A log-linear model with latent features for dyadic prediction. In Data Mining (ICDM), 2010 IEEE 10th International Conference on (pp. 364-373). IEEE. [1] """ import numpy as np import cPickle from MultiClassCF import MCCF, softmaxOutput, softmaxGradient class MultiMF(MCCF): def __init__(self): MCCF.__init__(self) self.K = 0 # instantiate hyperparameters self.u = {} self.v = {} self.u_avg = None self.v_avg = None # results storage # self.logfilename = "logs/MultiMF" self.modelconfigurefile = "modelconfigures/MultiMF_config" def set_model_hyperparameters(self, model_hyperparameters): if len(model_hyperparameters) != 1: raise ValueError("number of hyperparameters wrong") self.K = model_hyperparameters[0] def basicInitialize(self): print "No predefined parameters in MultiMF model" def initialize(self, uid, iid, predict = False): ## according to [1] ## if uid not in self.u: if predict: print "user new", uid###test self.u[uid] = self.u_avg else: self.u[uid] = np.random.normal(0.0, self.SCALE, size=self.L * self.K).reshape([self.L, self.K]) if iid not in self.v: if predict: print "item new", iid###test self.v[iid] = self.v_avg else: self.v[iid] = np.random.normal(0.0, self.SCALE, size=self.L * self.K).reshape([self.L, self.K]) return self def update(self, instance): """ update embeddings according to a single instance with SGD instance: [UserId, ItemId, LabelId] """ uid, iid, lid = instance ## calculate update step ## # intermediate # m = np.sum(np.multiply(self.u[uid], self.v[iid]), axis=1) mgrad = softmaxGradient(m, lid) # for u # delt_u = np.transpose(np.multiply(np.transpose(self.v[iid]), mgrad)) # for v # delt_v = np.transpose(np.multiply(np.transpose(self.u[uid]), mgrad)) self.u[uid] += (self.SGDstep * (delt_u - self.lamda * self.u[uid])) self.v[iid] += (self.SGDstep * (delt_v - self.lamda * self.v[iid])) return self def averageEmbedding(self): self.u_avg = np.mean(np.array([u for u in self.u.values()]), axis = 0) self.v_avg = np.mean(np.array([v for v in self.v.values()]), axis = 0) def predict(self, uid, iid, distribution = True): """ predict rating matrix entry given userID and itemID, distribution == True when probability distribution is output """ self.initialize(uid, iid, predict = True) # set avg embeddings for cold-start entries m = np.sum(np.multiply(self.u[uid], self.v[iid]), axis=1) return softmaxOutput(m, distribution=distribution) def modelconfigStore(self, modelconfigurefile = None): if modelconfigurefile is None: modelconfigurefile = self.modelconfigurefile paras = {"u": self.u, "v": self.v, "u_avg": self.u_avg, "v_avg": self.v_avg} with open(modelconfigurefile, "w") as f: cPickle.dump(paras, f) def modelconfigLoad(self, modelconfigurefile = None): if modelconfigurefile is None: modelconfigurefile = self.modelconfigurefile with open(modelconfigurefile, "r") as f: paras = cPickle.load(f) # write to model parameters # self.u = paras["u"] self.v = paras["v"] self.u_avg = paras["u_avg"] self.v_avg = paras["v_avg"] self.L = self.u_avg.shape[0] print "model successfully loaded from " + modelconfigurefile
PHP
UTF-8
1,606
2.640625
3
[]
no_license
<?php namespace App\Model\Entity; use Cake\ORM\Entity; /** * Employe Entity * * @property int $id * @property string $number * @property int $user_id * @property int $position_id * @property int|null $building_id * @property int $civility_id * @property int $language_id * @property string $email * @property string $name * @property string $firstName * @property bool $actif * * @property \App\Model\Entity\User $user * @property \App\Model\Entity\Position $position * @property \App\Model\Entity\Building $building * @property \App\Model\Entity\Civility $civility * @property \App\Model\Entity\Language $language * @property \App\Model\Entity\Formation[] $formations */ class Employe extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * * @var array */ protected $_accessible = [ 'number' => true, 'user_id' => true, 'position_id' => true, 'building_id' => true, 'civility_id' => true, 'language_id' => true, 'email' => true, 'name' => true, 'firstName' => true, 'actif' => true, 'user' => true, 'position' => true, 'building' => true, 'civility' => true, 'language' => true, 'formations' => true, 'files' => true ]; }
C#
UTF-8
1,538
3.328125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; namespace Catalog { /// <summary> /// Add new content to the catalog. /// Determine logic for further manipulation of the content. /// </summary> public interface ICatalog { /// <summary> /// Add current content's title and url to collections of data. /// </summary> /// <param name="content">A specifed content holding information about specific catalog items.</param> void Add(IContent content); /// <summary> /// Finds number instances of the class <see cref="Content"/> by search criteria. /// </summary> /// <param name="title">Determing the searched cirteria.</param> /// <param name="numberOfContentElementsToList">Determing the maximal number of contents to be collected.</param> /// <returns>List of items meeting this criterias. /// If number of founded contetents is lower than the desired number it returns only these which are found.</returns> IEnumerable<IContent> GetListContent(string title, Int32 numberOfContentElementsToList); /// <summary> /// Replace all occurences of urls with new ones. /// </summary> /// <param name="oldUrl">Url to be replaced.</param> /// <param name="newUrl">Url to replace withd.</param> /// <returns>Number of updated items.</returns> Int32 UpdateContent(string oldUrl, string newUrl); } }
Python
UTF-8
1,786
2.984375
3
[]
no_license
import csv,yaml,json import os import logger,utils def _check_format(file_path, content): """ check testcase format if valid """ if not content: # testcase file content is empty err_msg = u"Testcase file content is empty: {}".format(file_path) logger.log_error(err_msg) elif not isinstance(content, (list, dict)): # testcase file content does not match testcase format err_msg = u"Testcase file content format invalid: {}".format(file_path) logger.log_error(err_msg) def load_yaml_file(yaml_file): with open(yaml_file,'r',encoding='utf-8') as stream: yaml_content = yaml.load(stream,Loader=yaml.FullLoader) _check_format(yaml_file, yaml_content) return yaml_content def load_json_file(json_file): with open(json_file, encoding='utf-8') as data_file: try: json_content= json.load(data_file) except Exception as result: logger.log_error(result) _check_format(json_file, json_content) return json_content def load_csv_file(csv_file): csv_content_list = [] with open(csv_file, encoding='utf-8') as data_file: reader = csv.DictReader(data_file) for row in reader: csv_content_list.append(row) return csv_content_list def load_file(file_path): file_suffix = os.path.splitext(file_path)[1].lower() if file_suffix == '.json': return load_json_file(file_path) elif file_suffix in ['.yaml', '.yml']: return load_yaml_file(file_path) elif file_suffix == ".csv": return load_csv_file(file_path) else: err_msg = u"Unsupported file format: {}".format(file_path) logger.log_warning(err_msg) return [] def load_testcase(): pass
SQL
UTF-8
2,705
3.5
4
[]
no_license
CREATE DATABASE GYM USE GYM --CREACION DE TABLAS -------------------------------------------------------------------------------------------------------------------------------------- CREATE TABLE CLIENTES( ID INT NOT NULL, NOMBRE VARCHAR(15), APELLIDO VARCHAR(20), CEDULA VARCHAR(10), SEXO VARCHAR(10), F_NACIMIENTO date, PRIMARY KEY(ID) ) CREATE TABLE SUCURSALES( ID_SUCURSAL INT NOT NULL, NOMBRE_SUCURSAL VARCHAR(30), UBICACION VARCHAR(30) UNIQUE, PRIMARY KEY(ID_SUCURSAL) ) CREATE TABLE PLANES( ID VARCHAR(15) NOT NULL, NOMBRE VARCHAR(15), COD_SUCURSAL INT, COSTO DECIMAL, DESCRIPCION VARCHAR(30), PRIMARY KEY(ID), FOREIGN KEY (COD_SUCURSAL) REFERENCES SUCURSALES(ID_SUCURSAL) ) CREATE TABLE INSCRIPCIONES( NRO_INSCRIPCION INT NOT NULL UNIQUE, FECHA_INSCRIPCION DATE, ID_CLIENTE INT, PLAN_ID VARCHAR(15), INICIO DATE, FIN DATE, DEUDA DECIMAL, DESCRIPCION VARCHAR(40), PRIMARY KEY(NRO_INSCRIPCION), FOREIGN KEY (PLAN_ID) REFERENCES PLANES(ID), FOREIGN KEY (ID_CLIENTE) REFERENCES CLIENTES(ID) ) CREATE TABLE PAGO( COD_INSCRIPCION INT, FECHA DATE, SALDO DECIMAL, DETALLES VARCHAR(30), FOREIGN KEY (COD_INSCRIPCION) REFERENCES INSCRIPCIONES(NRO_INSCRIPCION) ) CREATE TABLE REDES( ID_REDES INT, WHATSAPP VARCHAR(25), FACEBOOK VARCHAR(30), INSTAGRAM VARCHAR(30), CORREO VARCHAR(40), PRIMARY KEY(ID_REDES) ) CREATE TABLE INFO_CONTACTO( ID_CLIENTE INT, TELEFONO VARCHAR(15), TEL_FAMILIAR VARCHAR(15), DIRECCION VARCHAR(40), ID_SOCIAL INT, FOREIGN KEY (ID_CLIENTE) REFERENCES CLIENTES(ID), FOREIGN KEY (ID_SOCIAL) REFERENCES REDES(ID_REDES), ) CREATE TABLE HISTORIAL( ID INT NOT NULL, FECHA DATE, FOREIGN KEY(ID) REFERENCES CLIENTES(ID) ) CREATE TABLE PERFILES( ID_PERFIL INT NOT NULL, ID_CLIENTE INT, ESTATURA VARCHAR(10), PESO_INICIAL VARCHAR(10), PESO_ACTUAL VARCHAR(10), PRIMARY KEY(ID_PERFIL), FOREIGN KEY (ID_CLIENTE) REFERENCES CLIENTES(ID) ) CREATE TABLE LESIONES( ID_PER INT NOT NULL, POSEE_LESIONES VARCHAR(5), NOMBRE_LESION VARCHAR(20), FOREIGN KEY (ID_PER) REFERENCES PERFILES(ID_PERFIL) ) CREATE TABLE LESIONADOS( ID_PERF INT NOT NULL, NOMBRE_LESION VARCHAR(20), DIA DATE, DESCRIPCION VARCHAR(50), FOREIGN KEY (ID_PERF) REFERENCES PERFILES(ID_PERFIL) ) CREATE TABLE USUARIOS( NOMBRE VARCHAR(30) NOT NULL, PASS VARCHAR(50) NOT NULL UNIQUE, CORREO VARCHAR(80) NOT NULL UNIQUE, )
SQL
UTF-8
1,281
3.359375
3
[]
no_license
set serveroutput on set verify off -- The 'spool' command redirects output to a text file. Don't forget to turn it off at the end. -- Also, it will still get the program text, so edit it before using it. spool "C:\users\patricia.obyrne\desktop\students2.js" declare -- The purpose of this program is to produce a script for mongodb in a file: -- -- Set up a cursor to loop through all of the students cursor students is select studentno, studentname, prog_code, stage_code from student; v_student students%rowtype;-- This will hold the current student -- begin -- This program generates a script for entering into MongoDB -- The structure of the mongodb script is: -- Student -- StudentNo as _id -- StudentName -- Prog_code -- Stage_code -- OPEN STUDENTS; LOOP FETCH STUDENTS INTO V_STUDENT; EXIT WHEN STUDENTS%NOTFOUND; -- Start the insert statement for the student dbms_output.PUT('db.student.insert({_id: "'||v_student.studentno||'", studentname: "'|| v_student.studentname||'", prog_code: "'|| v_student.prog_code||'", stage_code: '|| v_student.stage_code); dbms_output.PUT_line('})');--Finish the insert instruction for this student. end loop; close students; --dbms_output.FCLOSE(out_file); end; / spool off;
C
WINDOWS-1252
1,498
4.25
4
[]
no_license
/*****************************************************************/ /* Class: Computer Programming, Fall 2019 */ /* Author: JЦt */ /* ID: 108820008 */ /* Date: 2019.09.18 */ /* Purpose: Input and output a phone number */ /* Change History: log the change history of the program */ /*****************************************************************/ #include<stdio.h> int main() { int i,n; short s_fact=1; int i_fact=1; long l_fact=1; long long ll_fact=1; float f_fact=1; double d_fact=1; long double ld_fact=1; printf("Enter a positive integer: "); scanf("%d",&n); // input a number for(i=1;i<=n;i++) // multiply each variable from 1 to n { s_fact *= (short) i; i_fact *= (int) i; l_fact *= (long) i; ll_fact *= (long long) i; f_fact *= (float) i; d_fact *= (double) i; ld_fact *= (long double) i; } printf("Factorial of %d (short) : %hd\n",n,s_fact); printf("Factorial of %d (int) : %d\n",n,i_fact); printf("Factorial of %d (long) : %ld\n",n,l_fact); printf("Factorial of %d (long long) : %lld\n",n,ll_fact); printf("Factorial of %d (float) : %f\n",n,f_fact); printf("Factorial of %d (double) : %f\n",n,d_fact); printf("Factorial of %d (long double) : %Lf\n",n,ld_fact); // output n! in different types return 0; }
PHP
UTF-8
5,362
2.546875
3
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
<?php namespace Urbem\CoreBundle\Entity\Ldo; /** * AcaoValidada */ class AcaoValidada { /** * PK * @var integer */ private $codAcao; /** * PK * @var string */ private $ano; /** * PK * @var \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK */ private $timestampAcaoDados; /** * PK * @var integer */ private $codRecurso; /** * PK * @var string */ private $exercicioRecurso; /** * @var integer */ private $valor; /** * @var integer */ private $quantidade; /** * @var \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK */ private $timestamp; /** * OneToOne (owning side) * @var \Urbem\CoreBundle\Entity\Ppa\AcaoQuantidade */ private $fkPpaAcaoQuantidade; /** * Constructor */ public function __construct() { $this->timestampAcaoDados = new \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK; $this->timestamp = new \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK; } /** * Set codAcao * * @param integer $codAcao * @return AcaoValidada */ public function setCodAcao($codAcao) { $this->codAcao = $codAcao; return $this; } /** * Get codAcao * * @return integer */ public function getCodAcao() { return $this->codAcao; } /** * Set ano * * @param string $ano * @return AcaoValidada */ public function setAno($ano) { $this->ano = $ano; return $this; } /** * Get ano * * @return string */ public function getAno() { return $this->ano; } /** * Set timestampAcaoDados * * @param \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK $timestampAcaoDados * @return AcaoValidada */ public function setTimestampAcaoDados(\Urbem\CoreBundle\Helper\DateTimeMicrosecondPK $timestampAcaoDados) { $this->timestampAcaoDados = $timestampAcaoDados; return $this; } /** * Get timestampAcaoDados * * @return \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK */ public function getTimestampAcaoDados() { return $this->timestampAcaoDados; } /** * Set codRecurso * * @param integer $codRecurso * @return AcaoValidada */ public function setCodRecurso($codRecurso) { $this->codRecurso = $codRecurso; return $this; } /** * Get codRecurso * * @return integer */ public function getCodRecurso() { return $this->codRecurso; } /** * Set exercicioRecurso * * @param string $exercicioRecurso * @return AcaoValidada */ public function setExercicioRecurso($exercicioRecurso) { $this->exercicioRecurso = $exercicioRecurso; return $this; } /** * Get exercicioRecurso * * @return string */ public function getExercicioRecurso() { return $this->exercicioRecurso; } /** * Set valor * * @param integer $valor * @return AcaoValidada */ public function setValor($valor) { $this->valor = $valor; return $this; } /** * Get valor * * @return integer */ public function getValor() { return $this->valor; } /** * Set quantidade * * @param integer $quantidade * @return AcaoValidada */ public function setQuantidade($quantidade) { $this->quantidade = $quantidade; return $this; } /** * Get quantidade * * @return integer */ public function getQuantidade() { return $this->quantidade; } /** * Set timestamp * * @param \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK $timestamp * @return AcaoValidada */ public function setTimestamp(\Urbem\CoreBundle\Helper\DateTimeMicrosecondPK $timestamp = null) { $this->timestamp = $timestamp; return $this; } /** * Get timestamp * * @return \Urbem\CoreBundle\Helper\DateTimeMicrosecondPK */ public function getTimestamp() { return $this->timestamp; } /** * OneToOne (owning side) * Set PpaAcaoQuantidade * * @param \Urbem\CoreBundle\Entity\Ppa\AcaoQuantidade $fkPpaAcaoQuantidade * @return AcaoValidada */ public function setFkPpaAcaoQuantidade(\Urbem\CoreBundle\Entity\Ppa\AcaoQuantidade $fkPpaAcaoQuantidade) { $this->codAcao = $fkPpaAcaoQuantidade->getCodAcao(); $this->timestampAcaoDados = $fkPpaAcaoQuantidade->getTimestampAcaoDados(); $this->ano = $fkPpaAcaoQuantidade->getAno(); $this->codRecurso = $fkPpaAcaoQuantidade->getCodRecurso(); $this->exercicioRecurso = $fkPpaAcaoQuantidade->getExercicioRecurso(); $this->fkPpaAcaoQuantidade = $fkPpaAcaoQuantidade; return $this; } /** * OneToOne (owning side) * Get fkPpaAcaoQuantidade * * @return \Urbem\CoreBundle\Entity\Ppa\AcaoQuantidade */ public function getFkPpaAcaoQuantidade() { return $this->fkPpaAcaoQuantidade; } }
C++
UTF-8
533
3.265625
3
[]
no_license
//This namespoace is used for logging data into files #include<iostream> #include<fstream> namespace Logger{ std::string filename; std::fstream file; //Name the file with no file type void init(std::string f){ filename = f+".txt"; file.open(f, std::ios::out); } void close(){ file.close(); } void log(std::string s){ file << s; } void logln(std::string s){ file << s << std::endl; } void nl(){ file << " " << std::endl; } std::string getFile(){ return filename; } };
Python
UTF-8
590
3.921875
4
[]
no_license
#Jack Walters #Script to Encrypt a message with a given Caesar Cipher from convert import convert_to_num, convert_to_letter #my helper script def encrypt(msg, shift) : cipher = [encrypt_letter(i.lower(),shift) for i in msg] return ''.join(cipher) def encrypt_letter(letter, shift) : if (letter != " "): return convert_to_letter(convert_to_num(letter) + convert_to_num(shift)) return " " if __name__ == '__main__': msg = input("Enter plaintext you wish to be encrypted: ") shift = input("Enter letter value of Caesar Cipher: ").lower() print("Ciphertext: " + encrypt(msg, shift))
TypeScript
UTF-8
572
2.78125
3
[]
no_license
export interface Task{ text: string; done: boolean; } export interface TaskArr{ task: Task[]; } export interface FieldState{ addNewTask: boolean; } export const OPEN_FIELD = 'OPEN_FIELD'; export const ADD_TASK = 'ADD_TASK'; export const REMOVE_TASK = 'REMOVE_TASK'; interface OpenField { type: typeof OPEN_FIELD; payload: boolean; } interface AddTaskAction { type: typeof ADD_TASK; payload: Task; } interface RemoveTask { type: typeof REMOVE_TASK; payload: Task; } export type ActionTypes = OpenField | AddTaskAction | RemoveTask;
C++
UTF-8
867
2.953125
3
[ "MIT-Modern-Variant" ]
permissive
#include "synch.h" class EventBarrier { public: EventBarrier(); ~EventBarrier(); void Wait(); // 线程等待同步,需要同步的线程调用,调用后等待直到被唤醒,若栅栏是SIGNALED则直接返回 void Signal(); // 由控制栅栏的线程调用,唤醒当前等待的所有线程(广播),自己陷入等待直到线程全部被唤醒,然后重置栅栏状态为UNSIGNALED void Complete(); // 线程唤醒同步,从Wait被唤醒后调用Complete,陷入等待直到所有线程被唤醒 int Waiters(); // 返回当前等待的线程数量 private: int status; // 当前栅栏状态 int waitnum; // 等待线程数量 Lock* lock1; // lock1与signal搭配,线程等待同步 Condition * signal; Lock* lock2; // lock2与complete搭配,线程唤醒同步 Condition * complete; };
Python
UTF-8
2,358
2.734375
3
[]
no_license
#This dataset (#2) will resample billboard songs, and non-billboard songs will come from non-billboard artists #The size of the dataset will be the same as in dataset (#1) import os, random #1509 non #1324 billboard numOfValidationOrTestFilesNon = 151 numOfValidationOrTestFilesBillboard = 133 numOfTrainingFilesNon = 1208 billboardDirectory = '../lyrics/all-billboard' nonBillboardDirectory = '../lyrics/all-non-billboard-artist' billboardDirectoryDestination = '../lyrics/dataset_2/billboard-lyrics' nonBillboardDirectoryDestination = '../lyrics/dataset_2/non-billboard-lyrics' #Billboard for i in range(numOfValidationOrTestFilesBillboard): choosenFile = random.choice(os.listdir(billboardDirectory)) #move file to test folder if choosenFile.endswith(".txt"): print (billboardDirectory + '/' + choosenFile, billboardDirectoryDestination + '/test-set/' + choosenFile) os.rename(billboardDirectory + '/' + choosenFile, billboardDirectoryDestination + '/test-set/' + choosenFile) for j in range(numOfValidationOrTestFilesBillboard): choosenFile = random.choice(os.listdir(billboardDirectory)) if choosenFile.endswith(".txt"): os.rename(billboardDirectory + '/' + choosenFile, billboardDirectoryDestination + '/validation-set/' + choosenFile) for filename in os.listdir(billboardDirectory): if filename.endswith(".txt"): os.rename(billboardDirectory + '/' + filename, billboardDirectoryDestination + '/training-set/' + filename) print ('Done with billboard...') nonbillboard for i in xrange(numOfValidationOrTestFilesNon): choosenFile = random.choice(os.listdir(nonBillboardDirectory)) #move file to test folder if choosenFile.endswith(".txt"): os.rename(nonBillboardDirectory + '/' + choosenFile, nonBillboardDirectoryDestination + '/test-set/' + choosenFile) for j in xrange(numOfValidationOrTestFilesNon): choosenFile = random.choice(os.listdir(nonBillboardDirectory)) if choosenFile.endswith(".txt"): os.rename(nonBillboardDirectory + '/' + choosenFile, nonBillboardDirectoryDestination + '/validation-set/' + choosenFile) for k in xrange(numOfTrainingFilesNon): choosenFile = random.choice(os.listdir(nonBillboardDirectory)) if choosenFile.endswith(".txt"): os.rename(nonBillboardDirectory + '/' + choosenFile, nonBillboardDirectoryDestination + '/training-set/' + choosenFile) print ('Done')
Python
UTF-8
10,520
2.640625
3
[ "MIT" ]
permissive
"""PDB Warnings -------- This module is very specific and not recomended to be used straigth away! Notes ------ contains some translation and reordering scripts for some pdbs. """ def reorder_lines(header: dict, lines: list) -> list: """order_dict = { # charmm_gromos54 "DPPC": { "N": 4, # Choline "C11": 1, "C14": 2, "C15": 3, "C12": 5, "C11": 6, "P": 8, # Phosphate "O32":7, "O33":9, "O34": 10, "O31": 11, "C3": 12, # Glycerol "C2": 13, "O21": 14, "C21": 15, "O22": 16, "C22": 17, "C1": 32, "O11": 33, "C11": 34, "O12": 35, "C12": 36, "C23", "C24",": 18, # Fatty acid chain1 "C25",": 19, "C26",": 20, "C27",": 21, "C28",": 22, "C29",": 23, "C210": 24, "C211": 25, "C212": 26, "C213": 27, "C214": 28, "C215": 29, "C216": 30, "C13": 31, "C14", # Fatty acid chain2 "C15", "C2C": 37, "C16", "C2D": 38, "C17", "C2E": 39, "C18", "C2F": 40, "C19", "C2G": 41, "C110""C2H": 42, "C111""C2I": 43, "C112""C2J": 44, "C113""C2K": 45, "C114""C2L": 46, "C115""C2M": 47, "C116""C2N": 48, "C2O": 49, "C2P": 50}, "SOLV": { "OW":1, "HW1":2, "HW2":3 }} new_lines = ["" for x in range(len(lines))] residue = 0 offset = 0 for index.rst, line in enumerate(lines): res_index = header["resnum"] resname_index = header["resname"] atomname_index = header["atomname"] atomname = line[atomname_index] resname = line[resname_index] if(line[res_index]!=residue): residue = line[res_index] offset = index.rst #int(line[header["atomnum"]])-1 if(resname in order_dict): relativ_pos = order_dict[resname][atomname] new_lines[relativ_pos+offset] = line else: new_lines[offset] = line #print(new_lines[len(new_lines)-1]) return new_lines Args: header (dict): lines (list): """ print("HO") def rename_atom_types(lines, header, in_ff=False, out_ff=False, translation_unknown=False): translation_dict = {} charm_gromos_sel = ["gromos", "charmm"] reverse = 0 if type(in_ff) == bool or type(out_ff) == bool: translation_unknown = True elif in_ff in charm_gromos_sel and out_ff in charm_gromos_sel: if in_ff in "gromos": reverse = 1 translation_dict = { # charmm_gromos54 "DPPC": { "N": "N", # Choline "C13": "C33", "C14": "C34", "C15": "C35", "C12": "C32", "C11": "C31", "P": "P", # Phosphate "O13": "O32", "O14": "O33", "O11": "O34", "O12": "O31", "C1": "C3", # Glycerol "C2": "C2", "O21": "O21", "C21": "C21", "O22": "O22", "C22": "C22", "C3": "C1", "O31": "O11", "C31": "C11", "O32": "O12", "C32": "C12", "C23": "C23", # Fatty acid chain1 "C24": "C24", "C25": "C25", "C26": "C26", "C27": "C27", "C28": "C28", "C29": "C29", "C210": "C210", "C211": "C211", "C212": "C212", "C213": "C213", "C214": "C214", "C215": "C215", "C216": "C216", # Fatty acid chain2 "C33": "C13", "C34": "C14", "C35": "C15", "C36": "C16", "C37": "C17", "C38": "C18", "C39": "C19", "C310": "C110", "C311": "C111", "C312": "C112", "C313": "C113", "C314": "C114", "C315": "C115", "C316": "C116", }, "SOLV": {"OH2": "OW", "H1": "HW1", "H2": "HW2"}, "POT": {"POT": "NA"}, # dirty HACK! "NA": {"NA": "NA"}, # dirty HACK! "CLA": {"CLA": "CL"}, } else: print("ops i don't know the in_ff or out_ff") if translation_unknown: index = 1 resnum = 0 for line in lines: atom_name_index = header["atomname"] res_index = header["resname"] if resnum != line[header["resnum"]]: index = 1 resnum = line[header["resnum"]] key_res = line[res_index] key = line[atom_name_index] if key_res == "POT": line[res_index] = "NA+" if key_res == "CLA": line[res_index] = "CL-" atomname = key[0] + str(index) line[atom_name_index] = atomname index += 1 else: if not reverse: for line in lines: index = header["atomname"] res_index = header["resname"] key_res = line[res_index] key = line[index] if key_res == "POT": line[res_index] = "NA+" if key_res == "CLA": line[res_index] = "CL-" line[index] = translation_dict[key_res][key] else: print("not implemented") return lines def consecutivley_renumber(header: dict, lines: list) -> list: new_lines = [] for index, line in enumerate(lines): # print(str(index.rst) + "line:\t"+ str(line)) if isinstance(line, list): line[header["atomnum"]] = int(index) new_lines.append(line) return new_lines def form_columns(header: dict, lines: list) -> list: keys = [ ["key", 6], ["atomnum", 5], ["BLANK", 1], ["atomname", 4], ["altLoc", 1], ["resname", 3], ["BLANK", 1], ["chain", 1], ["resnum", 3], ["insertion", 1], ["BLANK", 2], ["x", 8, 3], ["y", 8, 3], ["z", 8, 3], ["occupancy", 6, 2], ["bfactor", 6, 2], ["BLANK", 7], ["segmentid", 4], ["element", 2], ["charge", 2], ] # get line format column_string = "" index = 0 for key in keys: if key[0] in header: if len(key) == 2: if "key" == key[0]: column_string += "{d[" + str(index) + "]:<" + str(key[1]) + "}" elif "atomname" == key[0]: column_string += "{d[" + str(index) + "]:<" + str(key[1]) + "}" else: column_string += "{d[" + str(index) + "]:>" + str(key[1]) + "}" elif len(key) == 3: column_string += "{d[" + str(index) + "]:>" + str(key[1]) + "." + str(key[2]) + "f}" else: raise Exception("unknown key in form_columns") index += 1 else: column_string += "".join([" " for x in range(key[1])]) column_string += "\n" # format lines new_lines = [] # dev function for floats def isfloat(value): try: float(value) if "." in str(value): return True return False except ValueError: return False for line in lines: data = [float(value) if (isfloat(value)) else str(value) for value in line] new_line = column_string.format(d=data) new_lines.append(new_line) return new_lines def check_ATOM_columns(lines: list) -> (dict, list): keys = ["key", "atomnum", "atomname", "resname", "resnum", "x", "y", "z", "occupancy", "bfactor", "segmentid"] # get sh ortest line - minimal columns lines = [line.split() for line in lines if (line.startswith("ATOM"))] len_lines = list(map(lambda x: len(x), lines)) min_len = min(len_lines) # all lines same length? if min_len * len(lines) != sum(len_lines): print("Not All ATOM lines have the same length!\n taking shortest line to build header!") line = lines[len_lines.index(min_len)] offset_pointer = 0 # check lines - add columns to standard template if min_len > len(keys): # does the line have the minimal number of groups? if len(line[3 + offset_pointer]) == 1: # is there a altloc column? keys.insert(3, "altLoc") offset_pointer += 1 if line[4 + offset_pointer]: # is there a chainID keys.insert(4 + offset_pointer, "chain") offset_pointer += 1 if len(line[5 + offset_pointer]) == 1: # is there an insertion column? keys.insert(5 + offset_pointer, "insertion") if min_len - offset_pointer > 10: if str(line[10]).isdigit(): keys.append("charge") else: keys.append("element") offset_pointer += 1 if min_len - offset_pointer > 11: if str(line[11]).isdigit(): keys.append("charge") else: keys.append("element") offset_pointer += 1 # make a dict pdb_header = {key: ind for ind, key in enumerate(keys)} return pdb_header, lines def read_pdb_simple(path) -> (list, list, list): in_file = open(path, "r") lines = in_file.readlines() header = True footer = False head_lines = [] atom_lines = [] foot_lines = [] for line in lines: if line.startswith("ATOM"): header = False elif not line.startswith("ATOM") and not header: footer = True if header: head_lines.append(line) elif footer: foot_lines.append(line) else: atom_lines.append(line) return head_lines, atom_lines, foot_lines def rename_atom_attribute(pattern: str, replace: str, lines: list) -> list: return [line.replace(pattern, replace) for line in lines if ("ATOM" in line)] def filter_atoms_from_residue(filter_out: str, residue_name: str, lines: list) -> (list, list): filtered_out = list(filter(lambda x: filter_out in x and residue_name in x, lines)) filtered_in = list(filter(lambda x: not (filter_out in x and residue_name in x), lines)) return filtered_in, filtered_out
Markdown
UTF-8
11,483
3.046875
3
[]
no_license
# Парсеры > При отправке данных используются более сложные форматы, чем основанные на простых формах. — Malcom Tredinnick, Django developers group REST framework включает некоторое количество встроенных классов парсеров, которые позволяют принимать запросы различных типов медиа. Также они дают возможность определять ваши собственные парсеры для гибкой настройки типов медиа, которые принимает ваш API. ## Как происходит определение парсера Набор валидных парсеров для представления всегда определяется как список классов. При обращении к `request.data` REST framework исследует заголовок `Content-Type` на наличие входящего запроса и определяет какой парсер использовать для пасрсинга содеражния запроса. Примечание: При разработке клиентских приложений всегда проверяйте наличие заговолока `Content-Type` при отправке данных в HTTP запросе. Если вы не уставновили тип контента, большинство клиентов буду по умолчанию использовать 'application/x-www-form-urlencoded' и возможно это не то, чего бы вы хотели. К примеру, если вы используете json данные с помощью jQuery и метода `.ajax()`, то вы должны удостовериться, что указали настройку `contentType: 'application/json'` ## Установка парсеров По умолчанию набор парсеров можно установить глобально, используя настройку `DEFAULT_PARSER_CLASSES`. Например, следующие настройки делают так, что допускаются лишь запросы, содержащие `JSON`, вместо парсеров по умолчанию, которые допускают как JSON, так и формы. ```python REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) } ``` Вы также можете установить парсеры для индивидуальных представлений или viewset с помощью классов-представлений `APIView` ```python from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): """ Представление, которое может принимать запросы POST с контентом JSON. """ parser_classes = (JSONParser,) def post(self, request, format=None): return Response({'received data': request.data}) ``` Или, если вы используете декоратор `@api_view` с представлениями-функциямим. ```python from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser @api_view(['POST']) @parser_classes((JSONParser,)) def example_view(request, format=None): """ Представление, которое может принимать запросы POST с контентом JSON. """ return Response({'received data': request.data}) ``` # Обращение к API ## JSONParser Парсит контент JSON. **.media_type**: application/json ## FormParser Парсит контент HTML форм. `request.data` будет заполнен данными из `QueryDict`. Предпочтительнее использовать одновременно `FormParser` и `MultiPartParser` для того чтобы обеспечить наиболее полную поддержику данных форм HTML. **.media_type**: `application/x-www-form-urlencoded` ##MultiPartParser Парсит многокомпонентный контент HTML форм, который поддерживает загрузку файлов. Обе `request.data` буду заполнены из `QueryDict`. Предпочтительнее использовать одновременно `FormParser` и `MultiPartParser` для того чтобы обеспечить наиболее полную поддержику данных форм HTML. **.media_type**: `.media_type: multipart/form-data` ## FileUploadParser Парсит необработанный контент. Свойство `request.data` является словарем с единственным ключом 'file', который содержит загруженный файл. Если представление, использующееся с `FileUploadParser` вызывается с аргументом `filename` в ключе URL, то данный аргумент будет использоваться в качестве имени файла. Если оно вызвано без аргумента `filename`, то клиент должен прописать имя файла в загаловке HTTP `Content-Disposition`. Например `Content-Disposition: attachment; filename=upload.jpg.` **.media_type**: */* Замечания: * `FileUploadParser` используется с native клиентом, который может загружать файл в виде необработанных запросов. Для web-based загрузок, или для native клиентов с поддержкой многокомпонентной загрузки, вы должны использовать парсер `MultiPartParser`. * Так как `media_type` парсера согласуется с любым типом контента `FileUploadParser` по большому счету должен быть единственным парсером, установленным на представлении API. * `FileUploadParser` не конфликтует с стандартной настройкой Джанго `FILE_UPLOAD_HANDLERS` и атрибутом `request.upload_handlers`. Для подробностей см [документацию Джанго](https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#upload-handlers). Пример основного использования: ```python # views.py class FileUploadView(views.APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) # urls.py urlpatterns = [ # ... url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view()) ] ``` # Кастомные парсеры Для того, чтобы применить кастомный парсер, вы должны переписать `BaseParser`, установить свойство `.media_type` и применить метод `.parse(self, stream, media_type, parser_context)`. Метод должен возвращать данные, которые заполняют свойство `request.data`. Следующие аргументы передаются `.parse()`: ### stream Потоковый объект, представляющий тело запроса. ### media_type Опционально. При наличии, представляет тип медиа контента входящего запроса. В зависимости от заголовка запроcа`Content-Type`: может включать параметры медиа типов. Например "text/plain; charset=utf-8". ### parser_context Опционально. Если поддерживается, то этот аргумент представляет из себя словарь, содержащий любой дополнительный контекст, который может потребоваться для того, чтобы спарсить запрос. По умочанию содержит следующие ключи: view, request, args, kwargs. ## Пример Ниже следует пример plaintext парсера, который заполняет свойство `request.data` строкой, представляющей тело запроса. ```python class PlainTextParser(BaseParser): """ Plain text parser. """ media_type = 'text/plain' def parse(self, stream, media_type=None, parser_context=None): """ Возвращает строку, представляющую тело запроса. """ return stream.read() ``` ## Сторонние пакеты Доступны следующие сторонние пакеты. ## YAML [REST framework YAML](http://jpadilla.github.io/django-rest-framework-yaml/) поддерживает парсинг YAML и рендеринг. До этого он был установлен в REST framework по умолчанию, а теперь доступен в качестве стороннего пакета. ### Установка и настройка Установка с помощью pip ```python $ pip install djangorestframework-yaml ``` Изменение настроек REST framework ```python REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_yaml.parsers.YAMLParser', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework_yaml.renderers.YAMLRenderer', ), } ``` ## XML [REST Framework XML](http://jpadilla.github.io/django-rest-framework-xml/) поддерживает неформальный формат XML. До этого он был установлен в REST framework по умолчанию, а теперь доступен в качестве стороннего пакета. ### Установка и настройка Установка с помощью pip ```python $ pip install djangorestframework-xml ``` Изменение настроек REST framework ```python REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_xml.parsers.XMLParser', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework_xml.renderers.XMLRenderer', ), } ``` ## MessagePack [MessagePack](https://github.com/juanriaza/django-rest-framework-msgpack) это быстрый и эффектиный бинарный формат сериализации. ## CamelCase JSON [djangorestframework-camel-case](https://github.com/vbabiy/djangorestframework-camel-case) предоставляет camel case рендеры и парсеры для JSON. Это позволит сериализаторам использовать имена полей в подчеркнутом стиле Питона, но при поля будут доступны в API в стиле camel case Javascript.
Java
UTF-8
680
2.015625
2
[]
no_license
package com.yh.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yh.mapper.SelectProjectsByPsIdMapper; import com.yh.pojo.Projects; import com.yh.service.SelectProjectsByPsIdService; /** * 根据公益类型ID查询项目 * @author 陈家亮 * */ @Service public class SelectProjectsByPsIdServiceImpl implements SelectProjectsByPsIdService { @Autowired private SelectProjectsByPsIdMapper SpbMapper; @Override public Projects selectByPstId(Integer psPstId) { Projects selectByPstId = SpbMapper.selectByPstId(psPstId); return selectByPstId; } }
Java
UTF-8
1,573
2.5625
3
[]
no_license
package fr.mmaillot.core.repository.datasource; import com.pkmmte.pkrss.Article; import com.pkmmte.pkrss.parser.Parser; import com.pkmmte.pkrss.parser.Rss2Parser; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.util.List; import fr.mmaillot.core.repository.entity.NewsEntity; import fr.mmaillot.core.repository.entity.mapper.NewsEntityRssMapper; import io.reactivex.Single; /** * Remote store to retrieve RSS news from Website */ public class RemoteNewsStore implements NewsDataStore { private final static String URL = "http://www.geekwire.com/feed/"; private final NewsEntityRssMapper mNewsEntityRssMapper; // Reusable XML Parser private final Parser parser; private final OkHttpClient mHttpClient; public RemoteNewsStore() { mNewsEntityRssMapper = new NewsEntityRssMapper(); parser = new Rss2Parser(); mHttpClient = new OkHttpClient(); } @Override public Single<List<NewsEntity>> news() { return Single.create(e -> { Request request = new Request.Builder() .url(URL) .build(); Response response = mHttpClient.newCall(request).execute(); List<Article> articles = parser.parse(response.body().string()); if (articles != null) { e.onSuccess(mNewsEntityRssMapper.transform(articles)); } else { e.onError(new Exception("Failed to load news from RSS")); } }); } }
Python
UTF-8
4,604
3.6875
4
[]
no_license
def run(): print('***************** B I E N V E N I D O S A L E X A M E N *****************') print("""Cual algoritmo quieres ejecutar: [1]. Algoritmo1Dpl [2]. Algoritmo2Dpl [3]. Algoritmo3Dpl [4]. Algoritmo4Dpl [5]. Algoritmo5Dpl [0]. Salir """) teclado = int(input("> ")) if teclado == 1: algoritmo1Dpl() repetir() if teclado == 2: algoritmo2Dpl() repetir() if teclado == 3: algoritmo3Dpl() repetir() if teclado == 4: algoritmo4Dpl() repetir() if teclado == 5: algoritmo5Dpl() repetir() if teclado == 0: print("Gracias Adios....") else: print("No es una opcion") run() def algoritmo1Dpl(): ## Datos de entrada print("************ Promediador de Notas ************") print("Cuanto saco en la Unidad 1: ") unidad1 = int(input("> ")) print("Cuanto saco en la Unidad 2: ") unidad2 = int(input("> ")) print("Cuanto saco en la Unidad 3: ") unidad3 = int(input("> ")) print("Cuanto saco en la practica Final: ") trabajoFinal = int(input("> ")) ## Linea en blanco print(" ") ## Logica notaFinal = ((unidad1 * 0.10) + (unidad2 * 0.15) + (unidad3 * 0.25) + (trabajoFinal * 0.50)) ## Datos de salida print("La nota final del estudiante es: ", notaFinal) def algoritmo2Dpl(): print("*************** Saca Bono ***************") print("Cuanto es tu salario: ") salario = int(input("> ")) print("Cuanto es tu puntaje: ") puntos = int(input("> ")) ## Logica if puntos >= 50 and puntos <= 100: bono = salario * 0.10 totalC = salario + bono ## Datos de salida print("Tu bono sera de " , bono) print("Total a Cobrar: " , totalC) elif (puntos >= 101 and puntos <= 150) : bono = salario * 0.50 totalC = salario + bono ## Datos de salida print("Tu bono sera de " ,bono) print("Total a Cobrar: " , totalC) elif (puntos >= 151): bono = salario * 0.80 totalC = salario + bono ## Datos de salida print("Tu bono sera de " , bono) print("Total a Cobrar: " , totalC) else: print("No tienes bono....") ## Final y despedida print("Gracias....") def algoritmo3Dpl(): ## Datos de entrada print("************ Determinador de vacuna del Covid19 ************") print("Dime tu nombre: ") nombre = str(input("> ")) print("Marca 1 = Masculino y 0 = Femenino : ") sexo = int(input("> ")) print("Dime tu edad: ") edad = int(input("> ")) ## Logica y datos de salida if (edad > 70): print("Vacuna de tipo [ C ] para " + nombre) elif (edad >= 16 and edad <= 69): if (sexo == 0): print("Vacuna de tipo [ B ] para " + nombre) elif (sexo == 1): print("Vacuna de tipo [ A ] para " + nombre) else: print("error") elif (edad < 16): print("Vacuna de tipo [ A ] para " + nombre) else: print("error.....") ## Final y despedida print("Gracias....") def algoritmo4Dpl(): ## Dato de entrada print("************ Interpretador de Operaciones Aritmeticas ************") print("Que operacion aritmetica aras:\n1. [+]\n2. [-]\n3. [*]\n4. [/]\n5. [^]\n") signo = int(input("> ")) print("Cual es el valor a: ") a = int(input("> ")) print("Cual es el valor b: ") b = int(input("> ")) ## Logica if signo == 1: operacion = a + b elif signo == 2: operacion = a + b elif signo == 3: operacion = a + b elif signo == 4: operacion = a + b elif signo == 5: operacion = a + b else: print("Erorr") print("Es igual a : " , operacion) def algoritmo5Dpl(): ## Datos de entrada print("************ Determinador de salarios especifico de 6 Años ************") print("Cauanto es tu salario: ") salario = int(input("> ")) ## Logica print("Año " + " : " + " Salario") salarioIncremento = salario * 0.10 for i in range(1, 6): salario = salarioIncremento + salario print(i , " : ", salario) print("Gracias....") def repetir(): print(""" """) print("""Deseas volver al menu [1]. Si [2]. No """) decicion = int(input("> ")) if decicion == 1: run() elif decicion == 2: print("Gracias Adios....") else: print("No existe esa opcion") repetir() if __name__ == "__main__": run()
Markdown
UTF-8
1,901
2.78125
3
[ "MIT" ]
permissive
# Ucool - a UI component library based on svelte #### Description Based on the framework of svelte and bulma, a management system based UI component library is implemented, which is convenient for developers to develop. It provides the reference of developer component style and effect, as well as the corresponding usage method, parameter description, etc. at the same time, it also provides the application case display realized by component library components. This system is based on the svelte framework for the management system to provide convenience for the front-end developers UI component library, developers in the component library website, will first arrive at the component page. The component page consists of component category information sidebar, component module list and API information list. Developers can click and select the required components (including basic components, form components, message components, data components, and other components) in the navigation bar. The page will display the corresponding component module list and the corresponding API information list. Developers can view the style and effect of components, relevant instructions, and copy and use the component code in the component module. According to the parameter name, property and calling method provided in the API information list, they can call the component and upload the relevant parameters, so as to realize the use of the component and reduce the workload of developers. In addition, developers can click to enter the case page to browse and operate the common functions (including customer management, order management, marketing personnel management, statistical analysis, etc.) provided by the system for developers. #### Instructions 1. Bulma framework installation and introduction (https://www.npmjs.com/package/bulma) 2. npm i ucool-ui-master #### Contact author 1832723334@qq.com
Java
UTF-8
7,519
2.46875
2
[]
no_license
package de.rwth.i9.palm.feature.researcher; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.text.WordUtils; import de.rwth.i9.palm.model.Author; import de.rwth.i9.palm.model.AuthorSource; import de.rwth.i9.palm.model.Publication; import de.rwth.i9.palm.model.SourceType; public class ResearcherBasicInformationImpl implements ResearcherBasicInformation { @Override public Map<String, Object> getResearcherBasicInformationMap( Author author ) { // researchers list container Map<String, Object> responseMap = new LinkedHashMap<String, Object>(); // if ( author.getPublications() == null || author.getPublications().isEmpty() ) // { // responseMap.put( "count", 0 ); // return responseMap; // } // author data responseMap.put( "author", printAuthorInformation( author ) ); // sources data List<Object> sources = new ArrayList<Object>(); for ( AuthorSource authorSource : author.getAuthorSources() ) { if ( authorSource.getSourceType().equals( SourceType.GOOGLESCHOLAR ) || authorSource.getSourceType().equals( SourceType.CITESEERX ) || authorSource.getSourceType().equals( SourceType.DBLP)) { Map<String, Object> sourceMap = new LinkedHashMap<String, Object>(); String label = "Google Scholar"; if ( authorSource.getSourceType().equals( SourceType.CITESEERX ) ) label = "CiteseerX"; if ( authorSource.getSourceType().equals( SourceType.DBLP ) ) label = "DBLP"; sourceMap.put( "source", label ); sourceMap.put( "url", authorSource.getSourceUrl() ); sources.add( sourceMap ); } } if ( !sources.isEmpty() ) responseMap.put( "sources", sources ); // prepare a list of map object containing year as the key and number of // publication and citation ays value Map<Integer, Object> publicationCitationYearlyMap = new HashMap<Integer, Object>(); // prapare data format for year SimpleDateFormat df = new SimpleDateFormat( "yyyy" ); // get maximum and minimum of year value int minYear = 0, maxYear = 0; // count number of publication and citation per year for ( Publication publication : author.getPublications() ) { // just skip publication without date if ( publication.getPublicationDate() == null ) continue; // get publication year Integer year = Integer.parseInt( df.format( publication.getPublicationDate() ) ); // get year timespan if ( minYear == 0 && maxYear == 0 ) { minYear = year; maxYear = year; } if ( minYear > year ) minYear = year; if ( maxYear < year ) maxYear = year; // check whether the year is available on the map key if ( publicationCitationYearlyMap.get( year ) == null ) { // still not available put new map Map<String, Integer> publicationCitationMap = new LinkedHashMap<String, Integer>(); publicationCitationMap.put( "totalPublication", 1 ); publicationCitationMap.put( "totalCitation", publication.getCitedBy() ); // put into yearly map publicationCitationYearlyMap.put( year, publicationCitationMap ); } else { Map<String, Integer> publicationCitationMap = (Map<String, Integer>) publicationCitationYearlyMap.get( year ); publicationCitationMap.put( "totalPublication", publicationCitationMap.get( "totalPublication" ) + 1 ); publicationCitationMap.put( "totalCitation", publicationCitationMap.get( "totalCitation" ) + publication.getCitedBy() ); } } // put coauthor to responseMap responseMap.put( "yearlyPublicationData", publicationCitationYearlyMap ); // D3 visualization data responseMap.put( "d3data", printYearlyPublicationInformation( publicationCitationYearlyMap, minYear, maxYear ) ); return responseMap; } private List<Object> printYearlyPublicationInformation( Map<Integer, Object> publicationCitationYearlyMap, int minYear, int maxYear ) { if ( minYear == 0 && maxYear == 0 ) { return Collections.emptyList(); } // main list contain 2 map List<Object> visualList = new ArrayList<Object>(); // publication information Map<String, Object> publicationMap = new LinkedHashMap<String, Object>(); publicationMap.put( "key", "Publication" ); publicationMap.put( "bar", true ); List<Object> publicationValues = new ArrayList<Object>(); publicationMap.put( "values", publicationValues ); //Map<String, Object> citationMap = new LinkedHashMap<String, Object>(); //citationMap.put( "key", "Citation" ); //List<Object> citationValues = new ArrayList<Object>(); //citationMap.put( "values", citationValues ); // put into main list visualList.add( publicationMap ); //visualList.add( citationMap ); for ( int i = minYear; i <= maxYear; i++ ) { String string = Integer.toString( i ); DateFormat format = new SimpleDateFormat( "yyyy", Locale.ENGLISH ); Long unixDate = (long) 0; try { Date date = format.parse( string ); unixDate = date.getTime(); } catch ( ParseException e ) { // TODO Auto-generated catch block e.printStackTrace(); } if ( publicationCitationYearlyMap.get( i ) != null ) { @SuppressWarnings( "unchecked" ) Map<String, Integer> publicationCitationMap = (Map<String, Integer>) publicationCitationYearlyMap.get( i ); publicationValues.add( new Object[] { unixDate, publicationCitationMap.get( "totalPublication" ), Integer.toString( i ) } ); // citationValues.add( new Object[] { unixDate, publicationCitationMap.get( "totalCitation" ) } ); } else { publicationValues.add( new Object[] { unixDate, 0 } ); // citationValues.add( new Object[] { unixDate, 0 } ); } } return visualList; } /** * Print researcher data * * @param researcher * @return */ private Map<String, Object> printAuthorInformation( Author researcher ) { Map<String, Object> researcherMap = new LinkedHashMap<String, Object>(); researcherMap.put( "id", researcher.getId() ); researcherMap.put( "name", WordUtils.capitalize( researcher.getName() ) ); if ( researcher.getPhotoUrl() != null ) researcherMap.put( "photo", researcher.getPhotoUrl() ); if ( researcher.getAcademicStatus() != null ) researcherMap.put( "status", researcher.getAcademicStatus() ); if ( researcher.getInstitution() != null ) researcherMap.put( "aff", researcher.getInstitution().getName() ); if ( researcher.getCitedBy() > 0 ) researcherMap.put( "citedBy", researcher.getCitedBy() ); if ( researcher.getPublicationAuthors() != null ) researcherMap.put( "publicationsNumber", researcher.getNoPublication() ); else researcherMap.put( "publicationsNumber", 0 ); if ( researcher.getEmail() != null && researcher.getEmail() != "" ) researcherMap.put( "email", researcher.getEmail() ); if ( researcher.getHomepage() != null && researcher.getHomepage() != "" ) researcherMap.put( "homepage", researcher.getHomepage() ); String otherDetail = ""; if ( researcher.getOtherDetail() != null ) otherDetail += researcher.getOtherDetail(); if ( researcher.getDepartment() != null ) otherDetail += ", " + researcher.getDepartment(); if ( !otherDetail.equals( "" ) ) researcherMap.put( "detail", otherDetail ); researcherMap.put( "isAdded", researcher.isAdded() ); return researcherMap; } }
TypeScript
UTF-8
2,384
2.6875
3
[]
no_license
declare module EVENTSOL { enum ReferenceType { Simple = 0, TotalHappens = 1, OneOrMoreHappens = 2, } interface IReference { type: ReferenceType; } interface IReferenceSimple extends IReference { eventName: string; timesHappens: number; } interface IReferencesTotalHappens extends IReference { references: Array<IReference>; } interface IReferencesOneOrMoreHappens extends IReference { references: Array<IReference>; } class ReferencedEvt extends EnvironmentEvt { private _references; private _times; private _totalTimes; constructor(name: string, status: EnvironmentStatus, type: EnvironmentEvtType, isRepeatable: boolean, callback: Function, reference: IReference, groupName?: string, times?: number, evtsTurnOn?: Array<string>, groupsTurnOn?: Array<string>, evtsTurnOff?: Array<string>, groupsTurnOff?: Array<string>); private registrationEvtSys(action); registerEvtSys(): void; unregisterEvtSys(): void; evtReferenceFired(evt: EnvironmentEvt): void; private turnEvtHelper(turnFunc); turnEvtON(): void; turnEvtOFF(): void; } abstract class Reference { abstract getInvolvedEventsName(): Array<string>; abstract actionsCheck(): boolean; abstract markEvtReferenceFired(name: string): boolean; abstract reset(): void; } abstract class AggregateRef extends Reference { protected _values: Reference[]; constructor(references: Array<IReference>); getInvolvedEventsName(): Array<string>; reset(): void; } class AndRef extends AggregateRef { constructor(data: IReferencesTotalHappens); actionsCheck(): boolean; markEvtReferenceFired(name: string): boolean; } class OrRef extends AggregateRef { constructor(data: IReferencesOneOrMoreHappens); actionsCheck(): boolean; markEvtReferenceFired(name: string): boolean; } class SimpleRef extends Reference { private _eventName; private _times2Fire; private _times; constructor(data: IReferenceSimple); getInvolvedEventsName(): Array<string>; actionsCheck(): boolean; markEvtReferenceFired(name: string): boolean; reset(): void; } }
Markdown
UTF-8
3,617
2.65625
3
[ "MIT" ]
permissive
# Expense Watch Expense Watch is an app to visualize your money go. It allows you to add the expenses as you spend them, and then view them in some cool graphs, so that you can manage money better. ### Features * Gulp jobs for development, building, emulating and running your app * Local development server with live reload, even inside ios emulator * Automatically inject all your JS sources into `index.html` * Auto min-safe all Angular DI through `ng-annotate`, no need to use weird bracket notation ### Installation Clone the repo ```bash git clone https://github.com/sachinb94/expense-watch-app.git ``` Install npm and bower dependencies ```bash npm install && bower install ``` after installation, just run: ```bash gulp ``` to start up the build job and file watchers. ### Set API Set the Server Uri in `app/scripts/config/Constants.js`. Currently the server is hosted at `https://expense-watch.herokuapp.com`. Server code can be cloned from `https://github.com/sachinb94/expense-watch` ## Workflow This doc assumes you have `gulp` globally installed (`npm install -g gulp`). If you do not have / want gulp globally installed, you can run `npm run gulp` instead. #### Development mode By running just `gulp`, we start our development build process, consisting of: - compiling, concatenating, auto-prefixing of all `.scss` files required by `app/styles/main.scss` - creating `vendor.js` file from external sources defined in `./vendor.json` - creating `vendor.css` file from external sources defined in `./vendor-css.json` - linting all `*.js` files `app/scripts`, see `.jshintrc` for ruleset - automatically inject sources into `index.html` so we don't have to add / remove sources manually - build everything into `.tmp` folder (also gitignored) - start local development server and serve from `.tmp` - start watchers to automatically lint javascript source files, compile scss and reload browser on changes #### Build mode By running just `gulp --build` or short `gulp -b`, we start gulp in build mode - concat all `.js` sources into single `app.js` file - version `main.css` and `app.js` - build everything into `www` - remove debugs messages such as `console.log` or `alert` with passing `--release` #### Emulate By running `gulp -e <platform>`, we can run our app in the simulator - <platform> can be either `ios` or `android`, defaults to `ios` - make sure to have iOS Simulator installed in XCode, as well as `ios-sim` package globally installed (`npm install -g ios-sim`) - for Android, [Ripple](http://ripple.incubator.apache.org/) or [Genymotion](https://www.genymotion.com/) seem to be the emulators of choice - It will run the `gulp --build` before, so we have a fresh version to test - In iOS, it will livereload any code changes in iOS simulator #### Emulate a specific iOS device By running `gulp select` you will see a prompt where you can choose which ios device to emulate. This works only when you have the `gulp -e` task running in one terminal window and run `gulp select` in another terminal window. #### Ripple Emulator Run `gulp ripple` to open your app in a browser using ripple. This is useful for emuating a bunch of different Android devices and settings, such as geolocation, battery status, globalization and more. Note that ripple is still in beta and will show weird debug messages from time to time. #### Run By running `gulp -r <platform>`, we can run our app on a connected device - <platform> can be either `ios` or `android`, defaults to `ios` - It will run the `gulp --build` before, so we have a fresh version to test ## License MIT
Java
UTF-8
603
2.015625
2
[]
no_license
package uk.co.vhome.clubbed.svc.enquiryhandler.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import uk.co.vhome.clubbed.svc.enquiryhandler.model.Enquiry; /** * Used to check if an {@link Enquiry} already exists. The naming purposely avoids clashing * with the {@code EntityRepository} bean that is an Axon Repository for persisting the {@code Enquiry} aggregate */ @RepositoryRestResource(exported = false) public interface NonAxonEntityRepository extends JpaRepository<Enquiry, String> { }
Python
UTF-8
1,863
3.671875
4
[]
no_license
"""Q. (Create a program that fulfills the following specification.) Female_Stats.Csv Female Stat Students Import The Female_Stats.Csv File The Data Are From N = 214 Females In Statistics Classes At The University Of California At Davi. Column1 = Student’s Self-Reported Height, Column2 = Student’s Guess At Her Mother’s Height, And Column 3 = Student’s Guess At Her Father’s Height. All Heights Are In Inches. Build A Predictive Model And Conclude If Both Predictors (Independent Variables) Are Significant For A Students’ Height Or Not When Father’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Mother’s Height. When Mother’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Father’s Height. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression as lr """ obj= lr() obj.fit(features,labels) plt.plot(features[:,0],labels, marker='o') plt.scatter(features[:,1],labels, marker='o') ###########YOU CANT PLOT IT################### """ dataset=pd.read_csv("Female_Stats.csv") features = dataset.iloc[:, -2:].values labels = dataset.iloc[:, :-2].values import statsmodels.api as sm features = sm.add_constant(features) features_opt = features[:, :] regressor_OLS = sm.OLS(endog = labels, exog = features_opt) regressor_OLS=regressor_OLS.fit() print(regressor_OLS.summary()) print("\n\tPVALUES are - \nmom - {}\ndad - {}".format(round(regressor_OLS.pvalues[0],2),round(regressor_OLS.pvalues[1],2))) print("Both the factors are affecting equally") #ANS 2 and ANS-3 """see the coefficients only.. they are the answers.. obj= lr() obj.fit(features,labels) x1=obj.predict([[1,66,66]]) x2=obj.predict([[1,67,67]]) x2=x2-x1 x2 """
PHP
UTF-8
48,868
2.78125
3
[]
no_license
<?php /* ** Time of Generation: ** Tue Jul 14 00:43:38 EDT 2015 */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [basics_cats.php] ****** */ /* ****** ****** */ function ATSCKiseqz($x) { return ($x === 0); } function ATSCKisneqz($x) { return ($x !== 0); } /* ****** ****** */ function ATSCKptrisnull($xs) { return ($xs === NULL) ; } function ATSCKptriscons($xs) { return ($xs !== NULL) ; } /* ****** ****** */ function ATSCKpat_int($tmp, $given) { return ($tmp === $given) ; } function ATSCKpat_bool($tmp, $given) { return ($tmp === $given) ; } function ATSCKpat_char($tmp, $given) { return ($tmp === $given) ; } function ATSCKpat_float($tmp, $given) { return ($tmp === $given) ; } /* ****** ****** */ function ATSCKpat_con0($con, $tag) { return ($con === $tag) ; } function ATSCKpat_con1($con, $tag) { return ($con[0] === $tag) ; } /* ****** ****** */ // function ATSINScaseof_fail($errmsg) { fprintf(STDERR, "ATSINScaseof_fail:%s", $errmsg); exit(1); return; } // function ATSINSdeadcode_fail() { fprintf(STDERR, "ATSINSdeadcode_fail"); exit(1); return; } // /* ****** ****** */ function ATSPMVempty() { return; } /* ****** ****** */ /* function ATSPMVlazyval_make (thunk) { return [0, thunk]; } */ /* ****** ****** */ function ATSPMVlazyval_eval (&$lazyval) { // $flag = $lazyval[0]; // if($flag===0) { $lazyval[0] = 1; $thunk = $lazyval[1]; $lazyval[1] = $thunk[0]($thunk); } else { $lazyval[0] = $flag + 1; } // end of [if] // return; // } // end of [ATSPMVlazyval_eval] /* ****** ****** */ function ats2phppre_echo_obj($x) { echo($x); return; } /* ****** ****** */ /* // function ats2phppre_echo0_obj() { return; } function ats2phppre_echo1_obj($x1) { echo($x1); return; } function ats2phppre_echo2_obj($x1, $x2) { echo $x1, $x2; return; } // function ats2phppre_echo3_obj ($x1, $x2, $x3) { echo $x1, $x2, $x3; return; } function ats2phppre_echo4_obj ($x1, $x2, $x3, $x4) { echo $x1, $x2, $x3, $x4; return; } function ats2phppre_echo5_obj ($x1, $x2, $x3, $x4, $x5) { echo $x1, $x2, $x3, $x4, $x5; return; } function ats2phppre_echo6_obj ($x1, $x2, $x3, $x4, $x5, $x6) { echo $x1, $x2, $x3, $x4, $x5, $x6; return; } // function ats2phppre_echo7_obj ($x1, $x2, $x3, $x4, $x5, $x6, $x7) { echo $x1, $x2, $x3, $x4, $x5, $x6, $x7; return; } function ats2phppre_echo8_obj ($x1, $x2, $x3, $x4, $x5, $x6, $x7, $x8) { echo $x1, $x2, $x3, $x4, $x5, $x6, $x7, $x8; return; } // */ /* ****** ****** */ function ats2phppre_print_newline() { ats2phppre_fprint_newline(STDOUT); } function ats2phppre_prerr_newline() { ats2phppre_fprint_newline(STDERR); } function ats2phppre_fprint_newline($out) { fprintf($out, "\n"); fflush($out); return; } /* ****** ****** */ function ats2phppre_lazy2cloref($lazyval) { return $lazyval[1]; } /* ****** ****** */ // function ats2phppre_assert_bool0($tfv) { if (!$tfv) exit("**EXIT**"); return; } function ats2phppre_assert_bool1($tfv) { if (!$tfv) exit("**EXIT**"); return; } // /* ****** ****** */ // function ats2phppre_assert_errmsg_bool0($tfv, $errmsg) { if (!$tfv) { fprintf(STDERR, "%s", $errmsg); exit(errmsg); }; return; } function ats2phppre_assert_errmsg_bool1($tfv, $errmsg) { if (!$tfv) { fprintf(STDERR, "%s", $errmsg); exit(errmsg); }; return; } // /* ****** ****** */ /* end of [basics_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [integer_cats.php] ****** */ /* ****** ****** */ function ats2phppre_abs_int0($x) { return abs($x); } function ats2phppre_neg_int0($x) { return ( -$x ); } /* ****** ****** */ function ats2phppre_succ_int0($x) { return ($x + 1); } function ats2phppre_pred_int0($x) { return ($x - 1); } /* ****** ****** */ function ats2phppre_add_int0_int0($x, $y) { return ($x + $y); } function ats2phppre_sub_int0_int0($x, $y) { return ($x - $y); } function ats2phppre_mul_int0_int0($x, $y) { return ($x * $y); } function ats2phppre_div_int0_int0($x, $y) { return intval($x / $y); } function ats2phppre_mod_int0_int0($x, $y) { return ($x % $y); } /* ****** ****** */ function ats2phppre_add_int1_int1($x, $y) { return ($x + $y); } function ats2phppre_sub_int1_int1($x, $y) { return ($x - $y); } function ats2phppre_mul_int1_int1($x, $y) { return ($x * $y); } function ats2phppre_div_int1_int1($x, $y) { return intval($x / $y); } /* ****** ****** */ function ats2phppre_lt_int0_int0($x, $y) { return ($x < $y); } function ats2phppre_lte_int0_int0($x, $y) { return ($x <= $y); } function ats2phppre_gt_int0_int0($x, $y) { return ($x > $y); } function ats2phppre_gte_int0_int0($x, $y) { return ($x >= $y); } function ats2phppre_eq_int0_int0($x, $y) { return ($x === $y); } function ats2phppre_neq_int0_int0($x, $y) { return ($x !== $y); } /* ****** ****** */ function ats2phppre_lt_int1_int1($x, $y) { return ($x < $y); } function ats2phppre_lte_int1_int1($x, $y) { return ($x <= $y); } function ats2phppre_gt_int1_int1($x, $y) { return ($x > $y); } function ats2phppre_gte_int1_int1($x, $y) { return ($x >= $y); } function ats2phppre_eq_int1_int1($x, $y) { return ($x === $y); } function ats2phppre_neq_int1_int1($x, $y) { return ($x !== $y); } /* ****** ****** */ /* end of [integer_cats.php] */ ?> <?php /* ****** * * HX-2014-11: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [bool_cats.php] ****** */ /* ****** ****** */ /* end of [bool_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [float_cats.php] ****** */ /* ****** ****** */ // function ats2phppre_double2int($x) { return intval($x); } function ats2phppre_int_of_double($x) { return intval($x); } // /* ****** ****** */ // function ats2phppre_int2double($x) { return floatval($x); } function ats2phppre_double_of_int($x) { return floatval($x); } // /* ****** ****** */ function ats2phppre_abs_double($x) { return abs($x); } function ats2phppre_neg_double($x) { return ( -$x ); } /* ****** ****** */ function ats2phppre_succ_double($x) { return ($x + 1); } function ats2phppre_pred_double($x) { return ($x - 1); } /* ****** ****** */ function ats2phppre_add_double_double($x, $y) { return ($x + $y); } function ats2phppre_sub_double_double($x, $y) { return ($x - $y); } function ats2phppre_mul_double_double($x, $y) { return ($x * $y); } function ats2phppre_div_double_double($x, $y) { return ($x / $y); } /* ****** ****** */ function ats2phppre_lt_double_double($x, $y) { return ($x < $y); } function ats2phppre_lte_double_double($x, $y) { return ($x <= $y); } function ats2phppre_gt_double_double($x, $y) { return ($x > $y); } function ats2phppre_gte_double_double($x, $y) { return ($x >= $y); } function ats2phppre_eq_double_double($x, $y) { return ($x === $y); } function ats2phppre_neq_double_double($x, $y) { return ($x !== $y); } /* ****** ****** */ /* end of [float_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [string_cats.php] ****** */ /* ****** ****** */ /* end of [string_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [print_cats.php] ****** */ /* ****** ****** */ // function ats2phppre_print_int($x) { fprintf(STDOUT, "%d", $x); return; } function ats2phppre_prerr_int($x) { fprintf(STDERR, "%d", $x); return; } function ats2phppre_fprint_int ($out, $x) { fprintf($out, "%d", $x); return; } // /* ****** ****** */ // function ats2phppre_print_bool($x) { ats2phppre_fprint_bool(STDOUT, $x); return; } function ats2phppre_prerr_bool($x) { ats2phppre_fprint_bool(STDERR, $x); return; } function ats2phppre_fprint_bool ($out, $x) { if($x) { fprintf($out, "true"); return; } else { fprintf($out, "false"); return; } // end of [if] } // /* ****** ****** */ // function ats2phppre_print_double($x) { fprintf(STDOUT, "%f", $x); return; } function ats2phppre_prerr_double($x) { fprintf(STDERR, "%f", $x); return; } function ats2phppre_fprint_double ($out, $x) { fprintf($out, "%f", $x); return; } // /* ****** ****** */ // function ats2phppre_print_string($x) { fprintf(STDOUT, "%s", $x); return ; } function ats2phppre_prerr_string($x) { fprintf(STDERR, "%s", $x); return ; } function ats2phppre_fprint_string ($out, $x) { fprintf($out, "%s", $x); return ; } // /* ****** ****** */ // function ats2phppre_print_obj($x) { print($x); return; } function ats2phppre_print_r_obj($x) { print_r($x); return; } // /* ****** ****** */ /* end of [print_cats.php] */ ?> <?php /* ****** * * HX-2014-09: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [filebas_cats.php] ****** */ /* ****** ****** */ // /* $ats2phppre_stdin = STDIN; $ats2phppre_stdout = STDOUT; $ats2phppre_stderr = STDERR; */ // /* ****** ****** */ /* end of [filebas_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [PHPref_cats.php] ****** */ /* ****** ****** */ class PHPref { public $value ; // this is the payload } /* end of [class] */ /* ****** ****** */ // function PHPref_new($x0) { $res = new PHPref; $res->value = $x0; return $res; } function PHPref_make_elt($x0) { return PHPref_new($x0); } // /* ****** ****** */ // function PHPref_get_elt($A) { return $A->value ; } // function PHPref_set_elt($A, $x) { $A->value = $x; return ; } // /* ****** ****** */ /* end of [PHPref_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [PHParref_cats.php] ****** */ /* ****** ****** */ // function PHParray_nil() { return array(); } function PHParray_sing($x) { return array($x); } function PHParray_pair($x1, $x2) { return array($x1, $x2); } // /* ****** ****** */ /* end of [PHParray_cats.php] */ ?> <?php /* ****** * * HX-2014-08: * for PHP code * translated from ATS * ****** */ /* ****** * beg of [PHParref_cats.php] ****** */ /* ****** ****** */ class PHParref { public $array ; // this is a PHParray } /* end of [class] */ /* ****** ****** */ // function PHParref_nil() { $res = new PHParref; $res->array = array(); return $res; } // function PHParref_sing($x) { $res = new PHParref; $res->array = array($x); return $res; } // function PHParref_pair($x1, $x2) { $res = new PHParref; $res->array = array($x1, x2); return $res; } // /* ****** ****** */ function PHParref_size($A) { return count($A->array) ; } function PHParref_length($A) { return count($A->array) ; } /* ****** ****** */ // function PHParref_get_at($A, $i) { return $A->array[$i] ; } // function PHParref_set_at($A, $i, $x) { $A->array[$i] = $x; return ; } // /* ****** ****** */ // function PHParref_unset($A, $k) { unset($A->array[$k]); return; } // /* ****** ****** */ // function PHParref_extend($A, $x) { $A->array[] = $x; return; } // /* ****** ****** */ function PHParref_copy ($A) { $A2 = new PHParref; $A2->array = $A->array; return $A2; } /* ****** ****** */ function PHParref_values($A) { $A2 = new PHParref; $A2->array = array_values($A->array); return $A2; } /* ****** ****** */ /* end of [PHParref_cats.php] */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function ats2phppre_list_make_intrange_2($arg0, $arg1) { /* // $tmpret0 */ __patsflab_list_make_intrange_2: $tmpret0 = ats2phppre_list_make_intrange_3($arg0, $arg1, 1); return $tmpret0; } // end-of-function function ats2phppre_list_make_intrange_3($arg0, $arg1, $arg2) { /* // $tmpret1 // $tmp12 // $tmp13 // $tmp14 // $tmp15 // $tmp16 // $tmp17 // $tmp18 // $tmp19 // $tmp20 // $tmp21 // $tmp22 // $tmp23 // $tmp24 // $tmp25 // $tmp26 // $tmp27 // $tmp28 // $tmp29 // $tmp30 // $tmp31 // $tmp32 */ __patsflab_list_make_intrange_3: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab0: $tmp12 = ats2phppre_gt_int0_int0($arg2, 0); if(!ATSCKpat_bool($tmp12, true)) goto __atstmplab1; $tmp13 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp13) { $tmp17 = ats2phppre_sub_int0_int0($arg1, $arg0); $tmp16 = ats2phppre_add_int0_int0($tmp17, $arg2); $tmp15 = ats2phppre_sub_int0_int0($tmp16, 1); $tmp14 = ats2phppre_div_int0_int0($tmp15, $arg2); $tmp20 = ats2phppre_sub_int0_int0($tmp14, 1); $tmp19 = ats2phppre_mul_int0_int0($tmp20, $arg2); $tmp18 = ats2phppre_add_int0_int0($arg0, $tmp19); $tmp21 = null; $tmpret1 = _ats2phppre_list_loop1_2($tmp14, $tmp18, $arg2, $tmp21); } else { $tmpret1 = null; } // endif break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab1: $tmp22 = ats2phppre_lt_int0_int0($arg2, 0); if(!ATSCKpat_bool($tmp22, true)) goto __atstmplab2; $tmp23 = ats2phppre_gt_int0_int0($arg0, $arg1); if($tmp23) { $tmp24 = ats2phppre_neg_int0($arg2); $tmp28 = ats2phppre_sub_int0_int0($arg0, $arg1); $tmp27 = ats2phppre_add_int0_int0($tmp28, $tmp24); $tmp26 = ats2phppre_sub_int0_int0($tmp27, 1); $tmp25 = ats2phppre_div_int0_int0($tmp26, $tmp24); $tmp31 = ats2phppre_sub_int0_int0($tmp25, 1); $tmp30 = ats2phppre_mul_int0_int0($tmp31, $tmp24); $tmp29 = ats2phppre_sub_int0_int0($arg0, $tmp30); $tmp32 = null; $tmpret1 = _ats2phppre_list_loop2_3($tmp25, $tmp29, $tmp24, $tmp32); } else { $tmpret1 = null; } // endif break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab2: $tmpret1 = null; break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret1; } // end-of-function function _ats2phppre_list_loop1_2($arg0, $arg1, $arg2, $arg3) { /* // $apy0 // $apy1 // $apy2 // $apy3 // $tmpret2 // $tmp3 // $tmp4 // $tmp5 // $tmp6 */ __patsflab__ats2phppre_list_loop1_2: $tmp3 = ats2phppre_gt_int0_int0($arg0, 0); if($tmp3) { $tmp4 = ats2phppre_sub_int0_int0($arg0, 1); $tmp5 = ats2phppre_sub_int0_int0($arg1, $arg2); $tmp6 = array($arg1, $arg3); // ATStailcalseq_beg $apy0 = $tmp4; $apy1 = $tmp5; $apy2 = $arg2; $apy3 = $tmp6; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; $arg3 = $apy3; goto __patsflab__ats2phppre_list_loop1_2; // ATStailcalseq_end } else { $tmpret2 = $arg3; } // endif return $tmpret2; } // end-of-function function _ats2phppre_list_loop2_3($arg0, $arg1, $arg2, $arg3) { /* // $apy0 // $apy1 // $apy2 // $apy3 // $tmpret7 // $tmp8 // $tmp9 // $tmp10 // $tmp11 */ __patsflab__ats2phppre_list_loop2_3: $tmp8 = ats2phppre_gt_int0_int0($arg0, 0); if($tmp8) { $tmp9 = ats2phppre_sub_int0_int0($arg0, 1); $tmp10 = ats2phppre_add_int0_int0($arg1, $arg2); $tmp11 = array($arg1, $arg3); // ATStailcalseq_beg $apy0 = $tmp9; $apy1 = $tmp10; $apy2 = $arg2; $apy3 = $tmp11; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; $arg3 = $apy3; goto __patsflab__ats2phppre_list_loop2_3; // ATStailcalseq_end } else { $tmpret7 = $arg3; } // endif return $tmpret7; } // end-of-function function ats2phppre_list_length($arg0) { /* // $tmpret44 */ __patsflab_list_length: $tmpret44 = _ats2phppre_list_loop_10($arg0, 0); return $tmpret44; } // end-of-function function _ats2phppre_list_loop_10($arg0, $arg1) { /* // $apy0 // $apy1 // $tmpret45 // $tmp47 // $tmp48 */ __patsflab__ats2phppre_list_loop_10: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab7: if(ATSCKptriscons($arg0)) goto __atstmplab10; __atstmplab8: $tmpret45 = $arg1; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab9: __atstmplab10: $tmp47 = $arg0[1]; $tmp48 = ats2phppre_add_int1_int1($arg1, 1); // ATStailcalseq_beg $apy0 = $tmp47; $apy1 = $tmp48; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab__ats2phppre_list_loop_10; // ATStailcalseq_end break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret45; } // end-of-function function ats2phppre_list_get_at($arg0, $arg1) { /* // $apy0 // $apy1 // $tmpret49 // $tmp50 // $tmp51 // $tmp52 // $tmp53 */ __patsflab_list_get_at: $tmp50 = ats2phppre_eq_int1_int1($arg1, 0); if($tmp50) { $tmp51 = $arg0[0]; $tmpret49 = $tmp51; } else { $tmp52 = $arg0[1]; $tmp53 = ats2phppre_sub_int1_int1($arg1, 1); // ATStailcalseq_beg $apy0 = $tmp52; $apy1 = $tmp53; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab_list_get_at; // ATStailcalseq_end } // endif return $tmpret49; } // end-of-function function ats2phppre_list_append($arg0, $arg1) { /* // $tmpret54 // $tmp55 // $tmp56 // $tmp57 */ __patsflab_list_append: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab11: if(ATSCKptriscons($arg0)) goto __atstmplab14; __atstmplab12: $tmpret54 = $arg1; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab13: __atstmplab14: $tmp55 = $arg0[0]; $tmp56 = $arg0[1]; $tmp57 = ats2phppre_list_append($tmp56, $arg1); $tmpret54 = array($tmp55, $tmp57); break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret54; } // end-of-function function ats2phppre_list_reverse($arg0) { /* // $tmpret58 // $tmp59 */ __patsflab_list_reverse: $tmp59 = null; $tmpret58 = ats2phppre_list_reverse_append($arg0, $tmp59); return $tmpret58; } // end-of-function function ats2phppre_list_reverse_append($arg0, $arg1) { /* // $tmpret60 */ __patsflab_list_reverse_append: $tmpret60 = _ats2phppre_list_loop_15($arg0, $arg1); return $tmpret60; } // end-of-function function _ats2phppre_list_loop_15($arg0, $arg1) { /* // $apy0 // $apy1 // $tmpret61 // $tmp62 // $tmp63 // $tmp64 */ __patsflab__ats2phppre_list_loop_15: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab15: if(ATSCKptriscons($arg0)) goto __atstmplab18; __atstmplab16: $tmpret61 = $arg1; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab17: __atstmplab18: $tmp62 = $arg0[0]; $tmp63 = $arg0[1]; $tmp64 = array($tmp62, $arg1); // ATStailcalseq_beg $apy0 = $tmp63; $apy1 = $tmp64; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab__ats2phppre_list_loop_15; // ATStailcalseq_end break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret61; } // end-of-function function ats2phppre_list_take($arg0, $arg1) { /* // $tmpret65 // $tmp66 // $tmp67 // $tmp68 // $tmp69 // $tmp70 */ __patsflab_list_take: $tmp66 = ats2phppre_gt_int1_int1($arg1, 0); if($tmp66) { $tmp67 = $arg0[0]; $tmp68 = $arg0[1]; $tmp70 = ats2phppre_sub_int1_int1($arg1, 1); $tmp69 = ats2phppre_list_take($tmp68, $tmp70); $tmpret65 = array($tmp67, $tmp69); } else { $tmpret65 = null; } // endif return $tmpret65; } // end-of-function function ats2phppre_list_drop($arg0, $arg1) { /* // $apy0 // $apy1 // $tmpret71 // $tmp72 // $tmp73 // $tmp74 */ __patsflab_list_drop: $tmp72 = ats2phppre_gt_int1_int1($arg1, 0); if($tmp72) { $tmp73 = $arg0[1]; $tmp74 = ats2phppre_sub_int1_int1($arg1, 1); // ATStailcalseq_beg $apy0 = $tmp73; $apy1 = $tmp74; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab_list_drop; // ATStailcalseq_end } else { $tmpret71 = $arg0; } // endif return $tmpret71; } // end-of-function function ats2phppre_list_split_at($arg0, $arg1) { /* // $tmpret75 // $tmp76 // $tmp77 */ __patsflab_list_split_at: $tmp76 = ats2phppre_list_take($arg0, $arg1); $tmp77 = ats2phppre_list_drop($arg0, $arg1); $tmpret75 = array($tmp76, $tmp77); return $tmpret75; } // end-of-function function ats2phppre_list_insert_at($arg0, $arg1, $arg2) { /* // $tmpret78 // $tmp79 // $tmp80 // $tmp81 // $tmp82 // $tmp83 */ __patsflab_list_insert_at: $tmp79 = ats2phppre_gt_int1_int1($arg1, 0); if($tmp79) { $tmp80 = $arg0[0]; $tmp81 = $arg0[1]; $tmp83 = ats2phppre_sub_int1_int1($arg1, 1); $tmp82 = ats2phppre_list_insert_at($tmp81, $tmp83, $arg2); $tmpret78 = array($tmp80, $tmp82); } else { $tmpret78 = array($arg2, $arg0); } // endif return $tmpret78; } // end-of-function function ats2phppre_list_remove_at($arg0, $arg1) { /* // $tmpret84 // $tmp85 // $tmp86 // $tmp87 // $tmp88 // $tmp89 // $tmp90 // $tmp91 // $tmp92 */ __patsflab_list_remove_at: $tmp85 = $arg0[0]; $tmp86 = $arg0[1]; $tmp87 = ats2phppre_gt_int1_int1($arg1, 0); if($tmp87) { $tmp89 = ats2phppre_sub_int1_int1($arg1, 1); $tmp88 = ats2phppre_list_remove_at($tmp86, $tmp89); $tmp90 = $tmp88[0]; $tmp91 = $tmp88[1]; $tmp92 = array($tmp85, $tmp91); $tmpret84 = array($tmp90, $tmp92); } else { $tmpret84 = array($tmp85, $tmp86); } // endif return $tmpret84; } // end-of-function function ats2phppre_list_app($arg0, $arg1) { /* */ __patsflab_list_app: ats2phppre_list_foreach($arg0, $arg1); return/*_void*/; } // end-of-function function ats2phppre_list_foreach($arg0, $arg1) { /* // $apy0 // $apy1 // $tmp95 // $tmp96 */ __patsflab_list_foreach: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab19: if(ATSCKptriscons($arg0)) goto __atstmplab22; __atstmplab20: // ATSINSmove_void; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab21: __atstmplab22: $tmp95 = $arg0[0]; $tmp96 = $arg0[1]; $arg1[0]($arg1, $tmp95); // ATStailcalseq_beg $apy0 = $tmp96; $apy1 = $arg1; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab_list_foreach; // ATStailcalseq_end break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return/*_void*/; } // end-of-function function ats2phppre_list_map($arg0, $arg1) { /* // $tmpret98 // $tmp99 // $tmp100 // $tmp101 // $tmp102 */ __patsflab_list_map: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab23: if(ATSCKptriscons($arg0)) goto __atstmplab26; __atstmplab24: $tmpret98 = null; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab25: __atstmplab26: $tmp99 = $arg0[0]; $tmp100 = $arg0[1]; $tmp101 = $arg1[0]($arg1, $tmp99); $tmp102 = ats2phppre_list_map($tmp100, $arg1); $tmpret98 = array($tmp101, $tmp102); break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret98; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function ats2phppre_option_is_some($arg0) { /* // $tmpret0 */ __patsflab_option_is_some: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab0: if(ATSCKptrisnull($arg0)) goto __atstmplab3; __atstmplab1: $tmpret0 = true; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab2: __atstmplab3: $tmpret0 = false; break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret0; } // end-of-function function ats2phppre_option_is_none($arg0) { /* // $tmpret1 */ __patsflab_option_is_none: // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab4: if(ATSCKptriscons($arg0)) goto __atstmplab7; __atstmplab5: $tmpret1 = true; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab6: __atstmplab7: $tmpret1 = false; break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret1; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function _ats2jspre_stream_patsfun_1__closurerize($env0, $env1) { return array(function($cenv) { return _ats2jspre_stream_patsfun_1($cenv[1], $cenv[2]); }, $env0, $env1); } function _ats2jspre_stream_patsfun_3__closurerize($env0, $env1) { return array(function($cenv) { return _ats2jspre_stream_patsfun_3($cenv[1], $cenv[2]); }, $env0, $env1); } function _ats2jspre_stream_patsfun_6__closurerize($env0, $env1) { return array(function($cenv) { return _ats2jspre_stream_patsfun_6($cenv[1], $cenv[2]); }, $env0, $env1); } function ats2phppre_stream_map_cloref($arg0, $arg1) { /* // $tmpret0 */ __patsflab_stream_map_cloref: $tmpret0 = array(0, _ats2jspre_stream_patsfun_1__closurerize($arg0, $arg1)); return $tmpret0; } // end-of-function function _ats2jspre_stream_patsfun_1($env0, $env1) { /* // $tmpret1 // $tmp2 // $tmp3 // $tmp4 // $tmp5 // $tmp6 */ __patsflab__ats2jspre_stream_patsfun_1: ATSPMVlazyval_eval($env0); $tmp2 = $env0[1]; // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab0: if(ATSCKptriscons($tmp2)) goto __atstmplab3; __atstmplab1: $tmpret1 = null; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab2: __atstmplab3: $tmp3 = $tmp2[0]; $tmp4 = $tmp2[1]; $tmp5 = $env1[0]($env1, $tmp3); $tmp6 = ats2phppre_stream_map_cloref($tmp4, $env1); $tmpret1 = array($tmp5, $tmp6); break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret1; } // end-of-function function ats2phppre_stream_filter_cloref($arg0, $arg1) { /* // $tmpret7 */ __patsflab_stream_filter_cloref: $tmpret7 = array(0, _ats2jspre_stream_patsfun_3__closurerize($arg0, $arg1)); return $tmpret7; } // end-of-function function _ats2jspre_stream_patsfun_3($env0, $env1) { /* // $tmpret8 // $tmp9 // $tmp10 // $tmp11 // $tmp12 // $tmp13 // $tmp14 */ __patsflab__ats2jspre_stream_patsfun_3: ATSPMVlazyval_eval($env0); $tmp9 = $env0[1]; // ATScaseofseq_beg do { // ATSbranchseq_beg __atstmplab4: if(ATSCKptriscons($tmp9)) goto __atstmplab7; __atstmplab5: $tmpret8 = null; break; // ATSbranchseq_end // ATSbranchseq_beg __atstmplab6: __atstmplab7: $tmp10 = $tmp9[0]; $tmp11 = $tmp9[1]; $tmp12 = $env1[0]($env1, $tmp10); if($tmp12) { $tmp13 = ats2phppre_stream_filter_cloref($tmp11, $env1); $tmpret8 = array($tmp10, $tmp13); } else { $tmp14 = ats2phppre_stream_filter_cloref($tmp11, $env1); ATSPMVlazyval_eval($tmp14); $tmpret8 = $tmp14[1]; } // endif break; // ATSbranchseq_end } while(0); // ATScaseofseq_end return $tmpret8; } // end-of-function function ats2phppre_stream_tabulate_cloref($arg0) { /* // $tmpret15 */ __patsflab_stream_tabulate_cloref: $tmpret15 = _ats2jspre_stream_aux_5($arg0, 0); return $tmpret15; } // end-of-function function _ats2jspre_stream_aux_5($env0, $arg0) { /* // $tmpret16 */ __patsflab__ats2jspre_stream_aux_5: $tmpret16 = array(0, _ats2jspre_stream_patsfun_6__closurerize($env0, $arg0)); return $tmpret16; } // end-of-function function _ats2jspre_stream_patsfun_6($env0, $env1) { /* // $tmpret17 // $tmp18 // $tmp19 // $tmp20 */ __patsflab__ats2jspre_stream_patsfun_6: $tmp18 = $env0[0]($env0, $env1); $tmp20 = ats2phppre_add_int1_int1($env1, 1); $tmp19 = _ats2jspre_stream_aux_5($env0, $tmp20); $tmpret17 = array($tmp18, $tmp19); return $tmpret17; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function _ats2phppre_intrange_patsfun_7__closurerize($env0) { return array(function($cenv, $arg0) { return _ats2phppre_intrange_patsfun_7($cenv[1], $arg0); }, $env0); } function _ats2phppre_intrange_patsfun_9__closurerize($env0) { return array(function($cenv, $arg0) { return _ats2phppre_intrange_patsfun_9($cenv[1], $arg0); }, $env0); } function _ats2phppre_intrange_patsfun_11__closurerize($env0) { return array(function($cenv, $arg0) { return _ats2phppre_intrange_patsfun_11($cenv[1], $arg0); }, $env0); } function _ats2phppre_intrange_patsfun_14__closurerize($env0) { return array(function($cenv, $arg0, $arg1) { return _ats2phppre_intrange_patsfun_14($cenv[1], $arg0, $arg1); }, $env0); } function _ats2phppre_intrange_patsfun_18__closurerize($env0) { return array(function($cenv, $arg0) { return _ats2phppre_intrange_patsfun_18($cenv[1], $arg0); }, $env0); } function _ats2phppre_intrange_patsfun_31__closurerize($env0, $env1) { return array(function($cenv, $arg0, $arg1) { return _ats2phppre_intrange_patsfun_31($cenv[1], $cenv[2], $arg0, $arg1); }, $env0, $env1); } function ats2phppre_int_repeat_lazy($arg0, $arg1) { /* // $tmp1 */ __patsflab_int_repeat_lazy: $tmp1 = ats2phppre_lazy2cloref($arg1); ats2phppre_int_repeat_cloref($arg0, $tmp1); return/*_void*/; } // end-of-function function ats2phppre_int_repeat_cloref($arg0, $arg1) { /* */ __patsflab_int_repeat_cloref: _ats2phppre_intrange_loop_2($arg0, $arg1); return/*_void*/; } // end-of-function function _ats2phppre_intrange_loop_2($arg0, $arg1) { /* // $apy0 // $apy1 // $tmp4 // $tmp6 */ __patsflab__ats2phppre_intrange_loop_2: $tmp4 = ats2phppre_gt_int0_int0($arg0, 0); if($tmp4) { $arg1[0]($arg1); $tmp6 = ats2phppre_sub_int0_int0($arg0, 1); // ATStailcalseq_beg $apy0 = $tmp6; $apy1 = $arg1; $arg0 = $apy0; $arg1 = $apy1; goto __patsflab__ats2phppre_intrange_loop_2; // ATStailcalseq_end } else { // ATSINSmove_void; } // endif return/*_void*/; } // end-of-function function ats2phppre_int_exists_cloref($arg0, $arg1) { /* // $tmpret7 */ __patsflab_int_exists_cloref: $tmpret7 = ats2phppre_intrange_exists_cloref(0, $arg0, $arg1); return $tmpret7; } // end-of-function function ats2phppre_int_forall_cloref($arg0, $arg1) { /* // $tmpret8 */ __patsflab_int_forall_cloref: $tmpret8 = ats2phppre_intrange_forall_cloref(0, $arg0, $arg1); return $tmpret8; } // end-of-function function ats2phppre_int_foreach_cloref($arg0, $arg1) { /* */ __patsflab_int_foreach_cloref: ats2phppre_intrange_foreach_cloref(0, $arg0, $arg1); return/*_void*/; } // end-of-function function ats2phppre_int_exists_method($arg0) { /* // $tmpret10 */ __patsflab_int_exists_method: $tmpret10 = _ats2phppre_intrange_patsfun_7__closurerize($arg0); return $tmpret10; } // end-of-function function _ats2phppre_intrange_patsfun_7($env0, $arg0) { /* // $tmpret11 */ __patsflab__ats2phppre_intrange_patsfun_7: $tmpret11 = ats2phppre_int_exists_cloref($env0, $arg0); return $tmpret11; } // end-of-function function ats2phppre_int_forall_method($arg0) { /* // $tmpret12 */ __patsflab_int_forall_method: $tmpret12 = _ats2phppre_intrange_patsfun_9__closurerize($arg0); return $tmpret12; } // end-of-function function _ats2phppre_intrange_patsfun_9($env0, $arg0) { /* // $tmpret13 */ __patsflab__ats2phppre_intrange_patsfun_9: $tmpret13 = ats2phppre_int_forall_cloref($env0, $arg0); return $tmpret13; } // end-of-function function ats2phppre_int_foreach_method($arg0) { /* // $tmpret14 */ __patsflab_int_foreach_method: $tmpret14 = _ats2phppre_intrange_patsfun_11__closurerize($arg0); return $tmpret14; } // end-of-function function _ats2phppre_intrange_patsfun_11($env0, $arg0) { /* */ __patsflab__ats2phppre_intrange_patsfun_11: ats2phppre_int_foreach_cloref($env0, $arg0); return/*_void*/; } // end-of-function function ats2phppre_int_foldleft_cloref($arg0, $arg1, $arg2) { /* // $tmpret16 */ __patsflab_int_foldleft_cloref: $tmpret16 = ats2phppre_intrange_foldleft_cloref(0, $arg0, $arg1, $arg2); return $tmpret16; } // end-of-function function ats2phppre_int_foldleft_method($arg0, $arg1) { /* // $tmpret17 */ __patsflab_int_foldleft_method: $tmpret17 = _ats2phppre_intrange_patsfun_14__closurerize($arg0); return $tmpret17; } // end-of-function function _ats2phppre_intrange_patsfun_14($env0, $arg0, $arg1) { /* // $tmpret18 */ __patsflab__ats2phppre_intrange_patsfun_14: $tmpret18 = ats2phppre_int_foldleft_cloref($env0, $arg0, $arg1); return $tmpret18; } // end-of-function function _057_home_057_hwxi_057_research_057_Postiats_055_contrib_057_git_057_contrib_057_libatscc_057_libatscc2php_057_SATS_057_intrange_056_sats__int_list_map_cloref($arg0, $arg1) { /* // $tmpret19 */ __patsflab_int_list_map_cloref: $tmpret19 = _ats2phppre_intrange_aux_16($arg0, $arg1, 0); return $tmpret19; } // end-of-function function _ats2phppre_intrange_aux_16($env0, $env1, $arg0) { /* // $tmpret20 // $tmp21 // $tmp22 // $tmp23 // $tmp24 */ __patsflab__ats2phppre_intrange_aux_16: $tmp21 = ats2phppre_lt_int1_int1($arg0, $env0); if($tmp21) { $tmp22 = $env1[0]($env1, $arg0); $tmp24 = ats2phppre_add_int1_int1($arg0, 1); $tmp23 = _ats2phppre_intrange_aux_16($env0, $env1, $tmp24); $tmpret20 = array($tmp22, $tmp23); } else { $tmpret20 = null; } // endif return $tmpret20; } // end-of-function function _057_home_057_hwxi_057_research_057_Postiats_055_contrib_057_git_057_contrib_057_libatscc_057_libatscc2php_057_SATS_057_intrange_056_sats__int_list_map_method($arg0, $arg1) { /* // $tmpret25 */ __patsflab_int_list_map_method: $tmpret25 = _ats2phppre_intrange_patsfun_18__closurerize($arg0); return $tmpret25; } // end-of-function function _ats2phppre_intrange_patsfun_18($env0, $arg0) { /* // $tmpret26 */ __patsflab__ats2phppre_intrange_patsfun_18: $tmpret26 = _057_home_057_hwxi_057_research_057_Postiats_055_contrib_057_git_057_contrib_057_libatscc_057_libatscc2php_057_SATS_057_intrange_056_sats__int_list_map_cloref($env0, $arg0); return $tmpret26; } // end-of-function function ats2phppre_int2_exists_cloref($arg0, $arg1, $arg2) { /* // $tmpret27 */ __patsflab_int2_exists_cloref: $tmpret27 = ats2phppre_intrange2_exists_cloref(0, $arg0, 0, $arg1, $arg2); return $tmpret27; } // end-of-function function ats2phppre_int2_forall_cloref($arg0, $arg1, $arg2) { /* // $tmpret28 */ __patsflab_int2_forall_cloref: $tmpret28 = ats2phppre_intrange2_forall_cloref(0, $arg0, 0, $arg1, $arg2); return $tmpret28; } // end-of-function function ats2phppre_int2_foreach_cloref($arg0, $arg1, $arg2) { /* */ __patsflab_int2_foreach_cloref: ats2phppre_intrange2_foreach_cloref(0, $arg0, 0, $arg1, $arg2); return/*_void*/; } // end-of-function function ats2phppre_intrange_exists_cloref($arg0, $arg1, $arg2) { /* // $tmpret30 */ __patsflab_intrange_exists_cloref: $tmpret30 = _ats2phppre_intrange_loop_23($arg0, $arg1, $arg2); return $tmpret30; } // end-of-function function _ats2phppre_intrange_loop_23($arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmpret31 // $tmp32 // $tmp33 // $tmp34 */ __patsflab__ats2phppre_intrange_loop_23: $tmp32 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp32) { $tmp33 = $arg2[0]($arg2, $arg0); if($tmp33) { $tmpret31 = true; } else { $tmp34 = ats2phppre_add_int0_int0($arg0, 1); // ATStailcalseq_beg $apy0 = $tmp34; $apy1 = $arg1; $apy2 = $arg2; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop_23; // ATStailcalseq_end } // endif } else { $tmpret31 = false; } // endif return $tmpret31; } // end-of-function function ats2phppre_intrange_forall_cloref($arg0, $arg1, $arg2) { /* // $tmpret35 */ __patsflab_intrange_forall_cloref: $tmpret35 = _ats2phppre_intrange_loop_25($arg0, $arg1, $arg2); return $tmpret35; } // end-of-function function _ats2phppre_intrange_loop_25($arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmpret36 // $tmp37 // $tmp38 // $tmp39 */ __patsflab__ats2phppre_intrange_loop_25: $tmp37 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp37) { $tmp38 = $arg2[0]($arg2, $arg0); if($tmp38) { $tmp39 = ats2phppre_add_int0_int0($arg0, 1); // ATStailcalseq_beg $apy0 = $tmp39; $apy1 = $arg1; $apy2 = $arg2; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop_25; // ATStailcalseq_end } else { $tmpret36 = false; } // endif } else { $tmpret36 = true; } // endif return $tmpret36; } // end-of-function function ats2phppre_intrange_foreach_cloref($arg0, $arg1, $arg2) { /* */ __patsflab_intrange_foreach_cloref: _ats2phppre_intrange_loop_27($arg0, $arg1, $arg2); return/*_void*/; } // end-of-function function _ats2phppre_intrange_loop_27($arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmp42 // $tmp44 */ __patsflab__ats2phppre_intrange_loop_27: $tmp42 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp42) { $arg2[0]($arg2, $arg0); $tmp44 = ats2phppre_add_int0_int0($arg0, 1); // ATStailcalseq_beg $apy0 = $tmp44; $apy1 = $arg1; $apy2 = $arg2; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop_27; // ATStailcalseq_end } else { // ATSINSmove_void; } // endif return/*_void*/; } // end-of-function function ats2phppre_intrange_foldleft_cloref($arg0, $arg1, $arg2, $arg3) { /* // $tmpret45 */ __patsflab_intrange_foldleft_cloref: $tmpret45 = _ats2phppre_intrange_loop_29($arg0, $arg1, $arg2, $arg3); return $tmpret45; } // end-of-function function _ats2phppre_intrange_loop_29($arg0, $arg1, $arg2, $arg3) { /* // $apy0 // $apy1 // $apy2 // $apy3 // $tmpret46 // $tmp47 // $tmp48 // $tmp49 */ __patsflab__ats2phppre_intrange_loop_29: $tmp47 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp47) { $tmp48 = ats2phppre_add_int0_int0($arg0, 1); $tmp49 = $arg3[0]($arg3, $arg2, $arg0); // ATStailcalseq_beg $apy0 = $tmp48; $apy1 = $arg1; $apy2 = $tmp49; $apy3 = $arg3; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; $arg3 = $apy3; goto __patsflab__ats2phppre_intrange_loop_29; // ATStailcalseq_end } else { $tmpret46 = $arg2; } // endif return $tmpret46; } // end-of-function function ats2phppre_intrange_foldleft_method($arg0, $arg1) { /* // $tmp50 // $tmp51 // $tmpret52 */ __patsflab_intrange_foldleft_method: $tmp50 = $arg0[0]; $tmp51 = $arg0[1]; $tmpret52 = _ats2phppre_intrange_patsfun_31__closurerize($tmp50, $tmp51); return $tmpret52; } // end-of-function function _ats2phppre_intrange_patsfun_31($env0, $env1, $arg0, $arg1) { /* // $tmpret53 */ __patsflab__ats2phppre_intrange_patsfun_31: $tmpret53 = ats2phppre_intrange_foldleft_cloref($env0, $env1, $arg0, $arg1); return $tmpret53; } // end-of-function function ats2phppre_intrange2_exists_cloref($arg0, $arg1, $arg2, $arg3, $arg4) { /* // $tmpret54 */ __patsflab_intrange2_exists_cloref: $tmpret54 = _ats2phppre_intrange_loop1_33($arg2, $arg3, $arg0, $arg1, $arg4); return $tmpret54; } // end-of-function function _ats2phppre_intrange_loop1_33($env0, $env1, $arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmpret55 // $tmp56 // $a2rg0 // $a2rg1 // $a2rg2 // $a2rg3 // $a2rg4 // $a2py0 // $a2py1 // $a2py2 // $a2py3 // $a2py4 // $tmpret57 // $tmp58 // $tmp59 // $tmp60 // $tmp61 */ __patsflab__ats2phppre_intrange_loop1_33: $tmp56 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp56) { // ATStailcalseq_beg $a2py0 = $arg0; $a2py1 = $arg1; $a2py2 = $env0; $a2py3 = $env1; $a2py4 = $arg2; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_34; // ATStailcalseq_end } else { $tmpret55 = false; } // endif return $tmpret55; // __patsflab__ats2phppre_intrange_loop2_34: $tmp58 = ats2phppre_lt_int0_int0($a2rg2, $a2rg3); if($tmp58) { $tmp59 = $a2rg4[0]($a2rg4, $a2rg0, $a2rg2); if($tmp59) { $tmpret57 = true; } else { $tmp60 = ats2phppre_add_int0_int0($a2rg2, 1); // ATStailcalseq_beg $a2py0 = $a2rg0; $a2py1 = $a2rg1; $a2py2 = $tmp60; $a2py3 = $a2rg3; $a2py4 = $a2rg4; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_34; // ATStailcalseq_end } // endif } else { $tmp61 = ats2phppre_add_int0_int0($a2rg0, 1); // ATStailcalseq_beg $apy0 = $tmp61; $apy1 = $a2rg1; $apy2 = $a2rg4; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop1_33; // ATStailcalseq_end } // endif return $tmpret57; } // end-of-function function ats2phppre_intrange2_forall_cloref($arg0, $arg1, $arg2, $arg3, $arg4) { /* // $tmpret62 */ __patsflab_intrange2_forall_cloref: $tmpret62 = _ats2phppre_intrange_loop1_36($arg2, $arg3, $arg0, $arg1, $arg4); return $tmpret62; } // end-of-function function _ats2phppre_intrange_loop1_36($env0, $env1, $arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmpret63 // $tmp64 // $a2rg0 // $a2rg1 // $a2rg2 // $a2rg3 // $a2rg4 // $a2py0 // $a2py1 // $a2py2 // $a2py3 // $a2py4 // $tmpret65 // $tmp66 // $tmp67 // $tmp68 // $tmp69 */ __patsflab__ats2phppre_intrange_loop1_36: $tmp64 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp64) { // ATStailcalseq_beg $a2py0 = $arg0; $a2py1 = $arg1; $a2py2 = $env0; $a2py3 = $env1; $a2py4 = $arg2; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_37; // ATStailcalseq_end } else { $tmpret63 = true; } // endif return $tmpret63; // __patsflab__ats2phppre_intrange_loop2_37: $tmp66 = ats2phppre_lt_int0_int0($a2rg2, $a2rg3); if($tmp66) { $tmp67 = $a2rg4[0]($a2rg4, $a2rg0, $a2rg2); if($tmp67) { $tmp68 = ats2phppre_add_int0_int0($a2rg2, 1); // ATStailcalseq_beg $a2py0 = $a2rg0; $a2py1 = $a2rg1; $a2py2 = $tmp68; $a2py3 = $a2rg3; $a2py4 = $a2rg4; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_37; // ATStailcalseq_end } else { $tmpret65 = false; } // endif } else { $tmp69 = ats2phppre_add_int0_int0($a2rg0, 1); // ATStailcalseq_beg $apy0 = $tmp69; $apy1 = $a2rg1; $apy2 = $a2rg4; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop1_36; // ATStailcalseq_end } // endif return $tmpret65; } // end-of-function function ats2phppre_intrange2_foreach_cloref($arg0, $arg1, $arg2, $arg3, $arg4) { /* */ __patsflab_intrange2_foreach_cloref: _ats2phppre_intrange_loop1_39($arg2, $arg3, $arg0, $arg1, $arg4); return/*_void*/; } // end-of-function function _ats2phppre_intrange_loop1_39($env0, $env1, $arg0, $arg1, $arg2) { /* // $apy0 // $apy1 // $apy2 // $tmp72 // $a2rg0 // $a2rg1 // $a2rg2 // $a2rg3 // $a2rg4 // $a2py0 // $a2py1 // $a2py2 // $a2py3 // $a2py4 // $tmp74 // $tmp76 // $tmp77 */ __patsflab__ats2phppre_intrange_loop1_39: $tmp72 = ats2phppre_lt_int0_int0($arg0, $arg1); if($tmp72) { // ATStailcalseq_beg $a2py0 = $arg0; $a2py1 = $arg1; $a2py2 = $env0; $a2py3 = $env1; $a2py4 = $arg2; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_40; // ATStailcalseq_end } else { // ATSINSmove_void; } // endif return/*_void*/; // __patsflab__ats2phppre_intrange_loop2_40: $tmp74 = ats2phppre_lt_int0_int0($a2rg2, $a2rg3); if($tmp74) { $a2rg4[0]($a2rg4, $a2rg0, $a2rg2); $tmp76 = ats2phppre_add_int0_int0($a2rg2, 1); // ATStailcalseq_beg $a2py0 = $a2rg0; $a2py1 = $a2rg1; $a2py2 = $tmp76; $a2py3 = $a2rg3; $a2py4 = $a2rg4; $a2rg0 = $a2py0; $a2rg1 = $a2py1; $a2rg2 = $a2py2; $a2rg3 = $a2py3; $a2rg4 = $a2py4; goto __patsflab__ats2phppre_intrange_loop2_40; // ATStailcalseq_end } else { $tmp77 = ats2phppre_add_int0_int0($a2rg0, 1); // ATStailcalseq_beg $apy0 = $tmp77; $apy1 = $a2rg1; $apy2 = $a2rg4; $arg0 = $apy0; $arg1 = $apy1; $arg2 = $apy2; goto __patsflab__ats2phppre_intrange_loop1_39; // ATStailcalseq_end } // endif return/*_void*/; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function ats2phppre_arrayref_exists_cloref($arg0, $arg1, $arg2) { /* // $tmpret0 */ __patsflab_arrayref_exists_cloref: $tmpret0 = ats2phppre_int_exists_cloref($arg1, $arg2); return $tmpret0; } // end-of-function function ats2phppre_arrayref_forall_cloref($arg0, $arg1, $arg2) { /* // $tmpret1 */ __patsflab_arrayref_forall_cloref: $tmpret1 = ats2phppre_int_forall_cloref($arg1, $arg2); return $tmpret1; } // end-of-function function ats2phppre_arrayref_foreach_cloref($arg0, $arg1, $arg2) { /* */ __patsflab_arrayref_foreach_cloref: ats2phppre_int_foreach_cloref($arg1, $arg2); return/*_void*/; } // end-of-function function ats2phppre_arrszref_make_elt($arg0, $arg1) { /* // $tmpret3 // $tmp4 */ __patsflab_arrszref_make_elt: $tmp4 = ats2phppre_arrayref_make_elt($arg0, $arg1); $tmpret3 = ats2phppre_arrszref_make_arrayref($tmp4, $arg0); return $tmpret3; } // end-of-function function ats2phppre_arrszref_exists_cloref($arg0, $arg1) { /* // $tmpret5 // $tmp6 */ __patsflab_arrszref_exists_cloref: $tmp6 = ats2phppre_arrszref_size($arg0); $tmpret5 = ats2phppre_int_exists_cloref($tmp6, $arg1); return $tmpret5; } // end-of-function function ats2phppre_arrszref_forall_cloref($arg0, $arg1) { /* // $tmpret7 // $tmp8 */ __patsflab_arrszref_forall_cloref: $tmp8 = ats2phppre_arrszref_size($arg0); $tmpret7 = ats2phppre_int_forall_cloref($tmp8, $arg1); return $tmpret7; } // end-of-function function ats2phppre_arrszref_foreach_cloref($arg0, $arg1) { /* // $tmp10 */ __patsflab_arrszref_foreach_cloref: $tmp10 = ats2phppre_arrszref_size($arg0); ats2phppre_int_foreach_cloref($tmp10, $arg1); return/*_void*/; } // end-of-function function ats2phppre_arrayref_make_elt($arg0, $arg1) { /* // $tmpret11 // $tmp12 */ __patsflab_arrayref_make_elt: $tmp12 = PHParref_make_elt($arg0, $arg1); $tmpret11 = $tmp12; return $tmpret11; } // end-of-function function ats2phppre_arrayref_get_at($arg0, $arg1) { /* // $tmpret13 */ __patsflab_arrayref_get_at: $tmpret13 = PHParref_get_at($arg0, $arg1); return $tmpret13; } // end-of-function function ats2phppre_arrayref_set_at($arg0, $arg1, $arg2) { /* */ __patsflab_arrayref_set_at: PHParref_set_at($arg0, $arg1, $arg2); return/*_void*/; } // end-of-function function ats2phppre_arrszref_make_arrayref($arg0, $arg1) { /* // $tmpret15 */ __patsflab_arrszref_make_arrayref: $tmpret15 = $arg0; return $tmpret15; } // end-of-function function ats2phppre_arrszref_size($arg0) { /* // $tmpret16 // $tmp17 */ __patsflab_arrszref_size: $tmp17 = PHParref_length($arg0); $tmpret16 = $tmp17; return $tmpret16; } // end-of-function function ats2phppre_arrszref_get_at($arg0, $arg1) { /* // $tmpret18 */ __patsflab_arrszref_get_at: $tmpret18 = PHParref_get_at($arg0, $arg1); return $tmpret18; } // end-of-function function ats2phppre_arrszref_set_at($arg0, $arg1, $arg2) { /* */ __patsflab_arrszref_set_at: PHParref_set_at($arg0, $arg1, $arg2); return/*_void*/; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** ** The PHP code is generated by atscc2php ** The starting compilation time is: 2015-7-14: 0h:43m ** */ function ats2phppre_ref($arg0) { /* // $tmpret0 */ __patsflab_ref: $tmpret0 = ats2phppre_ref_make_elt($arg0); return $tmpret0; } // end-of-function function ats2phppre_ref_make_elt($arg0) { /* // $tmpret1 // $tmp2 */ __patsflab_ref_make_elt: $tmp2 = PHPref_new($arg0); $tmpret1 = $tmp2; return $tmpret1; } // end-of-function function ats2phppre_ref_get_elt($arg0) { /* // $tmpret3 */ __patsflab_ref_get_elt: $tmpret3 = PHPref_get_elt($arg0); return $tmpret3; } // end-of-function function ats2phppre_ref_set_elt($arg0, $arg1) { /* */ __patsflab_ref_set_elt: PHPref_set_elt($arg0, $arg1); return/*_void*/; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ ?> <?php /* ** end of [libatscc2php_all.php] */ ?>
Java
UTF-8
3,373
2.578125
3
[]
no_license
package br.com.avenue.script.daos; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Component; import br.com.avenue.script.model.Movie; @Component public class MovieDAOImpl implements MovieDAO { BasicDataSource dbcpDataSource; NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public Movie save(Movie movie) { buildDataSource(); KeyHolder keyHolder = new GeneratedKeyHolder(); if(namedParameterJdbcTemplate == null) this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dbcpDataSource); String SQL = "INSERT INTO movies (title) VALUES (:title)"; MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("title", movie.getTitle()); try { namedParameterJdbcTemplate.update(SQL, parameters, keyHolder); movie.setId((Integer) keyHolder.getKey()); System.out.println("Created Record Name = " + movie.toString()); } catch (DuplicateKeyException ex) { System.out.println("Registro Duplicado"); } return movie; } @Override public Movie findByTitle(String titulo) { buildDataSource(); if(namedParameterJdbcTemplate == null) this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dbcpDataSource); Map<String, Object> params = new HashMap<String, Object>(); params.put("title", titulo); Movie result = new Movie(); String sql = "SELECT * FROM MOVIES WHERE title=:title"; try { result = namedParameterJdbcTemplate.queryForObject( sql, params, new MovieMapper()); } catch (EmptyResultDataAccessException ex) { System.out.println("Registro nao encontrardo"); return null; } return result; } @Override public List<Movie> findAll() { buildDataSource(); if(namedParameterJdbcTemplate == null) this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dbcpDataSource); Map<String, Object> params = new HashMap<String, Object>(); String sql = "SELECT * FROM MOVIES"; List<Movie> result = namedParameterJdbcTemplate.query(sql, params, new MovieMapper()); return result; } private static final class MovieMapper implements RowMapper<Movie> { public Movie mapRow(ResultSet rs, int rowNum) throws SQLException { Movie movie = new Movie(); movie.setTitle(rs.getString("title")); movie.setId(rs.getInt("id")); movie.setSettings(new SettingsDAOImpl().findByMovie(movie.getId())); return movie; } } private void buildDataSource() { dbcpDataSource = new BasicDataSource(); dbcpDataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dbcpDataSource.setUrl("jdbc:hsqldb:mem:avenue"); dbcpDataSource.setUsername("sa"); dbcpDataSource.setPassword(""); } public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate template) { this.namedParameterJdbcTemplate = template; } }
C++
UTF-8
1,381
3.546875
4
[]
no_license
#ifndef __INLINE_CONTAINER_H__ #define __INLINE_CONTAINER_H__ // Andrei Alexandrescu implementation of "inline containers" #include <vector> #include <list> #include <deque> template < typename T, class container = std::vector<T> > class inline_container : public container { public: inline_container() { } inline_container(const inline_container<T> &v) : container(v.begin(), v.end()) { } explicit inline_container(const T &a) : container(1, a) { } inline_container &operator()(const T &a) { this->push_back(a); return *this; } }; template <typename T> inline inline_container<T> make_vector(const T &a) { return inline_container<T>(a); } template <typename T> inline inline_container< T, std::list<T> > make_list(const T &a) { return inline_container< T, std::list<T> >(a); } template <typename T> inline inline_container< T, std::deque<T> > make_deque(const T &a) { return inline_container< T, std::deque<T> >(a); } #if 0 template <class container> inline const container::value_type min(const container &a) { return *std::min_element(a.begin(), a.end()); } template <class container> inline const container::value_type max(const container &a) { return *std::max_element(a.begin(), a.end()); } #endif #endif //__INLINE_CONTAINER_H__
C
UTF-8
1,815
2.828125
3
[]
no_license
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_list.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: jdesbord <jdesbord@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2020/01/21 16:56:03 by jdesbord #+# ## ## #+# */ /* Updated: 2020/02/01 21:32:19 by jdesbord ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "../includes/minishell.h" t_env *ft_lstenvnew(char *name, char *content) { t_env *new; if (!(new = malloc(sizeof(t_env) * 1))) return (NULL); new->name = name; new->content = content; new->next = NULL; return (new); } t_env *ft_lstenvlast(t_env *lst) { if (lst == NULL) return (NULL); return (lst->next ? ft_lstenvlast(lst->next) : lst); } void ft_lstenvadd_back(t_env **alst, t_env *new) { if (!(*alst) || (*alst)->name == NULL) { *alst = new; return ; } ft_lstenvlast(*alst)->next = new; } void ft_lstenvdelone(t_env *lst, void (*del)(void*)) { if (lst == NULL) return ; if (lst->content) del(lst->content); if (lst->name) del(lst->name); free(lst); } void ft_lstenvclear(t_env **lst, void (*del)(void*)) { if ((*lst) != NULL) ft_lstenvclear(&((*lst)->next), *del); ft_lstenvdelone(*lst, del); *lst = NULL; }
Java
UTF-8
4,755
2.15625
2
[]
no_license
package com.caved_in.commons.yml.converter; import com.caved_in.commons.item.ItemBuilder; import com.caved_in.commons.item.Items; import com.caved_in.commons.yml.ConfigSection; import com.caved_in.commons.yml.InternalConverter; import org.apache.commons.lang3.reflect.TypeUtils; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author geNAZt (fabian.fassbender42@googlemail.com) */ public class ItemStackYamlConverter implements Converter { private InternalConverter converter; public ItemStackYamlConverter(InternalConverter converter) { this.converter = converter; } @Override public Object toConfig(Class<?> type, Object obj, ParameterizedType genericType) throws Exception { org.bukkit.inventory.ItemStack itemStack = (org.bukkit.inventory.ItemStack) obj; Map<String, Object> saveMap = new HashMap<>(); saveMap.put("id", itemStack.getType().name()); if (itemStack.getDurability() > 0) { saveMap.put("data",itemStack.getDurability()); } saveMap.put("amount", itemStack.getAmount()); Converter listConverter = converter.getConverter(List.class); Map<Enchantment, Integer> itemEnchantments = itemStack.getEnchantments(); if (itemEnchantments.size() > 0) { Map<String, Object> saveEnchantMap = new HashMap<>(); for(Map.Entry<Enchantment, Integer> enchants : itemEnchantments.entrySet()) { saveEnchantMap.put(enchants.getKey().getName(),enchants.getValue()); } saveMap.put("enchantments",saveEnchantMap); } //todo implement enchant serialize Map<String, Object> meta = null; if (itemStack.hasItemMeta()) { meta = new HashMap<>(); meta.put("name", itemStack.getItemMeta().hasDisplayName() ? itemStack.getItemMeta().getDisplayName() : null); meta.put("lore", itemStack.getItemMeta().hasLore() ? listConverter.toConfig(List.class, itemStack.getItemMeta().getLore(), null) : null); } saveMap.put("meta", meta); return saveMap; } @Override public Object fromConfig(Class type, Object section, ParameterizedType genericType) throws Exception { Map<String, Object> itemstackMap; Map<String, Object> metaMap = null; if (section == null) { throw new NullPointerException("Item configuration section is null"); } if (section instanceof Map) { itemstackMap = (Map<String, Object>) section; metaMap = (Map<String, Object>) itemstackMap.get("meta"); } else { itemstackMap = (Map<String, Object>)((ConfigSection) section).getRawMap(); if (itemstackMap.containsKey("meta")) { metaMap = (Map<String, Object>)((ConfigSection) itemstackMap.get("meta")).getRawMap(); } } Material itemMaterial = Material.getMaterial((String)itemstackMap.get("id")); ItemBuilder itemBuilder = ItemBuilder.of(itemMaterial); if (itemstackMap.containsKey("data")) { short data = (short)itemstackMap.get("data"); itemBuilder.durability(data); } if (itemstackMap.containsKey("amount")) { int amount = (int)itemstackMap.get("amount"); itemBuilder.amount(amount); } if (metaMap != null) { if (metaMap.containsKey("name")) { itemBuilder.name((String)metaMap.get("name")); } if (metaMap.containsKey("lore")) { Converter listConverter = converter.getConverter(List.class); List<String> lore = new ArrayList<>(); lore = (List<String>)listConverter.fromConfig(List.class,metaMap.get("lore"),null); itemBuilder.lore(lore); } } /* If there's enchantments listed in the yml file for this item, then we're going to parse that section of the configuration, and then add it to the item. */ if (itemstackMap.containsKey("enchantments")) { Map<String, Object> enchantmentMap = new HashMap<>(); Converter mapConverter = converter.getConverter(Map.class); // enchantmentMap = ((ConfigSection)converter.getConverter(enchantmentMap.getClass()).fromConfig(enchantmentMap.getClass(),itemstackMap.get("enchantments"),TypeUtils.parameterize(enchantmentMap.getClass(),enchantmentMap.getClass().getGenericInterfaces()))).getRawMap(); enchantmentMap = (Map<String, Object>)mapConverter.fromConfig(Map.class,itemstackMap.get("enchantments"),null); for (Map.Entry<String, Object> enchant : enchantmentMap.entrySet()) { Enchantment enchantment = Enchantment.getByName(enchant.getKey()); itemBuilder.enchantment(enchantment,(int)enchant.getValue()); } } return itemBuilder.item(); } @Override public boolean supports(Class<?> type) { return ItemStack.class.isAssignableFrom(type); } }
Python
UTF-8
3,222
3.65625
4
[]
no_license
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ # 2021.03.16: # Note: the returned dtype is int, input is non-negative int # 3rd solution: brute force # Since x^0.5 < x/2 and x > 1, try 1 <= x <= x/2 """ if x <= 1: return x # for i in range(1, x//2+1): -> cause memory error i = 0 k = x//2 while i < k: i += 1 n = (i+1) ** 2 - x if n == 0: return i+1 m = i ** 2 - x if m * n < 0: return i return 1 """ # 4th solution: short cut """ return int(x ** 0.5) """ # 9th solution: Newton-Raphson method # f(a) = a^2 - x, f'(a) = 2a # -> 0 - f(a0) = f'(a0) * (a1 - a0) -> a1 = -f(a0)/f'(a0) + a0 # For sqrt: a1 = -(a0^2 - x)/(2*a0) + a0 """ if x <= 1: return x n_digits = len(str(x)) a0 = 10 ** (n_digits // 2) # initial guess tol_err = 1e-6 err = 1.0 i = 0 imax = 1000 while err > tol_err: i += 1 f = float(a0) ** 2 - float(x) fb = (float(a0)*(1.0 - tol_err)) ** 2 - float(x) # backward ff = (float(a0)*(1.0 + tol_err)) ** 2 - float(x) # forward fp = (ff - fb)/(2 * float(a0) * tol_err) # slope a1 = float(a0) - f/fp err = abs(a1/a0 - 1.0) a0 = a1 if i > imax: return -999 # deverged return int(a0) # converged """ # 10th solution: Newton-Raphson method # f(a) = a^2 - x, f'(a) = 2a # -> 0 - f(a0) = f'(a0) * (a1 - a0) -> a1 = -f(a0)/f'(a0) + a0 # For sqrt: a1 = -(a0^2 - x)/(2*a0) + a0 = a0/2 + x/(2a0) """ if x <= 1: return x n_digits = len(str(x)) a0 = 10 ** (n_digits // 2) # initial guess tol_err = 1e-6 err = 1.0 i = 0 imax = 1000 while err > tol_err: i += 1 a1 = float(a0)/2.0 + float(x)/(2.0*float(a0)) err = abs(a1/a0 - 1.0) a0 = a1 if i > imax: return -999 # deverged return int(a0) # converged """ # 11th solution: binary search # time complexity: O(logN) if x <= 1: return x n_a = len(str(x))//2 a_low = 0 a_up = 10 ** (n_a + 1) # to reduce the search range while a_low <= a_up: a_mid = (a_low + a_up) // 2 f = a_mid ** 2 if f == x: return a_mid if f > x: a_up = a_mid - 1 else: a_low = a_mid + 1 return a_up # crossed, return lower value # 3rd solution: 5600 ms (5%), 13.5 MB (37%) # 4th solution: 12 ms (98%), 13.4 MB (66%) # 9th solution: 20 ms (79%), 13.3 MB (66%) # 10th solution: 28 ms (40%), 13.5 MB (13%) # 11th solution: 12 ms (98%), 13.3 MB (90%) **
Shell
UTF-8
681
2.984375
3
[]
no_license
#! /bin/bash #------------------------------------------------------------ # Auteur : Alababa # Nom : Script automatisation de création des boite mails # Role : Automatiser la creation des boite mails #------------------------------------------------------------ # ROLE : AJOUTE UNE NOUVELLE RELATION FQDN - ADRESSE IP AU FICHIER DE ZONE DNS #On prendra en entrée : #$1 : le nom de la boutique if /bin/grep "^+$1." /etc/tinydns/root/data; then /bin/echo "Cette enregistrement existe déjà [ECHEC]" else /bin/echo "+$1.myshop.itinet.fr:88.177.168.133:1800" | sudo tee -a /etc/tinydns/root/data /usr/bin/ssh -i /var/www/Myshop/www/Server/key_dedibox root@dedibox.itinet.fr fi
Python
UTF-8
4,722
2.84375
3
[ "MIT" ]
permissive
import pandas as pd import numpy as np from typing import List, Optional from enum import Enum, auto from pandas.core.frame import DataFrame from sklearn import model_selection ''' - binary classification - multiclass classification - multilabel classification - single column regression - multi column regression - holdout - entity embeddings ''' class ProblemType(Enum): BINARY = auto(), MULTICLASS = auto(), REGRESSION = auto(), MULTI_COL_REGRESSION = auto(), HOLDOUT = auto(), MULTILABEL = auto(), ENTITY_EMBEDDING = auto() class CrossValidation: def __init__( self, df: DataFrame, target_cols: List[str], shuffle: bool, problem_type: ProblemType, holdout_pct=None, n_folds: int = 5, multilabel_delimiter: str = ',', random_state: int = 31 ): self.df = df self.target_cols = target_cols self.n_targets = len(self.target_cols) self.problem_type = problem_type self.shuffle = shuffle self.n_folds = n_folds self.holdout_pct = holdout_pct self.multilabel_delimiter = multilabel_delimiter self.random_state = random_state if self.shuffle is True: self.df = self.df.sample(frac=1).reset_index(drop=True) self.df['kfold'] = -1 def split(self): if self.problem_type in (ProblemType.BINARY, ProblemType.MULTICLASS): if self.n_targets != 1: raise Exception(f'Invalid number of targets {self.n_targets} for selected problem type: {self.problem_type}') target = self.target_cols[0] kf = model_selection.StratifiedKFold(n_splits=self.n_folds) for fold, (train_idx, val_idx) in enumerate(kf.split(X=self.df, y=self.df[target].values)): print(len(train_idx), len(val_idx)) self.df.loc[val_idx, 'kfold'] = fold elif self.problem_type in (ProblemType.REGRESSION, ProblemType.MULTI_COL_REGRESSION): if self.n_targets != 1 and self.problem_type == ProblemType.REGRESSION: raise Exception(f'Invalid combination of number of targets {self.n_targets} and problem type {self.problem_type}') if self.n_targets < 2 and self.problem_type == ProblemType.MULTI_COL_REGRESSION: raise Exception(f'Invalid combination of number of targets {self.n_targets} and problem type {self.problem_type}') target = self.target_cols[0] # calculate number of bins by Sturge's rule # I take the floor of the value, you can also # just round it num_bins = int(np.floor(1 + np.log2(len(self.df)))) # bin targets self.df.loc[:, "bins"] = pd.cut( self.df["target"], bins=num_bins, labels=False ) # initiate the kfold class from model_selection module kf = model_selection.StratifiedKFold(n_splits=self.n_folds) # fill the new kfold column # note that, instead of targets, we use bins! for fold, (train_idx, valid_idx) in enumerate(kf.split(X=self.df, y=self.df.bins.values)): print(len(train_idx), len(valid_idx)) self.df.loc[valid_idx, 'kfold'] = fold # drop the bins column self.df = self.df.drop("bins", axis=1) elif self.problem_type == ProblemType.HOLDOUT: holdout_pctg = self.holdout_pct n_holdout_samples = int(len(self.df) * holdout_pctg / 100) self.df.loc[:n_holdout_samples, 'kfold'] = 0 self.df.loc[n_holdout_samples: , 'kfold'] = 1 print(n_holdout_samples) elif self.problem_type == ProblemType.MULTILABEL: if self.n_targets != 1: raise Exception(f'Invalid combination of number of targets {self.n_targets} and problem type {self.problem_type}') targets = self.df[self.target_cols[0]].apply(lambda x: len(x.split(self.multilabel_delimiter))) print(targets.value_counts()) kf = model_selection.StratifiedKFold(n_splits=self.n_folds) for fold, (train_idx, valid_idx) in enumerate(kf.split(X=self.df, y=targets)): print(len(train_idx), len(valid_idx)) self.df.loc[valid_idx, 'kfold'] = fold else: raise Exception(f'Invalid problem type found : {self.problem_type}') return self.df if __name__ == '__main__': df = pd.read_csv('../inputs/train_cat.csv')
Python
UTF-8
357
2.640625
3
[]
no_license
# na = int(input()) a = set(map(int,input().split())) d={'update':a.update,'intersection_update':a.intersection_update,'symmetric_difference_update':a.symmetric_difference_update,'difference_update':a.difference_update} for i in range(int(input())): c = input().split() b = set(map(int,input().split())) d[c[0]](b) print(a) print(sum(a))
Markdown
UTF-8
5,087
3.109375
3
[ "MIT" ]
permissive
--- layout: post title: "Storytelling in Games, Pt. 1" date: 2020-06-30 categories: gaming --- I had an interesting experience recently while showing my wife The Last of Us 2. We had just come off her watching me play through Death Stranding, which was the first game she'd watched me play and really the first modern game she had been made aware of. Prior to this, she had the usual notion that games were largely brainless excuses to shoot zombies, play sports, and generally partake in dynamic but meaningless activities. And she wasn't 100% incorrect. Anyway. I notice that as I'm playing TLOU2, there are some parts of the game that hold her interest easily - specifically, all of the emotion-heavy moments in the beginning of the game when the plot is getting set up and there's a lot of key cinematics and dialog. And then her focus wanes. A pretty long section of sneaking around and killing infected comes up. I have to plow through 30 minutes of methodically killing around a dozen enemies. Then there's some awkward moments where I have to randomly scrounge around for supplies and craft some items even though it doesn't really make sense in the current context of this character's situation. My wife is taken completely out of the immersion. I realize that as a lifelong gamer, I've built up mental callouses to these gamey segments and know them for what they are, but have to kind of apologetically explain them away to my wife as I play as to why the game is the way it is. Which isn't to take away anything from TLOU2 - it's pretty fantastic - it's more a symptom of the medium at large. My wife is by all accounts a cinephile and bookworm. Definitely somebody who invests herself in a good story. But in a demographic the game industry has yet to attract. ## Interactive storytelling Games let you play *as* the character, wouldn't this obviously be the most effective way to experience a story and communicate empathy to the player? Well, yes and no. There's a few problems with this. The main problem is that, as a player, the number of actions and interactions with the world, in a fully-dynamic perspective, are limited. You're usually limited to explicit actions like movement, picking things up, shooting guns, manipulating levers, and so forth. This means that it's quite doable for games to communicate explosive action scenes in a dynamic, emergent way, because your interaction with the world, as the player, only needs to consist of things like running, taking cover, and shooting. But what if you wanted an interactive scene with two people having a conversation at a dinner table? Are you going to make controls for doing everything the person might do during that conversation? And what about the dialog itself? Of course all of this has to be scripted. On top of this, interactivity is a double-edged sword. You trade directorial control (composition, timing, frame-by-frame minutae) for player agency. Sometimes this trade-off is worth it and sometimes it isn't. A good example of an extreme of this approach is Half-Life, where the player experiences everything from the perspective of Gordon Freeman and there are no cuts or any sense of a disembodied camera. While this does work on some level, it also results in an abnormally mute and kind of power-less main character - you have the ability to mow down hundreds of headcrabs, but you can't even have a basic social interaction with somebody that doesn't consist of them monologuing exposition at you. ## The bias towards action With the above in mind, we can conclude that most games have no choice but to heavily rely on extrinsic events happening to advance the plot which the player can participate in. There are games which have explored more "inner monologue" type stories which manifest themselves physically in the game world, such as Alan Wake, but even these tend to fall back on familiar patterns of interaction with the world: movement, shooting, collecting. One of my favorite styles of movie can be described as "slow cinema", which typically features languid, surreal imagery and evokes a melancholic mood. Perhaps not a single definable event happens during the whole film. Plot, or the lack of it, is expressed in stunted, subtle interactions. It's all about the little touch, the nudge, the hesitation of the camera. A contemporary game would take a huge risk employing this method of storytelling. The lack of player agency, the difficulty in allowing the player to have meaningful interaction in a world where over-the-top action does not fit...it's a hard problem. Do you just put the whole thing on rails? How would you approach this? A typical gamer would not find anything "fun" about a setup with no enemies to kill, no overt puzzles to solve. Maybe I'm coming off as elitist, but I don't mean to be. I genuinely want games to move on from where they're at, and I think I'm not alone in this sentiment. There has been a lot of change recently in the game industry regarding concepts like cinematic storytelling which I'd like to explore in future posts.
SQL
UTF-8
1,063
3.8125
4
[]
no_license
/*A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.*/ SELECT * FROM TABLE_NAME; /* Line 3 will allow all the element of the table to be displayed as * means all colomns */ /* Sql keyword are not case sensitive */ select = SELECT /* Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. */ /* Important SQL Command */ SELECT /* extracts data from a database*/ UPDATE /* updates data in a database*/ DELETE /* deletes data from a database*/ INSERT INTO /* inserts new data into a database*/ CREATE DATABASE /* creates a new database*/ ALTER DATABASE /* modifies a database*/ CREATE TABLE /* creates a new table*/ ALTER TABLE /* modifies a table*/ DROP TABLE /* deletes a table*/ CREATE INDEX /* creates an index (search key)*/ DROP INDEX /* deletes an index*/
JavaScript
UTF-8
806
2.546875
3
[]
no_license
function test() { var len = 64000, samples = new Float32Array(len); for(var i = 0; i < len; ++i) { samples[i] = 1 / (i + 1); } var checksum = 0, checkLength = len; for(var i = 0; i < checkLength; ++i) { checksum += samples[i]; } var source = new AudioDataMemorySource(new AudioParameters(1, 44100), samples); var dest = new AudioDataDestination(); dest.writeAsync(source); var written = dest.__audio.__hardwareWritten; // internal vars Testing.waitForExit(2500); Assert.assertEquals(dest.currentWritePosition, len, "Data written"); var sum = 0, checked = 0; for (var j = 0; j < written.length; ++j) { if (isNaN(written[j])) continue; sum += written[j]; if (++checked >= checkLength) break; } Assert.assertEquals(sum, checksum, "Data checksum"); }
Java
UTF-8
325
2.5625
3
[]
no_license
package com.student.java.module05.task1; public class Runner { public static void main(String[] args){ int [] arg = {3,7,34,51,9,1,2,5,63,24}; System.out.println(ArrayMinMaxSort.getMax(arg)); System.out.println(ArrayMinMaxSort.getMin(arg)); ArrayMinMaxSort.sortArray(arg); } }
PHP
UTF-8
2,107
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Jobs; use App\TestRequest; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class ProcessTest implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $recordID; /** * Create a new job instance. * * @return void */ public function __construct(String $recordID) { $this->recordID = $recordID; } /** * Execute the job. * * @return void */ public function handle(TestRequest $testRequest) { $theRequest = $testRequest->where("id", $this->recordID)->first(); $testDestination = (string) $theRequest->destination; // TODO: Add multi-router/multi-location support // Which test to run? switch($theRequest->type){ case "traceroute": // IPv4 traceroute $traceResult = shell_exec("traceroute $testDestination"); $theRequest->result = $traceResult; break; case "ping": // IPv4 ping $pingResult = shell_exec("ping -c 4 $testDestination"); $theRequest->result = $pingResult; break; case "mtr": // IPv4 MTR $mtrResult = shell_exec("mtr -r -c 2 $testDestination --report-wide"); $theRequest->result = $mtrResult; break; case "v4_suite": // Complete IPv4 test suite $traceResult = shell_exec("traceroute $testDestination"); $pingResult = shell_exec("ping -c 4 $testDestination"); $mtrResult = shell_exec("mtr -r -c 2 $testDestination --report-wide"); $theRequest->result = "Traceroute:\n" . $traceResult . "\n\nPing:\n" . $pingResult . "\n\nMTR:\n" . $mtrResult; break; } $theRequest->done = 1; $theRequest->save(); } }
Go
UTF-8
178
2.796875
3
[]
no_license
package bridge // Drawer draws on the underlying graphics device type Drawer interface { // DrawEllipseInRect draws an ellipse in rectanlge DrawEllipseInRect(r Rect) string }
Java
UTF-8
1,314
2.078125
2
[]
no_license
package com.kerols2020.cloudgallery; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.google.firebase.auth.FirebaseAuth; public class CoverActivity extends AppCompatActivity { RelativeLayout relative; FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cover); relative=findViewById(R.id.LINEAR); auth=FirebaseAuth.getInstance(); relative.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moveToMainActivity(); } } ); } private void moveToMainActivity() { startActivity(new Intent(CoverActivity.this,MainActivity.class)); finish(); } @Override protected void onStart() { super.onStart(); if (auth.getCurrentUser()==null) goToSignupActivity(); } private void goToSignupActivity() { startActivity(new Intent(CoverActivity.this,SignUpActivity.class)); finish(); } }
C#
UTF-8
1,365
3.109375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; namespace OutlawHessDB { class dbConnection { public static string source = @"Data Source = ..\bandits.db"; //sets location of database file in project folder //variables public bool connStatus; //used to confirm connection visually in forms public string exception; //used to pass error message to forms if needed public void dbconnStatus(SQLiteConnection conn) { exception = null; //clears exception try //try catch to create and check connection to database and sets connection status { conn = new SQLiteConnection(); conn.ConnectionString = dbConnection.source; conn.Open(); if (conn.State == System.Data.ConnectionState.Open) connStatus = true; } catch (Exception ex) //catch will set exception value to error that has occured if an error occurs { if (conn.State == System.Data.ConnectionState.Open) conn.Close(); connStatus = false; exception = ex.ToString(); } } } }
C#
UTF-8
859
2.71875
3
[]
no_license
using CSharpDiscovery.Quest02; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace tests { [TestClass] public class DifferenceInMinutesTests { [TestMethod] public void DifferenceInMinutes_2DateTimesTheSameDay_OK() { var start = new DateTime(2021, 02, 01, 12, 0, 0, 0); var end = new DateTime(2021, 02, 01, 18, 0, 0, 0); Assert.AreEqual(360, DifferenceInMinutes_Exercice.DifferenceInMinutes(start, end)); } [TestMethod] public void DifferenceInMinutes_2DateTimesTheSameYear_OK() { var start = new DateTime(2021, 02, 01, 12, 23, 0, 0); var end = new DateTime(2021, 08, 01, 18, 0, 0, 0); Assert.AreEqual(260977, DifferenceInMinutes_Exercice.DifferenceInMinutes(start, end)); } } }
C++
UTF-8
1,622
2.5625
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; void binary(int a, int s[]) { int i = 7; while (a > 0) { s[i--] = a % 2; a /= 2; } if (i >= 0) { for (; i >= 0; i--) s[i] = 0; } } int decimal(int s[]) { int i, n = 0, t = 1; for (i = 7; i >= 0; i--) { if (s[i]) n += t; t *= 2; } return n; } int main(void) { int n, i, t, address[4], mask[4], ip[4][1005], a[32], b[32], c[32], d[32]; while (cin >> n) { for (i = 0; i < n; i++) scanf("%d.%d.%d.%d", &ip[0][i], &ip[1][i], &ip[2][i], &ip[3][i]); for (i = 0; i < 4; i++) sort(ip[i], ip[i] + n); for (i = 0; i < 4; i++) { binary(ip[i][0], a + 8 * i); binary(ip[i][n - 1], b + 8 * i); } for (i = 0; i < 32; i++) if (a[i] != b[i]) break; t = 32 - i; for (i = 0; i < 32; i++) { if (i < 32 - t) { c[i] = a[i]; d[i] = 1; } else { c[i] = 0; d[i] = 0; } } for (i = 0; i < 4; i++) { address[i] = decimal(c + i * 8); mask[i] = decimal(d + i * 8); } printf("%d.%d.%d.%d\n", address[0], address[1], address[2], address[3]); printf("%d.%d.%d.%d\n", mask[0], mask[1], mask[2], mask[3]); } return 0; } //转自https://segmentfault.com/a/1190000012569261
C++
UTF-8
1,721
3.03125
3
[]
no_license
#ifndef BOARDACTOR_HH #define BOARDACTOR_HH #include <QtWidgets> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QMimeData> /** * @file * @brief Implements graphic class BoardActor */ namespace Ui { /** * @brief Offers an graphical class for * different actors. Actors roam around the * gameboard and cause actions whenever their location hex tiles are flipped. */ class BoardActor: public QGraphicsPolygonItem { public: /** * @brief Constructor. * @param parent Parent GraphicsItem for actor * @param id Identification number for actor * @param actorType Type of actor */ explicit BoardActor(QGraphicsItem *parent = 0, int id = 0, std::string actorType = ""); /** * @brief Default destructor */ ~BoardActor() = default; /** * @brief drawActor draws the graphical actor on board * @post Exception quarantee: strong */ void drawActor(); /** * @brief overrided QT mousePressEvent tracks clicking of actor graphics * @param event QT scene mouse event * @post Drag event sends valid mimedata to item actor was dropped to * @post Exception quarantee: strong */ void mousePressEvent(QGraphicsSceneMouseEvent *event) override; private: //! Size of the actor int size_; //! Identification number of the actor int actorId_; //! Brush to color the actor with QBrush brush_; //! Type of the actor std::string actorType_; //! Polygon shape of the actor QPolygonF polygon_; //! TextItem to draw on top of the actor QGraphicsSimpleTextItem *textItem_; }; } #endif // BOARDACTOR_HH
JavaScript
UTF-8
1,447
2.953125
3
[]
no_license
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; export const Skills = props => { const skillsSortedByLevel = Object.values(props.skills).reduce((acc, skill) => { if (!acc[skill.level] && skill.level > 0) acc[skill.level] = [skill]; else acc[skill.level].push(skill); return acc; }, {}); // Skills should be displayed in pairs of levels side by side, with a "tab" of the level // and then a list of all the skills learned at that level // e.g.: Level 1: Slash Level 2: Searing light // Heal // Level 3: Fireball Level 4: Lightning bolt const skillBoxes = Object.keys(skillsSortedByLevel).map((skillLevel, i) => { return <li key={i} className="level-box"> <p className="level">Level {skillLevel}:</p> <ul className="skill-list"> {skillsSortedByLevel[skillLevel].map((skill, j) => <li key={j}>{`${skill.skillName[0].toUpperCase()}${skill.skillName.slice(1)}`}</li>)} </ul> </li>; }); const dualBoxes = []; for (let i = 0; i < skillBoxes.length; i += 2) { dualBoxes.push(<ul key={`${i}dual`} className="dual-box"> {skillBoxes[i]} {skillBoxes[i + 1]} </ul>); } return <div className="skills"> <ul>{dualBoxes}</ul> <div className="clearfix" style={{clear: 'both'}}></div> </div>; }; Skills.propTypes = { skills: PropTypes.object };
C++
UTF-8
3,246
2.78125
3
[ "BSL-1.0" ]
permissive
// Copyright David Stone 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <tm/evaluate/best_move.hpp> #include <tm/evaluate/compressed_battle.hpp> #include <tm/evaluate/depth.hpp> #include <tm/move/moves.hpp> #include <tm/compress.hpp> #include <tm/weather.hpp> #include <bounded/optional.hpp> #include <containers/array/array.hpp> #include <containers/index_type.hpp> namespace technicalmachine { template<Generation> struct Team; template<Generation generation> struct TranspositionTable { auto add_score(Team<generation> const & ai, Team<generation> const & foe, Weather weather, DepthValues const depth, BestMove best_move) -> void { auto const compressed_battle = compress_battle(ai, foe, weather); auto & value = m_data[index(compressed_battle)]; value.compressed_battle = compressed_battle; value.depth = depth; value.move = best_move.name; value.score = best_move.score; } auto get_score(Team<generation> const & ai, Team<generation> const & foe, Weather weather, DepthValues const depth) const -> bounded::optional<BestMove> { auto const compressed_battle = compress_battle(ai, foe, weather); auto const & value = m_data[index(compressed_battle)]; if (value.depth >= depth and value.compressed_battle == compressed_battle) { return BestMove{value.move, value.score}; } return bounded::none; } private: struct Value { CompressedBattle<generation> compressed_battle = {}; DepthValues depth = {}; Moves move = {}; double score = 0.0; }; static constexpr auto size = bounded::constant<1 << 13>; using Data = containers::array<Value, size.value()>; using Index = containers::index_type<Data>; template<bounded::bounded_integer Output> static constexpr auto update_hash(Output & output, bounded::bounded_integer auto input) { while (input != 0_bi) { auto const temp = input % size; input /= size; output = Output(output.value() xor temp.value()); } } template<std::size_t... indexes> static constexpr auto hash(CompressedBattle<generation> const & compressed_battle, std::index_sequence<indexes...>) { static_assert(bounded::pow(2_bi, bounded::log(size, 2_bi)) == size, "Size must be a power of 2"); auto result = bounded::integer<0, bounded::normalize<(size - 1_bi).value()>>(0_bi); (..., update_hash(result, compressed_battle[bounded::constant<indexes>])); return result; } static auto index(CompressedBattle<generation> const & compressed_battle) -> Index { return hash( compressed_battle, bounded::make_index_sequence(bounded::tuple_size<CompressedBattle<generation>>) ); } Data m_data; }; extern template struct TranspositionTable<Generation::one>; extern template struct TranspositionTable<Generation::two>; extern template struct TranspositionTable<Generation::three>; extern template struct TranspositionTable<Generation::four>; extern template struct TranspositionTable<Generation::five>; extern template struct TranspositionTable<Generation::six>; extern template struct TranspositionTable<Generation::seven>; extern template struct TranspositionTable<Generation::eight>; } // namespace technicalmachine
Markdown
UTF-8
6,619
2.828125
3
[]
no_license
Statsite [![Build Status](https://travis-ci.org/armon/statsite.png)](https://travis-ci.org/armon/statsite) ======== This is a stats aggregation server. Statsite is based heavily on Etsy's StatsD <https://github.com/etsy/statsd>. This is a re-implementation of the Python version of statsite <https://github.com/kiip/statsite>. Features -------- * Basic key/value metrics * Send timer data, statsite will calculate: - Mean - Min/Max - Standard deviation - Median, Percentile 95, Percentile 99 * Send counters that statsite will aggregate * Binary protocol Architecture ------------- Statsite is designed to be both highly performant, and very flexible. To achieve this, it implements the stats collection and aggregation in pure C, using libev to be extremely fast. This allows it to handle hundreds of connections, and millions of metrics. After each flush interval expires, statsite performs a fork/exec to start a new stream handler invoking a specified application. Statsite then streams the aggregated metrics over stdin to the application, which is free to handle the metrics as it sees fit. This allows statsite to aggregate metrics and then ship metrics to any number of sinks (Graphite, SQL databases, etc). There is an included Python script that ships metrics to graphite. Additionally, statsite tries to minimize memory usage by not storing all the metrics that are received. Counter values are aggregated as they are received, and timer values are stored and aggregated using the Cormode-Muthurkrishnan algorithm from "Effective Computation of Biased Quantiles over Data Streams". This means that the percentile values are not perfectly accurate, and are subject to a specifiable error epsilon. This allows us to store only a fraction of the samples. Install ------- Download and build from source:: $ git clone https://github.com/armon/statsite.git $ cd statsite $ pip install SCons # Uses the Scons build system, may not be necessary $ scons $ ./statsite Building the test code may generate errors if libcheck is not available. To build the test code successfully, do the following:: $ cd deps/check-0.9.8/ $ ./configure $ make # make install # ldconfig (necessary on some Linux distros) $ cd ../../ $ scons test_runner At this point, the test code should build successfully. Usage ----- Statsite is configured using a simple INI file. Here is an example configuration file:: [statsite] port = 8125 udp_port = 8125 log_level = INFO flush_interval = 10 timer_eps = 0.01 stream_cmd = python sinks/graphite.py localhost 2003 Then run statsite, pointing it to that file:: statsite -f /etc/statsite.conf Protocol -------- By default, Statsite will listen for TCP and UDP connections. A message looks like the following (where the flag is optional):: key:value|type[|@flag] Messages must be terminated by newlines (`\n`). Currently supported message types: * `kv` - Simple Key/Value. * `g` - Same as `kv`, compatibility with statsd gauges * `ms` - Timer. * `c` - Counter. After the flush interval, the counters and timers of the same key are aggregated and this is sent to the store. Examples: The following is a simple key/value pair, in this case reporting how many queries we've seen in the last second on MySQL:: mysql.queries:1381|kv The following is a timer, timing the response speed of an API call:: api.session_created:114|ms The next example is increments the "rewards" counter by 1:: rewards:1|c And this example decrements the "inventory" counter by 7:: inventory:-7|c Writing Statsite Sinks --------------------- Statsite only ships with a graphite sink by default, but any executable can be used as a sink. The sink should read its inputs from stdin, where each metric is in the form:: key|val|timestamp Each metric is separated by a newline. The process should terminate with an exit code of 0 to indicate success. Binary Protocol --------------- In addition to the statsd compatible ASCII protocol, statsite includes a lightweight binary protocol. This can be used if you want to make use of special characters such as the colon, pipe character, or newlines. It is also marginally faster to process, and may provide 10-20% more throughput. Each command is sent to statsite over the same ports in the following manner: <Magic Byte><Metric Type><Key Length><Value><Key> The "Magic Byte" is the value 0xaa (170). This switches the internal processing from the ASCII mode to binary. The metric type is one of: * 0x1 : Key value / Gauge * 0x2 : Counter * 0x3 : Timer The key length is a 2 byte unsigned integer with the length of the key, INCLUDING a NULL terminator. The key must include a null terminator, and it's length must include this. The value is a standard IEEE754 double value, which is 8 bytes in length. Lastly, the key is provided as a byte stream which is `Key Length` long, terminated by a NULL (0) byte. All of these values must be transmitted in Little Endian order. Here is an example of sending ("Conns", "c", 200) as hex: 0xaa 0x02 0x0600 0x0000000000006940 0x436f6e6e7300 Binary Sink Protocol -------------------- It is also possible to have the data streamed to be represented in a binary format. Again, this is used if you want to use the reserved characters. It may also be faster. Each command is sent to the sink in the following manner: <Timestamp><Metric Type><Value Type><Key Length><Value><Key> Most of these are the same as the binary protocol. There are a few. changes however. The Timestamp is sent as an 8 byte unsigned integer, which is the current Unix timestamp. The Metric type is one of: * 0x1 : Key value / Gauge * 0x2 : Counter * 0x3 : Timer The value type is one of: * 0x0 : No type (Key/Value) * 0x1 : Sum * 0x2 : Sum Squared * 0x3 : Mean * 0x4 : Count * 0x5 : Standard deviation * 0x6 : Minimum Value * 0x7 : Maximum Value * 0x80 OR `percentile` : If the type OR's with 128 (0x80), then it is a percentile amount. The amount is OR'd with 0x80 to provide the type. For example (0x80 | 0x32) = 0xb2 is the 50% percentile or medium. The 95th percentile is (0x80 | 0xdf) = 0xdf. The key length is a 2 byte unsigned integer representing the key length terminated by a NULL character. The Value is an IEEE754 double. Lastly, the key is a NULL-terminated character stream. To enable the binary sink protocol, add a configuration variable `binary_stream` to the configuration file with the value `yes`. An example sink is provided in `sinks/binary_sink.py`.
Java
UTF-8
1,990
2.609375
3
[]
no_license
package com.example.astroweather.data; public class WeatherInfo { private String imageId; private String longitude; private String latitude; private String cityName; private String pressure; private String description; private String date; private float temperature; public WeatherInfo(String imageId, String longitude, String latitude, String cityName, String pressure, String description, float temperature, String date) { this.imageId = imageId; this.longitude = longitude; this.latitude = latitude; this.cityName = cityName; this.pressure = pressure; this.description = description; this.temperature = temperature; this.date = date; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getPressure() { return pressure; } public void setPressure(String pressure) { this.pressure = pressure; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public float getTemperature() { return temperature; } public void setTemperature(float temperature) { this.temperature = temperature; } }
C#
UTF-8
1,735
3.234375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ether.WeightedSelector.Extensions { public static class ExtensionMethods { public static int AverageWeight<T>(this WeightedSelector<T> selector) { return selector.Items.Count == 0 ? 0 : (int) selector.Items.Average(t => t.Weight); } public static int Count<T>(this WeightedSelector<T> selector) { return selector.Items.Count(); } public static int MaxWeight<T>(this WeightedSelector<T> selector) { return selector.Items.Count == 0 ? 0 : selector.Items.Max(t => t.Weight); } public static int MinWeight<T>(this WeightedSelector<T> selector) { return selector.Items.Count == 0 ? 0 : selector.Items.Min(t => t.Weight); } public static int TotalWeight<T>(this WeightedSelector<T> selector) { return selector.Items.Count == 0 ? 0 : selector.Items.Sum(t => t.Weight); } #region "Sorting" public static List<WeightedItem<T>> ListByWeightDescending<T>(this WeightedSelector<T> selector) { var Result = (from Item in selector.Items orderby Item.Weight descending select Item).ToList(); return Result; } public static List<WeightedItem<T>> ListByWeightAscending<T>(this WeightedSelector<T> selector) { var Result = (from Item in selector.Items orderby Item.Weight ascending select Item).ToList(); return Result; } #endregion } }
C#
UTF-8
381
3.109375
3
[]
no_license
using System; namespace MethodsReturn { class Program { static void Main(string[] args) { Console.WriteLine(divideNumeros(18,7)); } static double divideNumeros(double n1, double n2) { return n1 / n2; } // static void divideNumeros(double n1, double n2)=> n1/n2; } }
Python
UTF-8
143
3.078125
3
[]
no_license
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ a = [''] * 15 for i in range(len(a)): a[i] = 'line' + str(i) print(a) print(a[9])
C++
UTF-8
1,272
4.125
4
[]
no_license
#include <iostream> #include "ArraySet.h" using namespace std; template<class ItemType> void display(ArraySet<ItemType>& set) { cout << "The bag contains " << set.getCurrentSize() << " items:" << endl; // convert to vector and iterate through vector<ItemType> setItems = set.toVector(); size_t numberOfEntries = static_cast<size_t>(setItems.size()); for (int i = 0; i < numberOfEntries; i++) { cout << setItems[i] << " "; } cout << endl; } int main() { // test functions with int int num[] = { 23, 56, 38, 81, 32, 13, 1 }; size_t size = sizeof(num) / sizeof(num[0]); auto intSet = ArraySet<int>(num, size); display<int>(intSet); cout << "\n(1 = true, 0 = false) Add 24: " << intSet.add(24) << endl; display<int>(intSet); cout << "\n(1 = true, 0 = false) Add 23: " << intSet.add(23) << endl; display<int>(intSet); cout << "\n(1 = true, 0 = false) Remove 23: " << intSet.remove(23) << endl; display<int>(intSet); cout << "\nClear!\n"; intSet.clear(); display<int>(intSet); cout << endl; // test template with different type const char * strings[] = { "Hi", "my", "name", "is", "Ryan" }; size = sizeof(strings) / sizeof(strings[0]); auto stringSet = ArraySet<const char *>(strings, size); display<const char *>(stringSet); cout << endl; }
Shell
UTF-8
306
3.140625
3
[]
no_license
#!/bin/bash for algo in tree naiveBayes knn; do csvs=$(find output/$algo -name "*.csv") first=1 for csv in $csvs; do if [[ $first == 1 ]]; then sed -n '1p' < $csv > output/$algo.csv first=0 fi sed -n '2p' < $csv >> output/$algo.csv done done
Java
UTF-8
5,249
1.859375
2
[]
no_license
13 https://raw.githubusercontent.com/CoboVault/cobo-vault-cold/master/app/src/main/java/com/cobo/cold/ui/fragment/main/AddressFragment.java /* * Copyright (c) 2020 Cobo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * in the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ package com.cobo.cold.ui.fragment.main; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.RecyclerView; import com.cobo.cold.R; import com.cobo.cold.databinding.AddressFragmentBinding; import com.cobo.cold.db.entity.AddressEntity; import com.cobo.cold.ui.fragment.BaseFragment; import com.cobo.cold.util.Keyboard; import com.cobo.cold.viewmodel.CoinViewModel; import java.util.List; import java.util.Objects; import static com.cobo.cold.ui.fragment.Constants.KEY_ADDRESS; import static com.cobo.cold.ui.fragment.Constants.KEY_ADDRESS_NAME; import static com.cobo.cold.ui.fragment.Constants.KEY_COIN_CODE; import static com.cobo.cold.ui.fragment.Constants.KEY_COIN_ID; import static com.cobo.cold.ui.fragment.Constants.KEY_ID; public class AddressFragment extends BaseFragment<AddressFragmentBinding> { String query; private CoinViewModel viewModel; private final AddressCallback mAddrCallback = new AddressCallback() { @Override public void onClick(AddressEntity addr) { if (mAddressAdapter.isEditing()) { mAddressAdapter.exitEdit(); } else { Bundle bundle = Objects.requireNonNull(getArguments()); Bundle data = new Bundle(); data.putString(KEY_COIN_CODE, bundle.getString(KEY_COIN_CODE)); data.putString(KEY_ADDRESS, addr.getAddressString()); data.putString(KEY_ADDRESS_NAME, addr.getName()); navigate(R.id.action_to_receiveCoinFragment, data); } } @Override public void onNameChange(AddressEntity addr) { viewModel.updateAddress(addr); } }; private AddressAdapter mAddressAdapter; public void exitEditAddressName() { if (mAddressAdapter.isEditing()) { mAddressAdapter.exitEdit(); } } public static Fragment newInstance(long id, @NonNull String coinId, @NonNull String coinCode) { AddressFragment fragment = new AddressFragment(); Bundle args = new Bundle(); args.putLong(KEY_ID, id); args.putString(KEY_COIN_ID, coinId); args.putString(KEY_COIN_CODE, coinCode); fragment.setArguments(args); return fragment; } @Override protected int setView() { return R.layout.address_fragment; } @Override protected void init(View view) { mAddressAdapter = new AddressAdapter(mActivity, mAddrCallback); mBinding.addrList.setAdapter(mAddressAdapter); mAddressAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { super.onChanged(); if (!TextUtils.isEmpty(query) && mAddressAdapter.getItemCount() == 0) { mBinding.empty.setVisibility(View.VISIBLE); mBinding.addrList.setVisibility(View.GONE); } else { mBinding.empty.setVisibility(View.GONE); mBinding.addrList.setVisibility(View.VISIBLE); } } }); } @Override protected void initData(Bundle savedInstanceState) { Bundle data = Objects.requireNonNull(getArguments()); Objects.requireNonNull(getParentFragment()); CoinViewModel.Factory factory = new CoinViewModel.Factory(mActivity.getApplication(), data.getLong(KEY_ID), data.getString(KEY_COIN_ID)); viewModel = ViewModelProviders.of(getParentFragment(), factory) .get(CoinViewModel.class); subscribeUi(viewModel.getAddress()); } private void subscribeUi(LiveData<List<AddressEntity>> address) { address.observe(this, entities -> mAddressAdapter.setItems(entities)); } public void setQuery(String s) { query = s; mAddressAdapter.getFilter().filter(s); } public void enterSearch() { if (mAddressAdapter != null) { mAddressAdapter.enterSearch(); } } @Override public void onStop() { super.onStop(); Keyboard.hide(mActivity, Objects.requireNonNull(getView())); } }
C++
UTF-8
1,516
3.65625
4
[]
no_license
/* Samantha Oxley ISTE 202 - Lab 05 Structs & File I/O simple setting/printing of struct data to output and then appended to file */ #include <iostream> #include <iomanip> #include <fstream> using namespace std; struct Commission{ int idNum; double base; double sales; double rate; }; void structSet(Commission&); void structPrint(Commission); int main(){ Commission comm; ofstream fout; string filename; structSet(comm); structPrint(comm); do{ cout << "Enter a filename to record user information:"; cin >> filename; fout.open(filename.c_str(), ios::app); }while( !fout.is_open() ); fout << "idNum:" << setw(10) << comm.idNum << endl; fout << "base:" << setw(10) << comm.base << endl; fout << "sales:" << setw(10) << comm.sales << endl; fout << "rate:" << setw(10) << comm.rate << endl; } void structSet(Commission& comm){ cout << "Please enter identification number:"; cin >> comm.idNum; cout << "Please enter base salary:"; cin >> comm.base; cout << "Please enter sales amount for period:"; cin >> comm.sales; cout << "Please enter commission rate(as fraction):"; cin >> comm.rate; cin.ignore(1000, '\n'); //flushhhhh } void structPrint(Commission comm){ cout << "idNum:" << setw(10) << comm.idNum << endl; cout << "base:" << setw(10) << comm.base << endl; cout << "sales:" << setw(10) << comm.sales << endl; cout << "rate:" << setw(10) << comm.rate << endl; }
Markdown
UTF-8
30,534
3.46875
3
[]
no_license
# Laporan Resmi Sistem Operasi Modul3 E09 #### Fandi Pranata Jaya - 05111740000056 #### Fadhil Musaad Al Giffary - 05111740000116 ## Nomor 1 ### Soal: 1. Buatlah program C yang bisa menghitung faktorial secara parallel lalu menampilkan hasilnya secara berurutan <br/>Contoh: <br/>./faktorial 5 3 4 <br/>3! = 6 <br/>4! = 24 <br/>5! = 120 ### Jawaban: Pertama - tama untuk menghitung faktorial secara parallel kita perlu membuat thread sebanyak parameter inputan yang di passing ke `int main()` dengan menggunakan syntax: ``` #include<stdio.h> #include<string.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> pthread_t tid[1005]; int main(int argc, char *argv[]) { t = argc-1; for (int i = 0; i < t; i++) { fact[i]=strtol(argv[i+1], NULL, 10); int err = pthread_create(&(tid[i]), NULL, &factorial, NULL); if (err != 0) printf("\n can't create thread : [%s]",strerror(err)); } } ``` Kemudian untuk menghitung faktorialnya digunakan fungsi seperti berikut: ``` int t, fact[1005], ans[1005]; void* factorial(void *arg) { pthread_t id = pthread_self(); for (int i = 0; i < t; i++) { if (pthread_equal(id, tid[i])) { ans[i]=1; for(int j=0; j<fact[i]; j++){ ans[i]=ans[i]*(fact[i]-j); } } } return NULL; } ``` Setelah itu agar hasilnya urut, maka perlu digunakan `pthread_join()` agar semua thread menunggu satu sama lain sampai semua selesai (return NULL) dan kemudian array inputan dan hasil disort dengan fungsi merge sort seperti syntax dibawah ini: ``` void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l+(r-l)/2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); } } int main(){ mergeSort(fact,0,t-1); mergeSort(ans,0,t-1); } ``` Kemudian tinggal print semua nilai yang ada di array yang sudah tersort secara urut. ## Nomor 2 ### Soal: 2. Pada suatu hari ada orang yang ingin berjualan 1 jenis barang secara private, dia memintamu membuat program C dengan spesifikasi sebagai berikut: * Terdapat 2 server: server penjual dan server pembeli * 1 server hanya bisa terkoneksi dengan 1 client * Server penjual dan server pembeli memiliki stok barang yang selalu sama * Client yang terkoneksi ke server penjual hanya bisa menambah stok * Cara menambah stok: client yang terkoneksi ke server penjual mengirim string “tambah” ke server lalu stok bertambah 1 * Client yang terkoneksi ke server pembeli hanya bisa mengurangi stok * Cara mengurangi stok: client yang terkoneksi ke server pembeli mengirim string “beli” ke server lalu stok berkurang 1 * Server pembeli akan mengirimkan info ke client yang terhubung dengannya apakah transaksi berhasil atau tidak berdasarkan ketersediaan stok * Jika stok habis maka client yang terkoneksi ke server pembeli akan mencetak “transaksi gagal” * Jika stok masih ada maka client yang terkoneksi ke server pembeli akan mencetak “transaksi berhasil” * Server penjual akan mencetak stok saat ini setiap 5 detik sekali * __Menggunakan thread, socket, shared memory__ ## Jawaban: Langkah pertama adalah membuat dua buah server untuk penjual dan pembeli yang memiliki suatu shared memory untuk memeriksa stock barang. Sintaks untuk keduanya adalah: ``` int *stock; ... key_t key = 1234; int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666); stock = shmat(shmid, NULL, 0); *stock = 0; ... shmdt(stock); shmctl(shmid, IPC_RMID, NULL); ``` Lalu, agar masing - masing server dapat terhubung dengan clientnya masing - masing maka dibuatkan socket untuk tiap server dengan port yang berbeda dalam hal ini, pembeli di assign dengan port 8080. Sintaks server pembeli menjadi: ``` #define PORT 8080 int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[10] = {0}; char *fail = "transaksi gagal"; char *success = "transaksi berhasil"; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } ``` Sedangkan penjual akan diberikan port 8000. Sntaksnya menjadi: ``` int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; ... if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } ``` Dapat diperhatikan bahwa untuk server pembeli hanya perlu mengirimkan hasil transaksi gagal atau berhasil sekaligus mengurangi stok sehingga pada main programnya hanya memerlukan: ``` while (1) { valread = read( new_socket , buffer, 10); if (*stock <= 0) { send(new_socket , fail , strlen(fail) , 0 ); } else { send(new_socket , success , strlen(success) , 0 ); (*stock)--; } } ``` Sedangkan untuk server penjual perlu menambah stok dan display stock setiap 5 detik secara paralel. Sehingga diperlukan multi threading ``` void* routine(void *arg) { pthread_t id = pthread_self(); if (pthread_equal(id, tid[0])) { while (1) { printf("Stock: %d\n", *stock); sleep(5); } } else { while (1) { valread = read( new_socket , buffer, 1024); (*stock)++; } } return NULL; } ... pthread_create(&(tid[0]),NULL,&routine,NULL); pthread_create(&(tid[1]),NULL,&routine,NULL); pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); ``` Jika sudah, maka pembuatan server telah selesai. Untuk membuat client cukup membuat socket dengan port yang bersesuaian dengan servernya dan inputan masing - masing. Untuk client pembeli sintaksnya: ``` #define PORT 8080 ... struct sockaddr_in address; int sock = 0, valread; struct sockaddr_in serv_addr; char input[10]; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if(inet_pton(AF_INET, "192.168.43.160", &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } while (1) { scanf("%s", input); send(sock , input , strlen(input) , 0 ); memset(buffer, 0, sizeof buffer); valread = read( sock , buffer, 1024); printf("%s\n",buffer ); } ``` Sedangkan untuk penjual sintaksnya: ``` #define PORT 8000 struct sockaddr_in address; int sock = 0, valread; struct sockaddr_in serv_addr; char input[10]; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if(inet_pton(AF_INET, "192.168.43.160", &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } while (1) { scanf("%s", input); send(sock , input , strlen(input) , 0 ); } ``` ## Nomor 3 ### Soal: 3. Agmal dan Iraj merupakan 2 sahabat yang sedang kuliah dan hidup satu kostan, sayangnya mereka mempunyai gaya hidup yang berkebalikan, dimana Iraj merupakan laki-laki yang sangat sehat,rajin berolahraga dan bangun tidak pernah kesiangan sedangkan Agmal hampir menghabiskan setengah umur hidupnya hanya untuk tidur dan ‘ngoding’. Dikarenakan mereka sahabat yang baik, Agmal dan iraj sama-sama ingin membuat satu sama lain mengikuti gaya hidup mereka dengan cara membuat Iraj sering tidur seperti Agmal, atau membuat Agmal selalu bangun pagi seperti Iraj. Buatlah suatu program C untuk menggambarkan kehidupan mereka dengan spesifikasi sebagai berikut: <br/>a. Terdapat 2 karakter Agmal dan Iraj <br/>b. Kedua karakter memiliki status yang unik * Agmal mempunyai WakeUp_Status, di awal program memiliki status 0 * Iraj memiliki Spirit_Status, di awal program memiliki status 100 * Terdapat 3 Fitur utama * All Status, yaitu menampilkan status kedua sahabat <br/>Ex: Agmal WakeUp_Status = 75 <br/> Iraj Spirit_Status = 30 * “Agmal Ayo Bangun” menambah WakeUp_Status Agmal sebesar 15 point * “Iraj Ayo Tidur” mengurangi Spirit_Status Iraj sebanyak 20 point * Terdapat Kasus yang unik dimana: * Jika Fitur “Agmal Ayo Bangun” dijalankan sebanyak 3 kali, maka Fitur “Iraj Ayo Tidur” Tidak bisa dijalankan selama 10 detik (Dengan mengirim pesan ke sistem “Fitur Iraj Ayo Tidur disabled 10 s”) * Jika Fitur “Iraj Ayo Tidur” dijalankan sebanyak 3 kali, maka Fitur “Agmal Ayo Bangun” Tidak bisa dijalankan selama 10 detik (Dengan mengirim pesan ke sistem “Agmal Ayo Bangun disabled 10 s”) * Program akan berhenti jika Salah Satu : * WakeUp_Status Agmal >= 100 (Tampilkan Pesan “Agmal Terbangun,mereka bangun pagi dan berolahraga”) * Spirit_Status Iraj <= 0 (Tampilkan Pesan “Iraj ikut tidur, dan bangun kesiangan bersama Agmal”) * Syarat Menggunakan Lebih dari 1 Thread ### Jawaban: Pertama - tama kita perlu membuat 3 thread untuk fitur "Agmal Ayo Bangun", "Iraj Ayo Tidur", "All Status". Kemudian membuat fungsi untuk ketiga thread tersebut dengan syntax seperti berikut: ``` void* agmalandiraj(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[0])) { if(inputflag==2){ //printf("%d %d %d %d %d\n",flag1,flag2,counter1,counter2,inputflag); if(flag1==1){ status[0]+=15; counter1++; if(counter1==3){ flag2=0; } if (status[0] >= 100) { puts("Agmal Terbangun,mereka bangun pagi dan berolahraga"); exit(0); } } inputflag = 0; }else{ if(counter2>=3){ sleep(10); puts("Agmal Ayo Bangun enable again"); counter2=counter2-3; flag1=1; inputflag = 0; } } } else if (pthread_equal(id, tid[1])) { if(inputflag==3){ //printf("%d %d %d %d %d\n",flag1,flag2,counter1,counter2,inputflag); if(flag2==1){ status[1]-=20; counter2++; if(counter2==3){ flag1=0; } if (status[1] <= 0) { puts("Iraj ikut tidur, dan bangun kesiangan bersama Agmal"); exit(0); } } inputflag = 0; }else{ if(counter1>=3){ sleep(10); puts("Iraj Ayo Tidur enable again"); counter1=counter1-3; flag2=1; inputflag = 0; } } } else if (pthread_equal(id, tid[2])){ if(inputflag==1){ inputflag = 0; printf("Agmal WakeUp_Status: %d\nIraj Spirit_Status: %d\n", status[0], status[1]); } } } return NULL; } ``` Fungsi tersebut perlu di looping terus agar thread dapat berjalan terus menerus sampai kondisi tertentu. Kemudian di `int main()` juga perlu dilakukan looping untuk menerima inputan user berulang kali seperti syntax berikut ini: ``` int main(){ while (1) { scanf(" %[^\t\n]s",inputString); //printf("%s\n",inputString); if (strcmp(inputString, "All Status") == 0) { inputflag = 1; } else if (strcmp(inputString, "Agmal Ayo Bangun") == 0){ inputflag = 2; if(counter2>=3){ puts("Agmal Ayo Bangun disabled 10 s"); } } else if (strcmp(inputString, "Iraj Ayo Tidur") == 0){ inputflag = 3; if(counter1>=3){ puts("Fitur Iraj Ayo Tidur disabled 10 s"); } } } } ``` Jika inputan user adalah "Agmal Ayo Bangun", maka akan menambah WakeUp_Status Agmal sebesar 15, jika inputan user adalah "Iraj Ayo Tidur", maka akan mengurangi Spirit_Status Iraj sebanyak 20, jika inputan user adalah "All Status", maka akan menampilkan WakeUp_Status dari Agmal dan Spirit_Status dari Iraj. Jika fitur Agmal Ayo Bangun dijalankan, maka counter1 akan ditambah 1, Jika fitur Iraj Ayo Tidur dijalankan, maka counter2 akan ditambah 1. Jika counter1>=3 maka counter1 akan dikurangi 3 dan fitur Iraj Ayo Tidur akan didisable selama 10 detik. Jika counter2>=3 maka counter2 akan dikurangi 3 dan fitur Agmal Ayo Bangun akan didisable selama 10 detik. Program akan berakhir jika WakeUp_Status Agmal >=100 dan Spirit_Status Iraj <=0. ## Nomor 4 ### Soal: 4. Buatlah sebuah program C dimana dapat menyimpan list proses yang sedang berjalan (ps -aux) maksimal 10 list proses. Dimana awalnya list proses disimpan dalam di 2 file ekstensi .txt yaitu SimpanProses1.txt di direktori /home/Document/FolderProses1 dan SimpanProses2.txt di direktori /home/Document/FolderProses2 , setelah itu masing2 file di kompres zip dengan format nama file KompresProses1.zip dan KompresProses2.zip dan file SimpanProses1.txt dan SimpanProses2.txt akan otomatis terhapus, setelah itu program akan menunggu selama 15 detik lalu program akan mengekstrak kembali file KompresProses1.zip dan KompresProses2.zip __Dengan Syarat :__ * Setiap list proses yang di simpan dalam masing-masing file .txt harus berjalan bersama-sama * Ketika mengkompres masing-masing file .txt harus berjalan bersama-sama * Ketika Mengekstrak file .zip juga harus secara bersama-sama * Ketika Telah Selesai melakukan kompress file .zip masing-masing file, maka program akan memberi pesan “Menunggu 15 detik untuk mengekstrak kembali” * Wajib Menggunakan Multithreading * Boleh menggunakan system ### Jawaban: Langkah pertama adalah membuat 2 thread yang akan berjalan bersamaan ``` for (int i = 0; i < 2; i++) { pthread_create(&(tid[i]), NULL, &playandcount, NULL); } for (int i = 0; i < 2; i++) pthread_join(tid[i],NULL); ``` Lalu tiap thread akan menjalankan routine sebagai berikut: ``` system("mkdir /home/[user]/Documents/FolderProses[id_thread]"); system("ps -aux | head > /home/[user]/Documents/FolderProses[id_thread]/SimpanProses[id_thread].txt"); system("zip -mj /home/[user]/Documents/FolderProses[id_thread]/KompresProses[id_thread].zip /home/[user]/Documents/FolderProses[id_thread]/SimpanProses[id_thread].txt"); sleep(15); system("unzip /home/[user]/Documents/FolderProses[id_thread]/KompresProses[id_thread].zip -d /home/[user]/Documents/FolderProses[id_thread]/"); ``` ## Nomor 5 ### Soal: 5. Angga, adik Jiwang akan berulang tahun yang ke sembilan pada tanggal 6 April besok. Karena lupa menabung, Jiwang tidak mempunyai uang sepeserpun untuk membelikan Angga kado. Kamu sebagai sahabat Jiwang ingin membantu Jiwang membahagiakan adiknya sehingga kamu menawarkan bantuan membuatkan permainan komputer sederhana menggunakan program C. Jiwang sangat menyukai idemu tersebut. Berikut permainan yang Jiwang minta. <br/>a. Pemain memelihara seekor monster lucu dalam permainan. Pemain dapat memberi nama pada monsternya. <br/>b. Monster pemain memiliki hunger status yang berawal dengan nilai 200 (maksimalnya) dan nanti akan berkurang 5 tiap 10 detik.Ketika hunger status mencapai angka nol, pemain akan kalah. Hunger status dapat bertambah 15 apabila pemain memberi makan kepada monster, tetapi banyak makanan terbatas dan harus beli di Market. <br/>c. Monster pemain memiliki hygiene status yang berawal dari 100 dan nanti berkurang 10 tiap 30 detik. Ketika hygiene status mencapai angka nol, pemain akan kalah. Hygiene status' dapat bertambah 30 hanya dengan memandikan monster. Pemain dapat memandikannya setiap 20 detik(cooldownnya 20 detik). <br/>d. Monster pemain memiliki health status yang berawal dengan nilai 300. Variabel ini bertambah (regenerasi)daa 5 setiap 10 detik ketika monster dalam keadaan standby. <br/>e. Monster pemain dapat memasuki keadaan battle. Dalam keadaan ini, food status(fitur b), hygiene status'(fitur c), dan ‘regenerasi’(fitur d) tidak akan berjalan. Health status dari monster dimulai dari darah saat monster pemain memasuki battle. Monster pemain akan bertarung dengan monster NPC yang memiliki darah 100. Baik monster pemain maupun NPC memiliki serangan sebesar 20. Monster pemain dengan monster musuh akan menyerang secara bergantian. <br/>f. Fitur shop, pemain dapat membeli makanan sepuas-puasnya selama stok di toko masih tersedia. * Pembeli (terintegrasi dengan game) * Dapat mengecek stok makanan yang ada di toko. * Jika stok ada, pembeli dapat membeli makanan. * Penjual (terpisah) * Bisa mengecek stok makanan yang ada di toko * Penjual dapat menambah stok makanan. Spesifikasi program: <br/>A. Program mampu mendeteksi input berupa key press. (Program bisa berjalan tanpa perlu menekan tombol enter) <br/>B. Program terdiri dari 3 scene yaitu standby, battle, dan shop. <br/>C. Pada saat berada di standby scene, program selalu menampilkan health status, hunger status, hygiene status, stok makanan tersisa, dan juga status kamar mandi (“Bath is ready” jika bisa digunakan, “Bath will be ready in [bath cooldown]s” jika sedang cooldown). Selain itu program selalu menampilkan 5 menu, yaitu memberi makan, mandi, battle, shop, dan exit. <br/>Contoh :<br/> <br/>Standby Mode <br/>Health : [health status] <br/>Hunger : [hunger status] <br/>Hygiene : [hygiene status] <br/>Food left : [your food stock] <br/>Bath will be ready in [cooldown]s <br/>Choices <br/>1. Eat <br/>2. Bath <br/>3. Battle <br/>4. Shop <br/>5. Exit<br/> <br/>D. Pada saat berada di battle scene, program selalu menampilkan health status milik pemain dan monster NPC. Selain itu, program selalu menampilkan 2 menu yaitu serang atau lari. <br/>Contoh :<br/> <br/>Battle Mode <br/>Monster’s Health : [health status] <br/>Enemy’s Health : [enemy health status] <br/>Choices <br/>1. Attack <br/>2. Run<br/> <br/>E. Pada saat berada di shop scene versi pembeli, program selalu menampilkan food stock toko dan milik pemain. Selain itu, program selalu menampilkan 2 menu yaitu beli dan kembali ke standby scene.<br/>Contoh :<br/> <br/>Shop Mode <br/>Shop food stock : [shop food stock] <br/>Your food stock : [your food stock] <br/>Choices <br/>1. Buy <br/>2. Back<br/> <br/>F. Pada program penjual, program selalu menampilkan food stock toko. Selain itu, program juga menampilkan 2 menu yaitu restock dan exit.<br/>Contoh :<br/> <br/>Shop <br/>Food stock : [shop food stock] <br/>Choices <br/>1. Restock <br/>2. Exit<br/> <br/>G. Pastikan terminal hanya mendisplay status detik ini sesuai scene terkait (hint: menggunakan system(“clear”)) ### Jawaban: Untuk program pembeli dan game, pertama - tama kita perlu membaca inputan untuk nama monster, kemudian membuat 5 thread dan fungsinya yaitu: 1. Thread untuk mengurangi secara otomatis hunger status sebesar 5 setiap 10 detik ketika standby mode, jika hunger status <= 0 maka exit program. 2. Thread untuk mengurangi secara otomatis hygiene status sebesar 10 setiap 30 detik ketika standby mode, jika hygiene status <= 0 maka exit program. 3. Thread untuk menambah hygiene status sebesar 15 ketika memilih option bath pada standby mode. Thread ini memiliki waktu cooldown 20 detik. 4. Thread untuk menambah secara otomatis health status sebesar 5 setiap 10 detik ketika standby mode. 5. Thread untuk user interface dari 3 mode (standby, battle, shop) dan battle mode. Pada battle mode, monster pemain akan bertarung dengan monster NPC yang memiliki darah 100. Baik monster user maupun NPC memiliki serangan sebesar 20. Monster user dengan monster musuh akan menyerang secara bergantian dengan diawali oleh user. Pada battle mode, user dapat memilih option menyerang atau melarikan diri. Battle mode akan dilooping terus dan akan kembali ke standby mode jika user melarikan diri atau monster lawan mati. Jika pada saat battle mode, health status dari monster user <= 0 maka exit program. <br/>Berikut syntax dari 5 fungsi thread tersebut: ``` void* hunger(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[0])) { if(flag==1){ sleep(10); if(flag==1){ hunger_stat-=5; if(hunger_stat<=0){ system("clear"); printf("Standby Mode\nMonster's Name: %s\nHealth : %d\nHunger : %d\nHygiene : %d\nFood Left : %d\nBath is ready\nChoices\n1. Eat\n2. Bath\n3. Battle\n4. Shop\n5. Exit\n", nama, health_stat, hunger_stat, hygiene_stat, food_stock); puts("You died because of starvation"); exit(0); } } } } } return NULL; } void* hygiene(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[1])) { if(flag==1){ sleep(30); if(flag==1){ hygiene_stat-=10; if(hygiene_stat<=0){ system("clear"); printf("Standby Mode\nMonster's Name: %s\nHealth : %d\nHunger : %d\nHygiene : %d\nFood Left : %d\nBath is ready\nChoices\n1. Eat\n2. Bath\n3. Battle\n4. Shop\n5. Exit\n", nama, health_stat, hunger_stat, hygiene_stat, food_stock); puts("You died because of dirty"); exit(0); } } } } } return NULL; } void* mandi(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[2])) { if(mandi_flag==1){ if(hygiene_stat<=100 && cooldown==0){ cooldown=20; hygiene_stat+=15; if(hygiene_stat>=100){ hygiene_stat=100; } } mandi_flag=0; } while(cooldown>0){ sleep(1); cooldown--; } } } return NULL; } void* regen(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[3])) { if(flag==1){ sleep(10); if(health_stat<300 && flag==1){ health_stat+=5; if(health_stat>=300){ health_stat=300; } } } } } return NULL; } void* game(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[4])) { if(flag==1){ if(cooldown==0){ system("clear"); printf("Standby Mode\nMonster's Name: %s\nHealth : %d\nHunger : %d\nHygiene : %d\nFood Left : %d\nBath is ready\nChoices\n1. Eat\n2. Bath\n3. Battle\n4. Shop\n5. Exit\n", nama, health_stat, hunger_stat, hygiene_stat, food_stock); sleep(1); } else{ system("clear"); printf("Standby Mode\nMonster's Name: %s\nHealth : %d\nHunger : %d\nHygiene : %d\nFood Left : %d\nBath will be ready in %ds\nChoices\n1. Eat\n2. Bath\n3. Battle\n4. Shop\n5. Exit\n", nama, health_stat, hunger_stat, hygiene_stat, food_stock, cooldown); sleep(1); } } else if(flag==2){ monster_health=100; while(1){ sleep(1); system("clear"); printf("Battle Mode\nMonster's Name: %s\nMonster's Health : %d\nEnemy's Health : %d\nChoices\n1. Attack\n2. Run\n", nama, health_stat, monster_health); input = mygetch() - '0'; if(input==1){ monster_health-=20; sleep(1); system("clear"); printf("Battle Mode: your's turn\nMonster's Name: %s\nMonster's Health : %d\nEnemy's Health : %d\nChoices\n1. Attack\n2. Run\n", nama, health_stat, monster_health); if(monster_health<=0){ puts("You win!"); flag=1; break; } sleep(1); health_stat-=20; if(health_stat<=0){ health_stat=0; system("clear"); printf("Battle Mode\nMonster's Name: %s\nMonster's Health : %d\nEnemy's Health : %d\n", nama, health_stat, monster_health); puts("You died because killed"); exit(0); } system("clear"); printf("Battle Mode: enemy's turn\nMonster's Name: %s\nMonster's Health : %d\nEnemy's Health : %d\n", nama, health_stat, monster_health); } else if(input==2){ puts("You ran away!"); flag=1; break; } } } else if(flag==3){ system("clear"); printf("Shop Mode\nShop food stock : %d\nYour food stock : %d\nChoices\n1. Buy\n2. Back\n", shop_stock[0], food_stock); sleep(2); } } } return NULL; } ``` Pada standby mode, user memiliki 5 option yaitu: 1. Eat yaitu menambah hunger status sebesar 15 dan mengurangi food stock sebesar 1 setiap kali makan. Hanya bisa dilakukan jika food stocknya ada (>0). 2. Bath yaitu menjalankan thread 3 yang menambah hygiene status sebesar 15. 3. Battle yaitu merubah mode menjadi battle mode. 4. Shop yaitu merubah mode menjadi shop mode. 5. Exit yaitu exit dari program. <br/>Pada shop mode, user memiliki 2 option yaitu: 1. Buy yaitu menambah food stock sebanyak 1 dan mengurangi shop food stock sebanyak 1. Option ini hanya bisa dijalankan jika shop food stocknya ada (>0). 2. Back yaitu kembali ke standby mode. <br/><br/>Berikut syntax dari standby mode dan shop mode: ``` int main(){ while (1) { if(flag==1){ input = mygetch() - '0'; if(input==1){ if(food_stock>0){ if(hunger_stat<=200){ hunger_stat+=15; food_stock--; if(hunger_stat>=200){ hunger_stat=200; } } } else{ puts("Your Food Stock is Empty"); sleep(1); } } else if(input==2 && cooldown==0){ mandi_flag=1; } else if(input==3){ flag=2; } else if(input==4){ flag=3; } else if(input==5){ puts("You Exit The Game"); exit(0); } } else if(flag==3){ input = mygetch() - '0'; if(input==1){ if(shop_stock[0]>0){ food_stock++; shop_stock[0]--; } else{ puts("The Shop is Out of Stock"); } } else if(input==2){ flag=1; } } } } ``` Kemudian program dapat mendeteksi inputan berupa key press (program bisa berjalan tanpa perlu menekan tombol enter). Syntaxnya adalah seperti berikut ini: ``` #include<termios.h> int mygetch ( void ) { int ch; struct termios oldt, newt; tcgetattr ( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr ( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr ( STDIN_FILENO, TCSANOW, &oldt ); return ch; } int input; int main(){ input = mygetch() - '0'; } ``` Digunakan shared memory untuk shop food stocknya sehingga nilai dari shop food stock pada pembeli dapat bernilai sama dengan penjual. Berikut syntaxnya: ``` #include<sys/shm.h> int main(){ key_t key = 1234; int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666); shop_stock = shmat(shmid, NULL, 0); } ``` Untuk program penjual, digunakan shared memory untuk shop food stocknya sehingga nilai dari shop food stock pada penjual dapat bernilai sama dengan pembeli. Selain itu juga dibuat 1 thread untuk user interfacenya. Kemudian untuk inputannya dapat dibaca dengan key press saja seperti program pembeli. Terdapat 2 mode pada program penjual yaitu: 1. Restock yaitu untuk menambah shop food stock sebesar 1. 2. Exit yaitu untuk exit dari program penjual. <br/><br/>Berikut syntax dari program penjual: ``` #include<stdio.h> #include<string.h> #include<sys/ipc.h> #include<sys/shm.h> #include<unistd.h> #include<pthread.h> #include<sys/wait.h> #include<stdlib.h> #include<termios.h> pthread_t tid[1]; int *shop_stock; int mygetch ( void ) { int ch; struct termios oldt, newt; tcgetattr ( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr ( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr ( STDIN_FILENO, TCSANOW, &oldt ); return ch; } void* shop(void *arg) { pthread_t id = pthread_self(); while (1) { if (pthread_equal(id, tid[0])) { system("clear"); printf("Shop\nFood stock : %d\nChoices\n1. Restock\n2. Exit\n", shop_stock[0]); sleep(1); } } return NULL; } void main() { key_t key = 1234; int input; int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666); shop_stock = shmat(shmid, NULL, 0); pthread_create(&(tid[0]), NULL, &shop, NULL); while (1) { input = mygetch() -'0'; if(input==1){ shop_stock[0] = shop_stock[0] + 1; } else if(input==2){ puts("You Exit The Shop"); exit(0); } } //shmdt(shop_stock); //shmctl(shmid, IPC_RMID, NULL); } ```
Java
UTF-8
4,204
2.171875
2
[]
no_license
package com.scm.services.config; import java.io.IOException; import java.util.Arrays; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.SignatureException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.UrlPathHelper; import com.scm.services.common.Constants; import com.scm.services.common.JwtTokenUtil; public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtTokenUtil jwtTokenUtil; @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader(Constants.HEADER_STRING); HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; logger.warn(request.getRequestURI()); String resourcePath=new UrlPathHelper().getPathWithinApplication(request); logger.warn(resourcePath); response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, responseType, Authorization, credential, X-XSRF-TOKEN"); logger.warn("filter cxaling--?"); String username = null; String authToken = null; if (header != null && header.startsWith(Constants.TOKEN_PREFIX)) { authToken = header.replace(Constants.TOKEN_PREFIX,""); try { username = jwtTokenUtil.getUsernameFromToken(authToken); } catch (IllegalArgumentException e) { logger.error("an error occured during getting username from token", e); } catch (ExpiredJwtException e) { logger.warn("the token is expired and not valid anymore", e); } catch(SignatureException e){ logger.error("Authentication Failed. Username or Password not valid."); } } else { logger.warn("couldn't find bearer string, will ignore the header"); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req)); logger.info("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); } } logger.info("chain"+req); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } }
Java
UTF-8
745
3.328125
3
[]
no_license
package ch07; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; public class AtomicIntegerFieldUpdaterTest { // 创建一个User类的age属性的更新器 private static AtomicIntegerFieldUpdater<User> updater = AtomicIntegerFieldUpdater.newUpdater(User.class, "age"); public static void main(String[] args) { User conan = new User("conan", 17); System.out.println(updater.getAndIncrement(conan)); System.out.println(updater.get(conan)); } @Getter @AllArgsConstructor static class User { private String name; public volatile int age;// 更新器对应的属性必须是public volatile修饰的 } }
Markdown
UTF-8
1,019
2.546875
3
[ "MIT" ]
permissive
# Requirements ## 1. 基础功能 ### 1.1 将md文件转换成html #### 1.1.1 块级元素 基础块级元素 === - `#`~`######` 6级标题 - `===`第7级标题 - `---`水平分隔线 - `>`引用 - `![]()`图片 - `|:--`表格 左上角单元格实现`\`分隔。 - `1.`有序列表 有序列表的序号使用定义的值,保证有空行间隔的有序列表的序号始终正确。 - `-/+/*`无序列表 - \`\`\`代码块 代码块实现高亮显示 - 文本段落 扩展块级元素 === - `!note(title,type)` 注意 - `!eg` 示例 #### 1.1.2 行内元素 基础行内元素 === - `~~``~~`删除线 - `**``**`加粗 - `*``*`斜体 - \`\`代码 - `<br/>`换行 扩展行内元素 === - `[up:text]`上标 - `[do:text]`下标 ## 2. 扩展功能 ### 2.1 可折叠目录 - 默认处于折叠状态 ### 2.2 Include功能 `[include](other.md)`包含其它的md文档内容到当前位置。 ### 2.3 top导航栏 ### 2.4 代码块高亮 ### 2.5 可以选择皮肤 ### 2.6 页内跳转
Java
UTF-8
2,055
2.609375
3
[]
no_license
package com.s206megame.towerdefense.tower; import com.s206megame.towerdefense.tower.basic.TowerType; import org.bukkit.Location; import org.bukkit.Material; import com.s206megame.towerdefense.tower.basic.Tower; import org.bukkit.Particle; import java.util.Arrays; import java.util.List; public class ArcherTower extends Tower { @Override public Material getDisplayItem() { return Material.BOW; } @Override public double getDamage() { switch (level) { case 1: return 10; case 2: return 12; case 3: return 15; } return 0; } @Override public double getHitDelay() { switch (level) { case 1: return 18; case 2: return 13; case 3: return 10; } return 0; } @Override public double getRange() { switch (level) { case 1: return 10; case 2: return 12; case 3: return 15; } return 0; } @Override public int getPrice(int level) { switch (level) { case 1: return 100; case 2: return 200; case 3: return 600; } return 0; } @Override public String getTitle() { return "[Lv."+getLevel()+"] 弓箭手塔"; } @Override public List<String> getDescription() { return Arrays.asList("§f冷血的§c弓箭手§f躲在堅固的堡壘中,","§f準確§c射殺§f迎面而來的§c敵人!", "§f無特殊效果"); } @Override protected Location getParticleStartPoint() { return new Location(getWorld(),0.5,6,0.5); } @Override protected Particle getParticle() { return Particle.CRIT; } @Override public TowerType getType() { return TowerType.THREE_BY_THREE; } }
C
UTF-8
1,509
3.75
4
[]
no_license
/* Naivna, rekurzivna implementacija problema maksimalnog ranca */ #include <stdio.h> #include <time.h> //Deklaracije koriscenih funkcija int max(int a, int b); int main() { clock_t pocetak, kraj; double cpu_time_used; int vrednosti[] = {45, 67, 69, 75}; int tezine[] = {9, 11, 10, 12}; int K = 20; int n = sizeof(vrednosti)/sizeof(vrednosti[0]); pocetak = clock(); int t = ranac(K, tezine, vrednosti, n); kraj = clock(); cpu_time_used = ((double)(kraj - pocetak))/CLOCKS_PER_SEC; printf("Rezultat: %d\n", t); printf("Vreme izvrsavanja: %lf\n", cpu_time_used); return 0; } //Definicije koriscenih funkcija: // Pomocna funkcija koja vraca maksimum svojih argumenata int max(int a, int b){ return (a > b)? a : b; } // Funkcija vraca maksimalnu vrednost koja moze biti smestena u ranac kapaciteta K int ranac(int K, int tezine[], int vrednosti[], int n){ // Bazni slucaj if (n == 0 || K == 0) return 0; // Ako je tezina n-tog predmeta veca od kapaciteta ranca K // tada predmet nece biti ubacen u ranac. if (tezine[n-1] > K) return ranac(K, tezine, vrednosti, n-1); //Inace vraca maksimum naredna dva slucaja: //1. uzima se n-ti predmet //2. ne uzima se n-ti predmet else return max( vrednosti[n-1] + ranac(K-tezine[n-1], tezine, vrednosti, n-1), ranac(K, tezine, vrednosti, n-1) ); }
C
UTF-8
131
2.546875
3
[]
no_license
#include<stdio.h> int main() { int a; char c = 6; int b = a; printf("%c", c); a=getchar(); putchar(a); return 0; }
PHP
UTF-8
2,904
2.703125
3
[ "MIT" ]
permissive
<?php /* * This file is part of fof/webhooks. * * Copyright (c) FriendsOfFlarum. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FoF\Webhooks; use Carbon\Carbon; use Flarum\Http\UrlGenerator; use Flarum\User\User; use FoF\Webhooks\Models\Webhook; class Response { /** * @var string */ public $title; /** * @var string */ public $url; /** * @var string */ public $description; /** * @var string */ public $color; /** * @var string */ public $timestamp; /** * @var User */ public $author; public $event; /** * @var UrlGenerator */ private $urlGenerator; /** * @var Webhook */ protected $webhook; /** * Response constructor. * * @param $event */ public function __construct($event) { $this->event = $event; $this->urlGenerator = resolve(UrlGenerator::class); } public function setTitle(string $title): self { $this->title = $title; return $this; } public function setURL(string $name, array $data = null, ?string $extra = null): self { $url = $this->urlGenerator->to('forum')->route($name, $data); if (isset($extra)) { $url = $url.$extra; } $this->url = $url; return $this; } public function setDescription(?string $description): self { $this->description = $description; return $this; } public function setAuthor(User $author): self { $this->author = $author; return $this; } public function setColor(?string $color): self { $this->color = $color; return $this; } public function setTimestamp(?string $timestamp): self { $this->timestamp = $timestamp ?: Carbon::now(); return $this; } public function getColor() { return $this->color ? hexdec(substr($this->color, 1)) : null; } public static function build($event): self { return new self($event); } public function getAuthorUrl(): ?string { return $this->author ? $this->urlGenerator->to('forum')->route('user', [ 'username' => $this->author->username, ]) : null; } public function getExtraText(): ?string { return $this->webhook->extra_text; } public function withWebhook(Webhook $webhook): self { $this->setWebhook($webhook); return $this; } protected function setWebhook(Webhook $webhook) { $this->webhook = $webhook; } public function __toString() { return "Response{title=$this->title,url=$this->url,author={$this->author->display_name}}"; } }
Java
UTF-8
4,283
1.953125
2
[]
no_license
package com.xiumiing.wxtest; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ImageView; import android.widget.TextView; import com.lody.virtual.client.core.VirtualCore; import com.lody.virtual.client.ipc.VActivityManager; import com.lody.virtual.remote.InstalledAppInfo; import com.xiumiing.wxtest.widgets.EatBeansView; import java.util.Locale; /** * @author Lody */ public class LoadingActivity extends AppCompatActivity { public static String TAG = "LoadingActivity"; private static final String PKG_NAME_ARGUMENT = "MODEL_ARGUMENT"; private static final String KEY_INTENT = "KEY_INTENT"; private static final String KEY_USER = "KEY_USER"; private PackageAppData appModel; private EatBeansView loadingView; private long mCurrentTimeMillis; public static void launch(Context context, String packageName, int userId) { Intent intent = VirtualCore.get().getLaunchIntent(packageName, userId); if (intent != null) { Intent loadingPageIntent = new Intent(context, LoadingActivity.class); loadingPageIntent.putExtra(PKG_NAME_ARGUMENT, packageName); loadingPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); loadingPageIntent.putExtra(KEY_INTENT, intent); loadingPageIntent.putExtra(KEY_USER, userId); context.startActivity(loadingPageIntent); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); loadingView = (EatBeansView) findViewById(R.id.loading_anim); int userId = getIntent().getIntExtra(KEY_USER, -1); String pkg = getIntent().getStringExtra(PKG_NAME_ARGUMENT); InstalledAppInfo setting = VirtualCore.get().getInstalledAppInfo(pkg, 0); if (setting != null) { appModel = new PackageAppData(App.getApp(), setting); } ImageView iconView = (ImageView) findViewById(R.id.app_icon); iconView.setImageDrawable(appModel.icon); TextView nameView = (TextView) findViewById(R.id.app_name); nameView.setText(String.format(Locale.ENGLISH, "Opening %s...", appModel.name)); Intent intent = getIntent().getParcelableExtra(KEY_INTENT); if (intent == null) { return; } mCurrentTimeMillis = System.currentTimeMillis(); Log.d(TAG, "onCreate: " + mCurrentTimeMillis); VirtualCore.get().setUiCallback(intent, mUiCallback); VUiKit.defer().when(() -> { // Log.d(TAG, "onCreate: " + appModel.fastOpen); // if (!appModel.fastOpen) { // try { // VirtualCore.get().preOpt(appModel.packageName); // } catch (Exception e) { // e.printStackTrace(); // } // } VActivityManager.get().startActivity(intent, userId); }); } private final VirtualCore.UiCallback mUiCallback = new VirtualCore.UiCallback() { @Override public void onAppOpened(String packageName, int userId) throws RemoteException { Log.d(TAG, "onCreate: " + String.valueOf(System.currentTimeMillis() - mCurrentTimeMillis)); // VirtualCore.OnEmitShortcutListener listener = new VirtualCore.OnEmitShortcutListener() { // @Override // public Bitmap getIcon(Bitmap originIcon) { // return originIcon; // } // // @Override // public String getName(String originName) { // return originName + "(嘿嘿)"; // } // }; // if (appModel instanceof PackageAppData) { // VirtualCore.get().createShortcut(0, appModel.packageName, listener); // } finish(); } }; @Override protected void onResume() { super.onResume(); loadingView.startAnim(); } @Override protected void onPause() { super.onPause(); loadingView.stopAnim(); } }
JavaScript
UTF-8
3,326
3.171875
3
[]
no_license
function GUI(p) { var controllers = []; this.addController = function(x1, y1, width, height, minValue, maxValue) { var s = new Slider(x1, y1, width, height, minValue, maxValue); controllers.push(s); return s; } this.addButton = function(x, y, width, height) { var b = new Button(x, y, width, height); controllers.push(b); return b; } this.draw = function() { for (var i=0; i<controllers.length; i++) { controllers[i].draw(p); } } this.mouseMoved = function() { for (var i=0; i<controllers.length; i++) { if (controllers[i].touches(p.mouseX, p.mouseY)) { controllers[i].hoveredOver = true; } else { controllers[i].hoveredOver = false; } } } this.mousePressed = function() { for (var i=0; i<controllers.length; i++) { if (controllers[i].touches(p.mouseX, p.mouseY)) { controllers[i].active = !controllers[i].active; controllers[i].makeCallback(); } } } } function Slider(x1, y1, width, height, minValue, maxValue) { //positioning and sizing: this.x1 = x1; this.y1 = y1; this.width = width; this.height = height; //variable value: this.value = minValue; this.minValue = minValue; this.maxValue = maxValue; //ui state: this.hoveredOver = false; this.active = false; this.touches = function(x, y) { return this.x1 < x && x < this.x1 + this.width && this.y1 < y && y < this.y1 + this.height; } this.backgroundStyle = function(p) { p.stroke(0); p.fill(255); } this.foregroundStyle = function(p) { p.noStroke(); p.fill(150); } this.draw = function(p) { this.backgroundStyle(p); p.rectMode(p.CORNER); p.rect(this.x1, this.y1, this.width, this.height); this.foregroundStyle(p); //draw horizontal slider var x = p.map(value, minValue, maxValue, this.x1, this.x1 + this.width); p.rect(this.x1, this.y1, x - this.x1, this.height); } this.makeCallback = function() { this.callback(this.value); } this.callback = function(value) {} } function Button(x, y, width, height) { //positioning and sizing: this.cenx = x; this.ceny = y; this.width = width; this.height = height; //ui state this.hoveredOver = false; this.active = false; this.touches = function(x, y) { return this.cenx - this.width/2 < x && x < this.cenx + this.width/2 && this.ceny - this.height/2 < y && y < this.ceny + this.height/2; } this.style = function(p) { p.noStroke(); if (this.active) { p.fill(0); } else if (this.hoveredOver) { p.fill(100); } else { p.fill(255); } } this.draw = function(p) { style(p); p.rectMode(p.CENTER); p.rect(this.cenx, this.ceny, this.width, this.height); } this.makeCallback = function() { callback(this.active); } this.callback = function(isActive) {} }
Python
UTF-8
191
3.46875
3
[]
no_license
import sys num1, num2 = input().split() num1 = int(''.join(list(reversed(num1)))) num2 = int(''.join(list(reversed(num2)))) if(num1 > num2): print(num1) else: print(num2)
Java
UTF-8
1,620
2.1875
2
[ "MIT" ]
permissive
package be.goofydev.bridger.bungee; import be.goofydev.bridger.api.model.proxy.Proxy; import be.goofydev.bridger.api.model.user.User; import be.goofydev.bridger.common.plugin.BridgerPlugin; import net.kyori.text.Component; import net.kyori.text.adapter.bungeecord.TextAdapter; import net.md_5.bungee.api.ProxyServer; import java.util.Set; import java.util.UUID; public class BungeeProxy implements Proxy { private final BridgerPlugin plugin; private final ProxyServer proxyServer; public BungeeProxy(BridgerPlugin plugin, ProxyServer proxyServer) { this.plugin = plugin; this.proxyServer = proxyServer; } @Override public String getId() { return this.plugin.getConfiguration().getProxyConfiguration().getProxyId(); } @Override public Set<User> getUsers() { return this.plugin.getUserProvider().getAll(); } @Override public User getUser(UUID uniqueId) { return this.plugin.getUserProvider().get(uniqueId); } @Override public boolean hasUser(UUID uniqueId) { return this.plugin.getUserProvider().has(uniqueId); } @Override public void broadcastMessage(Component message) { this.proxyServer.broadcast(TextAdapter.toBungeeCord(message)); } @Override public void executeCommand(String... command) { String fullCommand = String.join(" ", command); if (fullCommand.startsWith("/")) { fullCommand = fullCommand.substring(1); } this.proxyServer.getPluginManager().dispatchCommand(BridgerCommandSender.instance, fullCommand); } }
JavaScript
UTF-8
1,164
3.46875
3
[]
no_license
/** *查找触发事件的元素,绑定事件,查找要修改的元素,修改元素 *查找table下的thead下的input,绑定单击事件,查找table下的tbody下作为第一个子元素的td下的input,遍历所有input,将当前input的checked属性改为和全选input的checked一致 */ var chbAll=document.querySelector("table>thead input"); chbAll.onclick=function(){ var inputs=document.querySelectorAll("table>tbody td:first-child>input"); for(var input of inputs){ input.checked=chbAll.checked; } } /*查找table下的tbody下作为第一个子元素的td下的input,遍历所有input,遍历每个input,为每个input绑定单击事件,如果自己未选中则chbAll也不选中*/ /*否则查找table下tbody下作为第一个子元素的td下的未选中的input,只要找到chbAll不选否则chbAll选中*/ var inputs=document.querySelectorAll("table>tbody td:first-child>input"); for(var input of inputs){ input.onclick=function(){ if(!input.checked) chbAll.checked=false; else{ var checked=document.querySelector("table>tbody td:first-child>input:not(:checked)"); chbAll.checked=(checked==null); } } }
SQL
UTF-8
319
2.90625
3
[]
no_license
create database thietkevataoCSDL; use thietkevataoCSDL; CREATE TABLE contacts ( contact_id INT(11) NOT NULL AUTO_INCREMENT, last_name VARCHAR(30) NOT NULL, first_name VARCHAR(25), birthday DATE, CONSTRAINT contacts_pk PRIMARY KEY (contact_id) ); insert into contacts values (1, "phuc", "nguyen", "1989-01-06");
C++
UTF-8
978
2.953125
3
[]
no_license
class Solution { public: int getBouquetNum(vector<int>& bloomDay, int day, int k) { int bloomCount = 0; int ret = 0; for(int flowerDay : bloomDay) { if(flowerDay <= day) bloomCount++; else bloomCount = 0; if(bloomCount == k) { ret++; bloomCount = 0; } } return ret; } int minDays(vector<int>& bloomDay, int m, int k) { int low = 0; int high = -1; int ans = -1; for(int flowerDay : bloomDay) high = max(high, flowerDay); while(low <= high) { int mid = low + (high - low) / 2; if(getBouquetNum(bloomDay, mid, k) >= m) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } };
C
UTF-8
1,627
2.765625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int chatroomId, newClientListener, serverFd; int main(int argc, char const *argv[]) { mkfifo("newClientListener", 0666); newClientListener = open("newClientListener",O_WRONLY); printf("Enter which chatroom you would like to join (1-4): "); scanf("%d", &chatroomId); char chatroomName[10]; strcpy(chatroomName, "CHATROOM"); chatroomName[8] = chatroomId+'0'; chatroomName[9] = '\0'; mkfifo(chatroomName, 0666); printf("%s\n", chatroomName); serverFd = open (chatroomName, O_WRONLY); int pid = getpid(); char id[20]; int n; n=snprintf(id, 20, "clients/%d", pid); id[n] = '\0'; id[0] = chatroomId+'1'; write(newClientListener, id, 20); id[0] = 'c'; mkfifo(id, 0666); pid = open(id, O_RDONLY); fd_set rfds; struct timeval tv; int retval=1; FD_ZERO(&rfds); FD_SET(0, &rfds); FD_SET(pid, &rfds); while(1) { retval = select(pid+1, &rfds, NULL, NULL, NULL); if (retval!=-1) { if (FD_ISSET(0, &rfds)) { char buff[100]; int n=read(0, buff, 100); buff[n] = '\0'; write(serverFd, buff, n+1); } else if (FD_ISSET(pid, &rfds)) { char buff[100]; int n=read(pid, buff, 100); if (n==0) { printf("Server has shut down\n"); return 0; } buff[n] = '\0'; printf("Recieved from server: %s", buff); } } else { perror("select client error\n"); exit(1); } FD_ZERO(&rfds); FD_SET(0, &rfds); FD_SET(pid, &rfds); } return 0; }
Java
UTF-8
456
1.960938
2
[]
no_license
package in.co.sdrc.scpstn.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import in.co.sdrc.scpstn.domain.Subgroup; public interface SubgroupRepository extends JpaRepository<Subgroup, Integer>{ public List<Subgroup> findAllByOrderBySubgroupValueIdAsc(); public Subgroup findBySubgroupValueId(Integer subgroupValueId); public Subgroup findBySubgroupVal(String stringCellValue); }
Java
UTF-8
478
1.84375
2
[]
no_license
package com.weitao.dao; import com.weitao.bean.Category; import java.util.List; public interface CategoryMapper { int deleteByPrimaryKey(Integer caId); int insert(Category record); int insertSelective(Category record); Category selectByPrimaryKey(Integer caId); int updateByPrimaryKeySelective(Category record); int updateByPrimaryKey(Category record); /*查询父类下有多少子类*/ List<Category> selectCafather(String cafather); }
JavaScript
UTF-8
1,499
2.875
3
[]
no_license
var data = '', utilities = (function() { var convertStdin = function (input) { var parts = input.split(', '), latParts = parts[0].split(' '), lat = parseFloat(latParts[0]); latCard = latParts[1].replace(/^\s+|\s+$/, ''); lat = (latCard === 'S' ? lat *= -1 : lat); lngParts = parts[1].split(' '); lng = parseFloat(lngParts[0]); lngCard = lngParts[1].replace(/^\s+|\s+$/, ''); lng = (lngCard === 'W' ? lng *= -1 : lng); return [lat, lng]; }; var getStdin = function(cb) { var data = '', done = false, timer = setTimeout( function () { // Kill after timeout if no input is passed in if (done === false) { cb && cb(data); } }, 250); process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { data += chunk; }); process.stdin.on('end', function () { clearTimeout(timer); done = true; cb && cb(data); }); }; return { convertStdin : convertStdin, getStdin : getStdin } })(); exports.utilities = utilities;
Python
UTF-8
988
3.28125
3
[]
no_license
''' Practicing creating triggers The Fresh Fruit Delivery company needs help creating a new trigger called OrdersUpdatedRows on the Orders table. This trigger will be responsible for filling in a historical table (OrdersUpdate) where information about the updated rows is kept. A historical table is often used in practice to store information that has been altered in the original table. In this example, changes to orders will be saved into OrdersUpdate to be used by the company for auditing purposes. Instructions 100 XP - Create the new trigger for the Orders table. - Set the trigger to be fired only after UPDATE statements. ''' -- Set up a new trigger CREATE TRIGGER OrdersUpdatedRows ON Orders -- The trigger should fire after UPDATE statements AFTER UPDATE -- Add the AS keyword before the trigger body AS -- Insert details about the changes to a dedicated table INSERT INTO OrdersUpdate(OrderID, OrderDate, ModifyDate) SELECT OrderID, OrderDate, GETDATE() FROM inserted