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
TypeScript
UTF-8
2,701
2.515625
3
[]
no_license
const clusterMaker = require("clusters"); const hash = require("object-hash"); import { ICluster } from "./cluster"; import {extractUserFeatures} from "./dataTransformers/extractUserFeatures"; import { getDistance } from "./getDistance"; import { IDriver } from "./models/driver"; import { IRequest } from "./models/request"; import { IRider } from "./models/rider"; import { connection } from "./mysqldb"; import { INeo4jDb } from "./neo4jdb"; const MAX_FETCHING_DISTANCE = 2; // km export class RideMaker { /** * * NOTE: This function assumes that there are no two users have the same features(arrival, departure, startTime, endTime) * @param {number} day * @param {IRider[]} riders * @param {IDriver[]} drivers * @returns {ICluster[]} * @memberof RideMaker */ public findCluster(day: number, riders: IRider[], drivers: IDriver[]): ICluster[] { let resultClusters: ICluster[] = []; let allUsers: IRider[] = []; allUsers = allUsers.concat(riders); allUsers = allUsers.concat(drivers); const map: {[key: string]: IRider} = {}; const feautures: number[][] = []; allUsers.forEach((user) => { const feature = extractUserFeatures(user, day); feautures.push(feature); const key = hash(feature); if (map[key]) { throw new Error("ERROR! Expected all users have unique features but detected 2 users to have the same set of features."); } map[hash(feature)] = user; }); clusterMaker.k(drivers.length); clusterMaker.data(feautures); clusterMaker.clusters().forEach((cluster: {centroid: number, points: number[][]}) => { const usersInThisCluster = cluster.points.map((p) => map[hash(p)]); const driversInThisCluster = usersInThisCluster.filter((u) => u.type === "driver") as IDriver[]; const ridersInThisCluster = usersInThisCluster.filter((u) => u.type === "rider"); if (driversInThisCluster.length === 0) { /*skip this cluster*/ } else if (driversInThisCluster.length > 1) { resultClusters = resultClusters.concat(this.findCluster(day, ridersInThisCluster, driversInThisCluster)); } else if (driversInThisCluster.length === 1) { // I should do sorting here, but let's skip it for now const d = driversInThisCluster[0]; resultClusters.push({ driver: d, riders: ridersInThisCluster.slice(0, d.car.capacity) }); } }); return resultClusters; } }
Java
UTF-8
992
2.09375
2
[]
no_license
package bananaplan.controller; import bananaplan.domain.request.CaseRequest; import bananaplan.service.CaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * Created by paulou on 10/5/15. * All rights are reserved by BPT */ @RestController public class CaseController { @Autowired CaseService caseService; @RequestMapping(value = "/cases", method = RequestMethod.PUT) public void createCase(@RequestBody CaseRequest caseRequest){ caseService.createCase(caseRequest); } @RequestMapping(value = "/cases/{caseId}", method = RequestMethod.PUT) public void updateCase(@PathVariable Long caseId, @RequestBody CaseRequest caseRequest){ caseService.updateCase(caseId, caseRequest); } @RequestMapping(value = "/cases/{caseId}", method = RequestMethod.DELETE) public void deleteCase(@PathVariable Long caseId){ caseService.deleteCase(caseId); } }
Markdown
UTF-8
738
3.015625
3
[]
no_license
# Dummy example with grpc This project has to purpose for learning how to implement grpc (in a bad way maybe?), ### How to run You need to install dependencies with `npm i` Then you need to run the "microservice" that sum numbers with: `node src/server/sum.js` And run the "microservice" that subtracts numbers with: `node src/server/substraction.js` Then you need to run the server to receive http request with: `node src/client/index.js` To check how if it's running, it is only accepting this two requests: ```sh curl localhost:3000 -H "Content-Type: application/json" -d '{"action": "sum", "num1": 2, "num2": 3}' curl localhost:3000 -H "Content-Type: application/json" -d '{"action": "substract", "num1": 2, "num2": 3}' ```
Java
UTF-8
1,233
2.25
2
[]
no_license
package com.phihung.springmvc.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.phihung.springmvc.dao.CourseDao; import com.phihung.springmvc.entities.Course; import com.phihung.springmvc.entities.Student; @Service @Transactional public class CourseService { @Autowired private CourseDao courseDao; public List<Course> getAllCourse() { return courseDao.findAll(); } public Course getCourseById(int id) { return courseDao.findById(id); } public List<Student> getStudentByCourseId(int course_id) { return courseDao.getStudentByCourseId(course_id); } public List<Course>getCourseByTeacherId(int teacher_id){ return courseDao.getCourseByTeacherId(teacher_id); } public List<Course>getCourseByStudentId(int student_id){ return courseDao.getCourseByStudentId(student_id); } public void registerCourseForStudent(int masv, int course_id) { courseDao.registerCourseForStudent(masv, course_id); } public void update(Course course) { courseDao.updateCourse(course); } public void deleteCourse(int course_id) { courseDao.deleteCourse(course_id); } }
Swift
UTF-8
21,172
2.84375
3
[]
no_license
// // Bluetooth.swift // BluetoothTestDemo // // Created by Myron on 2017/10/19. // Copyright © 2017年 Myron. All rights reserved. // import Foundation import CoreBluetooth // MARK: - 基类 class Bluetooth: NSObject { /** 外设服务 */ var services: [String: CBService] = [:] /** 外设字符 */ var charateristics: [String: CBCharacteristic] = [:] // var log_open: Bool = true func log_tool(_ message: String, local: String = #function) { if log_open { print("Bluetooth: \(local) >> \(message)") } } func log_propertie(_ propertie: CBCharacteristicProperties) -> String { switch propertie { case CBCharacteristicProperties.authenticatedSignedWrites: return "authenticatedSignedWrites" case CBCharacteristicProperties.broadcast: return "broadcast" case CBCharacteristicProperties.extendedProperties: return "extendedProperties" case CBCharacteristicProperties.indicate: return "indicate" case CBCharacteristicProperties.indicateEncryptionRequired: return "indicateEncryptionRequired" case CBCharacteristicProperties.notify: return "notify" case CBCharacteristicProperties.notifyEncryptionRequired: return "notifyEncryptionRequired" case CBCharacteristicProperties.read: return "read" case CBCharacteristicProperties.write: return "write" case CBCharacteristicProperties.writeWithoutResponse: return "writeWithoutResponse" default: return "other" } } func log_value_16(_ value: Data) -> String { let values = [UInt8](value) var message = "[" for v in values { message += String(format: "0x%X, ", v) } return message + "]" } } // MARK: - 辅助方法 class BluetoothTools: Bluetooth, CBCentralManagerDelegate { /** 主设备管理对象 */ var manager: CBCentralManager? var complete: ((Bool) -> Void)? func is_open(_ complete: @escaping (Bool) -> Void) { self.complete = complete manager = CBCentralManager( delegate: self, queue: nil, options: nil ) } // MARK: - CBCentralManagerDelegate // 设备蓝牙状态变化监听,在获取 manager 时以及状态变化时会调用。 func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOn: complete?(true) default: complete?(false) } complete = nil manager = nil } } // MARK: - 中心设备 /** 蓝牙工具: 中心设备 */ class BluetoothCentral: Bluetooth, CBCentralManagerDelegate, CBPeripheralDelegate { // MARK: - Values /** 主设备管理对象 */ var manager: CBCentralManager? /** 外设 */ var peripherals: [String: CBPeripheral] = [:] var peripherals_total: [CBPeripheral] = [] /** 设置为 true,会自动监听 CBCharacteristicProperties.broadcast, CBCharacteristicProperties.notify, CBCharacteristicProperties.notifyEncryptionRequired 类型的 charateristic */ var auto_listen_notify: Bool = true // MARK: - Methods /** 创建蓝牙管理,并检测状态,如果打开则开始扫描 */ func open(queue: DispatchQueue? = nil, options: [String: Any]? = nil) { manager = CBCentralManager( delegate: self, queue: queue, options: options ) } // MARK: - CBCentralManagerDelegate // 设备蓝牙状态变化监听,在获取 manager 时以及状态变化时会调用。 func centralManagerDidUpdateState(_ central: CBCentralManager) { bluetooth_central_manager_state_update(state: central.state) switch central.state { case .unknown: log_tool("unknown") case .resetting: log_tool("resetting") case .unsupported: log_tool("unsupported") case .unauthorized: log_tool("unauthorized") case .poweredOff: log_tool("poweredOff") case .poweredOn: log_tool("poweredOn") //开始扫描周围的外设 /* 第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) */ manager?.scanForPeripherals( withServices: nil, options: nil ) } } // 扫描外设 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if !peripherals_total.contains(peripheral) { log_tool("name: \(String(describing: peripheral.name)); RSSI: \(RSSI);") peripherals_total.append(peripheral) if let key = bluetooth_central_manager_discover( peripheral: peripheral, name: peripheral.name, advertisementData: advertisementData ) { peripherals[key] = peripheral manager?.connect(peripheral, options: nil) } } } func centralManagerStopScan() { peripherals_total.removeAll() manager?.stopScan() } // MARK: - CBPeripheralDelegate //连接到Peripherals-成功 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { log_tool("Connect \(String(describing: peripheral.name)) success.") bluetooth_central_manager_connect_success(peripheral: peripheral, name: peripheral.name) //设置的peripheral委托CBPeripheralDelegate peripheral.delegate = self //扫描外设Services,成功后会进入方法:func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) peripheral.discoverServices(nil) } //连接到Peripherals-失败 func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { log_tool("Connect \(String(describing: peripheral.name)) error. >> error: \(String(describing: error))") bluetooth_central_manager_connect_error(peripheral: peripheral, name: peripheral.name, error: error) } //Peripherals断开连接 func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { log_tool("\(String(describing: peripheral.name)) is disconnect. >> error: \(String(describing: error))") bluetooth_central_manager_disconnect(peripheral: peripheral, name: peripheral.name, error: error) } // 扫描外设中的服务和特征(discover) func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let value = error { log_tool("name: \(String(describing: peripheral.name)); error: \(value)") return } if let services = peripheral.services { for service in services { log_tool("name: \(String(describing: peripheral.name)); server: \(service.uuid.uuidString);") if let key = bluetooth_central_manager_discover_service(peripheral: peripheral, service: service, name: service.uuid.uuidString) { self.services[key] = service peripheral.discoverCharacteristics(nil, for: service) } } } else { log_tool("name: \(String(describing: peripheral.name)); error: (no services)") } } // 扫描 Characteristic 特征符 func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let value = error { log_tool("name: \(String(describing: peripheral.name)); service: \(service.uuid.uuidString); error: \(value)") } else if let characteristics = service.characteristics { for characteristic in characteristics { log_tool("name: \(String(describing: peripheral.name)); service: \(service.uuid.uuidString); characteristic: \(characteristic.uuid.uuidString); propertie: \(log_propertie(characteristic.properties))") if let key = bluetooth_central_manager_discover_charateristics(peripheral: peripheral, service: service, characteristic: characteristic, name: characteristic.uuid.uuidString, properties: characteristic.properties) { self.charateristics[key] = characteristic if auto_listen_notify { switch characteristic.properties { case CBCharacteristicProperties.broadcast, CBCharacteristicProperties.notify, CBCharacteristicProperties.notifyEncryptionRequired: peripheral.setNotifyValue(true, for: characteristic) default: break } } bluetooth_central_manager_discovered_charateristics(peripheral: peripheral, service: service, characteristic: characteristic, name: characteristic.uuid.uuidString, properties: characteristic.properties) } } } else { log_tool("name: \(String(describing: peripheral.name)); service: \(service.uuid.uuidString); error: (no characteristics)") } } // MARK: - 接收到数据 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { var data: [UInt8] = [] if let value = error { log_tool("name: \(String(describing: peripheral.name)); characteristic: \(characteristic.uuid.uuidString); error: \(value)") } else if let value = characteristic.value { log_tool("name: \(String(describing: peripheral.name)); characteristic: \(characteristic.uuid.uuidString); value: \(log_value_16(value))") data = [UInt8](value) } else { log_tool("name: \(String(describing: peripheral.name)); characteristic: \(characteristic.uuid.uuidString); error: (no values)") } bluetooth_central_manager_update_value(peripheral: peripheral, didUpdateValueFor: characteristic, error: error, value: data) } // MARK: - 写数据 func writeCharacter(peripheral: CBPeripheral, characteristic: CBCharacteristic, value: Data) { if characteristic.properties.contains(CBCharacteristicProperties.write) { peripheral.writeValue( value, for: characteristic, type: CBCharacteristicWriteType.withResponse ) log_tool("name: \(String(describing: peripheral.name)); characteristic: \(characteristic.uuid.uuidString); proerties: \(log_propertie(characteristic.properties)); write: \(log_value_16(value))") } else { log_tool("name: \(String(describing: peripheral.name)); characteristic: \(characteristic.uuid.uuidString); proerties: \(log_propertie(characteristic.properties)); error: (can't write propertie)") } } } // MARK: - Sub Methods // 根据需要重新这些方法 extension BluetoothCentral { /** 1. 本机蓝牙状态变化调用,如果打开会自动开启扫描外设 */ #if os(OSX) func bluetooth_central_manager_state_update(state: CBCentralManagerState) { } #elseif os(iOS) func bluetooth_central_manager_state_update(state: CBManagerState) { } #endif /** 2. 获取到外设的回调。 返回 String 会对该外设进行备注在 var peripherals: [String: CBPeripheral] 字典中。 如果是需要的设备,请调用 manager?.connect(peripheral, options: nil) 如果已经不需要扫描了,请调用 func centralManagerStopScan() */ func bluetooth_central_manager_discover(peripheral: CBPeripheral, name: String?, advertisementData data: [String : Any]) -> String? { return nil } /** 2.1 连接成功的回调 */ func bluetooth_central_manager_connect_success(peripheral: CBPeripheral, name: String?) { } /** 2.2 连接失败的回调 */ func bluetooth_central_manager_connect_error(peripheral: CBPeripheral, name: String?, error: Error?) { } /** 3. 扫描到外设中的服务 */ func bluetooth_central_manager_discover_service(peripheral: CBPeripheral, service: CBService, name: String) -> String? { return nil } /** 4. 扫描到外设服务中的特征符,然后就可以用这些特征符进行通讯了。 如果需要监听某个数据通知,则调用 peripheral.setNotifyValue(true, for: characteristic) 如果需要检查类型,可以用 switch propertie { case CBCharacteristicProperties.authenticatedSignedWrites: break case CBCharacteristicProperties.broadcast: break case CBCharacteristicProperties.extendedProperties: break case CBCharacteristicProperties.indicate: break case CBCharacteristicProperties.indicateEncryptionRequired: break case CBCharacteristicProperties.notify: break case CBCharacteristicProperties.notifyEncryptionRequired: break case CBCharacteristicProperties.read: break case CBCharacteristicProperties.write: break case CBCharacteristicProperties.writeWithoutResponse: break default: break } */ func bluetooth_central_manager_discover_charateristics(peripheral: CBPeripheral, service: CBService, characteristic: CBCharacteristic, name: String, properties: CBCharacteristicProperties) -> String? { return nil } /** 4.1 设置完外设,可以开始收发数据 */ func bluetooth_central_manager_discovered_charateristics(peripheral: CBPeripheral, service: CBService, characteristic: CBCharacteristic, name: String, properties: CBCharacteristicProperties) { } /** 5.1 接收到数据 */ func bluetooth_central_manager_update_value(peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?, value: [UInt8]) { } /** 5.2 写数据 */ func bluetooth_central_manager_send(peripheral: CBPeripheral, characteristic: CBCharacteristic, value: Data) { writeCharacter(peripheral: peripheral, characteristic: characteristic, value: value) } func bluetooth_central_manager_send(name: String, character: String, value: Data) { if let peripheral = peripherals[name], let char = charateristics[character] { writeCharacter(peripheral: peripheral, characteristic: char, value: value) } } /** 6. 断开连接的回调 主动断开可以调用 manager?.cancelPeripheralConnection(peripheral: CBPeripheral) */ func bluetooth_central_manager_disconnect(peripheral: CBPeripheral, name: String?, error: Error?) { } } // MARK: - 外设 class BluetoothPeripheral: Bluetooth, CBPeripheralManagerDelegate { /** 外设管理 */ var manager: CBPeripheralManager? // MARK: - Methods /** 创建蓝牙管理,并检测状态,如果打开则开始扫描 */ func open(queue: DispatchQueue? = nil, options: [String: Any]? = nil) { manager = CBPeripheralManager( delegate: self, queue: queue, options: options ) } // MARK: - CBPeripheralManagerDelegate /** 状态更新,启动后会自动调用一次 通常在这时候调用 manager?.add(service: CBMutableService) */ func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { bluetooth_peripheral_manager_state_update() switch peripheral.state { case .unknown: log_tool("unknown") case .resetting: log_tool("resetting") case .unsupported: log_tool("unsupported") case .unauthorized: log_tool("unauthorized") case .poweredOff: log_tool("poweredOff") case .poweredOn: log_tool("poweredOn") bluetooth_peripheral_manager_deploy_service() for service in services { manager?.add(service.value as! CBMutableService) } } } /** 调用 manager?.add(service: CBMutableService) 之后会调用 通常会调用 manager?.startAdvertising(advertisementData: [String : Any]?) 来发送广播 manager?.startAdvertising([ CBAdvertisementDataServiceUUIDsKey: [ CBUUID ], CBAdvertisementDataLocalNameKey: String ]) 然后会调用 func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) */ var add_service: [CBService] = [] func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { if let value = error { log_tool("name: \(service.uuid.uuidString); error: \(value)") } else { log_tool("name: \(service.uuid.uuidString)") if !add_service.contains(service) { add_service.append(service) if add_service.count == services.count { manager?.startAdvertising([ CBAdvertisementDataServiceUUIDsKey: add_service.compactMap({$0.uuid}) ]) } } } } /** 设备开始广播 */ func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { log_tool("error: \(String(describing: error))") } /** 设备字符被订阅了 */ func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { log_tool("central: \(central.identifier.uuidString); characteristic: \(characteristic.uuid.uuidString)") } /** 设备字符被取消订阅 */ func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { log_tool("central: \(central.identifier.uuidString); characteristic: \(characteristic.uuid.uuidString)") } /** 收到读取请求 */ func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { log_tool("central: \(request.central.identifier.uuidString); characteristic: \(request.characteristic.uuid.uuidString); value: \(request.value != nil ? log_value_16(request.value!) : "nil")") } /** 收到输入请求 */ func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { for request in requests { log_tool("central: \(request.central.identifier.uuidString); characteristic: \(request.characteristic.uuid.uuidString); value: \(request.value != nil ? log_value_16(request.value!) : "nil")") } } /** 准备好来更新订阅 */ func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { log_tool("") } } extension BluetoothPeripheral { /** 1. 更新蓝牙状态 */ func bluetooth_peripheral_manager_state_update() { } /** 2. 蓝牙状态正常,开始设置 */ func bluetooth_peripheral_manager_deploy_service() { let service = CBMutableService( type: CBUUID(string: "FFF0"), primary: true ) let read = CBMutableCharacteristic( type: CBUUID(string: "FFA1"), properties: CBCharacteristicProperties.read, value: nil, permissions: CBAttributePermissions.readable ) let write = CBMutableCharacteristic( type: CBUUID(string: "FFA2"), properties: CBCharacteristicProperties.write, value: nil, permissions: CBAttributePermissions.writeable ) let notify = CBMutableCharacteristic( type: CBUUID(string: "FFA3"), properties: CBCharacteristicProperties.notify, value: nil, permissions: CBAttributePermissions.readable ) service.characteristics = [ read, write, notify ] services["TestService"] = service charateristics["readCharacteristic"] = read charateristics["writeCharacteristic"] = write charateristics["notifyCharacteristic"] = notify } /** */ /** */ /** */ }
C++
UTF-8
4,191
2.671875
3
[ "MIT" ]
permissive
#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <cmath> using namespace std; using namespace cv; int main() { string imgname = "lena.png"; int arr[256] = { 0 }; Mat original = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); Mat image = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); //binary Mat image2 = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); for (int i = 0; i < image2.rows; i++) { for (int j = 0; j < image2.cols; j++) { if (image2.at<uchar>(i, j) > 80) { image2.at<uchar>(i, j) = 255; } else { image2.at<uchar>(i, j) = 0; } } } //binary inverse Mat image3 = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); for (int i = 0; i < image2.rows; i++) { for (int j = 0; j < image2.cols; j++) { if (image3.at<uchar>(i, j) > 80) { image3.at<uchar>(i, j) = 0; } else { image3.at<uchar>(i, j) = 255; } } } //trunc Mat image4 = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); for (int i = 0; i < image4.rows; i++) { for (int j = 0; j < image4.cols; j++) { if (image4.at<uchar>(i, j) > 80) { image4.at<uchar>(i, j) = 255; } else { } } } //tozero Mat image5 = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); for (int i = 0; i < image5.rows; i++) { for (int j = 0; j < image5.cols; j++) { if (image5.at<uchar>(i, j) > 80) { } else { image5.at<uchar>(i, j) = 0; } } } //tozero inv Mat image6 = imread(imgname, CV_LOAD_IMAGE_GRAYSCALE); for (int i = 0; i < image6.rows; i++) { for (int j = 0; j < image6.cols; j++) { if (image6.at<uchar>(i, j) > 80) { image6.at<uchar>(i, j) = 0; } else { } } } //histogram array: each color value, how many times it repeats itself for (int i = 0; i < image.rows; i++) { for (int j = 0; j < image.cols; j++) { int index = (int)(image.at<uchar>(i, j)); arr[index]++; } } int max = 0; for (int i = 0; i < 255; i++) { if (arr[i] > max) { max = arr[i]; } } // ------------------------------ incremento 1 int alto = 750; int ancho = 750; Mat myMat1(alto, ancho, CV_32F, Scalar(0)); int inc = ancho / 256; for (int i = 0; i < 255; i++) { rectangle(myMat1, Point(inc * i, myMat1.rows), Point((inc*(i + 1) - 1), myMat1.rows - ((arr[i] * myMat1.rows) / (max))), Scalar(255, 255, 255, 0), CV_FILLED); } //------------------------------- incremento 2 Mat myMat2(alto, ancho, CV_32F, Scalar(0)); int inc2 = ancho / 256; for (int i = 0; i < 255; i += 2) { rectangle(myMat2, Point(inc * i, myMat2.rows), Point((inc*(i + 2) - 1), myMat2.rows - (((arr[i] + arr[i + 1]) * myMat2.rows) / (2 * max))), Scalar(255, 255, 255, 0), CV_FILLED); } //------------------------------- incremento 4 Mat myMat4(alto, ancho, CV_32F, Scalar(0)); int inc4 = ancho / 256; for (int i = 0; i < 255; i += 4) { rectangle(myMat4, Point(inc * i, myMat4.rows), Point((inc*(i + 4) - 1), myMat4.rows - (((arr[i] + arr[i + 1] + arr[i + 2] + arr[i + 3]) * myMat4.rows) / (4 * max))), Scalar(255, 255, 255, 0), CV_FILLED); } //--------------square Mat square(500, 500, CV_8UC1, Scalar(0)); int border = 50; for (int i = 0; i < square.rows; i++) { for (int j = 0; j < square.cols; j++) { if ((i > border && i < square.rows - border) && (j > border && j < square.cols - border)) { square.at<uchar>(i, j) = (uchar)(255); } } } //filters namedWindow("original", WINDOW_AUTOSIZE); imshow("original", original); namedWindow("binary inv", WINDOW_AUTOSIZE); imshow("binary inv", image3); namedWindow("threshold", WINDOW_AUTOSIZE); imshow("threshold", image4); namedWindow("tozero", WINDOW_AUTOSIZE); imshow("tozero", image5); namedWindow("tozero inv", WINDOW_AUTOSIZE); imshow("tozero inv", image6); //histograms namedWindow("Display window", WINDOW_AUTOSIZE); imshow("Display window", myMat1); namedWindow("Display window2", WINDOW_AUTOSIZE); imshow("Display window2", myMat2); namedWindow("Display window4", WINDOW_AUTOSIZE); imshow("Display window4", myMat4); namedWindow("binary", WINDOW_AUTOSIZE); imshow("binary", image2); namedWindow("square", WINDOW_AUTOSIZE); imshow("square", square); waitKey(0); }
C
UTF-8
714
4.03125
4
[]
no_license
#include "lists.h" /** *check_cycle - Checks if the single linkedlist contains a cycle. *@list: pointer to the head of the list. *Return: 0 if there is no loop. Otherwise 1 */ int check_cycle(listint_t *list) { /*we will use the algorithm turtle and rabbit*/ listint_t *turtle; listint_t *rabbit; turtle = list; rabbit = list; if(list == NULL) /* if list is equal to NULL there is no loop */ return(0); while (turtle && rabbit && rabbit->next) { turtle = turtle->next; /* move turtle forward one */ rabbit = rabbit->next->next; /* move rabbit forward two */ if (turtle == rabbit) /* if they are equal means loop found */ return(1); } return(0); /* loop exit means no loops found */ }
PHP
UTF-8
5,984
2.828125
3
[]
no_license
<?php function testDescr($d) { return (strlen(trim($d))>2); } function testNum($id0) { $id0 = trim($id0); $strl=strlen($id0); $ctr = 0; for ($i=0; $i<$strl; $i++) { $c=substr($id0,$i,1); $ctr+=($c>="0" && $c<="9"); } return (($strl>0) && ($ctr==strlen($id0) ) ); } function testId($id0) { $ok=false; $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"api-username: guy\r\n" . "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n" ) ); $context= stream_context_create($opts); $file = file_get_contents('http://178.62.37.42/albums', false, $context); $aAlbum =json_decode($file,true); foreach ($aAlbum as $k=>$v) { foreach ($v as $key => $value) { $id = $value["id"]; $ok = $ok || ($id==$id0); } } return $ok; } $funq = $_POST["submit"]; $id = $_POST["id"]; $title = $_POST["title"]; $created = $_POST["created"]; $updated = $_POST["updated"]; $er = $status = ""; switch ($funq) { case "Tracks": $link="tracks.php"; $link.="?id=".$id; $link.="&title=".$title; $link.="&created=".$created; $link.="&updated=".$updated; header('Location: '.$link); break; case "Add": $er=""; if (!testDescr($title)) $er="Full Title Required - ".$title; if (strlen($er)==0) { $created =date("Y-m-d G:i:s"); $updated =""; $postdata = http_build_query( array( "id" => "1", "title" => $title, "created_at" => $created, "updated_at" => $updated ) ); $opts = array('http' => array('method' => 'POST', 'header' => "api-username: guy\r\n". "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n", 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://178.62.37.42/albums', false, $context); $status = "Added Album"; } $link="album.php"; $link.="?id=".$id; $link.="&title=".$title; $link.="&created=".$created; $link.="&updated=".$updated; $link.="&tracks=".$tracks; $link.="&er=".$er; $link.="&status=".$status; header('Location: '.$link); exit; break; case "Change": $er=""; if (!testDescr($title)) $er="Full Title Required - ".$title; if (!testnum($id))$er.="ID must be numeric.";elseif (!testId($id)) $er.="ID ".$id." not found"; if (strlen($er)==0) { $updated=date("Y-m-d G:i:s"); $postdata = http_build_query( array("id" => $id, "title" => $title, "updated_at" => $updated, "created_at" => $created ) ); $opts = array('http' => array('method' => 'PUT', 'header' => "api-username: guy\r\n". "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n", 'content' => $postdata) ); $context = stream_context_create($opts); $result = file_get_contents('http://178.62.37.42/albums/'.$id, false, $context); $status="Changed Album"; } $link="album.php"; $link.="?id=".$id; $link.="&title=".$title; $link.="&created=".$created; $link.="&updated=".$updated; $link.="&tracks=".$tracks; $link.="&er=".$er; $link.="&status=".$status; header('Location: '.$link); exit; break; case "Delete": $er=""; if (!testNum($id)) $er="ID must be numeric."; elseif (!testId($id))$er="ID ".$id." not found"; if (strlen($er)==0) { $link="album.php"; $postdata = http_build_query( array("id" => $id, "title" => $title, "created_at" => $created, "updated_at" => $updated ) ); $opts = array('http' => array('method' => 'DELETE', 'header' => "api-username: guy\r\n". "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n", 'content' => $postdata) ); $context = stream_context_create($opts); $result = file_get_contents('http://178.62.37.42/albums/'.$id, false, $context); $status="Deleted Album"; } $link="album.php?er=".$er."&status=".$status; header('Location: '.$link); break; case "Enquire": $er=""; if (!testNum($id)) $er="ID must be numeric."; elseif (!testId($id)) $er="ID ".$id." not found"; if (strlen($er)==0) { $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"api-username: guy\r\n" . "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n" ) ); $context = stream_context_create($opts); $file = file_get_contents('http://178.62.37.42/albums/'.$id, false, $context); $aAlbum =json_decode($file,true); $aAlbum0 =$aAlbum["album"]; $tracks =$aAlbum0["tracks"]; $link="album.php"; $link.="?id=".$aAlbum0["id"]; $link.="&title=".$aAlbum0["title"]; $link.="&created=".$aAlbum0["created_at"]; $link.="&updated=".$aAlbum0["updated_at"]; $link.="&tracks=".count($tracks); } else { $link="album.php"; $link.="?id=".$id."&er=".$er; } header('Location: '.$link); exit; break; case "List": $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"api-username: guy\r\n" . "api-token: d55eb61bda4b6a45d2e7252f25c8949f\r\n" ) ); $context = stream_context_create($opts); print "<html> <head> <link href='main.css' rel='stylesheet'/><body> <h1>Album List</h1>"; $file = file_get_contents('http://178.62.37.42/albums', false, $context); $aAlbum=json_decode($file,true); print "<table> <tr> <th>ID</th> <th>Title</th> <th>Created</th> <th>Updated</th> <th>Tracks</th> </tr>"; foreach ($aAlbum as $k=>$v) { $aAlbums=$v; $ctr=count($aAlbums); foreach ($aAlbums as $key => $value) { $aAlbum0 =$value; $id =$aAlbum0["id"]; $title =$aAlbum0["title"]; $created =$aAlbum0["created_at"]; $updated =$aAlbum0["updated_at"]; $tracks =count($aAlbum0["tracks"]); $link ="album.php"; $link .="?id=".$id; $link .="&title=".$title; $link .="&created=".$created; $link .="&updated=".$updated; $link .="&tracks=".$tracks; print "<tr> <td><a href='".$link."'>".$aAlbum0["id"]."</a></td> <td>".$title."</td> <td>".$created."</td> <td>".$updated."</td> <td>".count($aAlbum0["tracks"])."</td> <tr>"; } } print "</table>"; print "<form action='album.php'> <input type='submit' value ='Exit'> </form> </body> </html>"; break; default: print "Error - unrecognised Function [".$funq."]"; } ?>
C
UTF-8
1,408
3.046875
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> // getpagesize #include <assert.h> #include "common.h" #include "shm.h" #define FILENAME "/mnt/hugetlbfs/test_mem_alloc" #define MM_SIZE (256UL*1024*1024) void write_data(mem_allocator* allocator) { uint64_t size = allocator->size; uint8_t* addr = (uint8_t*) allocator->addr; for(uint64_t i = 0; i < size; i++) { //D("%d = %d", *(addr+i), (int) (i & 0xff)); *(addr+i) = (i & 0xff); } } void check_data(mem_allocator* allocator) { uint64_t size = allocator->size; uint8_t* addr = (uint8_t*) allocator->addr; for(uint64_t i = 0; i < size; i++) { //D("%d == %d !?", *(addr+i), (int) (i & 0xff)); assert(*(addr+i) == (i & 0xff)); } } int main() { for (int i = 0; i < 3; i++) { mem_allocator* allocator; if( i == 0 ) allocator = create_mem_allocator(FILENAME, MM_SIZE); else if (i == 1) allocator = create_mem_allocator_with_addr(FILENAME, MM_SIZE, NULL); else allocator = create_mem_allocator_with_addr(FILENAME, MM_SIZE, (void*)0x0UL); if (allocator == NULL) { D("fail to create memory allocator."); exit(1); } write_data(allocator); check_data(allocator); destroy_mem_allocator(allocator); D("%d:fin.", i); } return 0; }
Markdown
UTF-8
2,238
3.4375
3
[]
no_license
# 436. Find Right Interval ## My submission ```java /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public int[] findRightInterval(Interval[] intervals) { int[] result = new int[intervals.length]; int[] re = new int[intervals.length]; Arrays.fill(result, Integer.MAX_VALUE); Arrays.fill(re, -1); if(intervals.length == 1) return new int[]{-1}; for(int i = 0; i < intervals.length; i++){ for(int j = 0; j < intervals.length; j++){ if(intervals[j].start >= intervals[i].end && intervals[j].start - intervals[i].end < result[i]){ result[i] = intervals[j].start - intervals[i].end; re[i] = j; } } } return re; } } ``` ## quick ```java /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class Solution { public int[] findRightInterval(Interval[] intervals) { if (intervals == null || intervals.length == 0) return new int[]{}; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < intervals.length; i++){ min = Math.min(min, intervals[i].start); max = Math.max(max, intervals[i].start); } int[] bucket = new int[max - min + 1]; Arrays.fill(bucket, -1); for (int i = 0; i < intervals.length; i++){ bucket[intervals[i].start - min] = i; } int[] ans = new int[intervals.length]; for (int i = 0; i < intervals.length; i++){ int target = intervals[i].end - min; if (target >= bucket.length){ ans[i] = -1; continue; } while (bucket[target] == -1){ target++; } ans[i] = bucket[target]; } return ans; } } ```
Java
UTF-8
7,069
2.921875
3
[]
no_license
import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Stack; import java.util.TreeSet; import java.util.WeakHashMap; interface Enumable { void methodA(); } enum MyEnum implements Enumable { INSTANCE, INSTANCE1("Ins"); private int i = 0; MyEnum(String a){ this.value = a; } MyEnum(){ } public String getValue() { return this.value; } private String value; public void methodA(){ System.out.println("A"); } } class A { Integer i; public A(Integer i){ this.i = i; } @Override public String toString() { return "A{" + "i=" + i + '}'; } /*@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; A a = (A) o; return Objects.equals(i, a.i); }*/ /*@Override public int hashCode() { return Objects.hash(i); }*/ } class Employee1Comaparator implements Comparator<Employee1>{ @Override public int compare(Employee1 e1, Employee1 e2) { /*if("ceo".equalsIgnoreCase(e1.getDesignation()) || "ceo".equalsIgnoreCase(e2.getDesignation())){ return -1; }*/ if("ceo".equalsIgnoreCase(e1.getDesignation())){ return -1; } if("ceo".equalsIgnoreCase(e2.getDesignation())){ return 1; } if(e1.getId()-e2.getId() == 0){ return e1.getDesignation().compareTo(e2.getDesignation()); } return e1.getId()-e2.getId(); } } class Employee1{ public int getId() { return id; } public void setId(int id) { this.id = id; } private int id; @Override public String toString() { return "Employee1{" + "id=" + id + ", name='" + name + '\'' + ", designation='" + designation + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } private String name; public Employee1(int id, String name, String designation) { this.id = id; this.name = name; this.designation = designation; } private String designation; } public class Test { public static void main(String[] args) { /*ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); ListIterator<Integer> iterator = list.listIterator(); int i = 5; while (iterator.hasNext()){ iterator.add(i); i++; System.out.println(iterator.next()); } System.out.println(list);*/ /* LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.add(1); linkedList.add(2); linkedList.add(3); ArrayList<Integer> integers = new ArrayList<>(); integers.add(3); integers.add(4); integers.add(5); linkedList.removeAll(integers); System.out.println(linkedList); Stack<Integer> stack = new Stack<>(); stack.ensureCapacity(3); System.out.println(stack);*/ /*LinkedHashMap<Integer,Integer> linkedHashMap = new LinkedHashMap(2,.75f,true); linkedHashMap.put(1000,1); linkedHashMap.put(2000,2); linkedHashMap.put(3000,3); linkedHashMap.put(4000,4); linkedHashMap.put(5000,5); linkedHashMap.put(6000,6); linkedHashMap.put(7000,7); for(Integer i : linkedHashMap.values()){ System.out.println(i); } linkedHashMap.get(1000); linkedHashMap.get(3000); for(Integer i : linkedHashMap.values()){ System.out.println(i); } System.out.println("\n\n"); for(Map.Entry entry : linkedHashMap.entrySet()){ System.out.println(entry); }*/ /*WeakHashMap<WeakReference<Integer>, Integer> weakHashMap = new WeakHashMap<>(); weakHashMap.put(new WeakReference<Integer>(1),1); weakHashMap.put(new WeakReference<Integer>(2),2); weakHashMap.put(new WeakReference<Integer>(3),3); weakHashMap.put(new WeakReference<Integer>(4),4); System.out.println(weakHashMap); System.gc(); try { Thread.sleep(5000l); } catch (InterruptedException e) { } System.out.println(weakHashMap);*/ /* List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); ListIterator<Integer> listIterator = list.listIterator(); listIterator.add(1); */ /* while (listIterator.hasPrevious()){ System.out.println(listIterator.previous()); } System.out.println(list); Map<String,String> map = new HashMap<>(); map.keySet().iterator();*/ /* HashMap<A,Integer> map = new HashMap(); A a = new A(0); A b = new A(0); A c = new A(0); System.out.println(a.hashCode()); System.out.println(b.hashCode()); System.out.println(c.hashCode()); map.put(a,0); map.put(b,1); map.put(c,2); System.out.println(map);*/ /*int a = 1; int b = 1; System.out.println(a==b); int i = 10; long l = i; */ /* MyEnum myEnum = MyEnum.INSTANCE; MyEnum myEnum1 = MyEnum.INSTANCE1; System.out.println(myEnum1.getValue()); System.out.println(myEnum.getValue()); */ /* List<Integer> list = new ArrayList<>(); list.add(10); list.add(1); list.add(0); list.add(2); list.add(30); list.add(9); list.add(7); list.add(null); Collections.sort(list); System.out.println(list);*/ Set<Employee1> set = new TreeSet<Employee1>(new Employee1Comaparator()); set.add(new Employee1(3,"batnu","developer")); set.add(new Employee1(10,"vaibhav","ceo")); set.add(new Employee1(5,"vaibhav","ceo")); set.add(new Employee1(1,"akhilesh","director")); set.add(new Employee1(-9,"prateek","qa")); set.add(new Employee1(1,"pranav","tester")); set.add(new Employee1(1,"batnu","analyst")); set.add(new Employee1(3,"batnu","ba")); System.out.println(set); } }
C++
UTF-8
1,421
2.9375
3
[]
no_license
#include <reader.hpp> #define NUM_LINES 1000 std::vector<workItem> createWorkItems(std::vector<std::string> lines) { std::vector<workItem> lineWorkItems; for(std::vector<std::string>::iterator it = lines.begin(); it != lines.end(); ++it) { std::istringstream iss(*it); do { std::string subs; iss >> subs; // Make sure to create a new workItem // Check if the string is not all whitespaces if(subs.find_first_not_of(' ') != std::string::npos) { lineWorkItems.push_back(workItem(subs, 1)); } } while (iss); } return lineWorkItems; } void spawnNewReaderThread() { std::string fileName = getNextSyncedFileName(); std::vector<std::string> lines; while(fileName.compare("")) { // 1. Readfile until eof. // 2. Break the string into words // 3. Create a work item for each word // 4. Send a chunk of work items to arbitrate // Read file as line by line std::string line; // File stream handle std::ifstream inputReadFile; inputReadFile.open(fileName); if(inputReadFile.is_open()) { // Read chunks of lines while(getline(inputReadFile, line)) { lines.push_back(line); } arbitrateWorkItems(createWorkItems(lines)); lines.clear(); } else { std::cout << fileName << " not found! \n"; } inputReadFile.close(); // Get the next file to read fileName = getNextSyncedFileName(); } readerFinshed(); }
Ruby
UTF-8
441
3.109375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def new_hash this_hash = Hash.new end def my_hash that_hash = { green: "hair" } end def pioneer grace_hash = { name: 'Grace Hopper' } end def id_generator id_hash = { id: 6 } end def my_hash_creator(key, value) created_hash = { key => value } end def read_from_hash(hash, key) hash[key] end def update_counting_hash(hash, key) if hash[key] hash[key] += 1 else hash[key] = 1 end hash end
C++
UTF-8
1,381
2.59375
3
[]
no_license
#include "doortile.hpp" #include "engine.hpp" DoorTile::DoorTile(SDL_Renderer* renderer, const std::string& filePath, int size, int x, int y) { script.doFile("assets/scripts/doortile.lua").openLibs(); script.push(x).setGlobal("posX"); script.push(y).setGlobal("posY"); posX = x; posY = y; source.x = 0; source.y = 0; source.h = size; source.w = size; script.getGlobal("posX").pop(destination.x); script.getGlobal("posY").pop(destination.y); destination.h = size; destination.w = size; loadTexture(renderer, filePath); registerLuaFuncs(); } DoorTile::~DoorTile() { } void DoorTile::update(float delta) { script.getGlobal("update").push(delta).call(1, 0); } void DoorTile::loadTexture(SDL_Renderer* renderer, const std::string& filePath) { SDL_Surface* loadedSurface = IMG_Load(filePath.c_str()); if (!loadedSurface) printf("Unable to load image %s! SDL_image Error: %s", filePath.c_str(), IMG_GetError()); else { texture = SDL_CreateTextureFromSurface(renderer, loadedSurface); if (texture == NULL) printf("Unable to create ctexture from %s! SDL Error: %s\n", filePath.c_str(), SDL_GetError()); } SDL_FreeSurface(loadedSurface); } int DoorTile::lua_loadNewRoom(lua_State* lua) { Engine::getInstance().getWorld()->nextRoom(); return 0; } void DoorTile::registerLuaFuncs() { lua_register(script.getState(), "loadNewRoom", lua_loadNewRoom); }
Java
UTF-8
7,650
1.929688
2
[ "Apache-2.0" ]
permissive
package com.github.zuihou.admin.rest.authority; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.github.zuihou.admin.entity.authority.po.AdminRole; import com.github.zuihou.admin.repository.authority.example.AdminRoleExample; import com.github.zuihou.admin.repository.authority.service.AdminRoleService; import com.github.zuihou.admin.rest.authority.api.AdminRoleApi; import com.github.zuihou.admin.rest.authority.dto.AdminRoleDto; import com.github.zuihou.admin.rest.authority.dto.AdminRolePageReqDto; import com.github.zuihou.admin.rest.authority.dto.AdminRoleSaveDto; import com.github.zuihou.admin.rest.authority.dto.AdminRoleUpdateDto; import com.github.zuihou.admin.rest.dozer.DozerUtils; import com.github.zuihou.base.Result; import com.github.zuihou.commons.constant.DeleteStatus; import com.github.zuihou.commons.constant.EnableStatus; import com.github.zuihou.commons.context.BaseContextHandler; import com.github.zuihou.commons.exception.core.ExceptionCode; import com.github.zuihou.page.plugins.openapi.OpenApiReq; import com.github.zuihou.utils.BizAssert; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import static com.github.zuihou.utils.BizAssert.assertNotEmpty; import static com.github.zuihou.utils.BizAssert.assertNotNull; /** * @author zuihou * @createTime 2017-12-12 20:49 */ @Api(value = "API - AdminRoleApiImpl", description = "角色管理") @RestController @RequestMapping("role") @Slf4j public class AdminRoleApiImpl implements AdminRoleApi { @Autowired private AdminRoleService adminRoleService; @Autowired private DozerUtils dozerUtils; @Override @ApiOperation(value = "查找角色", notes = "根据角色id[id]查找角色") @RequestMapping(value = "/get", method = RequestMethod.GET) public Result<AdminRoleDto> getRoleByAppIdAndId(@RequestParam("id") Long id) { String appId = BaseContextHandler.getAppId(); AdminRole role = adminRoleService.getByAppIdAndId(appId, id); if (role.getIsDelete()) { return Result.success(null); } return Result.success(dozerUtils.map(role, AdminRoleDto.class)); } @Override @ApiOperation(value = "查找角色", notes = "根据角色编码[code]查找角色") @RequestMapping(value = "/getByCode", method = RequestMethod.GET) public Result<AdminRoleDto> getRoleByAppIdAndCode(@RequestParam("code") String code) { String appId = BaseContextHandler.getAppId(); AdminRoleExample example = new AdminRoleExample(); example.createCriteria().andAppIdEqualTo(appId).andCodeEqualTo(code) .andIsDeleteEqualTo(DeleteStatus.UN_DELETE.getVal()); return Result.success(dozerUtils.map(adminRoleService.getUnique(example), AdminRoleDto.class)); } @Override @ApiOperation(value = "获取角色分页信息", notes = "获取角色分页信息 name/description 左模糊") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "第几页", defaultValue = "1", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "10", dataType = "int", paramType = "query") }) @RequestMapping(value = "/page", method = RequestMethod.GET) public Result<PageInfo<AdminRoleDto>> page(OpenApiReq openApiReq, AdminRolePageReqDto rolePageReqDto) { String appId = BaseContextHandler.getAppId(); AdminRoleExample example = new AdminRoleExample(); example.createCriteria().andAppIdEqualTo(appId).andCodeEqualTo(rolePageReqDto.getCode()) .andNameLike(AdminRoleExample.leftLike(rolePageReqDto.getName())) .andIsDeleteEqualTo(DeleteStatus.UN_DELETE.getVal()).andIsEnableEqualTo(rolePageReqDto.getIsEnable()) .andDescriptionLike(AdminRoleExample.leftLike(rolePageReqDto.getDescription())); example.setOrderByClause("create_time desc"); PageHelper.startPage(openApiReq.getPageNo(), openApiReq.getPageSize()); List<AdminRole> roleList = adminRoleService.find(example); return Result.success(new PageInfo<>(dozerUtils.mapPage(roleList, AdminRoleDto.class))); } @Override @ApiOperation(value = "新增角色", notes = "新增角色, 角色编码[code]不能重复") @ApiResponses({ @ApiResponse(code = 52000, message = "角色信息不能为空"), @ApiResponse(code = 52001, message = "角色编码[code]不能为空"), @ApiResponse(code = 52002, message = "角色编码[code]已存在"), }) @RequestMapping(value = "/save", method = RequestMethod.POST) public Result<AdminRoleDto> save(@RequestBody AdminRoleSaveDto adminRoleSaveDto) { assertNotNull(ExceptionCode.ROLE_NULL, adminRoleSaveDto); assertNotEmpty(ExceptionCode.ROLE_CODE_EMPTY, adminRoleSaveDto.getCode()); String appId = BaseContextHandler.getAppId(); String userName = BaseContextHandler.getUserName(); BizAssert.assertFalse(ExceptionCode.ROLE_CODE_EXIST, adminRoleService.check(appId, adminRoleSaveDto.getCode())); AdminRole role = dozerUtils.map(adminRoleSaveDto, AdminRole.class); role.setAppId(appId); role.setIsDelete(DeleteStatus.UN_DELETE.getVal()); role.setIsEnable(EnableStatus.ENABLE.getVal()); role.setCreateUser(userName); role.setUpdateUser(userName); role = adminRoleService.saveSelective(role); return Result.success(dozerUtils.map(role, AdminRoleDto.class)); } @Override @ApiOperation(value = "修改角色", notes = "修改指定id的角色") @ApiResponses({ @ApiResponse(code = 52000, message = "角色信息不能为空"), @ApiResponse(code = 52003, message = "角色[id]不能为空"), }) @RequestMapping(value = "/update", method = RequestMethod.POST) public Result<Boolean> update(@RequestBody AdminRoleUpdateDto adminRoleUpdateDto) { assertNotNull(ExceptionCode.ROLE_NULL, adminRoleUpdateDto); assertNotNull(ExceptionCode.ROLE_ID_NULL, adminRoleUpdateDto.getId()); String appId = BaseContextHandler.getAppId(); String userName = BaseContextHandler.getUserName(); AdminRole role = dozerUtils.map(adminRoleUpdateDto, AdminRole.class); role.setAppId(appId); role.setUpdateUser(userName); adminRoleService.updateByAppIdAndIdSelective(appId, role); return Result.success(true); } @Override @ApiOperation(value = "删除角色", notes = "删除指定id的角色") @ApiImplicitParam(name = "id", value = "角色id", required = true, paramType = "query", dataType = "long") @RequestMapping(value = "/remove", method = RequestMethod.POST) public Result<Boolean> remove(@RequestParam("id") Long id) { String appId = BaseContextHandler.getAppId(); adminRoleService.removeByAppIdAndId(appId, id); return Result.success(true); } }
Python
UTF-8
183
3.71875
4
[]
no_license
''' Write a program to print the first 14 odd numbers starting from 3 Output: 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ''' a = 14 odd = 3 for i in range(1,a+1): print(odd) odd+=2
PHP
UTF-8
3,279
2.796875
3
[]
no_license
<?php //include kan koneksi ke database disini include "config.php"; //jika form pencarian mengandung isi maka akan di proses if ((isset($_POST['submit'])) AND ($_POST['search'] <> "")) { //menerima dan membaca data yang di terima via form metode POST $search = $_POST['search']; //memilih table ke satu dari database mysql $sql1 = mysql_query("SELECT * FROM table1 WHERE detail LIKE '%$search%' ") or die(mysql_error()); //membuat jumlah hasil pencarian pada table ke satu //dengan fungsi mysql_num_rows() $jumlah1 = mysql_num_rows($sql1); //jika hasil pada table ke satu lebih dari pada 0 maka akan di proses if ($jumlah1 > 0) { //menampilkan jumlah hasil pencarian pada table ke satu echo '<p>Ditemukan '.$jumlah1.' data yang sesuai pada table ke satu!</p>'; //membuat pengulangan dengan fungsi while //untuk tampilan hasil table ke satu while ($hasil1 = mysql_fetch_array($sql1)) { //menampilkan nomor urut for($num=0;$num<$jumlah1;$num++){ } echo $num.'. '; //menampilkan hasil pencarian pada table ke satu echo $hasil1['detail'].'<br>'; } } //jika data tidak di temukan pada table ke satu //maka akan dilanjutkan ke table yang ke dua else { //memilih table ke satu dari database mysql $sql2 = mysql_query("SELECT * FROM table2 WHERE detail LIKE '%$search%' ") or die(mysql_error()); //membuat jumlah hasil pencarian pada table ke dua //dengan fungsi mysql_num_rows() $jumlah2 = mysql_num_rows($sql2); //jika hasil pada table ke dua lebih dari pada 0 maka akan di proses if ($jumlah2 > 0) { //menampilkan jumlah hasil pencarian pada table ke dua echo '<p>Ditemukan '.$jumlah2.' data yang sesuai pada table ke dua!</p>'; //membuat pengulangan dengan fungsi while //untuk tampilan hasil table ke dua while ($hasil2 = mysql_fetch_array($sql2)) { //menampilkan nomor urut for($num=0;$num<$jumlah2;$num++){ } echo $num.'. '; //menampilkan hasil pencarian pada table ke dua echo $hasil2['detail'].'<br>'; } } //jika data tidak di temukan pada table ke dua, maka akan dilanjutkan ke table yang ke tiga else { //memilih table ke tiga dari database mysql $sql3 = mysql_query("SELECT * FROM table3 WHERE detail LIKE '%$search%' ") or die(mysql_error()); //membuat jumlah hasil pencarian pada table ke tiga //dengan fungsi mysql_num_rows() $jumlah3 = mysql_num_rows($sql3); //jika hasil pada table ke tiga lebih dari pada 0 maka akan di proses if ($jumlah3 > 0) { //menampilkan jumlah hasil pencarian pada table ke dua echo '<p>Ditemukan '.$jumlah3.' data yang sesuai pada table ke tiga!</p>'; //membuat pengulangan dengan fungsi while //untuk tampilan hasil table ke tiga while ($hasil3 = mysql_fetch_array($sql3)) { //menampilkan nomor urut for($num=0;$num<$jumlah3;$num++){ } echo $num.'. '; //menampilkan hasil pencarian pada table ke tiga echo $hasil3['detail'].'<br>'; } } //jika semua data tidak di temukan pada ke 3 table else { echo "Data yang kamu cari tidak ada pada ke tiga table database kami!"; } } } } //jika form pencarian kosong else { echo 'Silahkan masukkan kata kunci yang kamu cari!'; } ?>
Java
UTF-8
801
2.109375
2
[]
no_license
package com.qpf.manage.web.controller; import com.qpf.manage.entity.User; import com.qpf.manage.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class UserController { @Autowired private UserService userService; @GetMapping({"login", ""}) public String login() { return "login"; } @PostMapping("login") public String doLogin(String email, String password) { User user = userService.login(email, password); if (user != null) { return "main"; } else { return login(); } } }
Java
UTF-8
8,529
2.0625
2
[ "Apache-2.0", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0", "BSD-3-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.tests.load; import java.lang.reflect.Constructor; import java.util.LinkedList; import java.util.List; import org.apache.ignite.Ignite; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cache.store.cassandra.common.SystemHelper; import org.apache.ignite.tests.utils.TestsHelper; import org.apache.logging.log4j.Logger; /** * Basic load test driver to be inherited by specific implementation for particular use-case. */ public abstract class LoadTestDriver { /** Number of attempts to setup load test */ private static final int NUMBER_OF_SETUP_ATTEMPTS = 10; /** Timeout between load test setup attempts */ private static final int SETUP_ATTEMPT_TIMEOUT = 1000; /** */ public void runTest(String testName, Class<? extends Worker> clazz, String logName) { logger().info("Running " + testName + " test"); Object cfg = null; int attempt; logger().info("Setting up load tests driver"); for (attempt = 0; attempt < NUMBER_OF_SETUP_ATTEMPTS; attempt++) { try { cfg = setup(logName); break; } catch (Throwable e) { logger().error((attempt + 1) + " attempt to setup load test '" + testName + "' failed", e); } if (attempt + 1 != NUMBER_OF_SETUP_ATTEMPTS) { logger().info("Sleeping for " + SETUP_ATTEMPT_TIMEOUT + " seconds before trying next attempt " + "to setup '" + testName + "' load test"); try { Thread.sleep(SETUP_ATTEMPT_TIMEOUT); } catch (InterruptedException ignored) { // No-op. } } } if (cfg == null && attempt == NUMBER_OF_SETUP_ATTEMPTS) { throw new RuntimeException("All " + NUMBER_OF_SETUP_ATTEMPTS + " attempts to setup load test '" + testName + "' have failed"); } // calculates host unique prefix based on its subnet IP address long hostUniquePrefix = getHostUniquePrefix(); logger().info("Load tests driver setup successfully completed"); try { List<Worker> workers = new LinkedList<>(); long startPosition = 0; logger().info("Starting workers"); for (int i = 0; i < TestsHelper.getLoadTestsThreadsCount(); i++) { Worker worker = createWorker(clazz, cfg, hostUniquePrefix + startPosition, hostUniquePrefix + startPosition + 100000000); workers.add(worker); worker.setName(testName + "-worker-" + i); worker.start(); startPosition += 100000001; } logger().info("Workers started"); logger().info("Waiting for workers to complete"); List<String> failedWorkers = new LinkedList<>(); for (Worker worker : workers) { boolean failed = false; try { worker.join(); } catch (Throwable e) { logger().error("Worker " + worker.getName() + " waiting interrupted", e); failed = true; } if (failed || worker.isFailed()) { failedWorkers.add(worker.getName()); logger().info("Worker " + worker.getName() + " execution failed"); } else logger().info("Worker " + worker.getName() + " successfully completed"); } printTestResultsHeader(testName, failedWorkers); printTestResultsStatistics(testName, workers); } finally { tearDown(cfg); } } /** */ protected abstract Logger logger(); /** */ protected abstract Object setup(String logName); /** */ protected void tearDown(Object obj) { } /** */ @SuppressWarnings("unchecked") private Worker createWorker(Class clazz, Object cfg, long startPosition, long endPosition) { try { Class cfgCls = cfg instanceof Ignite ? Ignite.class : CacheStore.class; Constructor ctor = clazz.getConstructor(cfgCls, long.class, long.class); return (Worker)ctor.newInstance(cfg, startPosition, endPosition); } catch (Throwable e) { logger().error("Failed to instantiate worker of class '" + clazz.getName() + "'", e); throw new RuntimeException("Failed to instantiate worker of class '" + clazz.getName() + "'", e); } } /** */ private void printTestResultsHeader(String testName, List<String> failedWorkers) { if (failedWorkers.isEmpty()) { logger().info(testName + " test execution successfully completed."); return; } if (failedWorkers.size() == TestsHelper.getLoadTestsThreadsCount()) { logger().error(testName + " test execution totally failed."); return; } String strFailedWorkers = ""; for (String workerName : failedWorkers) { if (!strFailedWorkers.isEmpty()) strFailedWorkers += ", "; strFailedWorkers += workerName; } logger().warn(testName + " test execution completed, but " + failedWorkers.size() + " of " + TestsHelper.getLoadTestsThreadsCount() + " workers failed. Failed workers: " + strFailedWorkers); } /** */ @SuppressWarnings("StringBufferReplaceableByString") private void printTestResultsStatistics(String testName, List<Worker> workers) { long cnt = 0; long errCnt = 0; long speed = 0; for (Worker worker : workers) { cnt += worker.getMsgProcessed(); errCnt += worker.getErrorsCount(); speed += worker.getSpeed(); } float errPercent = errCnt == 0 ? 0 : cnt + errCnt == 0 ? 0 : (float)(errCnt * 100 ) / (float)(cnt + errCnt); StringBuilder builder = new StringBuilder(); builder.append(SystemHelper.LINE_SEPARATOR); builder.append("-------------------------------------------------"); builder.append(SystemHelper.LINE_SEPARATOR); builder.append(testName).append(" test statistics").append(SystemHelper.LINE_SEPARATOR); builder.append(testName).append(" messages: ").append(cnt).append(SystemHelper.LINE_SEPARATOR); builder.append(testName).append(" errors: ").append(errCnt).append(", "). append(String.format("%.2f", errPercent).replace(",", ".")). append("%").append(SystemHelper.LINE_SEPARATOR); builder.append(testName).append(" speed: ").append(speed).append(" msg/sec").append(SystemHelper.LINE_SEPARATOR); builder.append("-------------------------------------------------"); logger().info(builder.toString()); } /** */ private long getHostUniquePrefix() { String[] parts = SystemHelper.HOST_IP.split("\\."); if (parts[2].equals("0")) parts[2] = "777"; if (parts[3].equals("0")) parts[3] = "777"; long part3 = Long.parseLong(parts[2]); long part4 = Long.parseLong(parts[3]); if (part3 < 10) part3 *= 100; else if (part4 < 100) part3 *= 10; if (part4 < 10) part4 *= 100; else if (part4 < 100) part4 *= 10; return (part4 * 100000000000000L) + (part3 * 100000000000L) + Thread.currentThread().getId(); } }
Java
UTF-8
969
3.3125
3
[]
no_license
package model; import javafx.scene.image.Image; /** * This class is responsible for setting the parameters of the model Long_truck and display of the model Long_truck. * @author Wang * */ public class Long_truck extends Obstacle { /** * This method is to set the parameters. * @param x indicate x-axis position in the window * @param y indicate y-axis position in the window * @param speed indicate the speed of the Long_truck */ public Long_truck(int x, int y, double speed) { super(x, y, speed); Set_longtruck_image(speed); } /** * Set truck image that depends on the speed. * @param speed indicate the speed of the truck */ private void Set_longtruck_image(double speed) { if(speed > 0) { setImage(new Image("file:src/main/resources/image/truck2Right.png", 200, 200, true, true)); } else { setImage(new Image("file:src/main/resources/image/truck2Left.png", 200, 200, true, true)); } } }
Python
UTF-8
211
3.140625
3
[]
no_license
def fib(n): if n == 1: return [0] elif n == 2: return [0,1] else: lista = [0,1] while len(lista) != n: lista.append(lista[-2] + lista[-1]) return lista
Markdown
UTF-8
1,904
3.234375
3
[]
no_license
# Deliveries: An Overview >[Deliveries](../appendix/glossary.md#delivery) provide the means of publishing and administering [Tests](../appendix/glossary.md#test). These govern when a test is taken, by whom, and how long it is. This section provides an overview of how to manage your deliveries, including what you need to do to construct them, and what to do with them afterwards. ![Deliveries](../resources/backend/deliveries/deliveries.png) **1.** Creating a new Delivery A delivery is a published test. In practice, publishing a test - i.e. creating a delivery - involves assembling all of the information required to assign and send out a particular test to selected [Test-takers](../appendix/glossary.md#test-taker). This includes such information as the test which is to be delivered, the group of test-takers to receive the test, and the circumstances (in particular the time frame) in which the test may be taken. See the [Tests section](../tests/what-is-a-test.md) for more details on what a test is before it is assembled as a delivery. A delivery can only be assembled after [Items](../appendix/glossary.md#item) have been created and populated and compiled in a test. Profiles of the [Test-takers](../appendix/glossary.md#test-taker) also need to be created and then gathered into [Groups](../appendix/glossary.md#group). A new delivery can then be put together: see [Creating a new Delivery](../deliveries/create-a-new-delivery.md) for information on how to do this. **2.** Using your delivery with test-takers Once your delivery is assembled, the groups of test-takers identified are able to sit the assessment you have prepared within the defined scenario. The [Results](../appendix/glossary.md#results) can then be collected for the whole delivery. For details on how to view the results of your delivery, see the section on [Viewing Results](../results/viewing-results.md).
Java
UTF-8
236
1.867188
2
[]
no_license
package org.library.services; import org.library.models.User; import org.springframework.security.core.userdetails.UserDetailsService; public interface UserService extends UserDetailsService { User createUser(User userDetails); }
C++
UTF-8
3,015
2.6875
3
[]
no_license
// BEGIN CUT HERE /* */ // END CUT HERE #line 7 "PalindromeEncoding.cpp" #include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> using namespace std; #define PB push_back #define MP make_pair #define REP(i,n) for(i=0;i<(n);++i) #define FOR(i,l,h) for(i=(l);i<=(h);++i) #define FORD(i,h,l) for(i=(h);i>=(l);--i) typedef vector<int> VI; typedef vector<string> VS; typedef vector<double> VD; typedef long long LL; typedef pair<int,int> PII; class PalindromeEncoding { public: int getLength(string s) { int t,t1; for (t=1;t<s.length();t++) if (s[t]!=s[0]) break; if ((t==s.length()-1)&&(s[t]==s[0])) return 1; bool mark=false; for (t1=t;t1<s.length();t1++) if (s[t1]==s[t1-1]) {mark=true;break;} if (mark) return t1-(t-1);else return s.length()-(t-1); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "0111001"; int Arg1 = 2; verify_case(0, Arg1, getLength(Arg0)); } void test_case_1() { string Arg0 = "00001"; int Arg1 = 2; verify_case(1, Arg1, getLength(Arg0)); } void test_case_2() { string Arg0 = "01010111100110101110000001011000101000010111000111"; int Arg1 = 6; verify_case(2, Arg1, getLength(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PalindromeEncoding ___test; ___test.run_test(-1); return 0; } // END CUT HERE
JavaScript
UTF-8
1,006
2.578125
3
[]
no_license
const express = require('express'); // We require and instantiate an Express Router to define the path to our resources const router = express.Router(); // We require the model const resources = require('./../resources/model'); // Create a new route for a GET request on all sensors and attach a callback function router.route('/').get(function (req, res, next) { // Reply with the sensor model when this route is selected res.send(resources.iot.sensors); }); // This route serves the passive infrared sensor router.route('/pir').get(function (req, res, next) { res.send(resources.iot.sensors.pir); }); // This routes serve the temperature sensor router.route('/temperature').get(function (req, res, next) { res.send(resources.iot.sensors.temperature); }); // This routes serve the light sensor router.route('/light').get(function (req, res, next) { res.send(resources.iot.sensors.light); }); // We export router to make it accessible for "requirers" of this file module.exports = router;
Markdown
UTF-8
1,034
2.984375
3
[]
no_license
# Sort People List Using standard java libraries to implement `sort` method. ```java static List<Person> sort(Iterable<Person> people, String sortField, String ascending) { //TODO: implement sort } class Person{ String ssn; Date dateOfBirth; String firstName; String lastName; Double heightIn; Double weightLb; } ``` ## Build ``` javac -d out src/*.java ``` ## Run Tests ``` java -ea -cp ./out Main ``` ## Design Considurations I've decide to use `java.util.Collections.sort()` to handle Person list sorting for maintainability. By decoupling sorting algorithm from the collection object, we can change collection object without changing sorting algorithm, and vise versa. ## Trade-offs See these links. https://stackoverflow.com/questions/25492648/what-is-the-time-complexity-of-collectionssort-method-in-java?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29
C
UTF-8
2,445
2.84375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<math.h> #define temperature 0.5 #define InitialMagnetization 1.0 double RightHandSide(double mag,double c); double factorial(int k); int main(void){ int i,j,k; double mag; double k1,k2,k3,k4; double h,a,b,n; double time; double c; double im; char filename[100]; FILE *fp; //fp = fopen("3-body_MasterEquation_M.ver_c_izon_T=0.5_InitialMagnetization=1.0.dat","wb"); a = 0.0; b = 1000.0; n = 10000.0; h = (b-a)/n;//h is fixed to 0.1; im = 0.6; //for(im=0.8;im<=InitialMagnetization;im+=0.1){ sprintf(filename,"3-body_MasterEquation_M.ver_c_izon_T=0.5_InitialMagnetization=%3.1f.dat",im); fp = fopen(filename,"wb"); for(c=3.0;c<=5.0;c+=0.01){ mag = im; for(time=a;time<=b;time+=h){ k1 = RightHandSide(mag,c); k2 = RightHandSide(mag+h*k1/2.0,c); k3 = RightHandSide(mag+h*k2/2.0,c); k4 = RightHandSide(mag+h*k3,c); mag = mag + h*(k1+2.0*k2+2.0*k3+k4)/6.0; } fprintf(fp,"%f %f\n",c,fabs(mag)); } fclose(fp); //} return 0; } double RightHandSide(double mag,double c){ int k,l; double summation_k; double summation_l; summation_l = 0.0; for(l=0;l<=20;l++){ summation_k = 0.0; for(k=0;k<=l;k++){ summation_k += ( factorial(l)/( factorial(k)*factorial(l-k) ) ) *( pow(pow((1+mag)/2.0,2)+pow((1-mag)/2.0,2),k)*pow(0.5*(1+mag)*(1-mag),l-k)/( 1.0+exp(-2.0*(2.0*k-l)/temperature) ) ); //if( (2.0*k-l)>0 ){ // summation_k += ( factorial(l)/( factorial(k)*factorial(l-k) ) ) // *( pow(pow((1+mag)/2.0,2)+pow((1-mag)/2.0,2),k)*pow(0.5*(1+mag)*(1-mag),l-k) ); //}else if( (2.0*k-l)==0 ){ // summation_k += 0.5*( factorial(l)/( factorial(k)*factorial(l-k) ) ) // *( pow(pow((1+mag)/2.0,2)+pow((1-mag)/2.0,2),k)*pow(0.5*(1+mag)*(1-mag),l-k) ); //}else if( (2.0*k-l)<0 ){ // summation_k += 0.0; //} } summation_l += ( pow(c,l)/factorial(l) )*summation_k; } return -(mag+1.0)+2.0*exp(-c)*summation_l; } double factorial(int k){ int i; double product=1.0; for(i=k;i>=0;i--){ if(i!=0){ product *= (double)i; }else if(i==0){ product *= 1.0; } } return product; }
Python
UTF-8
2,907
2.75
3
[]
no_license
import sys import math as m import numpy as np num_pins = 150 circle_diam = 180 inner_radius = (circle_diam-4) / 2 outer_radius = (circle_diam+4) / 2 length = 220 angle_step = np.radians(360 / num_pins) center = length / 2 volume = (length, length, 250) travel_z = 10 push_down_z = 3 def main(): pin_sequence = read_from_file(sys.argv[1]) output_contents = compile_to_gcode(pin_sequence) print(output_contents) def compile_to_gcode(seq): gcode_body = translate_pins_to_gcode(seq) all_gcode = gcode_prologue + gcode_body + gcode_epilogue return "\n".join([l + " ;" for l in all_gcode]) def translate_pins_to_gcode(seq): instructions = [] for i in range(1, len(seq)): prev_pin = seq[i-1] cur_pin = seq[i] move_from_to(instructions, prev_pin, cur_pin) return instructions def move_from_to(instructions, prev_pin, cur_pin): begin_instr = None end_instr = None cw_dist = (num_pins - (cur_pin - prev_pin)) if cur_pin > prev_pin else prev_pin - cur_pin if (cw_dist > (num_pins/2)): begin_instr = instr_mov(*turn_cw(cur_pin, inner_radius)) end_instr = instr_mov(*turn_ccw(cur_pin, inner_radius)) else: begin_instr = instr_mov(*turn_ccw(cur_pin, inner_radius)) end_instr = instr_mov(*turn_cw(cur_pin, inner_radius)) instructions.append(begin_instr) instructions.append(instr_mov(*location_of_pin(cur_pin, outer_radius))) instructions.append(instr_mov(z=push_down_z)) instructions.append(instr_mov(z=travel_z)) instructions.append(end_instr) def location_of_pin(i, r, angle_off=0): res = location_from_angle(angle_from_idx(i)+angle_off, r) return res def turn_cw(i, r): return location_of_pin(i, -angle_step/2, r) def turn_ccw(i, r): return location_of_pin(i, angle_step/2, r) def location_from_angle(angle, r): decimal_places = 4 x = np.around(center + r * m.cos(angle), decimal_places) y = np.around(center + r * m.sin(angle), decimal_places) return np.array([x, y]) def angle_from_idx(idx): return (2 * m.pi * idx / num_pins) + (m.pi/2) def sample_seq(): seq = [] for i in range(0, num_pins): seq.append(i) seq.append(int((i+(num_pins/2)) % num_pins)) return seq def instr_mov(x=None, y=None, z=None): x_arg = "" if x is None else f" X{x}" y_arg = "" if y is None else f" Y{y}" z_arg = "" if z is None else f" Z{z}" return f"G1{x_arg}{y_arg}{z_arg}" def read_from_file(fname): f = open(fname, 'r') contents = f.read() return [int(p) for p in contents.split(",")] wait = 'M25' use_abs = 'G90' home = 'G28' use_mm = 'G21' mov_center = instr_mov(center, center) mov_to_pin_0 = instr_mov(*location_of_pin(0, outer_radius)) gcode_prologue = [use_abs, home, instr_mov(z=10), mov_center, wait, mov_to_pin_0, wait] gcode_epilogue = [home] if __name__ =="__main__": main()
C++
UTF-8
2,140
3.265625
3
[]
no_license
#include <iostream> #include <random> #include <algorithm> #include <functional> #include <vector> using namespace std; int getRandomInteger(){ std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dst(10, 100); return dst( gen ); } void generate_random_seq( vector<int> &arr ){ iota(arr.begin(), arr.end(), getRandomInteger()); //shuffle(arr.begin(), arr.end(), std::mt19937( random_device{}() ) ); } template <typename f> void printAll(vector<int> arr, f& func) { for_each( arr.begin(), arr.end(), func); } int binarySearch(vector<int> v, int key, int start, int end){ int mid; if ( start > end ) { mid = start + (end - start) / 2; if ( v[mid] == key ) return mid; else if ( key < v[mid] ) return binarySearch( v, key, start, mid); else return binarySearch( v, key, mid, end); } return -1; } //use backtracking to generating power sets void sub(std::vector<vector<int> > &rs, vector<int> &ls, string str, int pos); void getPower(string str){ vector<vector<int> > rs; vector<int> list; sub(rs, list, str, 0); for(int i = 0; i < rs.size(); i++ ) { for( int j = 0; j < rs[i].size(); j++) cout << rs[i][j] - '0' << " "; cout << endl; } } void sub(std::vector<vector<int> > &rs, vector<int> &ls, string str, int pos){ rs.push_back(ls); for(int i = pos; i != str.length(); i++) { if (i == str.size() || str[i] == str[i+1]) // remove duplicate continue; ls.push_back( str[i]); sub(rs, ls, str, pos + 1); ls.pop_back(); } } int main(){ getPower("123"); } /* int main() { auto print = [](int a){ cout << a << " "; }; vector<int> v(10); generate_random_seq( v ); printAll( v, print); std::sort( v.begin(), v.end(), [](int a, int b)->bool{ return a < b;}); //cout << "max number is " << max_element( v.begin(), v.end() ) << endl; cout << "distance is " << std::distance( v.begin(), v.end() ) << endl; cout << std::count_if( v.begin(), v.end(), [&v](int a)->int{ return a > 95; } ); nth_element( v.begin(), v.begin() , v.end(), greater<int>()); cout << "max is "<< v[0] << endl; return 0; }*/
C
UTF-8
2,187
2.609375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_color5.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qtamaril <qtamaril@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/12 10:38:47 by qtamaril #+# #+# */ /* Updated: 2020/09/14 12:34:49 by qtamaril ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../../includes/cub3d.h" int check_color5_12(char **s, t_sets *sets, int is_floor) { int len; len = ft_strlen(s[1]); if (s[1][len - 1] == ',') { s[1][len - 1] = '\0'; if (is_floor) return (save_floor_color(s[1], s[2], s[4], sets)); else return (save_ceilling_color(s[1], s[2], s[4], sets)); } else if (s[2][0] == ',') { s[2][0] = '\0'; if (is_floor) return (save_floor_color(s[1], &s[2][1], s[4], sets)); else return (save_ceilling_color(s[1], &s[2][1], s[4], sets)); } else return (color_error()); } int check_color5_34(char **s, t_sets *sets, int is_floor) { int len; len = ft_strlen(s[3]); if (s[3][len - 1] == ',') { s[3][len - 1] = '\0'; if (is_floor) return (save_floor_color(s[1], s[3], s[4], sets)); else return (save_ceilling_color(s[1], s[3], s[4], sets)); } else if (s[4][0] == ',') { s[4][0] = '\0'; if (is_floor) return (save_floor_color(s[1], s[3], &s[4][1], sets)); else return (save_ceilling_color(s[1], s[3], &s[4][1], sets)); } else return (color_error()); } int check_color5(char **s, t_sets *sets, int is_floor) { if (!ft_strcmp(s[3], ",")) return (check_color5_12(s, sets, is_floor)); else if (!ft_strcmp(s[2], ",")) return (check_color5_34(s, sets, is_floor)); else return (color_error()); }
JavaScript
UTF-8
558
2.9375
3
[]
no_license
var input = require('../lib/console').getConsole(process); input.on('get',function(data) { var score = parseFloat(data); if ( score >= 90 && score <= 100 ) { console.log('A'); } else if ( score >= 80 && score <= 89.99 ) { console.log('B'); } else if ( score >= 70 && score <= 79.99 ) { console.log('C'); } else if ( score >= 60 && score <= 69.99 ) { console.log('D'); } else if ( score >= 50 && score <= 59.99 ) { console.log('E'); } else if ( score >= 0 && score <= 49.99 ) { console.log('F'); } else { console.log('?'); } });
Java
UTF-8
4,280
3.1875
3
[]
no_license
package nicolay.wk1; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Scanner; public class Main { /** * Main method to handle user input and run the related methods * @param args command line arguments * @throws SQLException */ public static void main(String args[]) throws SQLException { Connection conn = ConnectionManager.getInstance().getConnection(); ResultSet rs = null; try ( Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Scanner in = new Scanner(System.in); ) { boolean running = true; while(running) { System.out.println("What would you like to do?\n" + "(p) - Populate database from web service\n" + "(a) - Get aggregated data\n" + "(q) - Quit"); String response = in.next(); switch (response.toLowerCase().trim()) { case "p": // POPULATE DBUtil.clearTable("quotes"); List<Quote> quotes = WSUtil.getQuotes("https://bootcamp-training-files.cfapps.io/week1/week1-stocks.json"); DBUtil.saveQuotesToDatabase(quotes); rs = stmt.executeQuery("SELECT * FROM quotes"); rs.last(); System.out.println(rs.getRow() + " rows affected."); break; case "a": // AGGREGATE handleAggregateData(in); break; case "q": // QUIT running = false; break; default: // UNKNOWN COMMAND System.out.println("Command \"" + response + "\" not recognized."); } System.out.println(); } } catch (NumberFormatException e) { System.err.println("Improper date format provided;"); } catch (SQLException e) { System.err.println(e); } finally { ConnectionManager.getInstance().close(); if (rs != null) { rs.close(); } } } /** * Method to handle the user interaction for viewing aggregate view of data. * @param in Scanner used to take user input * @throws SQLException */ private static void handleAggregateData(Scanner in) throws SQLException { if (in == null) { return; } System.out.println("Please provide the symbol for the stock you would like to see: "); String symbol = in.next(); boolean running = true; Calendar calendar = new GregorianCalendar(); TimeSetting timeSetting = null; String[] dateRaw; while (running) { System.out.println("Aggregate by which measure of time?\n" + "(m) - month\n" + "(d) - day"); String measure = in.next(); switch(measure) { case "m": // MONTHLY System.out.println("Please provide the month for which you'd like to see aggregate" + " data (yyyy-mm): "); dateRaw = in.next().trim().split("-"); if (dateRaw.length < 2) { System.out.println("Improper date format\n"); break; } calendar = new GregorianCalendar(Integer.parseInt(dateRaw[0]), Integer.parseInt(dateRaw[1])-1, 1); timeSetting = TimeSetting.MONTH; running = false; break; case "d": // DAILY System.out.println("Please provide the date for which you'd like to see aggregate" + " data (yyyy-mm-dd): "); dateRaw = in.next().trim().split("-"); if (dateRaw.length < 3) { System.out.println("Improper date format\n"); break; } calendar = new GregorianCalendar(Integer.parseInt(dateRaw[0]), Integer.parseInt(dateRaw[1])-1, Integer.parseInt(dateRaw[2])); timeSetting = TimeSetting.DAY; running = false; break; default: // UNKNOWN COMMAND System.out.println("Command \"" + measure + "\" not recognized.\n"); break; } } AggregateQuote quote = DBUtil.getAggregateData(symbol, calendar, timeSetting); if (quote != null) { System.out.println(quote.toString()); } } }
JavaScript
UTF-8
3,239
2.984375
3
[]
no_license
var BBGrade = class BBGrade{ constructor(date, grade, type, name){ this.date = date; this.type = type; this.name = name; var splitScore = grade.split("/"); var gotten; var outOf; if(splitScore[0] == "" || splitScore[0] == "Excluded"){ gotten = 0; outOf = 0; } else if(splitScore[0] == "Missing"){ gotten = 0; outOf = parseFloat(grade.split("/")[1]); } else{ gotten = parseFloat(grade.split("/")[0]); outOf = parseFloat(grade.split("/")[1]); } this.score = [gotten, outOf]; } } var quarterEl = document.getElementById("term-"+quarter+"Q"); var gradeTable = quarterEl.children[2].children[2].children[1]; var allGrades = []; Array.prototype.forEach.call(gradeTable.children, function(row,index){ var newDate; var newGrade; var newType; var newName; if(row.children[0].children.length != 0){ newDate = row.children[3].children[0].value; newGrade = row.children[2].children[0].value; newType = row.children[1].children[0].value; newName = row.children[0].children[0].value; } else{ newDate = row.children[3].innerHTML; newGrade = row.children[2].innerHTML; newType = row.children[1].innerHTML; newName = row.children[0].innerHTML; } allGrades.push(new BBGrade(newDate,newGrade,newType,newName)); }); if(!isWeighted){ var totalEarned = 0; var totalOutOf = 0; allGrades.forEach((grade, ind) => { totalEarned+=grade.score[0]; totalOutOf+=grade.score[1]; }); var totalGrade = totalEarned/totalOutOf; var gradeLetter = "F"; if(totalGrade>=.6 && totalGrade<0.7){ gradeLetter = "D"; } else if(totalGrade>=0.7 && totalGrade<0.8){ gradeLetter = "C"; } else if(totalGrade>=0.8 && totalGrade<0.9){ gradeLetter = "B"; } else if(totalGrade>=0.9){ gradeLetter = "A"; } var gradeFormed = Math.round(totalGrade*10000)/100; var gradeDisp = document.querySelector("#term-"+quarter+"Q > h3"); gradeDisp.innerHTML = quarter+"Q Grade: "+gradeLetter+" ["+gradeFormed+"%]"; } else{ var typeInps = document.getElementById("typeInps"); if(typeInps){ var typeWeights = {}; var orgedGrades = {}; Array.prototype.forEach.call(typeInps.children, (type,index) => { typeWeights[type.name] = parseFloat(type.value); orgedGrades[type.name] = [0,0]; }); allGrades.forEach((grade,index) => { orgedGrades[grade.type][0]+=grade.score[0]; orgedGrades[grade.type][1]+=grade.score[1]; }); var totalGrade = 0; Object.entries(orgedGrades).forEach((type,ind) => { if(type[0] != "undefined"){ totalGrade+=(type[1][0]/type[1][1])*typeWeights[type[0]]; } }); var gradeLetter = "F"; if(totalGrade>=.6 && totalGrade<0.7){ gradeLetter = "D"; } else if(totalGrade>=0.7 && totalGrade<0.8){ gradeLetter = "C"; } else if(totalGrade>=0.8 && totalGrade<0.9){ gradeLetter = "B"; } else if(totalGrade>=0.9){ gradeLetter = "A"; } var gradeFormed = Math.round(totalGrade*10000)/100; var gradeDisp = document.querySelector("#term-"+quarter+"Q > h3"); gradeDisp.innerHTML = quarter+"Q Grade: "+gradeLetter+" ["+gradeFormed+"%]"; } else{ alert("Please add in the weights of the assignment types"); } }
Java
UTF-8
22,978
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package ca.cgjennings.apps.arkham.deck; import ca.cgjennings.apps.arkham.BusyDialog; import ca.cgjennings.apps.arkham.StrangeEons; import ca.cgjennings.apps.arkham.dialog.ErrorDialog; import ca.cgjennings.apps.arkham.plugins.BundleInstaller; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterAbortException; import java.io.File; import java.io.IOException; import java.util.UUID; import java.util.logging.Level; import resources.Language; /** * Creates simple PDF documents. PDF support is not built in; to use this class * the {@code core-PDFOutput.selibrary} library must be installed. (That * library provides a concrete implementation of the {@link PDFWriter} interface * defined in this class.) You can test whether PDF support is available by * calling {@link #isAvailable()}. * * <p> * For easy PDF creation, use one of the static {@link #printToPDF printToPDF} * methods that take a {@link Printable} or {@link DeckEditor}. Alternatively, * call {@link #createPDFWriter()} to obtain a high-level interface to the PDF * engine. * * @author Chris Jennings <https://cgjennings.ca/contact> * @since 3.0 */ public final class PDFPrintSupport { private PDFPrintSupport() { } /** * Returns {@code true} if PDF support is available. * * @return {@code true} if {@link #createPDFWriter} will not throw an * {@code UnsupportedOperationException} exception */ public synchronized static boolean isAvailable() { if (knownOK) { return true; } if (DEFAULT_IMPLEMENTATION_CLASS.equals(IMPLEMENTATION_CLASS)) { if (PDF_LIB_UUID == null) { PDF_LIB_UUID = UUID.fromString("c7c96b28-2c70-4632-b364-e060fd3a25b3"); } if (BundleInstaller.getBundleFileForUUID(PDF_LIB_UUID) != null) { knownOK = true; } } else { try { Class.forName(IMPLEMENTATION_CLASS, false, PDFPrintSupport.class.getClassLoader()); knownOK = true; } catch (Throwable t) { } } return knownOK; } private static UUID PDF_LIB_UUID; private static boolean knownOK; private static synchronized void applyHints(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } /** * Prints the contents of any {@link Printable} object to a PDF file. * * @param title the title of the PDF file * @param pageFormat the page format to use * @param printable the content to print * @param pdfFile the PDF file to create */ public static void printToPDF(final String title, final PageFormat pageFormat, final Printable printable, final File pdfFile) { if (pageFormat == null) { throw new NullPointerException("pageFormat"); } if (printable == null) { throw new NullPointerException("printable"); } if (pdfFile == null) { throw new NullPointerException("pdfFile"); } if (!isAvailable()) { throw new UnsupportedOperationException(); } new BusyDialog(Language.string("busy-exporting"), () -> { boolean existed = pdfFile.exists(); try { PDFWriter w = createPDFWriter(); try { final Configuration c = new Configuration(pdfFile); c.setTitle(title); c.setAuthor(System.getProperty("user.name")); c.setPageWidth(pageFormat.getWidth()); c.setPageHeight(pageFormat.getHeight()); w.setConfiguration(c); BufferedImage page = null; double ppi = 300d; do { try { int pw = (int) (pageFormat.getWidth() * ppi / 72d + 0.5); int ph = (int) (pageFormat.getHeight() * ppi / 72d + 0.5); page = new BufferedImage(pw, ph, BufferedImage.TYPE_INT_RGB); } catch (OutOfMemoryError oom) { ppi -= 50d; if (ppi < 150d) { throw oom; } } } while (page == null); for (int pageIndex = 0;; ++pageIndex) { Graphics2D g = page.createGraphics(); try { applyHints(g); g.setColor(Color.WHITE); g.fillRect(0, 0, page.getWidth(), page.getHeight()); g.setColor(Color.BLACK); g.scale(ppi / 72d, ppi / 72d); int result = printable.print(g, pageFormat, pageIndex); if (result == Printable.NO_SUCH_PAGE) { break; } } finally { g.dispose(); } w.addPage(page, 0d, 0d, c.getPageWidth(), c.getPageHeight()); } } catch (IOException e) { try { w.close(); w = null; } catch (IOException ie) { throw e; } } finally { if (w != null) { w.close(); } } } catch (PrinterAbortException pae) { if (!existed) { pdfFile.delete(); } } catch (Throwable t) { if (!existed) { pdfFile.delete(); } ErrorDialog.displayError(Language.string("psd-pdf-err"), t); } }); } /** * Prints the contents of any {@link Printable} object to a PDF file. * * @param title the title of the PDF file * @param paper the paper type to use * @param printable the content to print * @param pdfFile the PDF file to create */ public static void printToPDF(final String title, final PaperProperties paper, final Printable printable, final File pdfFile) { if (paper == null) { throw new NullPointerException("paper"); } if (printable == null) { throw new NullPointerException("printable"); } if (pdfFile == null) { throw new NullPointerException("pdfFile"); } if (!isAvailable()) { throw new UnsupportedOperationException(); } PageFormat pf = paper.createCompatiblePageFormat(false); printToPDF(title, pf, printable, pdfFile); } /** * Prints a the contents of a deck to a PDF file. * * @param deckEditor the editor displaying the deck to print * @param pdfFile the PDF file to write * @throws UnsupportedOperationException if PDF support is not available * @see #isAvailable() */ public static void printToPDF(final DeckEditor deckEditor, final File pdfFile) { if (deckEditor == null) { throw new NullPointerException("deckEd"); } if (pdfFile == null) { throw new NullPointerException("pdfFile"); } if (!isAvailable()) { throw new UnsupportedOperationException(); } new BusyDialog(Language.string("busy-exporting"), () -> { boolean existed = pdfFile.exists(); try { PDFWriter w = createPDFWriter(); final Deck deck = deckEditor.getDeck(); try { final Configuration c = new Configuration(pdfFile); c.setTitle(deck.getName()); c.setAuthor(System.getProperty("user.name")); c.setPageWidth(deck.getPaperProperties().getPageWidth()); c.setPageHeight(deck.getPaperProperties().getPageHeight()); w.setConfiguration(c); BufferedImage page = null; for (int i = 0; i < deck.getPageCount(); ++i) { double ppi = 300d; boolean ok = false; do { try { page = deckEditor.createPageImage(page, i, ppi); ok = true; } catch (OutOfMemoryError oom) { ppi -= 50d; page = null; if (ppi < 150d) { throw oom; } } } while (!ok); w.addPage(page, 0d, 0d, c.getPageWidth(), c.getPageHeight()); } } catch (IOException e) { try { w.close(); w = null; } catch (IOException ie) { throw e; } } finally { if (w != null) { w.close(); } } } catch (Throwable t) { if (!existed) { pdfFile.delete(); } ErrorDialog.displayError(Language.string("psd-pdf-err"), t); } }); } /** * Returns a new instance of a {@link PDFWriter}. * * @return a new, uninitialized PDF writer instance * @throws UnsupportedOperationException if no PDF support is available */ public static synchronized PDFWriter createPDFWriter() { try { return (PDFWriter) Class.forName(IMPLEMENTATION_CLASS).getConstructor().newInstance(); } catch (ClassNotFoundException e) { StrangeEons.log.log(Level.SEVERE, "expected to instantiate PDF writer but failed", e); } catch (Throwable t) { } throw new UnsupportedOperationException(); } /** * An interface implemented by classes that can provide very basic PDF * writing support. To use a PDF writer, follow these steps: * <ol> * <li> Get a new writer instance by calling * {@link PDFPrintSupport#createPDFWriter()}. * <li> Create a new {@link Configuration} object and fill in the members * with suitable configuration information. * <li> Load the configuration into the writer by calling * {@link #setConfiguration(ca.cgjennings.apps.arkham.deck.PDFPrintSupport.Configuration)}. * <li> Call * {@linkplain #addPage(java.awt.image.BufferedImage, double, double, double, double) addPage} * in sequence for each page you wish to add, supplying an image of the page * content. * <li> Call {@link #close()} after all pages have been added. * </ol> * * <p> * <b>This interface may change incompatibly in future versions.</b> */ public interface PDFWriter { /** * Sets the configuration information to be used by this writer to * create a PDF file. * * @param config configuration details that describe the destination, * page size, and basic metadata * @throws IOException if an I/O error occurs while initializing the PDF * file */ void setConfiguration(Configuration config) throws IOException; /** * Adds a new page that consists of a single image. * * @param pageImage an image to be drawn on the page * @param xInPoints the x-offset at which to draw the image * @param yInPoints the y-offset at which to draw the image * @param widthInPoints the width of the image * @param heightInPoints the height of the image * @throws IOException if an I/O error occurs while adding the page */ void addPage(BufferedImage pageImage, double xInPoints, double yInPoints, double widthInPoints, double heightInPoints) throws IOException; /** * Closes the PDF file once all pages have been added. * * @throws IOException if an I/O error occurs while finishing the PDF * file */ void close() throws IOException; } private static float defQuality = 0.8f; /** * Returns the default output quality level for new {@link Configuration}s. * * @return the default quality setting */ public static synchronized float getDefaultOutputQuality() { return defQuality; } /** * Sets the default output quality level. This is a value between 0 and 1 * inclusive, where higher values suggest higher quality output, generally * at the cost of larger file size. This is the default quality level for * new {@link Configuration}s. * * @param quality the new quality setting * @throws IllegalArgumentException if the quality is not in the range 0 to * 1. * @see Configuration#setQuality */ public static synchronized void setDefaultOutputQuality(float quality) { if (quality < 0f || quality > 1f) { throw new IllegalArgumentException("quality: " + quality); } defQuality = quality; } /** * This class is a simple container for the configuration information that * is passed to a {@link PDFWriter}. * * <p> * <b>This class may change incompatibly in future versions.</b> */ public static final class Configuration { private File destination; private double pageWidthInPoints = 8.5d * 72d; private double pageHeightInPoints = 11d * 72d; private String title; private String author; private String subject; private float quality = getDefaultOutputQuality(); /** * Creates a new configuration instance for writing a PDF file to the * specified destination. * * @param destination the PDF output file * @throws NullPointerException if the file is {@code null} */ public Configuration(File destination) { setOutputFile(destination); } /** * Creates a new configuration that copies its state from a template. * * @param toCopy the configuration to copy */ public Configuration(Configuration toCopy) { destination = toCopy.destination; pageWidthInPoints = toCopy.pageWidthInPoints; pageHeightInPoints = toCopy.pageHeightInPoints; title = toCopy.title; author = toCopy.author; subject = toCopy.subject; } /** * Returns the file that the destination will be written to; may not be * {@code null}. * * @return the destination */ public File getOutputFile() { return destination; } /** * Sets the file that the destination will be written to; may not be * {@code null}. * * @param destination the PDF output file * @throws NullPointerException if the file is {@code null} */ public void setOutputFile(File destination) { if (destination == null) { throw new NullPointerException("destination"); } this.destination = destination; } /** * Sets the width and height of document pages from a * {@link PaperProperties} object representing the target paper size. * * @param pp the paper properties to copy the page width and height from */ public void setPageDimensions(PaperProperties pp) { setPageWidth(pp.getPageWidth()); setPageHeight(pp.getPageHeight()); } /** * Returns the width of document pages, measured in points. * * @return the page width in points */ public double getPageWidth() { return pageWidthInPoints; } /** * Sets the width of document pages, measured in points; must be a * positive value. * * @param pageWidthInPoints the page width */ public void setPageWidth(double pageWidthInPoints) { if (pageWidthInPoints <= 0d) { throw new IllegalArgumentException("pageWidthInPoints: " + pageWidthInPoints); } this.pageWidthInPoints = pageWidthInPoints; } /** * Returns the height of document pages, measured in points. * * @return the page height in points */ public double getPageHeight() { return pageHeightInPoints; } /** * The height of document pages, measured in points; must be a positive * value. * * @param pageHeightInPoints the pageHeightInPoints to set */ public void setPageHeight(double pageHeightInPoints) { if (pageHeightInPoints <= 0d) { throw new IllegalArgumentException("pageHeightInPoints: " + pageHeightInPoints); } this.pageHeightInPoints = pageHeightInPoints; } /** * Returns the value to use as the title of the document in the PDF * metadata; if {@code null} a default, empty value is used. * * @return the document title */ public String getTitle() { return title; } /** * Sets the value to use as the title of the document in the PDF * metadata; if {@code null} a default, empty value is used. * * @param title the document title to set */ public void setTitle(String title) { this.title = title; } /** * Returns the value to use as the document author's name in the PDF * metadata; if {@code null} a default, empty value is used. * * @return the document author */ public String getAuthor() { return author; } /** * Sets the value to use as the document author's name in the PDF * metadata; if {@code null} a default, empty value is used. * * @param author the document author to set */ public void setAuthor(String author) { this.author = author; } /** * Returns the value to use as the subject of the document in the PDF * metadata; if {@code null} a default, empty value is used. * * @return the document subject */ public String getSubject() { return subject; } /** * Sets the value to use as the subject of the document in the PDF * metadata; if {@code null} a default, empty value is used. * * @param subject the document subject to set */ public void setSubject(String subject) { this.subject = subject; } /** * Returns the output quality level. This is a value between 0 and 1 * inclusive, where 1 represents maximum quality and 0 represents * minimum file size. * * @return the quality setting */ public float getQuality() { return quality; } /** * Sets the output quality level. This is a value between 0 and 1 * inclusive, where higher values suggest higher quality output, * generally at the cost of larger file size. Note that PDF writers are * not required to use this value. * * @param quality the new quality setting * @throws IllegalArgumentException if the quality is not in the range 0 * to 1. */ public void setQuality(float quality) { if (quality < 0f || quality > 1f) { throw new IllegalArgumentException("quality: " + quality); } this.quality = quality; } } private static final String DEFAULT_IMPLEMENTATION_CLASS = "ca.cgjennings.apps.arkham.deck.PDFWriterImpl"; private static String IMPLEMENTATION_CLASS = DEFAULT_IMPLEMENTATION_CLASS; /** * Sets the name of the concrete {@link PDFWriter} class to use. * * @param className the fully qualified name of a class with a no-arg * constructor that implements {@link PDFWriter}, or {@code null} to * use the default class */ public static synchronized void setImplementationClassName(String className) { if (className == null) { className = DEFAULT_IMPLEMENTATION_CLASS; } else { // verify that the class exists before switching try { Class.forName(className, false, PDFPrintSupport.class.getClassLoader()); } catch (Throwable t) { throw new IllegalArgumentException("could not find class: " + className); } } if (IMPLEMENTATION_CLASS.equals(className)) { return; } IMPLEMENTATION_CLASS = className; knownOK = false; } /** * Returns the name of the concrete {@link PDFWriter} class to use. * * @return the fully qualified name of a class use to create new * {@link PDFWriter}s */ public static synchronized String getImplementationClassName() { return IMPLEMENTATION_CLASS; } }
C
UTF-8
42,568
3.265625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> typedef struct ARRAY { //structure for entering the table and working with it char*** rows; //variable for storing cells int** cells; //variable for the number of cells in a row int count; //variable for the number of rows in the table } array; typedef struct COMMAND { //structure for entering orders char command[1000][1001]; //array for storing orders int count; //variable for counting the number of orders } command; typedef struct SELECTION { //structure for selecting cells on which to work int row_min; //minimum line int row_max; //maximum line int col_min; //minimum column int col_max; //maximum column } selection; typedef struct TMP_CELLS { //structure for temporary variables char* cells[10]; //cell bool use[10]; //a variable that indicates whether they were used or not } tmp_cells; char* tmp_ctor (char*, int*); //temporary variable memory allocation char* tmp_realloc (char*, int*); //changing allocated memory to a temporary variable void tmp_dtor (char*, int*); //freeing memory of a temporary variable void fdelim_and_row (char*, char*); //dividing a row into cells(if you entered -d) void fdelim_zero (char*, char); //dividing a row into cells(if you not entered -d) void ctor_row (array*); //memory allocation line void ctor_cell (array*, int); //cell memory allocation void ctor_length (array*, int, int, int); //word memory allocation void realloc_length (array*, int, int, int); //change allocated word memory void ctor_cells (array*); //memory allocation for the number of cells in a row void realloc_count_cells (array*); //changing allocated memory for the number of cells in a row void realloc_row (array*, int); //changing the memory allocated to a row void realloc_cell (array*, int, int); //changing allocated memory for cells void realloc_cells (array*, int, int); //change allocated memory for information of the number of cells void row_transfer (array*, char*); //entering a string into cells void free_arr (array*); //freeing memory in a table void free_tmp_cell (tmp_cells*); //freeing memory in temporary locations void table_alignment (array*); //table alignment void change_selection (char*, selection*, array*, tmp_cells*);//cell selection selection max (selection, array); //finds a cell with the maximum numeric value and sets the selection to it selection min (selection, array); //finds a cell with the minimum numeric value and sets the selection to it selection find (selection, array, char*, tmp_cells*); //selects the first cell whose value contains the substring STR void irow (array*, selection); //inserts one blank row above the selected cells void arow (array*, selection); //adds one blank row below the selected cells void drow (array*, selection); //deletes the selected rows void icol (array*, selection); //inserts one empty column to the left of the selected cells void acol (array*, selection); //adds one empty column to the right of the selected cells void dcol (array*, selection); //deletes the selected columns void set (array*, selection, char*); //sets the cell value to the string STR void clear (array*, selection); //the contents of the selected cells will be deleted void swap (array*, selection, char*, tmp_cells*); //replaces the contents of the selected cell void sum (array*, selection, char*, tmp_cells*); //stores the sum of the values of the selected cells void avg (array*, selection, char*, tmp_cells*); //same as sum, but the arithmetic mean is stored void count (array*, selection, char*, tmp_cells*); //same as sum, but the number of non-empty cells is stored void flen (array*, selection, char*, tmp_cells*); //stores the string length of the currently selected cell void fdef (array*, selection, char*, tmp_cells*); //the value of the current cell will be set to a temporary variable void fuse (array*, selection, char*, tmp_cells*);//the current cell will be set to the value from the temporary variable void inc (char*, tmp_cells*, array*); //the numeric value in the temporary variable will be incremented by 1 void sub (char*, tmp_cells*, array*);//subtracts the value of the _Y variable from the value in the temporary variable _X int check_len_row (array); //check of maximum layer of bulky rods bool quotes (char*, char); //check of the handle on the lid and the divider int main(int argc, char* argv[]) { FILE* fp; if ((fp = fopen(argv[argc-1], "r"))==NULL) { fprintf(stderr,"Cannot open file.\n"); exit(1); } char ch; //variable to read a character from a file char* tmp = NULL; //variable where the string will be written int len = 0; //length of the entered string char delim; //the sign that will divide the cells array arr = {NULL, NULL, 0}; //variable with table command commands = {{}, 0}; //variable with commands char* token; //auxiliary variable char s[2] = ";"; //symbol that divides orders int idx; //argument index with orders selection sel = {0, 0, 0, 0}; //custom cell selection variable selection tmp_sel = {0, 0, 0, 0}; //temporary cell selection variable //temporary cells tmp_cells tmp_cell = { {}, {false, false, false, false, false, false, false, false, false, false}}; int remember_i = -1; //variable for loops int max_cell; //a variable that determines to which cell to write out //determine which character will divide the cells at the output if (strcmp(argv[1], "-d") == 0) { if (argc != 5) { fprintf(stderr,"Wrong number of arguments.\n"); fclose(fp); exit(1); } else { delim = argv[2][0]; } } else { if (argc != 3) { fprintf(stderr,"Wrong number of arguments.\n"); fclose(fp); exit(1); } else { delim = ' '; } } tmp = tmp_ctor(tmp, &len); ctor_row(&arr); ctor_cells(&arr); //read the table from the file and enter it into the variable do { ch = (char) getc (fp); if (ch != EOF && ch != '\n') { tmp = tmp_realloc(tmp, &len); tmp[len-1] = ch; } if (ch == '\n' || ch == EOF) { tmp = tmp_realloc(tmp, &len); tmp[len - 1] = '\0'; if (strcmp (argv[1], "-d") == 0) { fdelim_and_row(tmp, argv[2]); } else { fdelim_zero(tmp, delim); } arr.count++; realloc_row(&arr, arr.count); realloc_count_cells(&arr); row_transfer(&arr, tmp); tmp_dtor(tmp, &len); tmp = tmp_ctor(tmp, &len); } } while (ch != EOF); free(tmp); fclose(fp); table_alignment(&arr); //determine where the orders will be if (strcmp (argv[1], "-d") == 0) { idx = 3; } else { idx = 1; } token = strtok(argv[idx], s); //we split orders and put them into an array while (token != NULL) { if (strlen(token) > 1000) { fprintf(stderr, "Too long command.\n"); free_arr(&arr); free(token); exit(1); } strcpy(commands.command[commands.count], token); commands.count++; token = strtok(NULL, s); } free(token); if (commands.count > 1000) { fprintf(stderr, "Too many commands"); free_arr(&arr); } //we follow the orders entered by the user for (int i = 0; i < commands.count; i++) { if (commands.command[i][0] == '[' && commands.command[i][1] != 'm' && commands.command[i][1] != 'f' && commands.command[i][1] != 's' && commands.command[i][2] != ']') { change_selection(commands.command[i], &sel, &arr, &tmp_cell); } if (commands.command[i][0] == '[' && commands.command[i][1] == 'm' && commands.command[i][2] == 'a') { sel = max(sel, arr); } if (commands.command[i][0] == '[' && commands.command[i][1] == 'm' && commands.command[i][2] == 'i') { sel = min(sel, arr); } if (commands.command[i][0] == '[' && commands.command[i][1] == 'f') { sel = find(sel, arr, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'i' && commands.command[i][1] == 'r') { irow(&arr, sel); } if (commands.command[i][0] == 'a' && commands.command[i][1] == 'r') { arow(&arr, sel); } if (commands.command[i][0] == 'd' && commands.command[i][1] == 'r') { drow(&arr, sel); } if (commands.command[i][0] == 'i' && commands.command[i][1] == 'c') { icol(&arr, sel); } if (commands.command[i][0] == 'a' && commands.command[i][1] == 'c') { acol(&arr, sel); } if (commands.command[i][0] == 'd' && commands.command[i][1] == 'c') { dcol(&arr, sel); } if (commands.command[i][0] == 's' && commands.command[i][1] == 'e') { set(&arr, sel, commands.command[i]); } if (commands.command[i][0] == 'c' && commands.command[i][1] == 'l') { clear(&arr, sel); } if (commands.command[i][0] == 's' && commands.command[i][1] == 'w') { swap(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 's' && commands.command[i][1] == 'u' && commands.command[i][2] == 'm') { sum(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'a' && commands.command[i][1] == 'v') { avg(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'c' && commands.command[i][1] == 'o') { count(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'l' && commands.command[i][1] == 'e') { flen(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'd' && commands.command[i][1] == 'e' && commands.command[i][2] == 'f') { fdef(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == 'u' && commands.command[i][1] == 's' && commands.command[i][2] == 'e') { fuse(&arr, sel, commands.command[i], &tmp_cell); } if (commands.command[i][0] == '[' && commands.command[i][1] == '_' && commands.command[i][2] == ']') { sel = tmp_sel; } if (commands.command[i][0] == '[' && commands.command[i][1] == 's' && commands.command[i][2] == 'e') { tmp_sel = sel; } if (commands.command[i][0] == 'i' && commands.command[i][1] == 'n' && commands.command[i][2] == 'c') { inc(commands.command[i], &tmp_cell, &arr); } if (commands.command[i][0] == 'g' && commands.command[i][1] == 'o' && commands.command[i][5] == '+') { int value = commands.command[i][6] - '0'; i += (value - 1); } if (commands.command[i][0] == 'g' && commands.command[i][1] == 'o' && commands.command[i][5] == '-') { int value = commands.command[i][6] - '0'; if (i != remember_i) { remember_i = i; i -= (value + 1); } } if (commands.command[i][0] == 'i' && commands.command[i][1] == 's' && commands.command[i][2] == 'z') { int x = commands.command[i][8] - '0'; int n = commands.command[i][11] - '0'; if (commands.command[i][10] == '-' && tmp_cell.cells[x] != NULL) { if (tmp_cell.cells[x][0] == '0') { i += (n - 1); } } if (commands.command[i][10] == '-' && tmp_cell.cells[x] != NULL) { if (tmp_cell.cells[x][0] == '0') { remember_i = i; i -= (n + 1); } } } if (commands.command[i][0] == 's' && commands.command[i][1] == 'u' && commands.command[i][2] == 'b') { sub(commands.command[i], &tmp_cell, &arr); } } max_cell = check_len_row(arr); printf("row_min: %d\n", sel.row_min); printf("row_max: %d\n", sel.row_max); printf("col_min: %d\n", sel.col_min); printf("col_max: %d\n", sel.col_max); for (int i = 0; i < arr.count; i ++){ for (int j = 0; j < max_cell; j++) { if (quotes(arr.rows[i][j], delim)) { if (j != max_cell - 1) printf("\"%s\"%c", arr.rows[i][j], delim); else printf("\"%s\"\n", arr.rows[i][j]); } else { if (j != max_cell - 1) printf("%s%c", arr.rows[i][j], delim); else printf("%s\n", arr.rows[i][j]); } } } //write the table to a file if ((fp = fopen(argv[argc-1], "w"))==NULL) { fprintf(stderr,"Cannot open file.\n"); free_arr(&arr); free_tmp_cell(&tmp_cell); exit(1); } for (int i = 0; i < arr.count; i ++){ for (int j = 0; j < max_cell; j++) { if (quotes(arr.rows[i][j], delim)) { if (j != max_cell - 1) fprintf(fp, "\"%s\"%c", arr.rows[i][j], delim); else fprintf(fp, "\"%s\"\n", arr.rows[i][j]); } else { if (j != max_cell - 1) fprintf(fp, "%s%c", arr.rows[i][j], delim); else fprintf(fp, "%s\n", arr.rows[i][j]); } } } fclose(fp); //freeing memory free_arr(&arr); free_tmp_cell(&tmp_cell); return 0; } //temporary variable memory allocation char* tmp_ctor (char* tmp, int* len) { *len = 0; char* tmp1 = malloc (1); tmp = tmp1; if (tmp == NULL) { fprintf(stderr, "malloc err"); free(tmp); exit (1); } return tmp; } //changing allocated memory to a temporary variable char* tmp_realloc (char* tmp, int* len) { (*len)++; char* tmp1 = realloc(tmp, *len+1); tmp = tmp1; if (tmp == NULL) { fprintf(stderr, "realloc err"); exit (1); } return tmp; } //freeing memory of a temporary variable void tmp_dtor (char* tmp, int* len) { memset(tmp, 0, *len); free (tmp); *len = 0; } //all delimeters are changed to \n void fdelim (char* row, char delim) { int i = 0; bool write = true; while (row[i] != '\0') { if (row[i] == '"' && (row[i+1] == delim || row[i+1] == '\0')) { write = true; } if (row[i] == '"' && i == 0) { write = false; } if (row[i] == '"' && i != 0) if (row[i-1] == '\n') write = false; if (row[i] == delim && write == true) { row[i] = '\n'; } i++; } } //remove quotation mark void delet_quotes (char* row, int i) { for (int j = i; j < (int) strlen(row); j++) row[j] = row[j+1]; } //adding a backslash void write_quotes (char* row, int i) { int len = (int) strlen(row) + 1; row = realloc (row, sizeof(char*) * len); row[len - 1] = '\0'; for (int j = len - 1; j > i; j--) { row[j] = row[j - 1]; } row[i] = '\\'; } //dividing a row into cells(if you entered -d) void fdelim_and_row (char* row, char* delim) { int i = 0; bool write = true; while (delim[i] != '\0') { fdelim(row, delim[i]); i++; } i = 0; while (row[i] != '\0') { if (row[i] == '"' && (row[i+1] == '\n' || row[i+1] == '\0') && write == false) { delet_quotes(row, i); write = true; } if (row[i] == '"' && i == 0 && write == true) { delet_quotes(row, i); write = false; } if (row[i] == '"' && i != 0) if (row[i-1] == '\n') { delet_quotes(row, i); write = false; } if (row[i] == '"') { write_quotes(row, i); i += 1; } if (row[i] == '\\') { write_quotes(row, i); i += 1; } i++; } } //dividing a row into cells(if you not entered -d) void fdelim_zero (char* row, char delim) { int i = 0; bool write = true; fdelim(row, delim); while (row[i] != '\0') { if (row[i] == '"' && (row[i+1] == '\n' || row[i+1] == '\0') && write == false) { delet_quotes(row, i); write = true; } if (row[i] == '"' && i == 0 && write == true) { delet_quotes(row, i); write = false; } if (row[i] == '"' && i != 0) if (row[i-1] == '\n') { delet_quotes(row, i); write = false; } if (row[i] == '"') { write_quotes(row, i); i += 1; } if (row[i] == '\\') { write_quotes(row, i); i += 1; } i++; } } //memory allocation line void ctor_row (array* arr) { arr->rows = malloc (sizeof(char***)); if (arr->rows == NULL) { fprintf(stderr, "malloc err"); exit (1); } } //cell memory allocation void ctor_cell (array* arr, int row) { arr->rows[row-1] = malloc (sizeof(char**)); if (arr->rows[row-1] == NULL) { fprintf(stderr, "malloc err"); exit (1); } } //word memory allocation void ctor_length (array* arr, int row, int cell, int length) { char* tmp = malloc (sizeof(char*) * length); arr->rows[row-1][cell-1] = tmp; if (arr->rows[row-1][cell-1] == NULL) { fprintf(stderr, "malloc err"); exit (1); } } //change allocated word memory void realloc_length (array* arr, int row, int cell, int length) { char* tmp = realloc (arr->rows[row-1][cell-1], sizeof(char*) * length); arr->rows[row-1][cell-1] = tmp; if (arr->rows[row-1][cell-1] == NULL) { fprintf(stderr, "realloc err"); exit (1); } arr->rows[row - 1][cell - 1][length] = '\0'; } //memory allocation for the number of cells in a row void ctor_cells (array* arr) { arr->cells = malloc (sizeof(int**)); if (arr->cells == NULL) { fprintf(stderr, "malloc err"); exit (1); } } //changing allocated memory for the number of cells in a row void realloc_count_cells (array* arr) { int** tmp = realloc (arr->cells, sizeof(int**) * (arr->count+1)); arr->cells = tmp; if (arr->cells == NULL) { fprintf(stderr, "realloc err"); exit (1); } } //changing the memory allocated to a row void realloc_row (array* arr, int count_row) { char*** tmp = realloc(arr->rows, sizeof(char***) * count_row); arr->rows = tmp; if (arr->rows == NULL) { fprintf(stderr, "realloc err"); exit (1); } } //changing allocated memory for cells void realloc_cell (array* arr, int row, int count_cell) { char** tmp = realloc (arr->rows[row-1], sizeof(char**) * count_cell); arr->rows[row-1] = tmp; if (arr->rows[row-1] == NULL) { fprintf(stderr, "realloc err"); exit (1); } } //change allocated memory for information of the number of cells void realloc_cells (array* arr, int row, int length) { int *tmp = realloc (arr->cells[row-1], sizeof(int*) * length); arr->cells[row-1] = tmp; if (arr->cells[row-1] == NULL) { fprintf(stderr, "realloc err"); exit (1); } } //entering a string into cells void row_transfer (array* arr, char* tmp) { char* tmp_cell = NULL; int count_cell = 0; char delim = '\n'; ctor_cell(arr, arr->count); tmp_cell = strtok(tmp, &delim); while( tmp_cell != NULL ) { count_cell++; realloc_cell(arr, arr->count, count_cell); ctor_length(arr, arr->count, count_cell, sizeof(tmp_cell) + 1); strcpy(arr->rows[arr->count-1][count_cell-1], tmp_cell); memset(tmp_cell, 0, strlen(tmp_cell)); tmp_cell = strtok(NULL, &delim); } arr->cells[arr->count - 1] = malloc(sizeof(count_cell)); // realloc_cells(arr, arr->count, sizeof(count_cell)); *arr->cells[arr->count - 1] = count_cell; free (tmp_cell); } //freeing memory in a table void free_arr (array* arr) { for (int i = arr->count - 1; i >= 0; i--) { for (int j = *arr->cells[i] - 1; j >= 0; j--) { free(arr->rows[i][j]); } free(arr->cells[i]); free (arr->rows[i]); } free (arr->cells); free(arr->rows); } //freeing memory in temporary locations void free_tmp_cell (tmp_cells* tmp_cell) { for (int i = 0; i < 10; i++) { if (tmp_cell->use[i]) free (tmp_cell->cells[i]); } } //table alignment void table_alignment (array* arr) { int max = 0; for (int i = 0; i < arr->count; i++) { if (max < *arr->cells[i]) max = *arr->cells[i]; } for (int i = 0; i < arr->count; i++) { if (max > *arr->cells[i]) { arr->rows[i] = realloc(arr->rows[i], sizeof(char**) * max + 100); for (int j = *arr->cells[i]; j < max; j++) { arr->rows[i][j] = malloc (sizeof(char*)); arr->rows[i][j][0] = '\0'; } *arr->cells[i] = max; } } } //cell selection void change_selection (char* command, selection* sel, array* arr, tmp_cells* tmp_cell) { sel->row_min = 0; sel->row_max = 0; sel->col_min = 0; sel->col_max = 0; int i = 1; int choose = 1; while (command[i] != ']') { if (command[i] == ',') { choose++; } else { switch (choose) { case 1: if (command[i] == '_') { sel->row_min = 1; sel->row_max = arr->count; } else sel->row_min = sel->row_min * 10 + (command[i] - '0'); break; case 2: if (command[i] == '_') { sel->col_min = 1; sel->col_max = *arr->cells[sel->row_min - 1]; } else { sel->col_min = sel->col_min * 10 + (command[i] - '0'); } break; case 3: if (command[i] == '-') sel->row_max = arr->count; else sel->row_max = sel->row_max * 10 + (command[i] - '0'); break; case 4: if (command[i] == '-') sel->col_max = *arr->cells[0]; else sel->col_max = sel->col_max * 10 + (command[i] - '0'); break; default: break; } } i++; } if (sel->row_max == 0) { sel->row_max = sel->row_min; } if (sel->col_max == 0) { sel->col_max = sel->col_min; } if (sel->col_max > *arr->cells[0]) { for (int j = *arr->cells[0]; j < sel->col_max; j++) { selection tmp = {arr->count, arr->count, *arr->cells[0], *arr->cells[0]}; acol(arr, tmp); } } if (sel->row_max > arr->count) { for (int j = arr->count; j < sel->row_max; j++) { selection tmp = {arr->count, arr->count, *arr->cells[0], *arr->cells[0]}; arow(arr, tmp); } } if (sel->col_max < 0 || sel->row_min < 0 || sel->col_min < 0 || sel->row_max < 0) { fprintf(stderr, "Selected cell cannot be negative.\n"); free_arr(arr); free_tmp_cell(tmp_cell); exit(1); } if (sel->col_max < sel->col_min) { fprintf(stderr, "Cell selection error.\n"); free_arr(arr); free_tmp_cell(tmp_cell); exit(1); } if (sel->row_max < sel->row_min) { fprintf(stderr, "Cell selection error.\n"); free_arr(arr); free_tmp_cell(tmp_cell); exit(1); } } //finds a cell with the maximum numeric value and sets the selection to it selection max (selection sel, array arr) { int number = atoi(arr.rows[sel.row_min - 1][sel.col_min - 1]); selection remember = {0, 0, 0, 0}; for (int i = sel.row_min - 1; i < sel.row_max; i++) { for (int j = sel.col_min - 1; j < sel.col_max; j++) { if (number <= atoi(arr.rows[i][j])) { number = atoi(arr.rows[i][j]); remember.row_min = i + 1; remember.row_max = i + 1; remember.col_min = j + 1; remember.col_max = j + 1; } } } return remember; } //finds a cell with the minimum numeric value and sets the selection to it selection min (selection sel, array arr) { int number = atoi(arr.rows[sel.row_min - 1][sel.col_min - 1]); selection remember = {0, 0, 0, 0}; for (int i = sel.row_min - 1; i < sel.row_max; i++) { for (int j = sel.col_min - 1; j < sel.col_max; j++) { if (number >= atoi(arr.rows[i][j])) { number = atoi(arr.rows[i][j]); remember.row_min = i + 1; remember.row_max = i + 1; remember.col_min = j + 1; remember.col_max = j + 1; } } } return remember; } //selects the first cell whose value contains the substring STR selection find (selection sel, array arr, char* commands, tmp_cells* tmp_cell) { int k = 6; selection remember = {0, 0, 0, 0}; for (int i = sel.row_min - 1; i < sel.row_max; i++) { for (int j = sel.col_min - 1; j < sel.col_max; j++) { for (int len = 0; len < (int) strlen(arr.rows[i][j]); len++){ if (commands[k] == ']') { remember.row_min = i + 1; remember.row_max = i + 1; remember.col_min = j + 1; remember.col_max = j + 1; return remember; } if (commands[k] != arr.rows[i][j][len]) { k = 5; } k++; } } } fprintf(stderr, "Cell not found.\n"); free_arr(&arr); free_tmp_cell(tmp_cell); exit(1); } //inserts one blank row above the selected cells void irow (array* arr, selection sel) { arr->count++; realloc_row(arr, arr->count); realloc_count_cells(arr); arr->cells[arr->count - 1] = arr->cells[0]; ctor_cell(arr, arr->count); realloc_cell(arr, arr->count, *arr->cells[0]); for (int i = 0; i < *arr->cells[0]; i++) { ctor_length(arr, arr->count, i + 1, 2); } for (int i = arr->count - 2; i >= (sel.row_min - 1); i--) { for (int j = 0; j < *arr->cells[i]; j++) { realloc_length(arr, i + 2, j + 1, sizeof(arr->rows[i][j])); strcpy(arr->rows[i + 1][j], arr->rows[i][j]); } } for (int i = 0; i < *arr->cells[0]; i++) { realloc_length(arr, sel.row_min, i + 1, 2); arr->rows[sel.row_min - 1][i][0] = '\0'; } realloc_count_cells(arr); arr->cells[arr->count - 1] = malloc(sizeof(*arr->cells[0])); *arr->cells[arr->count - 1] = *arr->cells[0]; } //adds one blank row below the selected cells void arow (array* arr, selection sel) { arr->count++; realloc_row(arr, arr->count); realloc_count_cells(arr); arr->cells[arr->count - 1] = arr->cells[0]; ctor_cell(arr, arr->count); realloc_cell(arr, arr->count, *arr->cells[0]); for (int i = 0; i < *arr->cells[0]; i++) { ctor_length(arr, arr->count, i + 1, 2); } for (int i = arr->count - 2; i >= sel.row_max; i--) { for (int j = 0; j < *arr->cells[i]; j++) { realloc_length(arr, i + 2, j + 1, sizeof(arr->rows[i][j])); strcpy(arr->rows[i + 1][j], arr->rows[i][j]); } } for (int i = 0; i < *arr->cells[0]; i++) { realloc_length(arr, sel.row_max + 1, i + 1, 2); arr->rows[sel.row_max][i][0] = '\0'; } realloc_count_cells(arr); arr->cells[arr->count - 1] = malloc(sizeof(*arr->cells[0])); *arr->cells[arr->count - 1] = *arr->cells[0]; } //deletes the selected rows void drow (array* arr, selection sel) { int max_row = arr->count; for (int k = sel.row_min; k <= sel.row_max; k++) { for (int i = sel.row_min - 1; i < arr->count - 1; i++) { for (int j = 0; j < *arr->cells[i]; j++) { realloc_length(arr, i + 1, j + 1, sizeof(arr->rows[i + 1][j])); strcpy(arr->rows[i][j], arr->rows[i + 1][j]); } } arr->count--; } for (int i = max_row - 1; i > (arr->count - 1); i--) { for (int j = *arr->cells[i] - 1; j >= 0; j--) { free(arr->rows[i][j]); } free(arr->cells[i]); free (arr->rows[i]); } } //inserts one empty column to the left of the selected cells void icol (array* arr, selection sel) { for (int i = 0; i < arr->count; i++) { *arr->cells[i]+= 1; realloc_cell(arr, i + 1, *arr->cells[i]); ctor_length(arr, i + 1, *arr->cells[i], 2); arr->rows[i][*arr->cells[i] - 1][0] = '\0'; } for (int i = 0; i < arr->count; i++) { for (int j = *arr->cells[i] - 1; j >= sel.col_min; j--) { realloc_length(arr, i + 1, j + 1, sizeof(arr->rows[i][j - 1])); strcpy(arr->rows[i][j], arr->rows[i][j - 1]); } } for (int i = 0; i < arr->count; i++) { realloc_length(arr, i + 1, sel.col_min, 2); arr->rows[i][sel.col_min - 1][0] = '\0'; } } //adds one empty column to the right of the selected cells void acol (array* arr, selection sel) { for (int i = 0; i < arr->count; i++) { *arr->cells[i]+= 1; realloc_cell(arr, i + 1, *arr->cells[i]); ctor_length(arr, i + 1, *arr->cells[i], 2); arr->rows[i][*arr->cells[i] - 1][0] = '\0'; } for (int i = 0; i < arr->count; i++) { for (int j = *arr->cells[i] - 1; j > sel.col_max; j--) { realloc_length(arr, i + 1, j + 1, sizeof(arr->rows[i][j - 1])); strcpy(arr->rows[i][j], arr->rows[i][j - 1]); } } for (int i = 0; i < arr->count; i++) { realloc_length(arr, i + 1, sel.col_max + 1, 2); arr->rows[i][sel.col_max][0] = '\0'; } } //deletes the selected columns void dcol (array* arr, selection sel) { for (int k = sel.col_min; k <= sel.col_max; k++) { for (int i = 0; i < arr->count; i++) { for (int j = sel.col_min; j < *arr->cells[i]; j++) { realloc_length(arr, i + 1, j, sizeof(arr->rows[i][j])); strcpy(arr->rows[i][j - 1], arr->rows[i][j]); } *arr->cells[i] -= 1; if (*arr->cells[i] != 0) { free(arr->rows[i][*arr->cells[i]]); realloc_cell(arr, i + 1, *arr->cells[i]); } } } } void set (array* arr, selection sel, char* commands) { char del[2] = " "; commands = strtok(commands, del); commands = strtok(NULL, del); if (commands[0] == '"') { delet_quotes(commands, 0); delet_quotes(commands, (int) strlen(commands) - 1); } for (int j = sel.row_min; j <= sel.row_max; j++) { for (int k = sel.col_min; k <= sel.col_max; k++) { realloc_length(arr, j, k, sizeof(commands)); strcpy(arr->rows[j - 1][k - 1], commands); } } } //the contents of the selected cells will be deleted void clear (array* arr, selection sel) { for (int j = sel.row_min; j <= sel.row_max; j++) { for (int k = sel.col_min; k <= sel.col_max; k++) { realloc_length(arr, j, k, 2); arr->rows[j - 1][k - 1][0] = '\0'; } } } //replaces the contents of the selected cell void swap (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { selection tmp_sel = {0, 0, 0, 0}; char* tmp = NULL; char del[2] = " "; int len = sizeof(arr->rows[sel.row_min - 1][sel.col_min - 1]); commands = strtok(commands, del); commands = strtok(NULL, del); change_selection(commands, &tmp_sel, arr, tmp_cell); for (int j = sel.row_min; j <= sel.row_max; j++) { for (int k = sel.col_min; k <= sel.col_max; k++) { tmp = malloc(sizeof(char*) * len); strcpy(tmp, arr->rows[j - 1][k - 1]); realloc_length(arr, j, k, sizeof(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1])); strcpy(arr->rows[j - 1][k - 1], arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1]); realloc_length(arr, tmp_sel.row_min, tmp_sel.col_min, sizeof(tmp)); strcpy(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1], tmp); } } free (tmp); } //stores the sum of the values of the selected cells void sum (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { selection tmp_sel = {0, 0, 0, 0}; char del[2] = " "; int sum = 0; char* cell_sum = NULL; commands = strtok(commands, del); commands = strtok(NULL, del); change_selection(commands, &tmp_sel, arr, tmp_cell); for (int i = sel.row_min; i <= sel.row_max; i++) { for (int j = sel.col_min; j <= sel.col_max; j++) { sum += atoi (arr->rows[i - 1][j - 1]); } } sprintf(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1], "%g", (double) sum); free (cell_sum); } //same as sum, but the arithmetic mean is stored void avg (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { selection tmp_sel = {0, 0, 0, 0}; char del[2] = " "; float sum = 0; char* cell_sum = NULL; commands = strtok(commands, del); commands = strtok(NULL, del); change_selection(commands, &tmp_sel, arr, tmp_cell); for (int i = sel.row_min; i <= sel.row_max; i++) { for (int j = sel.col_min; j <= sel.col_max; j++) { sum += atoi (arr->rows[i - 1][j - 1]); } } sum /= (sel.row_max - sel.row_min + 1) * (sel.col_max - sel.col_min + 1); sprintf(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1], "%g", (double) sum); free (cell_sum); } //same as sum, but the number of non-empty cells is stored void count (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { selection tmp_sel = {0, 0, 0, 0}; char del[2] = " "; int sum = 0; char* cell_sum = NULL; commands = strtok(commands, del); commands = strtok(NULL, del); change_selection(commands, &tmp_sel, arr, tmp_cell); for (int i = sel.row_min; i <= sel.row_max; i++) { for (int j = sel.col_min; j <= sel.col_max; j++) { if (arr->rows[i-1][j-1][0] != '\0') sum++; } } sprintf(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1], "%g", (double) sum); free (cell_sum); } //stores the string length of the currently selected cell void flen (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { selection tmp_sel = {0, 0, 0, 0}; char del[2] = " "; int len_old = 0; int len_new = 0; commands = strtok(commands, del); commands = strtok(NULL, del); change_selection(commands, &tmp_sel, arr, tmp_cell); len_old = strlen(arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1]); len_new = strlen(arr->rows[sel.row_min - 1][sel.col_min - 1]); realloc_length(arr, tmp_sel.row_min, tmp_sel.col_min, len_new); for (int i = len_old; i < len_new; i++) { arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1][i] = ' '; } arr->rows[tmp_sel.row_min - 1][tmp_sel.col_min - 1][len_new] = '\0'; } //the value of the current cell will be set to a temporary variable void fdef (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { char del[2] = " "; commands = strtok(commands, del); commands = strtok(NULL, del); int value = commands[1] - '0'; if (value >= 0 && 9 >= value) { tmp_cell->use[value] = true; tmp_cell->cells[value] = malloc(sizeof(char*) * strlen(arr->rows[sel.row_min - 1][sel.col_min - 1])); strcpy(tmp_cell->cells[value], arr->rows[sel.row_min - 1][sel.col_min - 1]); } else { fprintf(stderr, "This temporary variable does not exist.\n"); free_arr(arr); free_tmp_cell(tmp_cell); exit(1); } } //the current cell will be set to the value from the temporary variable void fuse (array* arr, selection sel, char* commands, tmp_cells* tmp_cell) { char del[2] = " "; commands = strtok(commands, del); commands = strtok(NULL, del); int value = commands[1] - '0'; if (value >= 0 && 9 >= value) { for (int j = sel.row_min; j <= sel.row_max; j++) { for (int k = sel.col_min; k <= sel.col_max; k++) { arr->rows[j - 1][k - 1] = realloc(arr->rows[j - 1][k - 1], sizeof(char*) * strlen(tmp_cell->cells[value])); strcpy(arr->rows[j - 1][k - 1], tmp_cell->cells[value]); } } } else { fprintf(stderr, "This temporary variable does not exist.\n"); free_arr(arr); free_tmp_cell(tmp_cell); exit(1); } } //the numeric value in the temporary variable will be incremented by 1 void inc (char* command, tmp_cells* tmp_cell, array* arr) { char* cell_value = NULL; int number = command[5] - '0'; int value = atoi (tmp_cell->cells[number]); int len = 0; int coefficient; value++; if (number >= 0 && number <= 9) { cell_value = malloc(sizeof(char*) * len); if (value >= 0) { coefficient = 1; } else { coefficient = -1; } while (value != 0) { int piece = value % 10; cell_value = tmp_realloc(cell_value, &len); cell_value[len - 1] = (piece * coefficient) + '0'; value /= 10; } if (coefficient == -1) { cell_value[len] = '-'; cell_value = tmp_realloc(cell_value, &len); } cell_value[len] = '\0'; for (int i = 0; i < (len / 2); i++) { char number = cell_value[i]; cell_value[i] = cell_value[len - 1 - i]; cell_value[len - 1 - i] = number; } tmp_cell->cells[number] = realloc(tmp_cell->cells[number], sizeof(char*) * strlen(cell_value)); strcpy(tmp_cell->cells[number], cell_value); } else { fprintf(stderr, "This temporary variable does not exist.\n"); free_tmp_cell(tmp_cell); free_arr(arr); free (cell_value); exit(1); } free (cell_value); } //subtracts the value of the _Y variable from the value in the temporary variable _X void sub (char* command, tmp_cells* tmp_cell, array* arr) { int number1 = command[5] - '0'; int value1 = atoi (tmp_cell->cells[number1]); int number2 = command[8] - '0'; int value2 = atoi (tmp_cell->cells[number2]); char* cell_value = NULL; int len = 0; int coefficient; value1 -= value2; if (number1 >= 0 && number1 <= 9 && number2 >= 0 && number2 <= 9) { cell_value = malloc(sizeof(char*) * len); if (value1 >= 0) { coefficient = 1; } else { coefficient = -1; } while (value1 != 0) { int piece = value1 % 10; cell_value = tmp_realloc(cell_value, &len); cell_value[len - 1] = (piece * coefficient) + '0'; value1 /= 10; } if (coefficient == -1) { cell_value[len] = '-'; cell_value = tmp_realloc(cell_value, &len); } cell_value[len] = '\0'; for (int i = 0; i < (len / 2); i++) { char number = cell_value[i]; cell_value[i] = cell_value[len - 1 - i]; cell_value[len - 1 - i] = number; } tmp_cell->cells[number1] = realloc(tmp_cell->cells[number1], sizeof(char*) * strlen(cell_value)); strcpy(tmp_cell->cells[number1], cell_value); } else { fprintf(stderr, "This temporary variable does not exist.\n"); free_tmp_cell(tmp_cell); free_arr(arr); free (cell_value); exit(1); } free (cell_value); } //check of maximum layer of bulky rods int check_len_row (array arr) { int len = 0; for (int i = 0; i < arr.count; i++) { int tmp_len = 0; for (int j = 0; j < *arr.cells[i]; j++) { if (arr.rows[i][j][0] != '\0') { tmp_len = j + 1; } } if (tmp_len > len) { len = tmp_len; } } return len; } //check of the handle on the lid and the divider bool quotes (char* cell, char delim) { int i = 0; while (cell[i] != '\0') { if (cell[i] == delim) return true; if (cell[i] == '"') return true; i++; } return false; }
PHP
UTF-8
702
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Cart extends Model { use HasFactory, SoftDeletes; public $timestamps = true; protected $fillable = [ 'customer_id', 'film_id', 'shopping_id' ]; /** * Get the customer having the cart * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function customer(){ return $this->belongsTo('App\Models\Customer','customer_id','id'); } public function film(){ return $this->belongsTo('App\Models\Film','film_id','id'); } }
C#
UTF-8
1,458
2.84375
3
[ "BSD-3-Clause", "MIT" ]
permissive
using System.ComponentModel; using System.Xml.Serialization; namespace Mercurial.XmlSerializationTypes { /// <summary> /// This class encapsulates a &lt;copy...&gt; node in the log output. /// </summary> [XmlType("copy")] [EditorBrowsable(EditorBrowsableState.Never)] public class LogEntryCopyNode { /// <summary> /// This is the backing field for the <see cref="Destination"/> property. /// </summary> private string _Destination = string.Empty; /// <summary> /// This is the backing field for the <see cref="Source"/> property. /// </summary> private string _Source = string.Empty; /// <summary> /// Gets or sets the source of the copy. /// </summary> [XmlAttribute("source")] public string Source { get { return _Source; } set { _Source = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the destination of the copy. /// </summary> [XmlText] public string Destination { get { return _Destination; } set { _Destination = (value ?? string.Empty).Trim(); } } } }
Markdown
UTF-8
2,245
3.890625
4
[]
no_license
### Introduction This second programming assignment is an R function that is able to cache potentially time-consuming computations. For example, taking the inverse of a numeric matrix is typically a fast operation. However, for a very long matrix, it may take too long to compute the inverse, especially if it has to be computed repeatedly (e.g. in a loop). If the contents of a matrix are not changing, it may make sense to cache the value of the inverse so that when we need it again, it can be looked up in the cache rather than recomputed. In this Programming Assignment you will take advantage of the scoping rules of the R language and how they can be manipulated to preserve state inside of an R object. The `<<-` operator is used to assign a value to an object in an environment that is different from the current environment. Below are two functions that are used to create a special object that stores a numeric Matrix and caches its inverse. The first function, `makeMatrix` creates a special "Matrix", which is really a list containing a function to 1. set the value of the Matrix 2. get the value of the Matrix 3. set the value of the inverse 4. get the value of the inverse <!-- --> makeCacheMatrix <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setinverse <- function(inverse) i <<- inverse getinverse <- function() i list(set = set, get =get, setinverse = setinverse, getinverse = getinverse) } The following function calculates the inverse of the special "Matrix" created with the above function. However, it first checks to see if the inverse has already been calculated. If so, it `get`s the inverse from the cache and skips the computation. Otherwise, it calculates the inverse of the data and sets the value of the inverse in the cache via the `setinverse` function. cacheSolve <- function(x, ...) { i <- x$getinverse() if(!is.null(i)) { message("Getting Cached Data") return(i) } data <- x$get() i <- solve(data, ...) x$setinverse(i) i }
Java
UTF-8
2,763
2.296875
2
[]
no_license
package thebetweenlands.manual.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import thebetweenlands.herblore.aspects.Aspect; import thebetweenlands.herblore.aspects.AspectManager; import thebetweenlands.herblore.aspects.AspectManager.AspectItem; import thebetweenlands.herblore.aspects.AspectManager.AspectItemEntry; import thebetweenlands.herblore.aspects.IAspectType; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; /** * Created by Bart on 10/12/2015. */ public class AspectItemSlideShowWidget extends ManualWidgetsBase { public IAspectType aspectType; public ArrayList<ItemStack> items = new ArrayList<>(); public int currentItems = 0; public AspectItemSlideShowWidget(int xStart, int yStart, IAspectType aspectType) { super(xStart, yStart); this.aspectType = aspectType; } public AspectItemSlideShowWidget(int xStart, int yStart, ArrayList<ItemStack> items) { super(xStart, yStart); this.items = items; } @Override public void drawForeGround() { super.drawForeGround(); List<ItemStack> subItems = items.subList(currentItems, currentItems + (items.size() - currentItems > 5 ? 6 : items.size() - currentItems)); int width = 0; for (ItemStack itemStack : subItems) { renderItem(xStart + width, yStart, itemStack, false, true, manual.manualType); width += 18; } } @Override public void resize() { super.resize(); if (aspectType != null) getItems(); } @Override @SideOnly(Side.CLIENT) public void updateScreen() { super.updateScreen(); if (manual.untilUpdate % 60 == 0) { if (currentItems + 1 < items.size() && items.size() - currentItems > 6) { currentItems++; } else currentItems = 0; drawForeGround(); } } public void mouseClicked(int x, int y, int mouseButton) { super.mouseClicked(x, y, mouseButton); if (mouseButton == 2 && x >= xStart && x <= xStart + 96 && y >= yStart && y <= yStart + 16) { if (currentItems + 1 < items.size() && items.size() - currentItems > 6) { currentItems++; } else currentItems = 0; drawForeGround(); } } public void getItems() { items.clear(); AspectManager manager = AspectManager.get(Minecraft.getMinecraft().theWorld); for(Entry<AspectItem, List<AspectItemEntry>> entry : AspectManager.getRegisteredItems().entrySet()) { List<Aspect> discoveredAspects = manager.getDiscoveredAspects(entry.getKey(), AspectManager.getMergedDiscoveryContainer(Minecraft.getMinecraft().thePlayer)); for(Aspect aspect : discoveredAspects) { if(aspect.type.equals(this.aspectType)) items.add(new ItemStack(entry.getKey().item, 1, entry.getKey().damage)); } } } }
C++
WINDOWS-1252
7,078
2.875
3
[]
no_license
// sherlock-game.cpp : Defines the entry point for the console application. // This is the console executable, that make use of the class fSherlock. // It is responsible for all user interaction: for game logic, please see the fSherlock class. #include "stdafx.h" // to comply with Unreal coding standards using FText = std::string; using int32 = int; void PrintArt(); int32 SetDifficulty(); void PrintIntro(); FText GetValidGuess(); void PlayGame(); bool AskToPlayAgain(); void PrintSummary(); // global variables fSherlock SherlockGame; FText Guess; int32 Level_Chosen; int32 main() { bool bPlayAgain = false; do { PrintArt(); SetDifficulty(); SherlockGame.GenerateSecretCode(); PrintIntro(); PlayGame(); bPlayAgain = AskToPlayAgain(); } while (bPlayAgain); return 0; } void PrintArt() { std::cout << "___________________________\n"; std::cout << "_______________________\n"; std::cout << "______________________\n"; std::cout << "____________________\n"; std::cout << "__________________\n"; std::cout << "_________________\n"; std::cout << "________________\n"; std::cout << "_______________\n"; std::cout << "_______________\n"; std::cout << "______________\n"; std::cout << "_____________\n"; std::cout << "___________\n"; std::cout << "__________\n"; std::cout << "________\n"; std::cout << "________________\n"; std::cout << "_______________\n"; std::cout << "______________\n"; std::cout << "_____________\n"; std::cout << "_______________\n"; std::cout << "____________\n"; std::cout << "________________\n"; std::cout << "_______________\n"; std::cout << "____________\n"; std::cout << "_____________\n"; std::cout << "______________\n"; std::cout << "_____________\n"; std::cout << "_______________\n"; std::cout << "________________\n"; std::cout << "__________________\n"; std::cout << "_________________\n"; std::cout << "_________________\n"; std::cout << "____________________\n"; std::cout << "_________________________\n"; std::cout << "________________________\n"; std::cout << "______________________\n"; std::cout << "_____________________\n"; std::cout << "____________________\n"; std::cout << "____________________\n"; std::cout << "___________________\n\n"; std::cout << "\tWelcome Sherlock.\n\n\tDo you think you can break my code?\n\n"; return; } int32 SetDifficulty() { std::cout << "Fist, select a level of difficulty."; do { std::cout << "\nPlease enter 1, 2 or 3: "; std::cin >> Level_Chosen; // clear cin buffer std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } while (Level_Chosen != 1 && Level_Chosen != 2 && Level_Chosen != 3); SherlockGame.SetCodeLength(Level_Chosen); return Level_Chosen; } void PrintIntro() { FText Code = SherlockGame.GetSecret_Code(); std::cout << "\n\nYou chose the difficulty level "<< Level_Chosen << ". Here are the rules:\n\n"; std::cout << "- The code is a " << Code.length() << " letter isogram.\n\n"; std::cout << "- You have " << SherlockGame.GetMax_Tries() << " tries: once you used them all, you lose.\n\n"; std::cout << "- Hints: if you receive an X, one letter of your guess is right and and at the right place. If you receive an |, one letter of your guess is right, but at the wrong place."; return; } void PlayGame() { SherlockGame.Reset(); int32 My_Max_Tries = SherlockGame.GetMax_Tries(); while (!SherlockGame.IsGameWon() && SherlockGame.GetCurrent_Try() <= My_Max_Tries) { std::cout << "\n\nTry " << SherlockGame.GetCurrent_Try() << ".\n"; GetValidGuess(); SherlockGame.SubmitValidGuess(Guess); if (!SherlockGame.IsGameWon() && SherlockGame.GetCurrent_Try() <= My_Max_Tries) { std::cout << "\nYou have " << (My_Max_Tries +1) - SherlockGame.GetCurrent_Try() << " tries left."; } } PrintSummary(); return; } FText GetValidGuess() { eGuessStatus GuessValidity = eGuessStatus::Invalid_Status; FText Code = SherlockGame.GetSecret_Code(); do { // get guess from user std::cout << "Please enter your guess: "; std::getline (std::cin,Guess); // check guess validity and gives user some feedback GuessValidity = SherlockGame.CheckGuessValidity(Guess); switch (GuessValidity) { case eGuessStatus::Contains_Digit: std::cout << "\nPlease enter a word containing letters only. "; break; case eGuessStatus::Not_Isogram: std::cout << "\nPlease enter a word without repeating letters. "; break; case eGuessStatus::Wrong_Length: std::cout << "\nPlease enter a word of " << Code.length() << " letters. "; break; default: return Guess; break; } } while (GuessValidity != eGuessStatus::OK); return Guess; } void PrintSummary() { if (SherlockGame.IsGameWon()) { std::cout << "\n\nYou're a smart cookie, you cracked the code!"; } else { std::cout << "\n\nToo bad! Better luck next time."; } } bool AskToPlayAgain() { std::cout << "\n\nDo you want to play again? [Y/N]\n"; FText User_Response; std::getline(std::cin, User_Response); return (User_Response[0] =='Y' || User_Response[0] == 'y'); }
C
UTF-8
1,600
4.125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct node { int value; struct node *next,*prev; }; struct node *head,*tail; //en-queue th value void enqueue(int value) { struct node *newnode; newnode=(struct node *)malloc(sizeof(struct node)); newnode->value=value; newnode->next=NULL; newnode->prev=NULL; if(!head) { head=tail=newnode; return; } else { tail->next=newnode; newnode->prev=tail; tail=newnode; return; } } //de-queue the value void dequeue() { if(!head) { printf("Empty!!!"); } else { head=head->next; printf("%d is deleted",head->prev->value); free(head->prev); head->prev=NULL; return; } } void display() { struct node *tmp; tmp=head; while(tmp!=NULL) { printf("%d-->",tmp->value); tmp=tmp->next; } } void search(int v) { struct node * tmp; tmp=head; while(tmp!=NULL) { if(tmp->value==v) { printf("The value %d is found\n",v); return; } tmp=tmp->next; } printf("The value %d is not found\n",v); } void main() { int ch, m; do { printf("Enter the choice: 1.insert 2.Search 3:Delete 4:Display 5:exit\n"); scanf ("%d", &ch); switch (ch) { case 1: { printf ("Enter the element to Insert: "); scanf ("%d", &m); enqueue(m); } break; case 2: { printf ("Enter the element to be searched: "); scanf ("%d", &m); search (m); } break; case 3: { dequeue(); } break; case 4: { printf ("Elements are:\n"); display (); } break; } } while (ch < 5); }
Python
UTF-8
11,228
2.703125
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 29 17:34:01 2018 @author: mauro """ from silx.gui import qt from sloth.gui.models.datanode import DataNode class DataModel(qt.QAbstractItemModel): sortRole = qt.Qt.UserRole filterRole = qt.Qt.UserRole + 1 """INPUTS: Node, QObject""" def __init__(self, root, parent=None): super(DataModel, self).__init__(parent=parent) self._header = ['Name', 'TypeInfo', 'AnotherHeader'] self._rootNode = root """INPUTS: QModelIndex""" """OUTPUT: int""" def rowCount(self, parent): if not parent.isValid(): parentNode = self._rootNode else: parentNode = parent.internalPointer() return parentNode.childCount() """INPUTS: QModelIndex""" """OUTPUT: int""" def columnCount(self, parent): return len(self._header) """INPUTS: QModelIndex, int""" """OUTPUT: QVariant, strings are cast to QString which is a QVariant""" def data(self, index, role): if not index.isValid(): return None node = index.internalPointer() typeInfo = node.typeInfo() if role == qt.Qt.DisplayRole or role == qt.Qt.EditRole: if index.column() == 0: return node.name() if index.column() == 1: return typeInfo if role == qt.Qt.DecorationRole: if index.column() == 0: typeInfo = node.typeInfo() if role == DataModel.sortRole: return node.typeInfo() if role == DataModel.filterRole: return node.typeInfo() """INPUTS: QModelIndex, QVariant, int (flag)""" def setData(self, index, value, role=qt.Qt.EditRole): if index.isValid(): node = index.internalPointer() if role == qt.Qt.EditRole: if index.column() == 0: node.setName(value) self.dataChanged.emit(index, index) return True return False """INPUTS: int, Qt::Orientation, int""" """OUTPUT: QVariant, strings are cast to QString which is a QVariant""" def headerData(self, section, orientation, role): if role == qt.Qt.DisplayRole: if orientation == qt.Qt.Horizontal: return self._header[section] if orientation == qt.Qt.Vertical: return section + 1 """INPUTS: QModelIndex""" """OUTPUT: int (flag)""" def flags(self, index): if not index.isValid(): return activeFlags = (qt.Qt.ItemIsEnabled | qt.Qt.ItemIsSelectable | qt.Qt.ItemIsEditable | qt.Qt.ItemIsUserCheckable) return activeFlags """INPUTS: QModelIndex""" """OUTPUT: QModelIndex""" """Should return the parent of the node with the given QModelIndex""" def parent(self, index): node = self.getNode(index) parentNode = node.parent() if parentNode == self._rootNode: return qt.QModelIndex() return self.createIndex(parentNode.row(), 0, parentNode) """INPUTS: int, int, QModelIndex""" """OUTPUT: QModelIndex""" """Should return a QModelIndex that corresponds to the given row, column and parent node""" def index(self, row, column, parent): parentNode = self.getNode(parent) childItem = parentNode.child(row) if childItem: return self.createIndex(row, column, childItem) else: return qt.QModelIndex() """CUSTOM""" """INPUTS: QModelIndex""" def getNode(self, index): if index.isValid(): node = index.internalPointer() if node: return node return self._rootNode """INPUTS: int, int, QModelIndex""" def insertRows(self, position, rows, parent=qt.QModelIndex()): parentNode = self.getNode(parent) self.beginInsertRows(parent, position, position + rows - 1) for row in range(rows): childCount = parentNode.childCount() childNode = DataNode("untitled" + str(childCount)) success = parentNode.insertChild(position, childNode) self.endInsertRows() return success """INPUTS: int, int, QModelIndex""" def removeRows(self, position, rows, parent=qt.QModelIndex()): parentNode = self.getNode(parent) self.beginRemoveRows(parent, position, position + rows - 1) for row in range(rows): success = parentNode.removeChild(position) self.endRemoveRows() return success SUBJECT, SENDER, DATE = range(3) # Work around the fact that QSortFilterProxyModel always filters datetime # values in QtCore.Qt.ISODate format, but the tree views display using # QtCore.Qt.DefaultLocaleShortDate format. class SortFilterProxyModel(qt.QSortFilterProxyModel): def filterAcceptsRow(self, sourceRow, sourceParent): # Do we filter for the date column? if self.filterKeyColumn() == DATE: # Fetch datetime value. index = self.sourceModel().index(sourceRow, DATE, sourceParent) data = self.sourceModel().data(index) # Return, if regExp match in displayed format. return (self.filterRegExp().indexIn(data.toString( qt.Qt.DefaultLocaleShortDate)) >= 0) # Not our business. return super(SortFilterProxyModel, self).filterAcceptsRow(sourceRow, sourceParent) class TestWindow(qt.QWidget): def __init__(self): super(TestWindow, self).__init__() self.proxyModel = SortFilterProxyModel() self.proxyModel.setDynamicSortFilter(True) self.sourceGroupBox = qt.QGroupBox("Original Model") self.proxyGroupBox = qt.QGroupBox("Sorted/Filtered Model") self.sourceView = qt.QTreeView() self.sourceView.setRootIsDecorated(False) self.sourceView.setAlternatingRowColors(True) self.proxyView = qt.QTreeView() self.proxyView.setRootIsDecorated(False) self.proxyView.setAlternatingRowColors(True) self.proxyView.setModel(self.proxyModel) self.proxyView.setSortingEnabled(True) self.sortCaseSensitivityCheckBox = qt.QCheckBox("Case sensitive\ sorting") self.filterCaseSensitivityCheckBox = qt.QCheckBox("Case sensitive\ filter") self.filterPatternLineEdit = qt.QLineEdit() self.filterPatternLabel = qt.QLabel("&Filter pattern:") self.filterPatternLabel.setBuddy(self.filterPatternLineEdit) self.filterSyntaxComboBox = qt.QComboBox() self.filterSyntaxComboBox.addItem("Regular expression", qt.QRegExp.RegExp) self.filterSyntaxComboBox.addItem("Wildcard", qt.QRegExp.Wildcard) self.filterSyntaxComboBox.addItem("Fixed string", qt.QRegExp.FixedString) self.filterSyntaxLabel = qt.QLabel("Filter &syntax:") self.filterSyntaxLabel.setBuddy(self.filterSyntaxComboBox) self.filterColumnComboBox = qt.QComboBox() self.filterColumnComboBox.addItem("Name") self.filterColumnComboBox.addItem("TypeInfo") self.filterColumnComboBox.addItem("Another") self.filterColumnLabel = qt.QLabel("Filter &column:") self.filterColumnLabel.setBuddy(self.filterColumnComboBox) self.filterPatternLineEdit.textChanged.connect( self.filterRegExpChanged) self.filterSyntaxComboBox.currentIndexChanged.connect( self.filterRegExpChanged) self.filterColumnComboBox.currentIndexChanged.connect( self.filterColumnChanged) self.filterCaseSensitivityCheckBox.toggled.connect( self.filterRegExpChanged) self.sortCaseSensitivityCheckBox.toggled.connect(self.sortChanged) sourceLayout = qt.QHBoxLayout() sourceLayout.addWidget(self.sourceView) self.sourceGroupBox.setLayout(sourceLayout) proxyLayout = qt.QGridLayout() proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3) proxyLayout.addWidget(self.filterPatternLabel, 1, 0) proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1, 1, 2) proxyLayout.addWidget(self.filterSyntaxLabel, 2, 0) proxyLayout.addWidget(self.filterSyntaxComboBox, 2, 1, 1, 2) proxyLayout.addWidget(self.filterColumnLabel, 3, 0) proxyLayout.addWidget(self.filterColumnComboBox, 3, 1, 1, 2) proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 4, 0, 1, 2) proxyLayout.addWidget(self.sortCaseSensitivityCheckBox, 4, 2) self.proxyGroupBox.setLayout(proxyLayout) mainLayout = qt.QVBoxLayout() mainLayout.addWidget(self.sourceGroupBox) mainLayout.addWidget(self.proxyGroupBox) self.setLayout(mainLayout) self.setWindowTitle("Test DataModel with Sort/Filter") self.resize(500, 450) self.proxyView.sortByColumn(SENDER, qt.Qt.AscendingOrder) self.filterColumnComboBox.setCurrentIndex(SENDER) self.filterPatternLineEdit.setText("") self.filterCaseSensitivityCheckBox.setChecked(True) self.sortCaseSensitivityCheckBox.setChecked(True) def setSourceModel(self, model): self.proxyModel.setSourceModel(model) self.sourceView.setModel(model) def filterRegExpChanged(self): syntax_nr = self.filterSyntaxComboBox.itemData( self.filterSyntaxComboBox.currentIndex()) syntax = qt.QRegExp.PatternSyntax(syntax_nr) if self.filterCaseSensitivityCheckBox.isChecked(): caseSensitivity = qt.Qt.CaseSensitive else: caseSensitivity = qt.Qt.CaseInsensitive regExp = qt.QRegExp(self.filterPatternLineEdit.text(), caseSensitivity, syntax) self.proxyModel.setFilterRegExp(regExp) def filterColumnChanged(self): self.proxyModel.setFilterKeyColumn( self.filterColumnComboBox.currentIndex()) def sortChanged(self): if self.sortCaseSensitivityCheckBox.isChecked(): caseSensitivity = qt.Qt.CaseSensitive else: caseSensitivity = qt.Qt.CaseInsensitive self.proxyModel.setSortCaseSensitivity(caseSensitivity) def addData(model, name): model.insertRow(0) model.setData(model.index(0, 0, qt.QModelIndex()), name) if __name__ == '__main__': from silx import sx sx.enable_gui() import sys app = qt.QApplication(sys.argv) app.setStyle("plastique") rootNode = DataNode("data1") childNode0 = DataNode("subdata1", rootNode) childNode1 = DataNode("subdata2", rootNode) childNode2 = DataNode("subsubdata1", childNode1) childNode3 = DataNode("subsubdata2", childNode1) model = DataModel(rootNode) addData(model, 'testAddData1') addData(model, 'testAddData2') window = TestWindow() window.setSourceModel(model) window.show() sys.exit(app.exec_())
Java
UTF-8
4,922
2.03125
2
[ "CC0-1.0" ]
permissive
package com.intro.client.render.drawables; import com.google.common.collect.Ordering; import com.intro.client.OsmiumClient; import com.intro.client.render.RenderManager; import com.intro.client.render.color.Colors; import com.intro.client.util.ElementPosition; import com.intro.common.config.Options; import com.intro.common.config.options.Option; import com.intro.common.config.options.StatusEffectDisplayMode; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.MobEffectTextureManager; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.effect.MobEffectInstance; import java.util.List; public class StatusEffectDisplay extends Scalable { public StatusEffectDisplay() { OsmiumClient.options.getElementPositionOption(Options.StatusEffectDisplayPosition).get().loadToScalable(this); this.maxEffectsDisplayed = OsmiumClient.options.getDoubleOption(Options.MaxStatusEffectsDisplayed).get().byteValue(); } private final Minecraft mc = Minecraft.getInstance(); private static StatusEffectDisplay instance; public int maxEffectsDisplayed; @Override public void render(PoseStack stack) { if(mc.player != null && (OsmiumClient.options.getEnumOption(Options.StatusEffectDisplayMode).get() == StatusEffectDisplayMode.CUSTOM || OsmiumClient.options.getEnumOption(Options.StatusEffectDisplayMode).get() == StatusEffectDisplayMode.BOTH)) { this.visible = true; MobEffectTextureManager spriteManager = mc.getMobEffectTextures(); stack.pushPose(); { int offY = 0; List<MobEffectInstance> effects = mc.player.getActiveEffects().stream().toList(); effects = Ordering.natural().reverse().sortedCopy(effects); this.width = 32; this.height = (effects.size() * 56) + (40); this.maxEffectsDisplayed = (int) OsmiumClient.options.getDoubleOption(Options.MaxStatusEffectsDisplayed).get().byteValue(); if(effects.size() != 0) { for(int i = 0; i < effects.size() && i < maxEffectsDisplayed; i++) { MobEffectInstance effect = effects.get(i); TextureAtlasSprite sprite = spriteManager.get(effect.getEffect()); int duration = effect.getDuration() / 20; int mins = duration / 60; int seconds = duration % 60; String formattedSeconds; if(seconds < 10) { formattedSeconds = "0" + seconds; } else { formattedSeconds = String.valueOf(seconds); } String formattedTime; if (effect.isNoCounter()) { formattedTime = "∞"; } else { formattedTime = mins + ":" + formattedSeconds; } String messageText = new TranslatableComponent(effect.getEffect().getDescriptionId()).getString() + (" " + (effect.getAmplifier() + 1) + ", " + formattedTime); stack.pushPose(); { RenderSystem.setShaderTexture(0, sprite.atlas().getId()); blit(stack, this.posX, this.posY + offY,this.getBlitOffset(), 32,32, sprite); drawCenteredString(stack, mc.font, messageText, this.posX + width / 2, this.posY + offY + 40, Colors.WHITE.getColor().getInt()); } stack.popPose(); offY += 56; } } } stack.popPose(); } else { this.visible = false; } } @Override public void destroySelf() { RenderManager.drawables.remove(this); } @Override public void onPositionChange(int newX, int newY, int oldX, int oldY) { OsmiumClient.options.put(Options.StatusEffectDisplayPosition, new Option<>(Options.StatusEffectDisplayPosition, new ElementPosition(newX, newY, this.scale))); } public static StatusEffectDisplay getInstance() { if(instance == null) { instance = new StatusEffectDisplay(); return instance; } return instance; } @Override public void onScaleChange(double oldScale, double newScale) { OsmiumClient.options.put(Options.StatusEffectDisplayPosition, new Option<>(Options.StatusEffectDisplayPosition, new ElementPosition(this.posX, this.posY, newScale))); } }
Markdown
UTF-8
631
3.734375
4
[]
no_license
**coordinate matrix** # Chapter 7 ||v|| = sqrt(v1^2 + v2^2 ..) //length of a vector Every vector in a standard basis for R^n has a unit vector that has length 1 {i,j} = {(1,0),(0,1)} vectors `u` and `v` are parallel if `u = cv` - if c > 0 then same direction if c < 0 then opposite if v is a nonzero vector in R^n then the vector: u = V / ||V|| has a length of 1 and has the same direction as v. `u` is called a unit vector in the direction of `v` distance(u,v) = ||u - v|| **dot product** is a scalar quantity u • v = u1v1 + u2v2 cos(theta) = u • v / (||u|| * ||v||) **euclidean n-space**
Python
UTF-8
280
3.84375
4
[]
no_license
def cube_c(x): return 12 * x def cube_a(x): return 6 * x ** 2 def cube_v(x): return x ** 3 x = int(input('enter the distance of the edge:')) print(f" the edge {x}, circumference of the cube {cube_c(x)}, area of the cube {cube_a(x)}, volume of the cube {cube_v(x)} ")
Java
UTF-8
3,110
2.234375
2
[ "MIT" ]
permissive
package com.resms.ssm.meta.mybatis.domain; import com.resms.ssm.common.AbstractDomain; import java.io.Serializable; import javax.annotation.Generated; /** * * table t_role * * @date 2020-02-19 01:28:25 */ public class Role extends AbstractDomain implements Serializable { @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.id") private Long id; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.role_name") private String roleName; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source Table: t_role") private static final long serialVersionUID = 1L; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source Table: t_role") public Role(Long id, String roleName) { this.id = id; this.roleName = roleName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source Table: t_role") public Role() { super(); } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.id") public Long getId() { return id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.id") public void setId(Long id) { this.id = id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.role_name") public String getRoleName() { return roleName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source field: t_role.role_name") public void setRoleName(String roleName) { this.roleName = roleName == null ? null : roleName.trim(); } @Override @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source Table: t_role") public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Role other = (Role) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getRoleName() == null ? other.getRoleName() == null : this.getRoleName().equals(other.getRoleName())); } @Override @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-02-19 01:28:25", comments="Source Table: t_role") public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getRoleName() == null) ? 0 : getRoleName().hashCode()); return result; } }
C
UTF-8
3,812
3.265625
3
[]
no_license
/* * ---------------- www.spacesimulator.net -------------- * ---- Space simulators and 3d engine tutorials ---- * * Author: Damiano Vitulli * * This program is released under the BSD licence * By using this program you agree to licence terms on spacesimulator.net copyright page * * * Tutorial 4: 3d engine - 3ds models loader * * Include File: texture.cpp * */ #include <stdio.h> #include <windows.h> #include <GL/glut.h> #include "texture.h" /********************************************************** * * VARIABLES DECLARATION * *********************************************************/ int num_texture=-1; //Counter to keep track of the last loaded texture /********************************************************** * * FUNCTION LoadBitmap(char *) * * This function loads a bitmap file and return the OpenGL reference ID to use that texture * *********************************************************/ int LoadBitm(char *filename) { int i, j=0; //Index variables FILE *l_file; //File pointer unsigned char *l_texture; //The pointer to the memory zone in which we will load the texture // windows.h gives us these types to work with the Bitmap files BITMAPFILEHEADER fileheader; BITMAPINFOHEADER infoheader; RGBTRIPLE rgb; num_texture++; // The counter of the current texture is increased if( (l_file = fopen(filename, "rb"))==NULL) return (-1); // Open the file for reading fread(&fileheader, sizeof(fileheader), 1, l_file); // Read the fileheader fseek(l_file, sizeof(fileheader), SEEK_SET); // Jump the fileheader fread(&infoheader, sizeof(infoheader), 1, l_file); // and read the infoheader // Now we need to allocate the memory for our image (width * height * color deep) l_texture = (byte *) malloc(infoheader.biWidth * infoheader.biHeight * 4); // And fill it with zeros memset(l_texture, 0, infoheader.biWidth * infoheader.biHeight * 4); // At this point we can read every pixel of the image for (i=0; i < infoheader.biWidth*infoheader.biHeight; i++) { // We load an RGB value from the file fread(&rgb, sizeof(rgb), 1, l_file); // And store it l_texture[j+0] = rgb.rgbtRed; // Red component l_texture[j+1] = rgb.rgbtGreen; // Green component l_texture[j+2] = rgb.rgbtBlue; // Blue component l_texture[j+3] = 255; // Alpha value j += 4; // Go to the next position } fclose(l_file); // Closes the file stream glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter // The next commands sets the texture parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // If the u,v coordinates overflow the range 0,1 the image is repeated glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //The minifying function glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // We don't combine the color with the original surface color, use only the texture map. // Finally we define the 2d texture glTexImage2D(GL_TEXTURE_2D, 0, 4, infoheader.biWidth, infoheader.biHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, l_texture); // And create 2d mipmaps for the minifying function gluBuild2DMipmaps(GL_TEXTURE_2D, 4, infoheader.biWidth, infoheader.biHeight, GL_RGBA, GL_UNSIGNED_BYTE, l_texture); free(l_texture); // Free the memory we used to load the texture return (num_texture); // Returns the current texture OpenGL ID }
Java
UTF-8
2,289
2.359375
2
[]
no_license
package com.DAO; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.hibernate.Session; import com.entity.Favorite; import com.entity.FavoriteReport; import com.entity.FavoriteUserReport; import com.entity.User; import com.entity.Video; import com.utils.HibernateUtils; public class FavoriteDAO { private Session hSession; public FavoriteDAO() { hSession = HibernateUtils.getSession(); } public List<Favorite> findID(User id) { String hql = " SELECT E FROM Favorite E WHERE E.user =:id"; Query query = hSession.createQuery(hql); query.setParameter("id", id); List<Favorite> list = query.getResultList(); return list; } public Favorite insert(Favorite entity) { this.hSession.beginTransaction(); Integer id = (Integer) this.hSession.save(entity); this.hSession.getTransaction().commit(); entity.setId(id); return entity; } public void delete(Favorite entity) { try { this.hSession.clear(); this.hSession.beginTransaction(); this.hSession.delete(entity); this.hSession.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); this.hSession.getTransaction().rollback(); throw e; } } public Favorite findById(int id) { Favorite entity = this.hSession.get(Favorite.class, id); return entity; } public List<Favorite> findAll() { String hql = "FROM Favorite"; Query query = hSession.createQuery(hql); List<Favorite> list = query.getResultList(); return list; } public List<FavoriteUserReport> reportFavoriteUsersByVideos(int video_id) { String hql = "select new com.entity.FavoriteUserReport(f.user.id,f.user.fullname," + " f.user.email,f.like_date) from Favorite f where f.video.id = :video_id"; Query query = hSession.createQuery(hql); query.setParameter("video_id", video_id); List<FavoriteUserReport> list = query.getResultList(); return list; } public List<FavoriteReport> reportFavoritesByVideos() { String hql = "select new com.entity.FavoriteReport(f.video.title,count(f),min(f.like_date),max(f.like_date)) " + " from Favorite f group by f.video.title "; Query query = hSession.createQuery(hql); List<FavoriteReport> list = query.getResultList(); return list; } }
Markdown
UTF-8
6,437
3.171875
3
[]
no_license
# 1 网络编程 ## 1.1 概述 - java是Internet上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序 - java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在java的本机安装系统里,由JVM进行控制,并且java实现了跨平台的网络库,程序员面对的是一个统一的网络编程环境。 - 计算机网络:把分布在不同地理区域的计算机与专门的外部设备通信线路互连成一个规模大、功能强的网络系统,从面使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。 - 网络编程的目的:直接或间接地通过网络协议与其它计算机进行通讯。 - 网络编程中的两个主要问题: - 如何准确地定位网络上一台式多台主机 - 通信双方地址 - 一定的规则 | 模型 | 说明 | | -------------------------- | -------------------------------------- | | OSI参考模型 | 过于理想化,未能在因特网上进行广泛推广 | | TCP/IP参数模型(TPC/IP协议) | 事实上的国际标准 | - 网络通信协议对比 | OSI参考模型 | TCP/IP参考模型 | TCP/IP各层对应协议 | | ---------------------- | --------------- | --------------------------- | | 应用层、表示层、会话层 | 应用层 | HTTP、ftp、telnet、DNS、... | | 传输层 | 传输层 | TCP、UDP、... | | 网络层 | 网络层 | IP、ICMP、ARP、... | | 数据链路层、物理层 | 物理+数据链路层 | Link | - 找到主机后如何可靠高效地进行数据传输 ## 1.2 通讯要素 - IP和端口号 - IP地址:InetAddress - 唯一的标识Internet上的计算机 - 本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost - 不易记忆 - 端口号:标识正在计算机上运行的进程(程序) - 不同的进程有不同的端口号 - 被规则为一个16位的整数0~65535。其中,0~1023被预先定义的服务通信占用(如Mysql占用端口3306,http占用端口80等)。除非我们需要访问这些特定服务,否则,就应该使用1024~65535这些端口中的某一个进行通信,以免发生端口冲突 - 端口号与IP地址的组合得出一个网络套接字。 - 网络通信协议 - 计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准 - 分层思想:由于结点之间联系很复杂,在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常用的复合方式是层次方式,即同层间可以通信、上一层可以调用下一层,而与再下一层不发生关系。各层互不影响,利于系统的开发和扩展。 - TCP/IP协议簇 - 传输层协议中有两个非常重要的协议: > TCP:传输控制协议,Transmission Control Protocol > > UDP:用户数据报协议,User Datagram Protocol - TCP/IP以两个主要协议:TCP和IP而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议 - IP(Internet Protocol)协议是网线层的主要协议,支持网络间互连的数据通信 - TCP/IP协议模型从更实用的角度出发,形成了高效的四层体系结构,即:物理链路层、IP层、传输层和应用层 ## 1.3 InetAddress类 > InetAddress位于java.net包下 > > 1. InetAddress用来代表IP地址。一个InetAddress的对象就代表着一个IP地址 > 2. 如何创建InetAddress对象:getByName(String host) > 3. 获取IP地址对应的域名:getHostName() > 4. 获取IP地址:getHostAddress() > 5. 获取本机的IP:getLocalHost() ## 1.4 TCP网络通信 ### 1.4.1 TCP协议 - 使用TCP协议前,须先建立TCP连接,形成传输数据通道 - 传输前,采用"三次握手"的方式,是可靠的 - TCP协议进行通信的两个应用进程:客户端、服务端 - 在连接中可进行大数据量的传输 - 传输完毕,需释放已建立的连接,效率低 ## 1.5 UDP网络通信 ### 1.5.1 UDP协议 - 将数据、源、目的封装成数据包,不需要建立连接 - 每个数据报的大小限制在64k内 - 因无需连接,是不可靠的 - 发送数据结束时无需释放资源,速度快 ## 1.6 URL编程 ## 1.6.1 Socket - 利用Socket开发网络应用程序早已被广泛的采用,以至于成为事实上的标准 - 通信的两端都要有Socket,是两台机器间通信的端点 - 网络通信其实就是Socket间的通信 - Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输 - 一般主动发起通信的应用程序叫客户端,等待通信请求的为服务端 ### 1.6.2 案例 - Socket客户端 > 1. 创建一个Socket的对象,通过构造器指明服务端的IP地址及其接收程序的端口号 > > Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090); > > 2. getOutputStream(),发送数据,方法返回OutputStream的子类对象 > > OutputStream os = socket.getOutputStream(); > > 3. 具体的输出过程 > > os.write("我是客户端".getBytes()); > > 4. 关闭相应的流和socket > > os.close(); > > socket.close(); - Socket服务端 > 1. 创建一个ServerSocket的对象,通过构造器指明自身的端口号 > > ServerSocket ss = new ServerSocket(9090); > > 2. 调用其accept方法,返回一个Socket的对象 > > Socket s = ss.accept(); > > 3. 调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流 > > InputStream is = s.getInputStream(); > > 4. 对获取的流进行操作 > > byte[] b = new byte[20]; > > int len; > > while((len = is.read(b)) != -1){ > > ​ String str = new String(0,0,len); > > ​ System.out.println(str); > > } > > 5. 关闭socket及相应的流 > > ss.close(); > > s.close(); > > is.close();
C++
UTF-8
849
2.84375
3
[]
no_license
#pragma once #include "Image.h" struct itemMap { std::vector<Image*> vecImage; int x; int y; itemMap():x(0),y(0) { data(); } void data(void) { vecImage.reserve(1); Image* img = new Image; vecImage.push_back(img); } void load(sf::String filename) { Image* img = new Image; img->load(filename); img->setScale(10,10); vecImage[0] = img; } void setXY(float newx, float newy) { x = newx; y = newy; vecImage[0]->setPosition(x,y); } void draw(sf::RenderWindow* window) { for(std::vector<Image*>::iterator it = vecImage.begin(); it != vecImage.end(); it++) (*it)->draw(window); } }; class Map { protected: std::vector<itemMap*> vecItemMap; public: void data(void); Map(void); ~Map(void); void Generate_Bottom(); void Generate_Middle(); void Generate_Top(); void drawMap(sf::RenderWindow* window); };
Python
UTF-8
3,303
2.921875
3
[ "MIT" ]
permissive
# -*- coding: utf8 -*- from __future__ import unicode_literals class ModelException(Exception): pass class Service(object): """ Base class of any service, provide some abstraction of common functions """ def __init__(self, connection, tableName): super(Service, self).__init__() self._connection = connection self._tableName = tableName try: self.createTable() except NotImplementedError: raise except: pass def createTable(self): """ Override this function to execute the statement that create your table. """ raise NotImplementedError() def schema(self): """ Note: override this function to return the schema of the table. It should return a list of tuples containing expected document field associated with a values set to whatever you like (still tbd) """ return [] def itm2dict(self, itm): """ Use the schema to build a dict from the item, where keys are fields (column names) and values are cell values. itm should be a list of values in column order. """ data = {} for i, (k, v) in enumerate(self.schema()): data[k] = itm[i] return data def getById(self, _id, fields=None): """ Return a document specific to this id _id is the _id of the document fields is the list of fields to be returned (all by default) """ cur = self._connection.cursor() if fields is None: cur.execute("SELECT * FROM %s WHERE _id=?" % (self._tableName), (_id, )) return self.itm2dict(cur.fetchone()) fields = ', '.join(fields) cur.execute("SELECT %s FROM %s WHERE _id=?" % (fields, self._tableName), (_id,)) return self.itm2dict(cur.fetchone()) def getOverallCount(self): cur = self._connection.cursor() cur.execute("SELECT COUNT(_id) AS count FROM %s" % self._tableName) return cur.fetchone()[0] def deleteAll(self): """ Warning: will delete ALL the documents in this collection """ cur = self._connection.cursor() cur.execute("DELETE FROM %s" % self._tableName) self._connection.commit() def deleteById(self, _id): cur = self._connection.cursor() cur.execute("DELETE FROM %s WHERE _id=?" % (self._tableName), (_id,)) self._connection.commit() def getAll(self): """ Returns all documents available in this collection. """ cur = self._connection.cursor() cur.execute("SELECT * FROM %s" % self._tableName) return map(self.itm2dict, cur.fetchall()) def set(self, _id, field, value): """ If _id is a list, it will be used as a list of ids. All documents matching these ids will be """ cur = self._connection.cursor() cur.execute("UPDATE %s SET %s=? WHERE _id=?" % (self._tableName, field), (value, _id)) self._connection.commit()
Ruby
UTF-8
3,432
2.90625
3
[]
no_license
module News def News.fetch_news(slack_response) case slack_response[0] when 'hacker-news' resp = News.get_json("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty") resp = resp[0..9] message = "Here are the top 10 HN stories: \n" resp.each do |story_id| story_url = "https://hacker-news.firebaseio.com/v0/item/#{story_id}.json?print=pretty" story_response = News.get_json(story_url) message += News.create_headlines(story_response) end when 'stock' resp = HTTParty.get('http://dev.markitondemand.com/Api/v2/Quote', :query => {:symbol => "#{slack_response[1]}"}) resp = resp.parsed_response if resp = resp["StockQuote"] message = "Company: #{resp["Name"]}\n"+ "Ticker: #{resp["Symbol"]}\n"+ "Price: $#{resp["LastPrice"]}\n"+ "Change: #{resp["Change"]}\n"+ "Mkt Cap: #{resp["MarketCap"]}\n"+ "Last Trade: #{resp["Timestamp"]}" else message = "Couldn't find that ticker :(" end #NYT top stories api when 'nyt' unless slack_response[1] slack_response[1] = "home" end if slack_response[1] == "popular" resp = News.get_json("http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?api-key=77c81381526472f019114e6da8e2a40f:14:61565219") resp = resp['results'] message = "Most popular stories from the NYT: \n" resp.each do |story| message += News.create_headlines(story) end else if resp = News.get_json("http://api.nytimes.com/svc/topstories/v1/#{slack_response[1]}.json?api-key=3e34bef4efc68cca88cb6b727c4beb6d:14:61565219") resp = resp['results'] message = "Top stories from the NYT #{slack_response[1]}: \n" resp.each do |story| message += News.create_headlines(story) end else message = "I support to below nyt commands: \n"+ "popular\n"+ "home\n"+ "world\n"+ "national\n"+ "politics\n"+ "nyregion\n"+ "business\n"+ "opinion\n"+ "technology\n"+ "science\n"+ "health\n"+ "sports\n"+ "arts\n"+ "fashion\n"+ "dining\n"+ "travel\n"+ "magazine\n"+ "realestate" end end else message = "I didn't understand that :(\n"+ "I have the below commands:\n"+ "hacker-news - Get top 10 HN articles\n"+ "stock [ticker] - Get latest stock price and change\n"+ "nyt [section] - Get top 10 HN articles\n"+ "-------------the end-------------" end puts message return message end def News.get_json(url) response = HTTParty.get(url) if response.parsed_response.first[0] == "Error" return false else response = JSON.parse(response.body) return response end end def News.create_headlines(hash) message = "*#{hash["title"]}*, #{hash["url"]} \n" end end
Markdown
UTF-8
39,723
4.3125
4
[]
no_license
**What exactly is a block of code?** * Syntactically, a block of code is a set of statements, which could be one statement,or as many as you like, grouped togetherbetween curly braces. * Once you’ve got a block of code, all the statements in that block are treated as a group to be executed together. * For instance, all the statements within the block in a while statement are executed if the condition of the while is true. * The same holds for a block in an if or else if. **= Vs == VS === in JavaScript** * = is used for assigning values to a variable. * == is used for comparing two variables, but it ignores the datatype of variable. * === is used for comparing two variables, but this operator also checks datatype and compares two values. * = is called as assignment operator * == and === are called as comparison operators. * = does not return true or false. * == Return true only if the two operands are equal. * === returns true only if both values and data types are the same for the two variables. **If we’re trying to generate a number between 0 and 4, why does the code have a 5 in it, as in Math.floor(Math.random() * 5)?** * Math.random generates a number between 0 and 1, but not including 1. * The maximum number you can get from Math.random is 0.999.... * When you multiply that number by 5, the highest number you’ll get is 4.999… * Math.floor always rounds a number down, so 1.2 becomes 1, but so does 1.9999. * If we generate a number from 0 to 4.999… then everything will be rounded down to 0 to 4. * This is not the only way to do it, and in other languages it’s often done differently, but this is how you’ll see it done in most JavaScript code * So if I wanted a random number between 0 and 100 (including 100), I’d write Math.floor(Math.random() * 101) **NULL Vs UNDEFINED** * Null and Undefined are both data types in JavaScript. * Undefined is a variable that has been declared but not assigned a value. * Null as an assignment value => So you can assign the value null to any variable which basically means it’s blank. * So by not declaring a value to a variable, JavaScript automatically assigns the value to undefined. ``` let name; //undefined let age = null //null; ``` ``` console.log(typeOf null) //object console.log(typeOf undefined) //undefined ``` * Remember, null is intended to represent an object that isn’t there. * Since these are different data types, if we compare them with strict equality ===, we get false. * But if we compare them with abstract equality ==, we get true. * So JavaScript does consider these to be relatively equal since they both represent an empty value. ``` console.log(null===undefined) //false console.log(null==undefined) //true ``` **parseInt Vs parseFloat** * JavaScript provides two methods for converting non-number primitives into numbers => parseInt() and parseFloat() . * parseInt() converts a value to ana integer. * parseFloat() converts a value into a floating-point number. **Function => arguments and parameters** * When you call a function you pass it arguments and those arguments then get matched up with the parameters in the function definition. * Each argument is passed to its corresponding parameter in the function. * Each parameter acts as a variable within the function. * When you define a function you can define it with one or more parameters. * When you call a function, you call it with arguments. **pass by value** * In Pass by Value, Function is called by directly passing the value of the variable as the argument. * Changing the argument inside the function doesn’t affect the variable passed from outside the function. * if the function changes the value of the parameter, this change is not reflected globally or in the calling function. ``` function callByValue(varOne, varTwo) { console.log("Inside Call by Value Method"); varOne = 100; varTwo = 200; console.log("varOne =" + varOne +"varTwo =" +varTwo); } let varOne = 10; let varTwo = 20; console.log("Before Call by Value Method"); console.log("varOne =" + varOne +"varTwo =" +varTwo); callByValue(varOne, varTwo) console.log("After Call by Value Method"); console.log("varOne =" + varOne +"varTwo =" +varTwo); output will be : --------------- Before Call by Value Method varOne =10 varTwo =20 Inside Call by Value Method varOne =100 varTwo =200 After Call by Value Method varOne =10 varTwo =20 ``` **scope of a variable** * If the variable is declared outside a function, then you can use it anywhere in your code. * If a variable is declared inside a function, then you can use it only within that function => This is known as a variable’s scope. * There are two kinds of scope: global and local. * If a variable is declared outside a function, it’s GLOBAL. * If it’s declared inside a function, it’s LOCAL. * The variables you define outside a function are globally scoped, and the function variables are locally scoped * If you use a variable without declaring it first, that variable will be global. * That means that even if you use a variable for the first time inside a function (because you meant for it to be local), the variable will actually be global, and be available outside the function too (which might cause confusion later). So, don’t forget to declare locals! ``` function playTurn(player, location) { points = 0; if (location == 1) { points = points + 100; } return points; } var total = playTurn("Jai", 1); alert(points); ``` * We forgot to declare points with “var/let/const” before we used it. So points is automatically global. * That means we can use points outside the function! The value doesn’t go away (like it should) when the function is done executing * If you forget to declare a local variable using var/let/const, that variable will be global, which could have unintended consequences in your program **What happens when I name a local variable the same thing as an existing global variable?** * Within the body of a function, a local variable takes precedence over a global variable with the same name. * If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. * For example, the following code prints the word “local”: ``` var scope = "global"; // Declare a global variable function checkscope( ) { var scope = "local"; // Declare a local variable with the same name document.write(scope); // Use the local variable, not the global one } checkscope( ); // Prints "local" ``` https://www.oreilly.com/library/view/javascript-the-definitive/0596101996/ch04.html **Javascript Objects** * They are just a acollection of properties **How to create an object** * Add a variable declaration for the object. * Next, start an object with a left curly brace. * Then all the object’s properties go inside * Each property has a name, a colon and then a value. * Each property is separated by a comma. * We end the object with a closing curly brace, and just like any other variable declaration, we end this one with a semicolon. ``` let chevy = { make: "Chevy", model: "Bel Air", year: 1957, color: "red", passengers: 2, convertible: false, mileage: 1021 }; ``` * Make sure you enclose your object in curly braces * Separate property name and property value with a colon * A property name can be a string, but we usually stick with valid variable names:Notice that if we are using a string with a aspace in it for a property name, we need to use quotes around the name. ``` let widget = { cost: 3.14, "on sale": true }; ``` **WE CAN USE A OBJECT'S PROPERTY JUST LIKE WE USE A VARIABLE, EXCEPT WE NEED TO USE DOT NOTATION TO ACCESS THE PROPERTY IN THE OBJECT** **How does a variable hold an object?** * Variables don’t actually hold objects. * Instead they hold a reference to an object. * The reference is like a pointer or an address to the actual object. * A variable doesn’t hold the object itself, but it holds something like a pointer. * In JavaScript we don’t reathis keyword refers to an object, that object which is executing the current bit of javascript code. In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called. To understand this keyword, only we need to know how, when and from where the function is called, does not matter how and where function is declared or defined.lly know what is inside a reference variable => We do know that whatever it is, it points to our object. * When we use dot notation, the JavaScript interpreter takes care of using the reference to get the object and then accesses its properties for us. * For example: ``` car.color; ``` * This means “use the object referenced by the variable car to access the color property.” **Initializing an object (a reference) variable** * When you declare and initialize an object, you make the object using object notation, but that object won’t fit in the cup. * So what goes in the cup is a reference to the object ``` let myCar = {...}; ``` * A reference to the Car object goes into the variable. * The Car object itself does not go into the variable! **passing objects to functions** * when you call a function and pass it an object, you’re passing the object reference, not the object itself. * So using our pass by value semantics, a copy of the reference is passed into the parameter, and that reference remains a pointer to the original object **this keyword** * this keyword refers to an object, that object which is executing the current bit of javascript code. * Every javascript function while executing has a reference to its current execution context, called this. * Execution context means here is how the function is called. * To understand this keyword, only we need to know how, when and from where the function is called, does not matter how and where function is declared or defined. **What’s the difference between a method and a function** * A method is just a function that’s been assigned to a property name in an object. * You call functions using the function name, while you call methods using the object dot notation and the name of the property. * You can also use the keyword this in a method to refer to the object whose method was called * A method is a function * We just call it a method because it lives inside an object. * So, a method can do anything a function can do precisely because a method is a function. **When is the value of this set to the object? When we define the object, or when we call the method?** * The value of this is set to the object when you call the method. * So when you call fiat.start(), this is set to fiat, and when you call chevy.start(), this is set to chevy. * It looks like this is set when you define the object, because in fiat.start, this is always set to fiat, and in chevy.start, this is always set to chevy. * There is a good reason the value of this is set when you call the method and not when you define the object. **for...of Vs for...in loops** * for..of and for…in loops give us a very clean and concise syntax to iterate over all kinds of iterables and enumerables like strings, arrays and object literals. * Use for…of to iterate over the values in an iterable, like an array ``` let animals = ['🐔', '🐷', '🐑', '🐇']; let names = ['Gertrude', 'Henry', 'Melvin', 'Billy Bob']; for (let animal of animals) { // Random name for our animal let nameIdx = Math.floor(Math.random() * names.length); console.log(`${names[nameIdx]} the ${animal}`); } // Henry the 🐔 // Melvin the 🐷 // Henry the 🐑 // Billy Bob the 🐇 ``` * Strings are also an iterable type, so you can use for…of on strings: ``` let str = 'abcde'; for (let char of str) { console.log(char.toUpperCase().repeat(3)); } // AAA // BBB // ... ``` **for...in loop** * Use for…in to iterate over the properties of an object (the object keys) ``` let oldCar = { make: 'Toyota', model: 'Tercel', year: '1996' }; for (let key in oldCar) { console.log(`${key} --> ${oldCar[key]}`); } // make --> Toyota // model --> Tercel ``` * We can also use for…in to iterate over the index values of an iterable like an array or a string: ``` let str = 'Turn the page'; for (let index in str) { console.log(`Index of ${str[index]}: ${index}`); } // Index of T: 0 // Index of u: 1 ``` ``` const object = { a: 1, b: 2, c: 3 }; for (const property in object) { console.log(`${property}: ${object[property]}`); } // expected output: // "a: 1" // "b: 2" // "c: 3" ``` **How behavior affects state...** * Objects contain state and behavior. * An object’s properties allow us to keep state about the object. * An object’s methods allow us to have behavior. **onload property of window object** * first create a function that has the code you’d like executed once the page is fully loaded. * After you’ve done that, you take the window object, and assign the function to its onload property * The window object will call any function you’ve assigned to its onload property, but only after the page is fully loaded. ``` <script> function init() { var planet = document.getElementById("greenplanet"); planet.innerHTML = "Red Alert: hit by phaser fire!"; } window.onload = init; </script> ``` * Here, we’re assigning the function init to the window.onload property. * Make sure we don't use parentheses after the function name! * We're not calling the function; we're just assigning the function value to the window.onload property. * Here the event is the “page is loaded” event. * A common way to deal with that situation is through a callback, also known as an event handler. * A callback works like this: give a function to the object that knows about the event => When the event occurs, that object will call you back, or notify you, by calling that function. **How to set an attribute with setAttribute** ``` planet.setAttribute("class", "redtext"); ``` * We take our element object =>planet * And we use its setAttribute method to either add a new attribute or change an existing attribute. * The method takes two arguments, the name of the attribute you want to set or change and the value you'd like to set that attribute to. * Note if the attribute doesn’t exist a new one will be created in the element. **NaN** * JavaScript uses the value NaN, more commonly known as “Not a Number”, to represent numeric results that, well, can’t be represented. * Take 0/0 for instance => 0/0 evaluates to something that just can’t be represented in a computer, so it is represented by NaN in JavaScript. * NaN MAY BE THE WEIRDEST VALUE IN THE WORLD. * Not only does it represent all the numeric values that can’t be represented, it is the only value in JavaScript that isn’t equal to itself! * If you compare NaN to NaN, they aren’t equal! * NaN isn’t equal to anything, not even itself, so, any kind of test for equality with NaN is off the table. * Instead we need to use a special function: isNaN. ``` if (isNaN(myNum)) { myNum = 0; } ``` * Use the isNaN function, which returns true if the value passed to it is not a number. **understanding the equality operator** **CASE#1: Comparing a number and a string** * If you’re comparing a string and a number the same thing happens every time => the string is converted into a number, and the two numbers are then compared. * This doesn’t always go well, because not all strings can be converted to numbers. * 99 == "vanilla" => 99 == NaN => false * Here we’re comparing a number and a string. * But this time, when we try to convert the string to a number, we fail. * When we try to convert “vanilla” to a number, we get NaN, and NaN isn’t equal to anything. And so the result is false. **CASE#2: Comparing a boolean with any other type** * In this case, we convert the boolean to a number, and compare. * true converts to 1 and false converts to 0. * sometimes this case requires doing more than one type conversion * 1==true => 1==1 => true * "1"==true => "1"==1 => 1 == 1 => true **CASE#3: Comparing null and undefined** * Comparing these values evalutates to true. * These values both essentially represent “no value” (that is, a variable with no value, or an object with no value), so they are considered to be equal. * undefined == null => true * Undefined and null are always equal. **CASE#4** * 1 == "" => 1 == 0 => false * Here we’re comparing a number and a string. * The empty string is converted to the number 0. * 1 and 0 are not the same => So this evaluates to false. **What happens if I compare a number, like 99, to a string, like “ninety-nine”, that can’t be converted to a number?** * JavaScript will try to convert “ninety-nine” to a number, and it will fail, resulting in NaN. * So the two values won’t be equal, and the result will be false. **what if I try something like “true” == true?** * That is comparing a string and a boolean, so according to the rules, JavaScript will first convert true to 1, and then compare “true” and 1. * It will then try to convert “true” to a number, and fail, so you’ll get false **Two values are strictly equal only if they havethe same type and the same value** * === will find two values equal only if they are the same type and the same value. **look at concatenation and addition** * We figured out that when you use the + operator with numbers you get addition, and when you use it with strings you get concatenation. * If you try to add a number and a string, JavaScript converts the number to a string and concatenates the two (opposite of what it does with equality) ``` let addi = 3 + "4"; ``` * When we have a string added to a number, we get concatenation, not addition. * The result variable is set to “34" (not 7). **So if I want JavaScript to convert a string into a number to add it to another number, how would I do that?** * There’s a function that does this named Number ``` let num = 3 + Number("4"); ``` * This statement results in num being assigned the value 7. * The Number function takes an argument, and if possible, creates a number from it. * If the argument can’t be converted to a number, Number returns.... wait for it..... NaN. **How to determine if two objects are equal** * When we test equality of two object variables, we compare the references to those objects * variables hold references to objects, and so whenever we compare two objects, we’re comparing object references. * Two references are equal only if they reference the same object * The only way a test for equality between two variables containing object references returns true is when the two references point to the same object **truthy and falsy** * There are values in JavaScript that aren’t true or false, but that are nevertheless treated as true or false in a conditional. * We call these values truthy and falsey precisely because they aren’t technically true or false, but they behave like they are (again, inside a conditional). * Concentrate on knowing what is falsey, and then everything else you can consider truthy ``` var testThis; if (testThis) { // do something } var element = document.getElementById("elementThatDoesntExist"); if (element) { // do something } if (0) { // do another thing } if ("") { // does code here ever get evaluated? Place your bets. } if (NaN) { // Hmm, what's NaN doing in a boolean test? } ``` * To remember which values are truthy and which are falsey, just memorize the five falsey values— undefined, null, 0, "” and NaN—and remember that everything else is truthy. * Here are some examples of truthy values: ``` if ([]) { //This is an array. It's not undefined, null, zero, “” or NaN. It has to be true! // this will happen } var element = document.getElementById("elementThatDoesExist"); if (element) { // so will this } if (1) { //Only the number 0 is falsey, all others are truthy // gonna happen } var string = "mercy me"; if (string) { //Only the empty string is falsey, all other strings are truthy. // this will happen too } ``` **Strings** **The length property** * The length property holds the number of characters in the string. * It’s quite handy for iterating through the characters of the string. **The charAt method** * The charAt method takes an integer number between zero and the length of the string (minus one), and returns a string containing the single character at that position of the string. * Think of the string a bit like an array, with each character at an index of the string, with the indices starting at 0 (just like an array). * If you give it an index that is greater than or equal to the length of the string, it returns the empty string. ``` let input = "jenny@wickedlysmart.com"; for(var i = 0; i < input.length; i++) { if (input.charAt(i) === "@") { console.log("There's an @ sign at index " + i); } } ``` **The indexOf method** * This method takes a string as an argument and returns the index of the first character of the first occurrence of that argument in the string. ``` let phrase = "the cat in the hat"; let index = phrase.indexOf("cat"); console.log("there's a cat sitting at index " + index); ////there's a cat sitting at index 4 ``` * You can also add a second argument, which is the starting index for the search * Because we're starting the search at index 5, we're skipping the first “the" and finding the second “the” at index 11. ``` index = phrase.indexOf("the", 5); console.log("there's a the sitting at index " + index); //there's a the sitting at index 11 ``` ``` index = phrase.indexOf("dog"); console.log("there's a dog sitting at index " + index); //there's a dog sitting at index -1 ``` **The substring method** * Give the substring method two indices, and it will extract and return the string contained within them. ``` let data = "name|phone|address"; let val = data.substring(5, 10); console.log("Substring is " + val); ``` * We'd like the string from index 5 and up to (but not including) 10 returned **The split method** * The split method takes a character that acts as a delimiter, and breaks the string into parts based on the delimiter. ``` let data = "name|phone|address"; let vals = data.split("|"); console.log("Split array is ", vals); //Split array is [ 'name', 'phone', 'address' ] ``` **instanceOf operator** * The instanceof operator in JavaScript is used to check the type of an object at run time. * It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not. **we take the letter and convert it to a number by using a helper array that contains the letters A-F. To get the number, we can use the indexOf method to get the index of the letter in the array** ``` function parseGuess(guess) { var alphabet = ["A", "B", "C", "D", "E", "F", "G"]; if (guess === null || guess.length !== 2) { alert("Oops, please enter a letter and a number on the board."); } else { firstChar = guess.charAt(0); var row = alphabet.indexOf(firstChar); } } ``` **document.getElementsByTagName** * This method takes a tag name, like img or p or div, and returns a list of elements that match it * It returns an object that you can treat like an array, but it’s actually an object called a NodeList. * A NodeList is a collection of Nodes, which is just a technical name for the element objects that you see in the DOM tree. * You can iterate over this collection by getting its length using the length property, and then access each item in the NodeList using an index with the bracket notation, just like an array. **what is an event handler** * We write handlers to handle events. * Handlers are typically small pieces of code that know what to do when an event occurs. * In terms of code, a handler is just a function. * When an event occurs, its handler function is called. * For example ``` function pageLoadedHandler() { alert("I'm alive!"); } window.onload = pageLoadedHandler; ``` **setTimeout** * setTimeout allows us to run a function once after the interval of time. ``` function timerHandler() { alert("Hey what are you doing just sitting there staring at a blank screen?"); } setTimeout(timerHandler, 5000); ``` * First we write an event handler. * This is the handler that will be called when the time event has occurred. * Using setTimeout is a bit like setting a stop watch. * Here we’re asking the timer to wait 5000 milliseconds (5 seconds). * And then call the handler timerHandler. * And here, we call setTimeout, which takes two arguments: the event handler and a time duration (in milliseconds). * setTimeout function essentially creates a countdown timer and associates a handler with that timer. * That handler is called when the timer hits zero. * Now to tell setTimeout what handler to call, we need to pass it a reference to the handler function. * setTimeout stores the reference away to use later when the timer has expired. **setInterval** * setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. ``` let tick = true; function ticker() { if (tick) { console.log("Tick"); tick = false; } else { console.log("Tock"); tick = true; } } setInterval(ticker, 1000); ``` * To stop an interval timer, save the result of calling setInterval in a variable and then pass that to clearInterval later, when you want to stop the timer. ``` let t = setInterval(ticker, 1000); clearInterval(t); ``` **function declaration Vs function expressions** ``` function quack(num) { for (let i = 0; i < num; i++) { console.log("Quack!"); } } quack(3); ``` * formally, the first statement above is a function declaration, which creates a function that has a name—in this case quack—that can be used to reference and invoke the function. ``` let fly = function(num) { for (let i = 0; i < num; i++) { console.log("Flying!"); } }; fly(3); ``` * When we use the function keyword this way—that is, within a statement, like an assignment statement—we call this a function expression. * Unlike the function declaration, this function doesn’t have a name. * The expression results in a value that is then assigned to the variable fly. * We are assigning it to the variable fly and then later invoking it, so it must be a reference to a function * Function declarations are evaluated before the rest of the code is evaluated. * Function expressions get evaluated later, with the rest of the code. * A function declaration doesn’t return a reference to a function; rather it creates a variable with the name of the function and assigns the new function to it. * A function expression returns a reference to the new function created by the expression. * The process of invoking a function created by a declaration is exactly the same for one created with an expression. * You can hold function references in variables. * Function declarations are statements;function expressions are used in statements. **How can a function be an expression?** * An expression is anything that evaluates to a value. * 3+4 evaluates to 7, Math.random() * 6 evaluates to a random number, and a function expression evaluates to a function reference. **Difference between function declaration and function expression** * With a declaration, a function is created and setup before the rest of the code gets evaluated. * With a function expression, a function is created as the code executes, at runtime. * Another difference has to do with function naming— when you use a declaration, the function name is used to create and set up as a variable that refers to the function. * When you use a function expression, you typically don’t provide a name for the function, so either you end up assigning the function to a variable in code, or you use the function expression in other ways. * Remember quack is defined with a function declaration, and fly with a function expression. * Both result in function references, which are stored in the variables quack and fly. * The function declaration takes care of assigning the reference to a variable with the name you supply => in this case quack. * When you have a function expression, you need to assign the resulting reference to a variable yourself => Here we’re storing the reference in the fly variable. **“What makes JavaScript functions first class?”** ❏ We can assign functions to variables. ❏ We can pass functions to functions. ❏ We can return functions from functions. **Array sort methods** * The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. * By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last. * The sort() method casts elements to strings and compares the strings to determine the orders. ``` let numbers = [0, 1 , 2, 3, 10, 20, 30 ]; numbers.sort(); console.log(numbers); //output [ 0, 1, 10, 2, 20, 3, 30 ] ``` * In this example, the sort() method places 10 before 2 because the string “10” comes before “2” when doing a string comparison. * To fix this, you need to pass a comparison function to the sort() method. * The sort() method will use the compare function to determine the orders of elements. ``` array.sort(comparefunction) ``` * The sort() method accepts an optional argument which is a function that compares two elements of the array. * If you omit the compare function, the sort() method sorts the elements with the sort order based on the Unicode code point values of elements as mentioned earlier. * The compare function of the sort() method accepts two arguments and returns a value that determines the sort order ``` function compare(a,b) { // ... } ``` * The compare() function accepts two arguments a and b. The sort() method will sort elements based on the return value of the compare() function with the following rules: * If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first. * If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b will come first. * If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged. ``` let numbers = [0, 1 , 2, 3, 10, 20, 30 ]; numbers.sort(function(a,b){ if(a > b) return 1; if(a < b) return -1; return 0; }); console.log(numbers); //Output [ 0, 1, 2, 3, 10, 20, 30 ] ``` * The sort method has sorted numbersArray in ascending order because when we return the values 1, 0 and -1, we’re telling the sort method: * 1: place the first item after the second item * 0: the items are equivalent, you can leave them in place * -1: place the first item before the second item. * You know that the comparison function we pass to sort needs to return a number greater than 0, equal to 0, or less than 0 depending on the two items we’re comparing: * if the first item is greater than second, we return a value greater than 0; if first item is equal to the second, we return 0; and if the first item is less than the second, we return a value less than 0. ``` function compareNumbers(num1, num2) { return num1 - num2; } ``` ``` function whereAreYou() { var justAVar = "Just an every day LOCAL"; function inner() { return justAVar; } return inner; } ``` * First we encounter a local variable, named justAVar. We assign the string “Just an every day LOCAL” to the variable. * All local variables are stored in an environment. It holds all the variables defined in the local scope. In this example, the environment just has one variable, the justAVar variable. * We then create a function, with the name inner. * And finally, when we return the function, we don’t just return the function; we return the function with the environment attached to it. * Every function has an attached environment, which contains the local variables within its enclosing scope. ``` //CALLING A FUNCTION var innerFunction = whereAreYou(); var result = innerFunction(); console.log(result); ``` * First, we call whereAreYou. We already know that returns a function reference. So we create a variable innerFunction and assign it that function. Remember, that function reference is linked to an environment. ``` var innerFunction = whereAreYou(); ``` * Next we call innerFunction. To do that we evaluate the code in the function’s body, and do that in the context of the function’s environment ``` var result = innerFunction(); ``` **If we have a function that is returned from within a function, it carries its environment around with it.** * A free variable is one that isn't defined in the local scope and the environments closes the function. By that we mean that it provides values for all the free variables. ``` function justSayin(phrase) { var ending = ""; if (beingFunny) { ending = " -- I'm just sayin!"; } else if (notSoMuch) { ending = " -- Not so much."; } alert(phrase + ending); } ``` ```//free variables : beingFunny, notSoMuch //environment : beingFunny = true; notSoMuch = false; ``` **Function closure** * A function typically has local variables in its code body and it also might have variables that aren’t defined locally, which we call free variables. * The name free comes from the fact that within the function body, free variables aren’t bound to any values (in other words, they’re not declared locally in the function). * When we have an environment that has a value for each of the free variables, we say that we’ve closed the function. * When we take the function and the environment together, we say we have a closure. **A closure results when we combine a function that has free variables with an environment that provides variable bindings for all those free variables.** **object constructors** * Using constructors is a two-step process: first we define a constructor, and then we use it to create objects * A constructor is useful when you want to create lots of objects with the same property names and methods ``` function Dog(name, breed, weight) { this.name = name; this.breed = breed; this.weight = weight; } let fido = new Dog("Fido", "Mixed", 38); ``` **How constructors work** * The first thing new does is create a new, empty object * Next, new sets this to point to the new object. * Remember that new first creates a new object before assigning it to this (and then calling your constructor function). * If you don’t use new, a new object will never be created. * That means any references to this in your constructor won’t refer to a new object, but rather, will refer to the global object of your application * With this set up, we now call the function Dog, passing "Fido", "Mixed" and 38 as arguments. * Next the body of the function is invoked. Like most constructors, Dog assigns values to properties in the newly created this object. * Finally, once the Dog function has completed its execution the new operator returns this, which is a reference to the newly created object. * After the new object has been returned, we assign that reference to the variable fido. * You can do anything in a constructor you can do in a regular function, like declare and use variables, use for loops, call other functions, and so on. * The only thing you don’t want to do is return a value (other than this) from a constructor because that will cause the constructor to not return the object it’s supposed to be constructing. **this keyword in constructors** * When you call a constructor (to create an object) the value of this is set to the new object that’s being created so all the code that is evaluated in the constructor applies to that new object. * When you call a method on an object, this is set to the object whose method you called. * So the this in your methods will always refer to the object whose method was called. **instance of operator** * The instanceof operator returns true if the object was created by the specified constructor. ``` if (cadi instanceof Car) { console.log("Congrats, it's a Car!"); }; ``` * In this case we're saying “Is the cadi object an instance that was created by the Car constructor?” **every method** ``` let areAllOdd = oddNumbers.every(function(x) { return ((x % 2) !== 0); }); ``` * The every method takes a function and tests each value of the array to see if the function returns true or false when called on that value. * If the function returns true for all the array items, then the result of the every method is true. **Why don’t we have to say "new Math" to instantiate a math object before I use it?** * Math is not a constructor, or even a function. It’s an object. * Math is a built-in object that you can use to do things like get the value of pi (with Math.PI) or generate a random number (with Math.random). * Think of Math as just like an object literal that has a bunch of useful properties and methods in it, built-in for you to use whenever you write JavaScript code. * It just happens to have a capital first letter to let you know that it’s built-in to JavaScript. **How do we write the code to ask if two objects have the same constructor?** ``` ((fido instanceof Dog) && (spot instanceof Dog)) ``` * If this expression results in true, then fido and spot were indeed created by the same constructor. **prototypes** * JavaScript objects can inherit properties and behavior from other objects. * JavaScript uses what is known as prototypal inheritance, and the object you’re inheriting behavior from is called the prototype * The whole point of this scheme is to inherit and reuse existing properties (including methods), while extending those properties in your brand new object. * When an object inherits from another, it gains access to all its methods and properties. **How inheritance work** * When you call a method on an object instance, and that method isn’t found in the instance, you check the prototype for that method. ``` fido.bark(); ``` * To evaluate this code we look in the fido instance for a bark method. But there isn’t one. * If we can’t find bark in the fido instance, then we take a look next at its prototype. * Checking the Dog prototype we see it does have a bark method. * Finally, once we find the bark method, we invoke it, which results in Fido barking. * If we write code that needs fido.name, the value will come from the fido object. * But if we want the value of fido.species, we first check the fido object, but when it isn’t found there, we check the dog prototype **hasOwnProperty method** * The hasOwnProperty method returns true if a property is defined in an object instance. * If it’s not, but you can access that property, then you can assume the property must be defined in the object’s prototype. ``` spot.hasOwnProperty("species"); fido.hasOwnProperty("species"); ``` * Both of these return the value false because species is defined in the prototype, not the object instances spot and fido.
Markdown
UTF-8
4,495
2.53125
3
[ "MIT" ]
permissive
# Summary ![This Shrine is very fancy](https://github.com/MoyTW/MTW_AncestorSpirits/blob/master/About/Preview.png) You Ancestors are watching you, and they are hard to impress. To ignore them would be foolish, though - they're the foundation of your tribal magic, and if they're displeased are more than capable of calling down storms, plagues, and divine punishments. If, on the other hand, you manage to honor and please your ancestors, they can gift you with Magic, which is the basis for all your Petitions - Petitions which can call rain or lightning, or heal sick or injured tribe members. ![They aren't currently ghostly, but at some point, if I get around to it, they will be. I hate graphics-stuff though.](https://github.com/MoyTW/MTW_AncestorSpirits/blob/master/About/Images/RoomAndAncestorCard.jpg) Every so often, your Ancestors will drop in to visit! They don't need to eat or sleep, but they do get bored sometimes. Mostly they're here just to see the sights! Ugliness and disorder will anger them, but beautiful and rich surroundings will please them. When your Ancestors return to their Anchor, they will pass judgement on your village. If they're pleased, they will grant you more magic when the season turns. If they're not, you may even lose magic. If they're incredibly displeased you may suffer a curse, so ensure that this does not happen! ![Some balance work needed.](https://github.com/MoyTW/MTW_AncestorSpirits/blob/master/About/Images/ChoosingPetitions.jpg) The Magic that you accumulate can be spent on Petitions. The amount of magic spent is equal to the number of attached and lit Braziers (those are the buildings on the left/right of the Shrine). You can spend between double and half the listed magic price. The chance of success at half magic is slightly over half, and at double they will for sure grant your petition. Vary your spend depending on urgency, but overall you will probably have better long-term results by using less on more attempts. # Current Petitions + smite attackers - call upon your Ancestors to destroy your attackers with lightning + beating rain - call upon your Ancestors to bring rain + howling wind - call upon your Ancestors to bring wind + sweltering heat - call upon your Ancestors to bring a heat wave + icy chill - call upon your Ancestors to bring a cold snap + help heal wounds - call upon your Ancestors to help your wounded warriors heal + help cure sickness - call upon your Ancestors to help banish sickness + bless crops - call upon your Ancestors to make your crops grow faster and survive ill conditions + cleanse the skies - call upon your Ancestors to blow away unnatural weather # Disclaimer This mod is current very much a work-in-progress! It can be applied to in-progress games, but don't use it on any saves you're not prepared to use. # Installation Information Basic installation: - If there is an existing version of this mod, delete the old version - Download and unzip into the RimWorld/Mods folder - Activate the mod and restart RimWorld ## Adding to existing saves *This mod adds a hidden Ancestor Faction!* This means that if you attempt to add it to an ongoing game, you must also have Orion's Faction Discovery mod (forums https://ludeon.com/forums/index.php?topic=25159.0 or steam http://steamcommunity.com/sharedfiles/filedetails/?id=751841890) or this mod will throw an error when loaded. Starting a new game does not require the Faction Discovery mod and will work fine. ## Compatibility This mod should be safe to use with any mods which do not detour any of the same functions. The detours are listed below. If you discover an issue, please post in the thread here (https://ludeon.com/forums/index.php?topic=27186.0) so I can add it to the known conflicts. ### Known Mod Conflicts + This mod conflicts with Hospitality. I've added a compatibility mod, which can be found here: https://github.com/MoyTW/MTW_AncestorsHospitalityCompatibility ### Detours This mod detours the following functions, and will conflict with any mods that also detour them: + Verse.AI.GenAI.CanBeArrested + Verse.AI.Job.ExposeData + RimWorld.Pawn_ApparalTracker.get_PsychologicallyNude + RimWorld.Pawn_NeedsTracker.ShouldHaveNeed # Download See here: https://github.com/MoyTW/MTW_AncestorSpirits/releases At some future point I may put it on Steam, but I don't feel it's nearly done enough for that. # Thanks To + Ratsys (examples and injection code) + Orion (examples and code from Hospitality)
Java
UTF-8
2,919
2.796875
3
[ "MIT" ]
permissive
package org.shapelogic.scripting; import java.util.Map; import java.util.TreeMap; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** ScriptEngineFactory get ScriptEngine by name. * <br /> * Create script and evaluate. * * @author Sami Badawi * */ public class ScriptEngineCache { public static final boolean GET_ENGINE_BY_EXTENSION = false; static private ScriptEngineManager _scriptEngineManager; static private Map<String, ScriptEngine> _scriptEngineMap = new TreeMap<String,ScriptEngine>(); static public ScriptEngineManager getScriptEngineManager() { if (_scriptEngineManager == null) _scriptEngineManager = new ScriptEngineManager(); return _scriptEngineManager; } /** I should also create one for extension */ static public ScriptEngine getScriptEngineByName(String language) { ScriptEngine scriptEngine = _scriptEngineMap.get(language); if (scriptEngine == null) { scriptEngine = getNewScriptEngineByName(language); _scriptEngineMap.put(language, scriptEngine); } return scriptEngine; } /** I should also create one for extension */ static public ScriptEngine getNewScriptEngineByName(String language) { ScriptEngine scriptEngine = getScriptEngineManager().getEngineByName(language); if (scriptEngine == null) { throw new IllegalArgumentException( "No script engine on classpath to handle language: " + language ); } return scriptEngine; } /** I should also create one for extension */ static public ScriptEngine getScriptEngineByExtension(String extension) { ScriptEngine scriptEngine = _scriptEngineMap.get(extension); if (scriptEngine == null) { scriptEngine = getScriptEngineManager().getEngineByExtension(extension); if (scriptEngine == null) { throw new IllegalArgumentException( "No script engine on classpath to handle extension: " + extension ); } _scriptEngineMap.put(extension, scriptEngine); } return scriptEngine; } static public Object eval(String script, String language) throws Exception { ScriptEngine scriptEngine = getScriptEngineByName(language); if (scriptEngine != null) return scriptEngine.eval(script); return null; } static public ScriptEngine script(String script, String language) throws Exception { ScriptEngine scriptEngine = getScriptEngineByName(language); if (scriptEngine != null) scriptEngine.eval(script); return scriptEngine; } static public void put(String key, Object value, String language) throws Exception { ScriptEngine scriptEngine = getScriptEngineByName(language); if (scriptEngine != null) scriptEngine.put(key, value); } }
Java
UTF-8
646
2.1875
2
[]
no_license
package com.ibm.watson.developer_cloud.natural_language_classifier.v1.model; import com.google.gson.annotations.SerializedName; import com.ibm.watson.developer_cloud.service.model.GenericModel; public class ClassifiedClass extends GenericModel { private Double confidence; @SerializedName("class_name") private String name; public Double getConfidence() { return this.confidence; } public String getName() { return this.name; } public void setConfidence(Double confidence) { this.confidence = confidence; } public void setName(String name) { this.name = name; } }
Python
UTF-8
140
3.09375
3
[]
no_license
#!/usr/bin/python3 x = 0 for i in range(ord('z'), ord('a') - 1, -1): print("{}".format(chr(i - x)), end="") x = 32 if x == 0 else 0
C++
UTF-8
427
2.859375
3
[]
no_license
// kth smallest element in c++ #include <bits/stdc++.h> using namespace std ; int main(){ int n ; cin>>n; int k; cin>> k ; priority_queue<int> p ; for(int i= 0 ;i<n;i++){ int n ; cin>>n; p.push(n); if(p.size()>k) { p.pop(); } } cout<<p.top()<<endl; return 0 ; } /* 6 3 7 10 4 3 20 15 7 */
JavaScript
UTF-8
4,676
2.953125
3
[]
no_license
var canvas = document.getElementById("GameScreen"); var ctx = canvas.getContext("2d"); var pellet_hdl = new Image() pellet_hdl.src = "pellet.png" var pac_hdl = new Image() pac_hdl.src = "capman.png" var rgho_hdl = new Image() rgho_hdl.src = "RedGhost.png" var bgho_hdl = new Image() bgho_hdl.src = "BlueGhost.png" var ogho_hdl = new Image() ogho_hdl.src = "OrangeGhost.png" var pgho_hdl = new Image() pgho_hdl.src = "PinkGhost.png" var sizeConst = 30 setInterval(Game, 1000/60); function Tile(x, y) { this.posx = x; this.posy = y; this.width = sizeConst; this.height = sizeConst; this.draw = function() { ctx.fillStyle = "#0000ff"; ctx.fillRect(this.posx, this.posy, this.width, this.height); }; } function Pellet(x, y) { this.posx = x; this.posy = y; this.width = sizeConst; this.height = sizeConst; this.draw = function() { //ctx.fillStyle = "#00ffff"; //ctx.fillRect(this.posx + sizeConst/4, this.posy + sizeConst/4, this.width/2, this.height/2); ctx.drawImage(pellet_hdl, this.posx, this.posy) }; } function Map() { this.Tiles = new Array(); this.Pellets = new Array(); this.addTile = function(tile) { this.Tiles[this.Tiles.length] = tile }; this.addPellet = function(pellet) { this.Pellets[this.Pellets.length] = pellet }; this.makeMap = function(array) { var xplace = sizeConst; var yplace = sizeConst; for (var i = 0; i < array.length; i++) { var data = array[i]; for (var j = 0; j < data.length; j++) { var t = data[j]; if (t == 'b') { this.addTile(new Tile(xplace, yplace)); } if (t == ' ') { this.addPellet(new Pellet(xplace, yplace)); } xplace += sizeConst; } xplace = sizeConst; yplace += sizeConst; } }; this.DrawMap = function() { for (var i = 0; i < this.Tiles.length; i++) this.Tiles[i].draw(); for (var i = 0; i < this.Pellets.length; i++) this.Pellets[i].draw(); }; } GameMap = new Map() function PoppulateMap() { GameMap.makeMap(BaseMap); } PoppulateMap(); pac = new Pacman(sizeConst * 2, sizeConst * 2, pac_hdl) document.addEventListener("keydown", buttons, false); //Button code! function buttons(e) { //console.log("Hi!"); var key = e.keyCode; //left if (key == 37) { if (pac.checkWall(-30, 0, GameMap.Tiles) == 1) pac.orientation = "left"; else { pac.queue = "left"; pac.queueTimer = 30; } } //right if (key == 39) { if (pac.checkWall(30, 0, GameMap.Tiles) == 1) pac.orientation = "right"; else { pac.queue = "right"; pac.queueTimer = 30; } } //up if (key == 38) { if (pac.checkWall(0, -30, GameMap.Tiles) == 1) pac.orientation = "up"; else { pac.queue = "up"; pac.queueTimer = 30; } } //down if (key == 40) { if (pac.checkWall(0, 30, GameMap.Tiles) == 1) pac.orientation = "down"; else { pac.queue = "down"; pac.queueTimer = 30; } } } Ghosts = new Array() Ghosts[1] = new Ghost(sizeConst * 4, sizeConst * 11, rgho_hdl) document.addEventListener("keydown", Red_buttons, false); //Button code! function Red_buttons(e) { //console.log("Hi!"); var key = e.keyCode; //left if (key == 65) { if (Ghosts[1].checkWall(-30, 0, GameMap.Tiles) == 1) Ghosts[1].orientation = "left"; else { Ghosts[1].queue = "left"; Ghosts[1].queueTimer = 30; } } //right if (key == 68) { if (Ghosts[1].checkWall(30, 0, GameMap.Tiles) == 1) Ghosts[1].orientation = "right"; else { Ghosts[1].queue = "right"; Ghosts[1].queueTimer = 30; } } //up if (key == 87) { if (Ghosts[1].checkWall(0, -30, GameMap.Tiles) == 1) Ghosts[1].orientation = "up"; else { Ghosts[1].queue = "up"; Ghosts[1].queueTimer = 30; } } //down if (key == 83) { if (Ghosts[1].checkWall(0, 30, GameMap.Tiles) == 1) Ghosts[1].orientation = "down"; else { Ghosts[1].queue = "down"; Ghosts[1].queueTimer = 30; } } } Ghosts[2] = new Ghost(sizeConst * 4, sizeConst * 15, bgho_hdl) Ghosts[3] = new Ghost(sizeConst * 4, sizeConst * 19, ogho_hdl) Ghosts[4] = new Ghost(sizeConst * 4, sizeConst * 23, pgho_hdl) function Game() { ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, canvas.width, canvas.height); pac.update(); for (var i = 1; i <= 4; i++) Ghosts[i].update(); pac.wallCollision(GameMap.Tiles); pac.getPellet(GameMap.Pellets); for (var i = 1; i <= 4; i++) Ghosts[i].wallCollision(GameMap.Tiles); for (var i = 1; i <= 4; i++) { if (Ghosts[i].PacCollision(pac) == 1) { alert("GAME OVER"); } } GameMap.DrawMap(); pac.draw(); for (var i = 1; i <= 4; i++) Ghosts[i].draw(); //levelMap.drawMap(_globalDrawOffsetX, _globalDrawOffsetY); }
C++
UTF-8
517
2.5625
3
[]
no_license
#include <iostream> #include "global.h" #include "Problem.h" #include "Search.h" #include "FileUtil.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { vector<string> fileStr; FileUtil file; fileStr = file.loadFile("input.txt"); Problem problem = Problem(fileStr); Solution solution; Search search; solution = search.doSearch(problem); file.writeFile("output.txt",solution.getActions(),solution.getCosts()); return 0; }
C#
UTF-8
647
3.09375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackathonMFClever { public class Way { public string Address; public uint Time;//время в пути в минутах public uint Distance; public Way(string address, uint time, uint distance) { Address = address; Time = time; Distance = distance; } public override string ToString() { return $"Way: {Address} Time: {Time} Distance: {Distance}"; } } }
PHP
UTF-8
2,037
2.5625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: EZ * Date: 2020/4/2 * Time: 21:16 */ namespace EasySwoole\WeChat\Bean\OfficialAccount\ServiceMessage; use EasySwoole\Spl\SplArray; use EasySwoole\WeChat\Bean\OfficialAccount\RequestConst; class Video extends RequestedReplyMsg { protected $video = []; protected $msgtype = RequestConst::MSG_TYPE_VIDEO; /** * @return SplArray */ public function buildMessage() : SplArray { $data = $this->toArray(null, Video::FILTER_NOT_NULL); return new SplArray($data); } /** * @param string $mediaId * * @return Video */ public function setMediaId(string $mediaId) : Video { $this->video['media_id'] = $mediaId; return $this; } /** * @return null|string */ public function getMediaId() : ?string { return $this->video['media_id'] ?? null; } /** * @param string $title * * @return Video */ public function setTitle(string $title) : Video { $this->video['title'] = $title; return $this; } /** * @return null|string */ public function getTitle() : ?string { return $this->video['title'] ?? null; } /** * @param string $title * * @return Video */ public function setThumbMediaId(string $thumbMediaId) : Video { $this->video['thumb_media_id'] = $thumbMediaId; return $this; } /** * @return null|string */ public function getThumbMediaId() : ?string { return $this->video['thumb_media_id'] ?? null; } /** * @param string $description * * @return Video */ public function setDescription(string $description) : Video { $this->video['description'] = $description; return $this; } /** * @return null|string */ public function getDescription() : ?string { return $this->video['description'] ?? null; } }
Python
UTF-8
565
2.625
3
[]
no_license
import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import tensorflow as tf import pandas as pd import xlrd DATA_FILE = 'data/USA_Housing.xls' # Step 1: read in data from the .xls file book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8") sheet = book.sheet_by_index(0) data = np.asarray([[sheet.row_values(i)[2], sheet.row_values(i)[5]] for i in range(1, sheet.nrows)]) n_samples = sheet.nrows - 1 print(data) weights = tf.Variable(tf.random_normal([2,3],stdev=0.1),name="weights") print(weights)
Ruby
UTF-8
7,333
2.578125
3
[]
no_license
# frozen_string_literal: true module PushKit module APNS # The PushClient class provides an interface for delivering push notifications using HTTP/2. # class PushClient # @return [Hash] The default hosts for each of the environments supported by APNS. # HOSTS = { production: 'api.push.apple.com', development: 'api.development.push.apple.com' }.freeze # @return [Hash] The default port numbers supported by APNS. # PORTS = { default: 443, alternative: 2197 }.freeze # @return [String] The host to use when connecting to the server. # attr_reader :host # @return [Integer] The port to use when connecting to the server. # attr_reader :port # @return [String] The APNS topic, usually the app's bundle identifier. # attr_reader :topic # @return [PushKit::APNS::TokenGenerator] The token generator to authenticate requests with. # attr_reader :token_generator # Creates a new PushClient for the specified environment and port. # # You can manually specify the host like 'api.push.apple.com' or use the convenience symbols :production and # :development which correspond to the host for that environment. # # You can also manually manually specify a port number like 443 or use the convenience symbols :default and # :alternative which correspond to the port numbers in Apple's documentation. # # @param options [Hash] The options for the client: # host [String|Symbol] The host (can also be :production or :development). # port [Integer|Symbol] The port number (can also be :default or :alternative). # topic [String] The APNS topic (matches the app's bundle identifier). # token_generator [PushKit::APNS::TokenGenerator] The token generator to authenticate the requests with. # def initialize(options = {}) extract_host(options) extract_port(options) extract_topic(options) extract_token_generator(options) end # Deliver one or more notifications. # # @param notifications [Splat] The notifications to deliver. # def deliver(*notifications, &block) unless notifications.all?(Notification) raise ArgumentError, 'The notifications must all be instances of PushKit::APNS::Notification.' end latch = Concurrent::CountDownLatch.new(notifications.count) notifications.each do |notification| deliver_single(notification) do |*args| latch.count_down block.call(*args) if block.is_a?(Proc) end end latch.wait nil end private # @return [HTTPClient] The HTTP client. # def client @client ||= HTTPClient.new("https://#{host}:#{port}") end # Deliver a single notification. # # @param notification [PushKit::APNS::Notification] The notification to deliver. # @return [Boolean] Whether the notification was sent. # def deliver_single(notification, &block) token = notification.device_token unless token.is_a?(String) && token.length.positive? raise ArgumentError, 'The notification must have a device token.' end headers = headers(notification) payload = notification.payload.to_json request = { method: :post, path: "/3/device/#{token}", headers: headers, body: payload } client.request(**request) do |code, response_headers, response_body| handle_result(notification, code, response_headers, response_body, &block) end end # Handle the result of a single delivery. # # @param notification [PushKit::APNS::Notification] The notification to handle delivery of. # @param code [Integer] The response status code. # @param headers [Hash] The response headers. # @param body [String] The response body. # @param block [Proc] A block to call after processing the response. # def handle_result(notification, code, headers, body, &block) uuid = headers['apns-id'] notification.uuid = uuid if uuid.is_a?(String) && uuid.length.positive? success = code.between?(200, 299) begin result = JSON.parse(body) rescue JSON::JSONError result = nil end return unless block.is_a?(Proc) block.call(notification, success, result) end # Returns the additional request headers for a notification. # # @param notification [PushKit::APNS::Notification] The notification to compute additional headers for. # @return [Hash] The additional headers for the notification. # def headers(notification) headers = { 'content-type' => 'application/json', 'apns-topic' => topic } headers.merge!(token_generator.headers) headers.merge!(notification.headers) headers.each_with_object({}) do |(key, value), hash| hash[key] = value.to_s unless value.nil? end end # Extract the :host attribute from the options and store it in an instance variable. # # @param options [Hash] The options passed in to the `initialize` method. # def extract_host(options) @host = options[:host] @host = HOSTS[@host] if @host.is_a?(Symbol) return if @host.is_a?(String) && @host.length.positive? raise ArgumentError, 'The :host attribute must be provided.' end # Extract the :port attribute from the options and store it in an instance variable. # # @param options [Hash] The options passed in to the `initialize` method. # def extract_port(options) @port = options[:port] @port = PORTS[@port] if @port.is_a?(Symbol) return if @port.is_a?(Integer) && @port.between?(1, 655_35) raise ArgumentError, 'The :port must be a number between 1 and 65535.' end # Extract the :topic attribute from the options and store it in an instance variable. # # @param options [Hash] The options passed in to the `initialize` method. # def extract_topic(options) @topic = options[:topic] return if @topic.is_a?(String) && @topic.length.positive? raise ArgumentError, 'The :topic must be provided.' end # Extract the :token_generator attribute from the options and store it in an instance variable. # # @param options [Hash] The options passed in to the `initialize` method. # def extract_token_generator(options) @token_generator = options[:token_generator] return if @token_generator.is_a?(TokenGenerator) raise ArgumentError, 'The :token_generator attribute must be a `PushKit::APNS::TokenGenerator` instance.' end end end end
Java
UTF-8
3,035
2.421875
2
[]
no_license
package ru.zvezdov.webApp.controllers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.*; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import ru.zvezdov.webApp.dao.CardsDao; import ru.zvezdov.webApp.model.Card; import javax.servlet.http.HttpSession; import java.util.Enumeration; import java.util.List; import java.util.Random; /** * Created by Dmitry on 14.07.2017. */ @org.springframework.stereotype.Controller @RequestMapping("/game") public class GameController { private static final Logger logger = LogManager.getLogger(CardsManagingController.class); private final CardsDao cardsDao; @Autowired public GameController(CardsDao cardsDao) { this.cardsDao = cardsDao; } @PostMapping public String playGame(@RequestParam int grade, Model model, HttpSession session) { logger.info("Grade:" + grade); session.setAttribute("grade", grade); logger.info(session.getAttribute("grade")); List<Card> cardsByGrade = cardsDao.getCardsByGrade(grade); if (cardsByGrade.isEmpty()) { session.removeAttribute("grade"); return "redirect:/words"; } Random random = new Random(); Card card = cardsByGrade.get(random.nextInt(cardsByGrade.size())); session.setAttribute("card", card); session.setAttribute("cards", cardsByGrade); return "game"; } @GetMapping("/know") public String know(@SessionAttribute("card") Card card, @SessionAttribute("cards") List<Card> cards, HttpSession session) { cards.remove(card); card.incGrade(); cardsDao.updateCard(card); if (cards.isEmpty()) { session.removeAttribute("cards"); session.removeAttribute("grade"); session.removeAttribute("card"); return "redirect:/words"; } session.setAttribute("card", cards.get(0)); return "game"; } @GetMapping("/donotknow") public String donotknow(@SessionAttribute("card") Card card, @SessionAttribute("grade") int grade, HttpSession session) { List<Card> cardsByGrade = cardsDao.getCardsByGrade(grade); if (cardsByGrade.isEmpty()) { session.removeAttribute("grade"); session.removeAttribute("cards"); session.removeAttribute("card"); return "redirect:/words"; } Random random = new Random(); card = cardsByGrade.get(random.nextInt(cardsByGrade.size())); session.setAttribute("card", card); session.setAttribute("cards", cardsByGrade); return "game"; } @GetMapping("/stopgame") public String donotknow(HttpSession session) { session.removeAttribute("grade"); session.removeAttribute("cards"); session.removeAttribute("card"); return "redirect:/words"; } }
Markdown
UTF-8
1,295
3.671875
4
[]
no_license
# jen jen is an extension to jQuery which adds a family of functions to generate html from objects #### The object spec: * tag - the name of the tag, i.e. div. * children - objects which represent child nodes which will also be jenned. - can be an object or an array of objects * on_* - an event handler to be registered, i.e. on_click. * all other properties will be added as DOM elememt properties, i.e. class. * if the var passed into the function is an array, each object is jenned and added using the desired method. * if the var is neither an array nor an object, then a text node will be jenned using the string representation of the var. #### The functions: * jen - vanilla jen, appends the jenned element(s) to the end of the selected element(s). * rejen - replaces the html content of the selected element(s) with the jenned element. * prejen - prepends jenned element(s). * jenbefore - adds jenned elements(s) outside and before the selected element(s). * jenafter - adds jenned element(s) outside and after the selected element(s). * unjen - turns the selected element(s) into an object (matching the object spec above). #### Example: $("body").jen({tag:"div", id:"jendiv", class:"someclass", on_click: function() {console.log("you clicked me!");}, children:"hello there"});
Java
UTF-8
283
2.046875
2
[]
no_license
package project.demo.model; import lombok.Data; @Data public class AuthenticationResponse { private final String jwt; private String isAdmin; public AuthenticationResponse(String jwt, String isAdmin){ this.jwt = jwt; this.isAdmin = isAdmin; } }
Java
UTF-8
3,694
1.828125
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; final class HighlightInfoComposite extends HighlightInfo { private static final @NonNls String LINE_BREAK = "<hr size=1 noshade>"; private HighlightInfoComposite(@NotNull List<? extends HighlightInfo> infos, @NotNull HighlightInfo anchorInfo) { super(null, null, anchorInfo.type, anchorInfo.startOffset, anchorInfo.endOffset, createCompositeDescription(infos), createCompositeTooltip(infos), anchorInfo.type.getSeverity(null), false, null, false, 0, anchorInfo.getProblemGroup(), null, anchorInfo.getGutterIconRenderer(), anchorInfo.getGroup(), null, anchorInfo.psiElement); highlighter = anchorInfo.getHighlighter(); List<Pair<IntentionActionDescriptor, RangeMarker>> markers = ContainerUtil.emptyList(); List<Pair<IntentionActionDescriptor, TextRange>> ranges = ContainerUtil.emptyList(); for (HighlightInfo info : infos) { if (info.quickFixActionMarkers != null) { if (markers == ContainerUtil.<Pair<IntentionActionDescriptor, RangeMarker>>emptyList()) markers = new ArrayList<>(); markers.addAll(info.quickFixActionMarkers); } if (info.quickFixActionRanges != null) { if (ranges == ContainerUtil.<Pair<IntentionActionDescriptor, TextRange>>emptyList()) ranges = new ArrayList<>(); ranges.addAll(info.quickFixActionRanges); } } quickFixActionMarkers = ContainerUtil.createLockFreeCopyOnWriteList(markers); quickFixActionRanges = ContainerUtil.createLockFreeCopyOnWriteList(ranges); } static @NotNull HighlightInfoComposite create(@NotNull List<? extends HighlightInfo> infos) { // derive composite's offsets from an info with tooltip, if present HighlightInfo anchorInfo = ContainerUtil.find(infos, info -> info.getToolTip() != null); if (anchorInfo == null) anchorInfo = infos.get(0); return new HighlightInfoComposite(infos, anchorInfo); } private static @Nullable @NlsSafe String createCompositeDescription(@NotNull List<? extends HighlightInfo> infos) { StringBuilder description = new StringBuilder(); boolean isNull = true; for (HighlightInfo info : infos) { String itemDescription = info.getDescription(); if (itemDescription != null) { itemDescription = itemDescription.trim(); description.append(itemDescription); if (!itemDescription.endsWith(".")) { description.append('.'); } description.append(' '); isNull = false; } } return isNull ? null : description.toString(); } private static @Nullable @NlsSafe String createCompositeTooltip(@NotNull List<? extends HighlightInfo> infos) { StringBuilder result = new StringBuilder(); for (HighlightInfo info : infos) { String toolTip = info.getToolTip(); if (toolTip != null) { if (!result.isEmpty()) { result.append(LINE_BREAK); } toolTip = XmlStringUtil.stripHtml(toolTip); result.append(toolTip); } } if (result.isEmpty()) { return null; } return XmlStringUtil.wrapInHtml(result); } }
Java
UTF-8
1,432
2.71875
3
[]
no_license
import instruments.Piano; import instruments.Saxophone; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestSaxophone { Saxophone saxophone; @Before public void before() { saxophone = new Saxophone("Mendini", "Wood", "Gold", "Brass", 99.99, 199.99, "Alto"); } @Test public void canGetTypeOfSaxophone() { assertEquals("Alto", saxophone.typeOfSaxophone()); } @Test public void canGetManufacturer() { assertEquals("Mendini", saxophone.getManufacturer()); } @Test public void canGetInstrumentType() { assertEquals("Wood", saxophone.getInstrumentType()); } @Test public void canGetColour() { assertEquals("Gold", saxophone.getColour()); } @Test public void canGetInstrumentMaterial() { assertEquals("Brass", saxophone.getInstrumentMaterial()); } @Test public void canGetTradePrice() { assertEquals(99.99, saxophone.getTradePrice(), 0); } @Test public void canGetSellOnPrice() { assertEquals(199.99, saxophone.getSellOnPrice(), 0); } @Test public void canPlay() { assertEquals("Saxophone is playing: The Saxophone Song", saxophone.play("The Saxophone Song")); } @Test public void canGetMarkupPrice() { assertEquals(100.00, saxophone.calculateMarkUp(), 0.1); } }
PHP
UTF-8
2,833
2.609375
3
[]
no_license
<?php class clientepotencial extends EntidadBase { private $cp_nit; private $cp_nombre; private $cp_ciudad; private $cp_direccion; private $cp_telefono; private $cp_observaciones; public function __construct($adapter) { $table = "clientepotencial"; parent::__construct($table, $adapter); } function getCp_nit() { return $this->cp_nit; } function getCp_nombre() { return $this->cp_nombre; } function getCp_ciudad() { return $this->cp_ciudad; } function getCp_direccion() { return $this->cp_direccion; } function getCp_telefono() { return $this->cp_telefono; } function getCp_observaciones() { return $this->cp_observaciones; } function setCp_nit($cp_nit) { $this->cp_nit = $cp_nit; } function setCp_nombre($cp_nombre) { $this->cp_nombre = $cp_nombre; } function setCp_ciudad($cp_ciudad) { $this->cp_ciudad = $cp_ciudad; } function setCp_direccion($cp_direccion) { $this->cp_direccion = $cp_direccion; } function setCp_telefono($cp_telefono) { $this->cp_telefono = $cp_telefono; } function setCp_observaciones($cp_observaciones) { $this->cp_observaciones = $cp_observaciones; } public function save() { $query = "INSERT INTO clientepotencial (cp_nit,cp_nombre,cp_ciudad,cp_direccion,cp_observaciones,cp_telefono) VALUES( '" . $this->cp_nit . "', '" . $this->cp_nombre . "', '" . $this->cp_ciudad . "', '" . $this->cp_telefono . "', '" . $this->cp_observaciones . "', '" . $this->cp_direccion . "'); "; $save = $this->db()->query($query); //echo "SQL> ".$query; //$this->db()->error; return $save; } public function update() { $query = "UPDATE clientepotencial SET cp_nit=".$_POST['cp_nit'].",cp_nombre='".$_POST['cp_nombre']."', cp_ciudad='".$_POST['cp_ciudad']."',cp_direccion='".$_POST['cp_direccion']."',cp_observaciones='".$_POST['cp_observaciones']."' where cp_nit = '".$_POST['cp_nit']."'"; $update = $this->db()->query($query); //echo "SQL> ".$query; //$this->db()->error; return $update; } public function buscar(){ $query = "SELECT * where cp_nit = ".$this->cp_nit." ( '" . $this->cp_nombre . "', '" . $this->cp_ciudad . "', '" . $this->cp_telefono . "', '" . $this->cp_observaciones . "', '" . $this->cp_direccion . "'); "; } }
C++
SHIFT_JIS
1,143
2.9375
3
[]
no_license
#ifndef CONSTANT_BUFFER_H_ #define CONSTANT_BUFFER_H_ #include"../../Device/Device.h" /** * @brief 萔VF[_[obt@ */ class ConstBuffer { public: /** * @brief RXgN^ */ ConstBuffer(); /** * @brief fXgN^ */ ~ConstBuffer(); // Rs[RXgN^iÖٓIRs[j ConstBuffer(const ConstBuffer&src) { src.mp_buffer->AddRef(); mp_buffer = src.mp_buffer; m_slot_number = src.m_slot_number; } // =Zq̃I[o[[hiIRs[j void operator =(const ConstBuffer&src) { if (src.mp_buffer) { src.mp_buffer->AddRef(); } if (mp_buffer) { mp_buffer->Release(); } mp_buffer = src.mp_buffer; m_slot_number = src.m_slot_number; } /** * @brief obt@̍쐬 */ bool Create( ID3D11Device* dev, UINT const_struct_size, int slot_number ); /** * @brief XbgԍԂ */ int GetSlotNum(); /** * @brief obt@Ԃ */ ID3D11Buffer* GetBuffer(); private: //! obt@ ID3D11Buffer*mp_buffer; //! o^Xbgԍ int m_slot_number; }; #endif
JavaScript
UTF-8
2,903
2.625
3
[ "MIT" ]
permissive
const LocalObjectStore = require('../'); const temp = require('temp'); const fs = require('graceful-fs'); const path = require('path'); const async = require('async'); const assert = require('chai').assert; // Automatically track and cleanup files at exit temp.track(); env = { test: true }; describe("LocalObjectStore", function() { var dir; var store; beforeEach(function() { dir = temp.mkdirSync('store'); store = new LocalObjectStore(dir); }); it('should store in specified dir', function() { assert.equal(store.dir, dir); }); it('should store data in process.cwd/store when dir is not specified', function() { store = new LocalObjectStore(); assert.equal(store.dir, path.join(process.cwd(), 'store')); }); describe('#list()', function() { it('should return no objects', function() { store.list(function(err, entries) { assert.isNull(err); assert.deepEqual(entries, []); }); }); it('should list three objects', function(done) { var adds = [1, 2, 3].map(function(i) { return function(cb) { store.add({ id: i, name: "OBJ" + i }, cb); }; }); async.parallel(adds, function() { store.list(function(err, entries) { assert.isNull(err); assert.equal(entries.length, 3); assert.deepEqual(entries[0], { id: 1, name: "OBJ1" }); assert.deepEqual(entries[1], { id: 2, name: "OBJ2" }); assert.deepEqual(entries[2], { id: 3, name: "OBJ3" }); done(); }); }); }); }); describe('#add()', function() { it('should save object', function(done) { var obj = { id: 'donkey', name: 'burro' }; store.add(obj, function(err) { assert.ok(!err); var file = path.join(dir, 'donkey.json'); assert.isTrue(fs.existsSync(file)); fs.readFile(file, 'utf8', function(err, content) { assert.isNull(err); try { assert.deepEqual(obj, JSON.parse(content)); done(); } catch (e) { console.log(e); done(e); } }); }); }); }); describe('#remove()', function() { it('should remove object', function(done) { var obj = { id: 'donkey', name: 'burro' }; var file = path.join(store.dir, obj.id + '.json'); store.add(obj, function(err) { assert.ok(!err, 'error on save: ' + err); assert.isTrue(fs.existsSync(file), 'create file'); store.remove(obj.id, function(err) { assert.ok(!err, 'error on remove: ' + err); assert.isFalse(fs.existsSync(file), 'remove file'); done(); }); }); }); }); });
C++
UTF-8
413
2.71875
3
[]
no_license
#ifndef CLIENTE_HPP #define CLIENTE_HPP #include <string> using namespace std; class Cliente { public: void set_cliente(string nome, string endereco, string cidade, string uf, string cep, string telefone); void print(); private: string nome_; string endereco_; string cidade_; string uf_; string cep_; string telefone_; }; #endif
Java
UTF-8
551
2.453125
2
[]
no_license
package ch03.classfile; import org.joou.ULong; public class ConstantLongInfo extends ConstantInfo { /* type ConstantLongInfo struct { val int64 } func (self *ConstantLongInfo) readInfo(reader *ClassReader) { bytes := reader.readUint64() self.val = int64(bytes)*/ long val; @Override public int getType() { return ConstantInfo.CONSTANT_Long; } @Override public void readInfo(ClassReader reader) { ULong uLong=reader.readUInt64(); this.val=uLong.longValue(); } }
Python
UTF-8
813
2.9375
3
[]
no_license
import urllib.request, json from jinja2 import Environment, FileSystemLoader tickers = '' # Fetch all the tickers from CoinGecko and append to add to tickers string for i in range(1, 11): api = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page={i}&sparkline=false" with urllib.request.urlopen(api) as url: data = json.loads(url.read().decode()) for crypto in data: tickers += "'" + crypto['symbol'].upper() + "'" + ',' # Get the data template from "data.jinja2" and render the tickers on there file_loader = FileSystemLoader("./") env = Environment(loader=file_loader) template = env.get_template("data.jinja2") output = template.render(tickers=tickers) # Dump the jinja template to "data.py" with open("data.py", "w") as fh: fh.write(output)
Java
UTF-8
695
2.5625
3
[]
no_license
package Cookie; public class contact { private String Uname,email,sub,msg; public contact(String uname, String email, String sub, String msg) { super(); Uname = uname; this.email = email; this.sub = sub; this.msg = msg; } public String getUname() { return Uname; } public void setUname(String uname) { Uname = uname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSub() { return sub; } public void setSub(String sub) { this.sub = sub; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
TypeScript
UTF-8
3,489
3.546875
4
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
interface PluralizedEntry { one: string; other: string; } type Entry = string | string[] | PluralizedEntry; type Entries = Record<string, Entry>; type Variables = Record<string, any>; interface I18nOptions { strings?: Entries; } const hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key); /** * Returns the pluralization object key corresponding to the given number. * * @param count Count. * * @return Pluralization key. */ const getPluralizationKey = (count: number): keyof PluralizedEntry => count === 1 ? 'one' : 'other'; /** * Returns an entry from locale data. * * @param entry Locale data. * @param count Pluralization count, if applicable. * * @return Entry string or object. */ const getEntry = (strings: Entries, key: string): Entry => hasOwn(strings, key) ? strings[key] : key; /** * Returns true if the given entry is a pluralization entry, or false otherwise. * * @param entry Entry to test. * * @return Whether entry is a pluralization entry. */ const isPluralizedEntry = (entry: Entry): entry is PluralizedEntry => typeof entry === 'object' && 'one' in entry; /** * Returns true if the given entry is a string entry, or false otherwise. * * @param entry Entry to test. * * @return Whether entry is a string entry. */ const isStringEntry = (entry: Entry): entry is string => typeof entry === 'string'; /** * Returns the resulting string from the given entry, incorporating pluralization if necessary. * * @param entry Entry string or object. * @param count Pluralization count, if applicable. * * @return Entry string. */ function getString(entry: Entry, count?: number): string | string[] { if (isPluralizedEntry(entry)) { if (typeof count !== 'number') { throw new TypeError('Expected count for PluralizedEntry'); } return entry[getPluralizationKey(count)]; } return entry; } /** * Returns string with variable substitution. * * @param string Original string. * @param variables Variables to replace. * * @return String with variables substituted. */ export const replaceVariables = (string: string, variables: Variables): string => string.replace(/%{(\w+)}/g, (match, key) => (hasOwn(variables, key) ? variables[key] : match)); class I18n { strings: Entries; constructor({ strings }: I18nOptions = {}) { this.strings = Object.assign(Object.create(null), strings); this.t = this.t.bind(this); } /** * Returns the translated string by the given key. * * @param keyOrKeys Key or keys to retrieve. * @param variables Variables to substitute in string. * * @return Translated string. */ t(keyOrKeys: string, variables?: Variables): string; t(keyOrKeys: string[], variables?: Variables): string[]; t(keyOrKeys: string | string[], variables: Variables = {}): string | string[] { const isSingular = !Array.isArray(keyOrKeys); const keys: string[] = isSingular ? [keyOrKeys] : keyOrKeys; const entries = keys.map((key) => getEntry(this.strings, key)); const strings = entries .map((entry) => (isPluralizedEntry(entry) ? getString(entry, variables?.count) : entry)) .map((entry) => (isStringEntry(entry) ? replaceVariables(entry, variables) : entry)); return isSingular ? strings[0] : strings.flat(); } } // eslint-disable-next-line no-underscore-dangle const i18n = new I18n({ strings: globalThis._locale_data }); const { t } = i18n; export { I18n, i18n, t };
PHP
UTF-8
2,887
2.96875
3
[]
no_license
<?php //very nice --> https://www.sitepoint.com/counting-the-ago-time-how-to-keep-publish-dates-fresh/ define( 'TIMEBEFORE_NOW', 'just now' ); define( 'TIMEBEFORE_MINUTE', '{num} minute ago' ); define( 'TIMEBEFORE_MINUTES', '{num} minutes ago' ); define( 'TIMEBEFORE_HOUR', '{num} hour ago' ); define( 'TIMEBEFORE_HOURS', '{num} hours ago' ); define( 'TIMEBEFORE_YESTERDAY', 'yesterday' ); define( 'TIMEBEFORE_FORMAT', '%e %b' ); define( 'TIMEBEFORE_FORMAT_YEAR', '%e %b, %Y' ); function time_ago( $time ) { $out = ''; // what we will print out $now = time(); // current time $diff = $now - $time; // difference between the current and the provided dates if( $diff < 60 ) // it happened now return TIMEBEFORE_NOW; elseif( $diff < 3600 ) // it happened X minutes ago return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES ); elseif( $diff < 3600 * 24 ) // it happened X hours ago return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS ); elseif( $diff < 3600 * 24 * 2 ) // it happened yesterday return TIMEBEFORE_YESTERDAY; else // falling back on a usual date format as it happened later than yesterday return strftime( date( 'Y', $time ) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time ); } /** * returns a url from the uploaded image (imgur.com) */ function upload_img($filename, $fileSize) { /* debug_to_console($img); $filename = $img['tmp_name']; */ $client_id = "58c99d37e158363"; $handle = fopen($filename, "r"); $data = fread($handle, $fileSize); $pvars = array('image' => base64_encode($data)); $timeout = 30; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/upload'); curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id)); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars); $out = curl_exec($curl); curl_close ($curl); $pms = json_decode($out,true); $url= $pms['data']['link']; return $url; } function debug_to_console( $data ) { $output = $data; if ( is_array( $output ) ) $output = implode( ',', $output); echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>"; } function getFilePath($filename){ $filename = substr( $filename ,9, strlen($filename) - 1); $filename = substr( $filename, 0, -2); return $filename; } function getFileSize($fileSize){ $fileSize = substr( $fileSize ,8, strlen($fileSize) - 1); $fileSize = substr( $fileSize, 0, -1); return intval($fileSize); } ?>
C++
UTF-8
7,110
2.5625
3
[]
no_license
/* * SerialNodeNet.h * * Created on: 02.01.2018 * Author: rea */ #ifndef SERIALNODENET_H_ #define SERIALNODENET_H_ #include <stddef.h> #include "SerialNode.h" #include "OnMessageHandler.h" #include "OnPreConnectHandler.h" namespace SerialMsgLib{ class SerialNodeNet { public: virtual ~SerialNodeNet(); static SerialNodeNet* init(byte systemId); static SerialNodeNet* getInstance(); byte getSystemId(); /** * getProcessingNode(); * return the node which was currently processed by processNodes(); */ SerialNode* getProcessingNode(); void setProcessingNode(SerialNode* pNode); /* * SerialNode* SerialNodeNet::getNode(byte nodeId); * > nodeId ... id of node * > returns ... node */ SerialNode* getNode(byte nodeId); /** * SerialNode* getRootNode(); * return the first node in the node list */ SerialNode* getRootNode(); void setRootNode(SerialNode* pNode); SerialNode* getNodeByAcb(tAcb* pAcb); /** * static bool areAllNodesConnected(); * < returns ...true if all nodes connected , or no node found */ bool areAllNodesConnected(); /** * void update(byte* pMessage,size_t messageSize,SerialPort *pPort); * Is called if a message was received by serialRx. * It checks the address, and searches for the node * If a local node is found, it calls the onMessage routine of the node * If the node isn't found , it forwards the message. * >pMessage ...complete message: header (+data) * >messageSize ...size of header+data * >pPort ...the port on which the message was received * */ void update(const byte* pMessage, size_t messageSize, SerialPort *pPort); /** * forward(const byte* pMessage, size_t messageSize,SerialPort* pSourcePort) * A message received from pSourcePort but no node found in the system * If the node isn't found , it asks on all ports for * the remote systemId, if found it forwards the message exclusive to the port. * If not found, search for link (see forward) to a port * If no links found (which is supposed to be only in case of CR), * the message is sent to all ports without the ports that have the same remote systemId * as the message fromAddress. This means, it is only forwarded to other systems. * In case of connection request (CR): * 1. delete possibly existing link to remote system * 2. create a open link. * the link is closed by the ACK of the remote system */ bool forward(const byte* pMessage, size_t messageSize, SerialPort* pSourcePort); /** * static void SerialNode::processNodes(bool bLifeCheck); * this routine has to be put into the main loop * it reads on all ports for all nodes in the SerialNodeNet * > lifeCheck ...checks periodically all node connections (recommended) */ void processNodes(bool lifeCheck=true); /** * SerialNode* createNode(byte localNodeId, bool active=false, byte remoteSysId=0,byte remoteNodeId=0,SerialPort* pSerialPort=NULL); * factory method for SerialNodes * this is the proper method to create new nodes * * A SeriaNode can transmit and receive messages to other nodes. * To exchange messages the node have to be connected. * All local nodes are directly reachable. All remote nodes are reachable * over the ports. If you do not specify a specific serialport, the node tries to * send or receive on all ports until it is connected and the nodes port is set. * > localNodeId ... local address of this node . Must be unique for one system * > active ... true, node sends connection requests to remote node * ... false nodes waits for connection request from remote * > remoteSystemId ... the id of the remote system. All connected systems have a unique id * If set and node is active, it sends connection requests to the remote node(s). * If set and node is passive, it waits for CR from the remote node(s). * If not set and node is passive and waits to be connected from any active node * If not set and active, send CR to all remote passive system nodes, that wants * to connect. (first wins) * * > remoteNodeId ... id of the remote node, see remoteSystemId * If set and node is active, only try to connect to one remote node * If set and node is passive, only wait for connect to one remote node * If not set (or 0) and active try to connect to all remote nodes of a system (remoteSystemId) * If not set (or 0) and passive wait for connect to remote nodes a system (remoteSystemId) * > pSerialPort ... if set the node can only communicate over this port. */ SerialNode* createNode(byte localNodeId, bool active = false, byte remoteSysId = 0, byte remoteNodeId = 0,SerialPort* pSerialPort = NULL); /* * void setOnMessageHandler(OnMessageHandler* pOnMessageHandler) * set your MessageHandler for nodes * (>) pHeader Header of the received data, see OnMessageHandler.h * (>) pData Application Data * (>) datasize datasize of application data * (>) pNode node on that message was received */ void setOnMessageHandler(OnMessageHandler* pOnMessageHandler); /* * void callOnMessage(const tSerialHeader* pHeader, const byte* pData, size_t dataSize, SerialNode* pNode); * sets the user onMessageHandler, that handles all application messages */ void callOnMessage(const tSerialHeader* pHeader, const byte* pData, size_t dataSize, SerialNode* pNode); /* * setOnPreConnectHandler(OnPreConnectHandler& rOnPreConnectHandler) * sets a user preConnect handler, where a node can be set ready to connect (setReady()) */ void setOnPreConnectHandler(OnPreConnectHandler* pOnPreConnectHandler); /* * void callOnPreConnect(SerialNode* pNode); * is called by onMessage before a node is connected */ void callOnPreConnect(SerialNode* pNode); /* * void checkConnection(tStamp periodMsec = 1000); * check for all period msec for each node, if there was a message received * in the last second (see SERIALONODE_TIMELIFECHECK_LATE), if not it send a life message * if node is disconnected it sends a CR message * > period ...time period between the lifeChecks, default 500 msec */ void checkConnection(SerialNode* pNode,tStamp periodMsec = 500); /* * LcbList* getLcbList(); * List of links between ports * < returns ...the Link List */ LcbList* getLcbList(); private: // a single instance of SerialNodeNet static SerialNodeNet* pInst; SerialNodeNet(byte systemId); // the id of the local system // the node that is currently processed for life checking // if pProcessingNode has concurrent listener ports, the pProcessingNode's port is the current listener SerialNode* pProcessingNode=NULL; byte systemId=0; SerialNode* pSerialNodeList = NULL; LcbList lcbList; OnMessageHandler* pOnMessageHandler=NULL; OnPreConnectHandler* pOnPreConnectHandler=NULL; }; }; #endif /* SERIALNODENET_H_ */
JavaScript
UTF-8
409
2.78125
3
[]
no_license
var express = require('express') var axios = require('axios') var app = express() app.get('/', function(req, res) { axios.get('http://localhost:5000/message') .then(apiResp => { res.contentType = "text/html" res.status = 200 res.send("<h1>" + apiResp.data.message + "</h1>") }) }) app.listen(3000, () => console.log(`app listening on port ${3000}!`))
Java
UTF-8
952
2.171875
2
[]
no_license
package com.gaejangmo.apiserver.model.like.domain; import com.gaejangmo.apiserver.model.common.domain.BaseTimeEntity; import com.gaejangmo.apiserver.model.user.domain.User; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Getter @NoArgsConstructor @EqualsAndHashCode(of = "id", callSuper = false) public class Likes extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "user_source_id", foreignKey = @ForeignKey(name = "fk_user_to_source_likes")) private User source; @ManyToOne @JoinColumn(name = "user_target_id", foreignKey = @ForeignKey(name = "fk_user_to_likes_target")) private User target; @Builder public Likes(final User source, final User target) { this.source = source; this.target = target; } }
JavaScript
UTF-8
6,038
2.703125
3
[ "MIT" ]
permissive
HTMLDecorators.StdDecorators.Navigation = (function (document, window) { /** * Handles navigation * * @decorator Navigation * @decNamespace std * @decParam string id The id of the decorator * @decParam string activeClass The active classname for the links * @decParam string hashHandler The handler function for hash detection * @decParam string default The id of a @Content decorator to set active as default * @decParam boolean routes If routes are used or not * * @example navigation-content * @example navigation-hashhandler * * @class HTMLDecorators.StdDecorators.Navigation * @extends HTMLDecorators.Decorator * @constructor */ function Navigation() { HTMLDecorators.Decorator.call(this, { activeClass : 'active' }); /** * Returns a map of registered HTMLDecorators.StdDecorators.Content instances * * @var contentsMap * @memberOf HTMLDecorators.StdDecorators.Navigation * @type array */ this.contentsMap = {}; } HTMLDecorators.ExtendsClass(Navigation, HTMLDecorators.Decorator); /** * Sets a link active * * @param id The link id * @memberOf HTMLDecorators.StdDecorators.Navigation * @method setActive * @return void */ Navigation.prototype.setActive = function (id) { var links = this.element.querySelectorAll('a'), i = 0, len = links.length, link, content; for(i; i < len; ++i) { link = links[i]; link.classList.remove(this.config.activeClass); if(link.dataset.id == id) { link.classList.add(this.config.activeClass); } } for(var contentId in this.contentsMap) { content = this.contentsMap[contentId]; content.visibility.hide(); if(contentId == id) { content.visibility.show(); } } } /** * Routes to the default content * * @memberOf HTMLDecorators.StdDecorators.Navigation * @method toDefault * @return void */ Navigation.prototype.toDefault = function () { var dec; // timeout to wait till the decators have been rendered setTimeout(function() { if(dec = this.findById(this.config.default)) { this.setActive(this.config.default); } else { this.log('Cant find @Content with id "' + this.config.default + '"'); } }.bind(this),0); } /** * Renders the decorator * * @memberOf HTMLDecorators.StdDecorators.Navigation * @method render * @return void */ Navigation.prototype.render = function () { var links = this.element.querySelectorAll('a'), i = 0, len = links.length, link; for(i; i < len; ++i) { link = links[i]; link.onclick = function (e) { var dataset = e.currentTarget.dataset, dec, href = e.currentTarget.getAttribute('href'); if(typeof dataset.external != 'undefined') { return true; } if(href[0] != '#') { e.preventDefault(); } if(dec = this.findById(dataset.id)) { this.setActive(dataset.id); location.hash = dataset.id; } else { this.log('Decorator with ID "' + dataset.id + '" does not exist'); } }.bind(this); } if(this.paramExist('default')) { this.toDefault(); } if(this.paramExist('hashChangeHandler')) { window.addEventListener('hashchange', function (e) { this.callFunction(this.config.hashChangeHandler); }.bind(this),false); this.callFunction(this.config.hashChangeHandler); } } return Navigation; })(document, window); HTMLDecorators.StdDecorators.Content = (function (document, window) { /** * Handles content of a navigation * * @decorator Content * @decNamespace std * @decParam string nav The id of the @Navigation decorator * @decParam string id The id to the @Navigations a[data-id] attribute * * @example navigation-content * * @class HTMLDecorators.StdDecorators.Content * @extends HTMLDecorators.Decorator * @constructor */ function Content() { HTMLDecorators.Decorator.call(this); } HTMLDecorators.ExtendsClass(Content, HTMLDecorators.Decorator); /** * Initializes the decorator * * @memberOf HTMLDecorators.StdDecorators.Content * @method initialized * @return void */ Content.prototype.initialized = function () { this.visibility = this.createDecorator('Visible', HTMLDecorators.StdDecorators.Visible); } /** * Renders the decorator * * @memberOf HTMLDecorators.StdDecorators.Content * @method render * @return void */ Content.prototype.render = function () { this.visibility.hide(); // update references for when put with a @Component decorator this.visibility.element = this.element; this.visibility.id = this.id; var dec; if(dec = this.findById(this.config.nav)) { if(dec.name == 'Navigation') { dec.contentsMap[this.config.id] = this; } else { this.log('Decorator must be from type "Navigation"'); } } else { this.log('Could not find decorator with id "' + this.config.nav + '"'); } if(this.paramExist('visible') && this.config.visible=='true') { this.visibility.show(); } } return Content; })(document, window);
TypeScript
UTF-8
20,228
2.625
3
[ "MIT" ]
permissive
/// <reference path="./Android/Android.d.ts" /> declare namespace Titanium { /** * The top level Geolocation module. The Geolocation module is used for accessing device location based information. */ namespace Geolocation { /** * The user authorized the app to access location data with full accuracy. */ const ACCURACY_AUTHORIZATION_FULL: number; /** * The user authorized the app to access location data with reduced accuracy. */ const ACCURACY_AUTHORIZATION_REDUCED: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request the best * accuracy available. */ const ACCURACY_BEST: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request highest possible * accuracy and combine it with additional sensor data. */ const ACCURACY_BEST_FOR_NAVIGATION: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request more * accurate location updates with higher battery usage. */ const ACCURACY_HIGH: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request location * updates accurate to the nearest 100 meters. */ const ACCURACY_HUNDRED_METERS: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request location * updates accurate to the nearest kilometer. */ const ACCURACY_KILOMETER: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request less * accurate location updates with lower battery usage. */ const ACCURACY_LOW: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request location * updates accurate to the nearest 10 meters. */ const ACCURACY_NEAREST_TEN_METERS: number; /** * The level of accuracy used when an app isn’t authorized for full accuracy location data. */ const ACCURACY_REDUCED: number; /** * Use with [accuracy](Titanium.Geolocation.accuracy) to request location * updates accurate to the nearest three kilometers. */ const ACCURACY_THREE_KILOMETERS: number; /** * The location data is used for tracking location changes to the automobile specifically during vehicular navigation. */ const ACTIVITYTYPE_AUTOMOTIVE_NAVIGATION: string; /** * The location data is used for tracking any pedestrian-related activity. */ const ACTIVITYTYPE_FITNESS: string; /** * The location data is being used for an unknown activity. */ const ACTIVITYTYPE_OTHER: string; /** * The location data is used for tracking movements of other types of vehicular * navigation that are not automobile related. */ const ACTIVITYTYPE_OTHER_NAVIGATION: string; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the application is authorized to start location services at any time. This authorization * includes the use of all location services, including monitoring regions and significant location changes. */ const AUTHORIZATION_ALWAYS: number; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the application is authorized to use location services. * @deprecated Use [Titanium.Geolocation.AUTHORIZATION_ALWAYS](Titanium.Geolocation.AUTHORIZATION_ALWAYS) as advised by Apple. */ const AUTHORIZATION_AUTHORIZED: number; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the application is not authorized to use location services, *or* * location services are disabled. */ const AUTHORIZATION_DENIED: number; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the application is not authorized to use location servies *and* * the user cannot change this application's status. */ const AUTHORIZATION_RESTRICTED: number; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the authorization state is unknown. */ const AUTHORIZATION_UNKNOWN: number; /** * A [locationServicesAuthorization](Titanium.Geolocation.locationServicesAuthorization) value * indicating that the application is authorized to start most location services only while running in the foreground. */ const AUTHORIZATION_WHEN_IN_USE: number; /** * Error code indicating that the user denied access to the location service. */ const ERROR_DENIED: number; /** * Error code indicating that the heading could not be determined. */ const ERROR_HEADING_FAILURE: number; /** * Error code indicating that the user's location could not be determined. */ const ERROR_LOCATION_UNKNOWN: number; /** * Error code indicating that the network was unavailable. */ const ERROR_NETWORK: number; /** * Error code indicating that region monitoring is delayed. */ const ERROR_REGION_MONITORING_DELAYED: number; /** * Error code indicating that region monitoring is denied. */ const ERROR_REGION_MONITORING_DENIED: number; /** * Error code indicating a region monitoring failure. */ const ERROR_REGION_MONITORING_FAILURE: number; } /** * Base event for class Titanium.Geolocation */ interface GeolocationBaseEvent extends Ti.Event { /** * Source object that fired the event. */ source: Titanium.Geolocation; } /** * Fired when the device detects interface and requires calibration. */ interface Geolocation_calibration_Event extends GeolocationBaseEvent { } /** * Fired when an heading update is received. */ interface Geolocation_heading_Event extends GeolocationBaseEvent { /** * If `success` is `false`, the error code is available. */ code: number; /** * If `success` is false, a string describing the error. */ error: string; /** * Dictionary object containing the heading data. */ heading: HeadingData; /** * Indicate if the heading event was successfully received. Android returns this since SDK 7.5.0. */ success: boolean; } /** * Fired when a location update is received. */ interface Geolocation_location_Event extends GeolocationBaseEvent { /** * if `success` is false, the error code if available. */ code: number; /** * If `success` is true, actual location data for this update. */ coords: LocationCoordinates; /** * If `success` is false, a string describing the error. */ error: string; /** * If `success` is true, object describing the location provider generating this update. */ provider: LocationProviderDict; /** * Indicates if location data was successfully retrieved. */ success: boolean; } /** * Fired when location updates are paused by the OS. */ interface Geolocation_locationupdatepaused_Event extends GeolocationBaseEvent { } /** * Fired when location manager is resumed by the OS. */ interface Geolocation_locationupdateresumed_Event extends GeolocationBaseEvent { } /** * Fired when changes are made to the authorization status for location services. */ interface Geolocation_authorization_Event extends GeolocationBaseEvent { /** * New authorization status for the application. */ authorizationStatus: number; } interface GeolocationEventMap extends ProxyEventMap { authorization: Geolocation_authorization_Event; calibration: Geolocation_calibration_Event; heading: Geolocation_heading_Event; location: Geolocation_location_Event; locationupdatepaused: Geolocation_locationupdatepaused_Event; locationupdateresumed: Geolocation_locationupdateresumed_Event; } /** * The top level Geolocation module. The Geolocation module is used for accessing device location based information. */ class Geolocation extends Titanium.Module { /** * Specifies the requested accuracy for location updates. */ static accuracy: number; /** * The type of user activity to be associated with the location updates. */ static activityType: number; /** * Determines if the app can do background location updates. */ static allowsBackgroundLocationUpdates: boolean; /** * The name of the API that this proxy corresponds to. */ static readonly apiName: string; /** * Indicates if the proxy will bubble an event to its parent. */ static bubbleParent: boolean; /** * The minimum change of position (in meters) before a 'location' event is fired. */ static distanceFilter: number; /** * Requested frequency for location updates, in milliseconds. * @deprecated Android legacy mode operation is deprecated. For new development, use * either simple mode or manual mode. See "Configurating Location Updates on Android" * in the main description of this class for more information. * */ static frequency: never; /** * Indicates whether the current device supports a compass. */ static readonly hasCompass: boolean; /** * Minimum heading change (in degrees) before a `heading` event is fired. */ static headingFilter: number; /** * JSON representation of the last geolocation received. */ static readonly lastGeolocation: string; /** * The Window or TabGroup whose Activity lifecycle should be triggered on the proxy. */ static lifecycleContainer: Titanium.UI.Window | Titanium.UI.TabGroup; /** * A value that indicates the level of location accuracy the app has permission to use. */ static readonly locationAccuracyAuthorization: number; /** * Returns an authorization constant indicating if the application has access to location services. */ static readonly locationServicesAuthorization: number; /** * Indicates if the user has enabled or disabled location services for the device (not the application). */ static readonly locationServicesEnabled: boolean; /** * Indicates whether the location updates may be paused. */ static pauseLocationUpdateAutomatically: boolean; /** * Determines the preferred location provider. * @deprecated Android legacy mode operation is deprecated. For new development, use * either simple mode or manual mode. See "Configurating Location Updates on Android" * in the main description of this class for more information. * */ static preferredProvider: never; /** * Specifies that an indicator be shown when the app makes use of continuous * background location updates. */ static showBackgroundLocationIndicator: boolean; /** * Determines whether the compass calibration UI is shown if needed. */ static showCalibration: boolean; /** * Indicates if the location changes should be updated only when a significant change * in location occurs. */ static trackSignificantLocationChange: boolean; /** * Adds the specified callback as an event listener for the named event. */ static addEventListener<K extends keyof GeolocationEventMap>(name: K, callback: (this: Titanium.Geolocation, event: GeolocationEventMap[K]) => void): void; /** * Adds the specified callback as an event listener for the named event. */ static addEventListener(name: string, callback: (param0: Titanium.Event) => void): void; /** * Applies the properties to the proxy. */ static applyProperties(props: any): void; /** * Fires a synthesized event to any registered listeners. */ static fireEvent<K extends keyof GeolocationEventMap>(name: K, event?: GeolocationEventMap[K]): void; /** * Fires a synthesized event to any registered listeners. */ static fireEvent(name: string, event?: any): void; /** * Resolves an address to a location. */ static forwardGeocoder(address: string, callback?: (param0: ForwardGeocodeResponse) => void): Promise<ForwardGeocodeResponse>; /** * Retrieves the current compass heading. */ static getCurrentHeading(callback?: (param0: HeadingResponse) => void): Promise<HeadingResponse>; /** * Retrieves the last known location from the device. */ static getCurrentPosition(callback?: (param0: LocationResults) => void): Promise<LocationResults>; /** * Returns `true` if the app has location access. */ static hasLocationPermissions(authorizationType: number): boolean; /** * Removes the specified callback as an event listener for the named event. */ static removeEventListener<K extends keyof GeolocationEventMap>(name: K, callback: (this: Titanium.Geolocation, event: GeolocationEventMap[K]) => void): void; /** * Removes the specified callback as an event listener for the named event. */ static removeEventListener(name: string, callback: (param0: Titanium.Event) => void): void; /** * Requests for location access. */ static requestLocationPermissions(authorizationType: number, callback?: (param0: LocationAuthorizationResponse) => void): Promise<LocationAuthorizationResponse>; /** * Requests the user's permission to temporarily use location services with full accuracy. */ static requestTemporaryFullAccuracyAuthorization(purposeKey: string, callback: (param0: LocationAccuracyAuthorizationResponse) => void): void; /** * Tries to resolve a location to an address. */ static reverseGeocoder(latitude: number, longitude: number, callback?: (param0: ReverseGeocodeResponse) => void): Promise<ReverseGeocodeResponse>; } } /** * Simple object returned in the callback from the * [forwardGeocoder](Titanium.Geolocation.forwardGeocoder) method. * Note that Android includes a number of extra fields. */ interface ForwardGeocodeResponse extends ErrorResponse { /** * Estimated accuracy of the geocoding, in meters. */ accuracy?: number; /** * Full address. */ address?: string; /** * City name. */ city?: string; /** * Error code. Returns 0 if `success` is `true`. */ code?: number; /** * Country name. */ country?: string; /** * Country code. */ countryCode?: string; /** * Country code. Same as `countryCode`. */ country_code?: string; /** * Display address. Identical to `address`. */ displayAddress?: string; /** * Error message, if any returned. */ error?: string; /** * Latitude of the geocoded address. */ latitude?: string; /** * Longitude of the geocoded address. */ longitude?: string; /** * Postal code. */ postalCode?: string; /** * First line of region. */ region1?: string; /** * Not used. */ region2?: string; /** * Street name, without street address. */ street?: string; /** * Street name. */ street1?: string; /** * Indicates if the operation succeeded. */ success?: boolean; } /** * Simple object representing a place, returned in the callback from the * [reverseGeocoder](Titanium.Geolocation.reverseGeocoder) method. */ interface GeocodedAddress { /** * Full address. */ address?: string; /** * City name. */ city?: string; /** * Country name. */ country?: string; /** * Country code. */ countryCode?: string; /** * Country code. To be replaced by `countryCode`. * @deprecated Use the `countryCode` property for parity. */ country_code: never; /** * Display address. Identical to `address`. * @deprecated Use the `address` property for parity. */ displayAddress: never; /** * Latitude of the geocoded point. */ latitude?: number; /** * Longitude of the geocoded point. */ longitude?: number; /** * Postal code */ postalCode?: string; /** * First line of region. */ region1?: string; /** * Not used. */ region2?: string; /** * State name. */ state?: string; /** * Street name, without street address. */ street?: string; /** * Street name. */ street1?: string; /** * Postal code. To be replaced by `postalCode` * @deprecated Use the `postalCode` property for parity. */ zipcode: never; } /** * Simple object holding compass heading data. */ interface HeadingData { /** * Accuracy of the compass heading, in platform-specific units. */ accuracy?: number; /** * Declination in degrees from magnetic North. */ magneticHeading?: number; /** * Timestamp for the heading data, in milliseconds. */ timestamp?: number; /** * Declination in degrees from true North. */ trueHeading?: number; /** * Raw geomagnetic data for the X axis. */ x?: number; /** * Raw geomagnetic data for the Y axis. */ y?: number; /** * Raw geomagnetic data for the Z axis. */ z?: number; } /** * Argument passed to the [getCurrentHeading](Titanium.Geolocation.getCurrentHeading) callback. */ interface HeadingResponse extends ErrorResponse { /** * Error code. */ code?: number; /** * Error message, if any returned. */ error?: string; /** * If `success` is true, the actual heading data. */ heading?: HeadingData; /** * Indicates a successful operation. */ success?: boolean; } /** * Argument passed to the callback when a request finishes successfully or erroneously. */ interface LocationAccuracyAuthorizationResponse extends ErrorResponse { /** * The level of location accuracy the app has granted. */ accuracyAuthorization?: number; } /** * Argument passed to the callback when a request finishes successfully or erroneously. */ interface LocationAuthorizationResponse extends ErrorResponse { } /** * Simple object holding the data for a location update. */ interface LocationCoordinates { /** * Accuracy of the location update, in meters. */ accuracy?: number; /** * Altitude of the location update, in meters. */ altitude?: number; /** * Vertical accuracy of the location update, in meters. */ altitudeAccuracy?: number; /** * The floor of the building on which the user is located. */ floor?: LocationCoordinatesFloor; /** * Compass heading, in degrees. May be unknown if device is not moving. On * iOS, a negative value indicates that the heading data is not valid. */ heading?: number; /** * Latitude of the location update, in decimal degrees. */ latitude?: number; /** * Longitude of the location update, in decimal degrees. */ longitude?: number; /** * Current speed in meters/second. On iOS, a negative value indicates that the * heading data is not valid or the accuracy is configured incorrectly. * Note: Due to the Apple Geolocation API, set the <Titanium.Geolocation.accuracy> * property to <Titanium.Geolocation.ACCURACY_BEST_FOR_NAVIGATION> in order to properly * measure speed changes and prevent the app from returning negative values. */ speed?: number; /** * Timestamp for this location update, in milliseconds. */ timestamp?: number; } /** * Simple object holding floor of the building on which the user is located. */ interface LocationCoordinatesFloor { /** * The logical floor of the building. */ level?: number; } /** * Simple object describing a location provider. */ interface LocationProviderDict { /** * Accuracy of the location provider, either fine (1) or coarse (2). */ accuracy?: number; /** * Name of the location provider. */ name?: string; /** * Power consumption for this provider, either low (1), medium (2), or high (3). */ power?: number; } /** * Argument passed to the [getCurrentPosition](Titanium.Geolocation.getCurrentPosition) callback. */ interface LocationResults extends ErrorResponse { /** * If `success` is true, actual location data for this update. */ coords?: LocationCoordinates; /** * If `success` is true, object describing the location provider generating this update. */ provider?: LocationProviderDict; } /** * Simple object returned in the callback from the * [reverseGeocoder](Titanium.Geolocation.reverseGeocoder) method. */ interface ReverseGeocodeResponse extends ErrorResponse { /** * Error code. Returns 0 if `success` is `true`. */ code?: number; /** * Error message, if any returned. */ error?: string; /** * An array of reverse-geocoded addresses matching the requested location. */ places?: GeocodedAddress[]; }
Python
UTF-8
1,008
3.015625
3
[]
no_license
import wget,os import pandas as pd def url(expert): if expert.lower() in ["a", "b", "c", "d", "e"]: return "https://data.csail.mit.edu/graphics/fivek/img/tiff16_" + expert.lower() + "/" return -1 def images_names(): categories = pd.read_csv("categories.txt") names = categories["names"] images = [name + ".tif" for name in names] return images def get_dataset(expert): SOURCE = url(expert) names = images_names() out_dir = "Expert_" + str(expert).upper() if not os.path.isdir(out_dir): os.mkdir(out_dir) for name in names: image_url = SOURCE + name if not os.path.exists(os.path.join(out_dir, name)): try: image = wget.download(image_url, out = out_dir) print("\nSuccessfully downloaded " + name) except Exception as e: print(e) def main(): expert = input("Type the expert (A-E , a-e): ") get_dataset(expert) if __name__ == "__main__": main()
C#
UTF-8
4,457
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Specialized; namespace Views.Util { /// <summary> /// Applies an index offset into a source view, with modulus. /// </summary> /// <typeparam name="T">The type of element observed by the view.</typeparam> public sealed class OffsetView<T> : SourceViewBase<T> { /// <summary> /// The offset into the source view where this view begins. This offset is added when reading. /// </summary> private readonly int offset; /// <summary> /// Initializes a new instance of the <see cref="OffsetView&lt;T&gt;"/> class. /// </summary> /// <param name="source">The source view.</param> /// <param name="offset">The offset into the source view where this view begins. This offset may be negative.</param> public OffsetView(IView<T> source, int offset) : base(source) { this.offset = offset; } /// <summary> /// Gets the offset into the source view where this view begins. This offset may be negative. /// </summary> public int Offset { get { return this.offset; } } /// <summary> /// Gets the item at the specified index. /// </summary> /// <param name="index">The index of the item to get.</param> public override T this[int index] { get { return this.source[this.ViewToSourceIndex(index)]; } } /// <summary> /// A notification that the source collection has added an item. /// </summary> /// <param name="collection">The collection that changed.</param> /// <param name="index">The index of the new item.</param> /// <param name="item">The item that was added.</param> public override void Added(INotifyCollectionChanged collection, int index, T item) { this.CreateNotifier().Reset(); } /// <summary> /// A notification that the source collection has removed an item. /// </summary> /// <param name="collection">The collection that changed.</param> /// <param name="index">The index of the removed item.</param> /// <param name="item">The item that was removed.</param> public override void Removed(INotifyCollectionChanged collection, int index, T item) { this.CreateNotifier().Reset(); } /// <summary> /// A notification that the source collection has replaced an item. /// </summary> /// <param name="collection">The collection that changed.</param> /// <param name="index">The index of the item that changed.</param> /// <param name="oldItem">The old item.</param> /// <param name="newItem">The new item.</param> public override void Replaced(INotifyCollectionChanged collection, int index, T oldItem, T newItem) { this.CreateNotifier().Replaced(this.SourceToViewIndex(index), oldItem, newItem); } /// <summary> /// Takes an index and applies a modulus so that it is in the range <c>[0, <see cref="SourceViewBase{T}.Count"/>)</c>. /// </summary> /// <param name="index">The index to normalize.</param> /// <returns>The normalized index.</returns> private int NormalizeIndex(int index) { var count = this.Count; index %= count; if (index < 0) index += count; return index; } /// <summary> /// Converts a view index to a source index. /// </summary> /// <param name="index">The index to convert.</param> /// <returns>The converted index.</returns> private int ViewToSourceIndex(int index) { return this.NormalizeIndex(index + this.offset); } /// <summary> /// Converts a source index to a view index. /// </summary> /// <param name="index">The index to convert.</param> /// <returns>The converted index.</returns> private int SourceToViewIndex(int index) { return this.NormalizeIndex(index - this.offset); } } }
Markdown
UTF-8
7,588
2.9375
3
[ "MIT" ]
permissive
--- layout: post title: iOS中的机器学习 date: 2017-04-26 categories: iOS cover: /img/iOS_ML/apple-ml.png author: 永超 --- 随着iOS 11的发布,苹果公司也正是加入到了机器学习的战场。在新的iOS 11中,苹果内置了CoreML机器学习框架,并完全支持iOS、watchOS、macOS和tvOS。苹果希望开发者使用这些框架来整合机器学习到他们的应用程序中,而不用去考虑框架是如何工作的。苹果还表示,开发者不必一定是机器学习工作者,相反,开发者只需要将训练好的模型使用其提供的工具转化为所支持的文件格式即可,不必考虑机器学习算法,只需要专注于应用程序的用户体验。 CoreML除了支持层数超过30层的深度学习之外,还支持决策树的融合、SVM、线性模型等,由于其底层建立在Metal和Accelerate等技术上,能够最大限度的发挥CPU和GPU的优势,因此在可以在移动设备上直接运行机器学习模型,数据可以不用离开设备直接被分析等。 苹果也在大力的宣传CoreML框架,在WWDC之后,有多个Machine Learning的session,基本上都是在介绍iOS中的机器学习该如何使用等最佳实践,从其session中可以看到目前iOS系统应用中已经有部分应用程序使用了机器学习,来提高应用程序的用户体验: * 相册 --- 场景识别、人类识别 * 键盘 --- 智能响应、下一个字的预测 * Apple Watch --- 智能响应、手写预测 * 相机 --- 实时图像识别 * Siri --- 智能分词、机器人 在构建机器学习的工程中需要两个步骤 --- 训练和推理。 训练包括 --- 学习算法,注意可能的行为和尽量在一个实体中收集所有的行为。在iOS机器学习情况下,苹果公司推出了MLModel的概念。模型将所有行为,属性,特征以及您认为的任何内容集合到一个实体中。 模型在这里起关键作用。 iOS中的机器学习不能没有模型,模型可以被认为是训练机器或代码的结果。模型由下一步可以使用的所有功能组成 - 推理。 推理包括 --- 传递对象数据到模型,模型给出相应的结果,而这些结果将作为具体应用程序业务逻辑数据来使用。 这种训练和推理的过程更多的来自于实证方式,而不是纯理论的呈现。 苹果公司更加的希望开发者去进行推理而不是训练,训练是一个庞大的任务,并且会有很多的模型被贡献,开发者可以直接使用这些模型从而忽略训练的过程,直接进行推理并得到对应的结果来使用。 在WWDC session的视频讲座中介绍到,iOS的机器学习是一个分层的架构,顶层是用户直接体验机器学习结果的应用程序,在应用程序的底层有iOS机器学习的各类框架以供使用。 ![](/img/iOS_ML/apple-ml-layer.png) 应用程序直接访问第二层 - Vision,NLP,GamePlayKit框架。 Vision用于处理图像,视频,音频 - 如人脸检测,跟踪对象等。NLP更多地依赖于文本处理,识别语言等。大多数基本机器学习功能可以使用这些特定于领域的框架来访问。而GamePlayKit通常用于游戏中的,当然在应用程序中也可以使用其相关的机器学习特性。 虽然有些功能不属于Vision,NLP这两个类别,但是可以使用第三层 - CoreML框架实现。 这也是苹果新增的一个框架,它是基础机器学习框架,涉及深度和标准的学习过程。 它以数字,文字,图像等的形式进行输入,可用于标注图像、实时视频描述等。 所有这些框架都建立在Accelerate和Metal框架之上,构成了第四层和最后一层。 这些可以在CPU或者GPU上进行数学运算,也可以用于创建自定义模型,使得硬件能够发挥其最大的性能。 说到模型,有各种各样的类型 --- 预测文字,情感分析,音乐标签,手写识别,风格转移,场景分类,翻译等。MLModel支持树形组合,前馈神经网络,递归神经网络,广义线性模型,向量机,卷积神经网络等。 我们在哪里得到模型? 苹果在其[网站](https://developer.apple.com/machine-learning/)上提供了4个模型等等。 为了方便开发者创建自己的定制模型,苹果还推出了模型转化工具[CoreML Tools](https://pypi.python.org/pypi/coremltools)。 * 它是一个标准的Python包 * 将机器学习模型转化为MLModels * 它有3层 --- 转换器,CoreML绑定和转换库,以及CoreML规范 * 转换器 - 将模型从其他格式转换为CoreML接受的形式 * CoreML绑定 - 获取模型的Python包的预测和结果 * 转换器库 - 这是用于构建转换器的高级API * CoreML规范 - 自己编写新模型。 接下来看看如何在应用程序中实现基本的机器学习功能。 我们的目标是使用Apple提供的[Inceptionv3](https://docs-assets.developer.apple.com/coreml/models/Inceptionv3.mlmodel)图像分类模型,分类图像并获得图像描述。 1. 获取模型,并将其包含在应用程序中 2. 进行相关的编码 当我们将模型添加进Xcode中并包含在当前工程后,Xcode便于自动识别模型为MLModel,并生成相应的类供调用。 ![](/img/iOS_ML/xcode-mlmodel.png) 该应用程序包含一个ImageView,描述该图像的Label以及一个选择图像的Button。 ![](/img/iOS_ML/xcode-storyboard.png) 我们的目标使用逻辑伪代码表示如下: ``` let model = Inceptionv3() if let prediction = try? model.prediction(image: image as) {//Make sure the image is in CVPixelBufferFormat descriptionLabel.text = prediction.classLabel } else { descriptionLabel.text = "Oops. Error in processing!!" } ``` 在上述伪代码中,我们需要将UIImage转为CVPixelBufferFormat格式,但是这却比较的费劲,还记得上面提到过的Vision框架吗?其实Vision框架提供了相应的API供我们转化使用。 在开始之前,我们需要导入相关的框架: ``` swfit import CoreML import Vision ``` 接下来需要一步步完成如下步骤: * 使用`VNCoreMLModel `获取模型类 * 通过提供的模型创建请求`request` * 在Block回调中,使用请求响应,并从`VNClassificationObservation `中获得结果 * 该结果数组中的第一个会给出与图像匹配最高的分类标签 代码如下: ``` swift func makePrediction(image: CVPixelBuffer) { if let model = try? VNCoreMLModel(for: Inceptionv3().model) { // get the model let request = VNCoreMLRequest(model: model) { [weak self] response, error in // create a request using the model if let results = response.results as? [VNClassificationObservation], let topResult = results.first{ DispatchQueue.main.async { [weak self] in self?.label.text = "\(topResult.identifier)\n\(Int(topResult.confidence * 100))% Sure"//Update the label } } } //The following is to perform the request let handler = VNImageRequestHandler(ciImage: CIImage(image: imageView.image!)!) DispatchQueue.global(qos: .userInteractive).async { do { try handler.perform([request]) } catch { print(error) } } } } ``` 主要的代码部分完成了,经过其他的完善,应用程序的表现如下: ![](/img/iOS_ML/IMG_0007.PNG)
Shell
UTF-8
471
3.125
3
[]
no_license
#!/bin/bash PROTOCOL=http # or https FRONTEND_IP=$(dig +short @${CONSUL_ADDR} -p 8600 frontend.service.consul) PUBLIC_IP=$(aws ec2 describe-instances --filter Name=private-ip-address,Values=${FRONTEND_IP} Name=instance-state-name,Values=running --query Reservations[*].Instances[*].PublicIpAddress[][] --output text ) PORT=$(dig +short @${CONSUL_ADDR} -p 8600 frontend.service.consul srv | awk 'NR==1 { printf "%s", $3 }') echo ${PROTOCOL}://${PUBLIC_IP}:${PORT}
Java
UTF-8
1,739
2.796875
3
[]
no_license
import java.awt.*; import java.util.LinkedList; import java.util.List; import java.util.Random; public class Enemy extends GameObject { private Maze maze; int vv=1; int yy=0; Coordinate start; LinkedList<Vertex> pathVertex; public Enemy(float x, float y, int width, int height, ID id, Maze maze) { super(x, y, width, height, id); this.maze = maze; vv = 1; start = maze.start; } @Override public void tick() { if (this.maze.start != start) { start = this.maze.start; yy = 0; } BFSMazeSolverVertex bfsv = new BFSMazeSolverVertex(); pathVertex = bfsv.BFSMazeSolverVertex(maze); } @Override public boolean collision() { return false; } @Override public void render(Graphics g) { yy = yy + vv; if(pathVertex.size() > yy){ this.setX((int) pathVertex.get(yy).getRectangle().getX()); this.setY((int) pathVertex.get(yy).getRectangle().getY()); maze.end = new Coordinate((int)this.getX(), (int)this.getY());} if(id == ID.Enemy) g.setColor(Color.yellow); int radius = 40; int centerX = 50; int centerY = 100; int angle = 30; int dx = (int) (radius * Math.cos(angle * Math.PI / 180)); int dy = (int) (radius * Math.sin(angle * Math.PI / 180)); g.fillArc((int) x* Game.GRID_SIZE, (int) y* Game.GRID_SIZE, width* Game.GRID_SIZE, height* Game.GRID_SIZE, angle, 360 - 2 * angle); // g.fillRect((int) x* Game.GRID_SIZE,(int) y* Game.GRID_SIZE,width* Game.GRID_SIZE,height* Game.GRID_SIZE); } @Override public Rectangle getBounds() { return null; } }
Java
UTF-8
2,931
2.453125
2
[]
no_license
package com.example.demo; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.tomcat.util.codec.binary.Base64; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.interfaces.RSAPublicKey; import java.security.spec.X509EncodedKeySpec; @Component public class TokenFilter implements Filter { public static RSAPublicKey getPublicKey(String key) throws GeneralSecurityException { byte[] encoded = Base64.decodeBase64(key); return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encoded)); } private boolean tokenVerifier(String token) throws GeneralSecurityException { token = token.replace("Bearer", ""); DecodedJWT jwt = JWT.decode(token); ResponseEntity<String> response = new RestTemplate().getForEntity(jwt.getIssuer(), String.class); if(response.getStatusCodeValue() == 200){ String publicKey = new Gson().fromJson(response.getBody(), JsonObject.class).get("public_key").getAsString(); try { Algorithm algorithm = Algorithm.RSA256(getPublicKey(publicKey), null); JWTVerifier verifier = JWT.require(algorithm).build(); verifier.verify(token); return true; } catch (Exception e){ System.out.println("Exception in verifying " + e.toString()); return false; } } else { return false; } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse; try { if (tokenVerifier(httpServletRequest.getHeader("Authorization").replace("Bearer ", ""))) { filterChain.doFilter(servletRequest, servletResponse); } else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } catch (GeneralSecurityException | JWTDecodeException e) { e.printStackTrace(); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } }
PHP
UTF-8
1,094
2.578125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateElementsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('elements', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('num'); $table->float('difficulte'); $table->string('nom'); $table->boolean('envol'); $table->boolean('accro')->nullable(); $table->boolean('BI')->comment('Barre Inférieure'); $table->boolean('BS')->comment('Barre Supérieure'); $table->string('image')->nullable(); $table->timestamps(); $table->foreignId('agres_id')->constrained(); $table->foreignId('famille_id')->constrained(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('elements'); } }
PHP
UTF-8
3,431
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Livewire; use App\Helpers\Tools; use Livewire\Component; class TextTools extends Component { public $string = ''; public $charCount = 0; public $wordCount = 0; public $lineCount = 0; public $paraCount = 0; public function updatedString() { $this->string = mb_convert_encoding($this->string, 'UTF-8', 'UTF-8'); $this->charCount = strlen($this->string); $this->wordCount = str_word_count($this->string); // $this->lineCount = substr_count($this->string, "\n"); $this->lineCount = empty($this->string) ? 0 : count(explode("\n", $this->string)); // $this->paraCount = substr_count($this->string, "\n\n"); $this->paraCount = empty($this->string) ? 0 : count(explode("\n\n", $this->string)); } public function resetClear() { $this->string = ''; $this->charCount = 0; $this->wordCount = 0; $this->lineCount = 0; $this->paraCount = 0; } public function getLower() { $this->string = Tools::text()->lowerCase($this->string); } public function getUpper() { $this->string = Tools::text()->upperCase($this->string); } public function titleCase() { $this->string = Tools::text()->titleCase($this->string); } public function capitalize() { $this->string = Tools::text()->capitalize($this->string); } public function swapCase() { $this->string = Tools::text()->swapCase($this->string); } public function reverseText() { $this->string = Tools::text()->reverseText($this->string); } public function removeAccents() { $this->string = Tools::text()->removeAccents($this->string); } public function tabsToSpaces() { $this->string = Tools::text()->tabsToSpaces($this->string); } public function spacesToTabs() { $this->string = Tools::text()->spacesToTabs($this->string); } public function spacesToNewlines() { $this->string = Tools::text()->spacesToNewlines($this->string); } public function newlinesToSpaces() { $this->string = Tools::text()->newlinesToSpaces($this->string); } public function removeExtraWhiteSpace() { $this->string = Tools::text()->removeExtraWhiteSpace($this->string); } public function removeAllWhiteSpace() { $this->string = Tools::text()->removeAllWhiteSpace($this->string); } public function extractEmails() { $this->string = Tools::text()->extractEmails($this->string); } public function extractURLs() { $this->string = Tools::text()->extractURLs($this->string); } public function extractNumbers() { $this->string = Tools::text()->extractNumbers($this->string); } public function morseToText() { $this->string = Tools::text()->morseToText($this->string); } public function textToMorse() { $this->string = Tools::text()->textToMorse($this->string); } public function countCharFreq() { $this->string = Tools::text()->countCharFreq($this->string); } public function countWordFreq() { $this->string = Tools::text()->countWordFreq($this->string); } public function render() { return view('livewire.text-tools'); } }
Ruby
UTF-8
1,287
3.359375
3
[]
no_license
def lattice_path(array) temp = [] sum = 0 count = 0 while count < array.length - 1 sum = sum + array[count] puts sum temp.push(sum) count += 1 end temp.push(array.last) sum = 0 sum = temp.inject(:+) * 2 temp.push(sum) return temp end # below works, just not dynamic arr = [1, 3, 6, 20] def lattice_path(array) temp = [1] sum = array[0] + array[1] temp << sum sum = sum + array[2] temp << sum temp << array.last sum = temp.inject(:+) temp << (sum * 2) return temp end # below works... now just need to make it recursive and add the grid number def lattice_path(array) temp = [1] count = 2 sum = array[0] + array[1] temp.push(sum) while count < array.length - 1 sum = sum + array[count] temp << sum count += 1 end temp << array.last sum = temp.inject(:+) temp << (sum * 2) return temp end def lattice_path(array, grid) return array.last if array[1] == grid temp = [1] count = 2 sum = array[0] + array[1] temp.push(sum) while count < array.length - 1 sum = sum + array[count] temp << sum count += 1 end temp << array.last sum = temp.inject(:+) temp << (sum * 2) lattice_path(temp, grid) end #=> 137846528820 #has not been verified!
JavaScript
UTF-8
287
3.0625
3
[]
no_license
// ES6 允许为函数的参数设置默认值, 即直接写在参数定义的后面 function loglog(x,y='world'){ console.log(x,y) } loglog('hello') function fetch(url,{body = '', method = 'GET' , headers={}}){ console.log(method); } //GET fetch('http://wanglinzhizhi.me',{});
Python
UTF-8
1,114
2.84375
3
[ "MIT" ]
permissive
from django.test import TestCase from django.urls import reverse from .models import Post class TestingPosts(TestCase): def setUp(self): """Setting up common variables in this method""" Post.objects.create(text='This is a test post') def test_post_name(self): """Test that the post name is correct""" post_object = Post.objects.get(id=1) expected_text = f"{post_object.text}" self.assertEqual(expected_text, "This is a test post") def test_if_the_page_loads(self): """Twst if the response is 200 when the page is requested""" res = self.client.get('') self.assertEqual(res.status_code, 200) def test_that_the_page_loads_using_urls_name(self): """Test that HomePageView is called when request the right url""" res = self.client.get(reverse('home')) self.assertEqual(res.status_code, 200) def test_that_the_right_template_is_used(self): """Test that the righttemplate is called by the view""" res = self.client.get(reverse('home')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'posts/home.html')
SQL
UTF-8
397
2.765625
3
[]
no_license
------------------------------------------------------------------ -- 삭제(Delete) : 존재하는 데이터를 제거하는 것 ------------------------------------------------------------------ SELECT * FROM PRODUCT p; -- [1] 유통기한이 지난 상품의 정보를 삭제 DELETE product WHERE expire < sysdate; -- [2] 상품번호가 5번인 상품을 삭제 DELETE product WHERE NO = 5;
PHP
UTF-8
1,120
2.578125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace backend\models; use Yii; /** * This is the model class for table "taxonomy_items". * * @property integer $id * @property integer $vid * @property string $name */ class TaxonomyItems extends \yii\db\ActiveRecord { public $_parent; /** * @inheritdoc */ public static function tableName() { return '{{%taxonomy_items}}'; } /** * @inheritdoc */ public function rules() { return [ [['vid', 'name'], 'required'], [['vid', 'pid', 'weight'], 'integer'], [['parent'], 'safe'], [['name'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'vid' => 'Vid', 'name' => 'Name', 'parent' => 'Parent', ]; } public function getParent() { return $this->hasOne(self::className(), ['id' => 'pid']); } public function setParent($data) { if (is_numeric($data['name'])) $this->pid = $data['name']; } }
PHP
UTF-8
2,153
2.578125
3
[]
no_license
<?php namespace Main\Command; use Main\Command\Command; use \Main\Misc\Registry; use \Main\Misc\Request; use \Main\Misc\Response; use \Main\EventCheck; use Main\db; use \Main\Events; require_once 'Command.php'; require_once 'Request.php'; require_once 'Response.php'; require_once 'db.php'; require_once 'EventCheck.php'; require_once 'Events.php'; class UsersCommand extends Command { public function Execute(Request $request) { $db = new db(); $eventGet = new Events(); $response = Registry::Instance()->Response; $time = $_SESSION['time']; $start = date("Y-m-d", strtotime('2018-11-27')); $end = date("Y-m-d", strtotime('2019-01-18')); if ($eventGet->isDateInRange($start, $end, $time)) { $event = $db->getLtdDragons(28); } else { $event = new EventCheck(); $ltd = $event->checkSeason(); $season = $db->getLtdDragons($ltd); $ltd = $event->checkMonth(); $month = $db->getLtdDragons($ltd); $ltd = $event->checkQuarter(); $quarter = $db->getLtdDragons($ltd); $ltd = $event->checkEvent('main'); $event = $db->getLtdDragons($ltd); $leap = $this->isLeap(date("Y", strtotime($time))); $response->IndexSetOut('season', $season); $response->IndexSetOut('month', $month); $response->IndexSetOut('qt', $quarter); $response->IndexSetOut('leap', $leap); } // Get Response object $response->SetViewName("UsersView"); // Set view we want to display $response->IndexSetOut('cmd', $request->IndexGetProperty('cmd')); // Pass this view the command value for display $response->IndexSetOut('time', date("d-m-Y", strtotime($time))); $response->IndexSetOut('event', $event); return $response; } function isLeap($year) { if ((0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400)) { return true; } else { return false; } } } ?>
Java
UTF-8
570
2.640625
3
[]
no_license
package com.kimhong.thymeleaf.model; import javax.validation.constraints.NotBlank; public class Testing { @NotBlank String firstName; public Testing() { } public Testing(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Override public String toString() { return "Testing{" + "firstName='" + firstName + '\'' + '}'; } }
Python
UTF-8
1,041
3.1875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun May 3 14:34:42 2020 @title: toyrobot.py @author: Petelin """ import mypy import unittest class Table(): def __init__(self, xsize=0, ysize=0): self.xmax=xsize self.ymax=ysize self.robot = None class Robot(): def __init__(self): self.position = None self.facing = 'None' def place(self, x=0, y=0, f='N'): self.position = (x,y) self.facing = f def left(self): if self.facing == 'S': self.facing = 'E' elif self.facing == 'N': self.facing = 'W' elif self.facing == 'W': self.facing = 'S' elif self.facing == 'E': self.facing = 'N' def right(self): if self.facing == 'S': self.facing = 'W' elif self.facing == 'N': self.facing = 'E' elif self.facing == 'W': self.facing = 'N' elif self.facing == 'E': self.facing = 'S'
JavaScript
UTF-8
116
3.203125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
function sumArray(arr) { var sum = 0; for( i = 0; i < arr.length; i++) { sum+=arr[i] } return sum; }