branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>hipobali/phpmyadmin-data<file_sep>/lvOne.sql
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 20, 2019 at 02:20 AM
-- Server version: 5.7.25-0ubuntu0.16.04.2
-- PHP Version: 7.0.33-5+ubuntu16.04.1+deb.sury.org+1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `lvOne`
--
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2018_12_29_090518_create_products_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`price` double(8,2) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `name`, `price`, `created_at`, `updated_at`) VALUES
(1, 'pepsi', 400.00, '2018-12-29 03:42:06', '2018-12-29 03:42:06'),
(2, 'cocacola', 400.00, '2018-12-29 03:49:15', '2018-12-29 03:49:15'),
(3, 'sponsar', 600.00, '2018-12-29 03:52:01', '2018-12-29 03:52:01'),
(4, 'nabati', 500.00, '2018-12-29 04:24:08', '2018-12-29 04:24:08'),
(5, 'shark', 600.00, '2018-12-29 04:24:20', '2018-12-29 04:24:20'),
(6, 'yolo', 300.00, '2018-12-29 04:24:31', '2018-12-29 04:24:31'),
(7, 'max+', 600.00, '2018-12-29 22:17:26', '2019-01-06 01:14:11');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/project.sql
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 20, 2019 at 02:21 AM
-- Server version: 5.7.25-0ubuntu0.16.04.2
-- PHP Version: 7.0.33-5+ubuntu16.04.1+deb.sury.org+1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `project`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `created_at`) VALUES
(1, 'mgmg', '<EMAIL>', '<PASSWORD>', '2019-01-04 22:41:25'),
(2, 'susu', '<EMAIL>', '<PASSWORD>', '2019-01-05 10:13:49');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/groupOne.sql
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 20, 2019 at 02:20 AM
-- Server version: 5.7.25-0ubuntu0.16.04.2
-- PHP Version: 7.0.33-5+ubuntu16.04.1+deb.sury.org+1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `groupOne`
--
-- --------------------------------------------------------
--
-- Table structure for table `books`
--
CREATE TABLE `books` (
`id` int(11) NOT NULL,
`v_name` varchar(255) NOT NULL,
`v_cover` text NOT NULL,
`v_file` text NOT NULL,
`cat_id` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`id`, `v_name`, `v_cover`, `v_file`, `cat_id`, `created_at`) VALUES
(6, 'Basic networking tutorial 1', 'network.jpg', 'Basic Networking Tutorial - 18.mp4', 4, '2019-01-06 13:27:32'),
(7, 'Basic networking tutorial 2', 'net3.jpg', 'Basic Networking Tutorial - 02.mp4', 4, '2019-01-07 18:43:39'),
(9, 'Basic networking tutorial 3', 'net2.png', 'Basic Networking Tutorial - 03.mp4', 4, '2019-01-07 18:45:16'),
(13, '<NAME>', '16-58-07-500fd9f9d72a6059d64886492334349b033bba0d.jpg', 'DJ_Snake_-_Taki_Taki_ft._Selena_Gomez,_Ozuna,_Cardi_B.mp4', 5, '2019-01-08 00:14:05'),
(14, 'Resistance', 'userone.svg', 'The.Resistance.Banker.2018.1080p {CM}-1.mp4', 6, '2019-01-08 11:32:48'),
(16, '​ေအာင္​ထက္​', 'FB_IMG_1544807403923.jpg', 'ေအာင္ထက္_-_ကမာá»á€á€Šá€¹_သေရြ႔.mp4', 6, '2019-01-30 10:15:06'),
(17, 'Test', 'IMG_20190219_142903.jpg', 'Ryan_Gosling_ft._Emma_Stone_-_City_of_Stars_(Lyrics_Video).mp4', 5, '2019-02-20 09:57:36');
-- --------------------------------------------------------
--
-- Table structure for table `category`
--
CREATE TABLE `category` (
`id` int(11) NOT NULL,
`cat_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`id`, `cat_name`) VALUES
(1, 'English Speaking'),
(2, 'Japanese Speaking'),
(3, 'thai speaking'),
(4, 'networking'),
(5, 'Music '),
(6, 'movies');
-- --------------------------------------------------------
--
-- Table structure for table `channel`
--
CREATE TABLE `channel` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `channel`
--
INSERT INTO `channel` (`id`, `name`, `email`, `password`, `created_at`) VALUES
(1, 'mgmg', '<EMAIL>', '<PASSWORD>', '2019-01-05 10:35:01'),
(2, 'HtunHtun', '<EMAIL>', '<PASSWORD>', '2019-01-05 19:08:40'),
(3, '<NAME>', '<EMAIL>', '<PASSWORD>', '2019-01-08 00:09:42'),
(4, 'ayeaye', '<EMAIL>', '827ccb0eea8a706c4c34a16891f84e7b', '2019-01-09 07:49:04'),
(5, 'hlahla', '<EMAIL>', '827ccb0eea8a706c4c34a16891f84e7b', '2019-01-09 09:44:44'),
(6, '<NAME>', '<EMAIL>', 'c5fe25896e49ddfe996db7508cf00534', '2019-01-30 09:59:41'),
(7, 'Moe', '<EMAIL>', 'b857eed5c9405c1f2b98048aae506792', '2019-01-30 10:02:21'),
(8, 'Phu', '<EMAIL>', 'db05f148f2917241069c87bcbe348873', '2019-01-30 10:04:03'),
(9, 'Ohnmar', '<EMAIL>', '<PASSWORD>', '2019-01-30 10:05:29'),
(10, '<NAME>', '<EMAIL>', '85a08f53c3b5388d376dd53c3f6e642f', '2019-01-30 10:17:00'),
(11, 'phyo', '<EMAIL>', '58a2f3d9ee30d69332877379de5ed0ff', '2019-02-20 10:02:02'),
(12, '<NAME>', '<EMAIL>', '25d55ad283aa400af464c76d713c07ad', '2019-02-20 10:02:40'),
(13, '<NAME>', '<EMAIL>', '25d55ad283aa400af464c76d713c07ad', '2019-02-20 10:11:23');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `books`
--
ALTER TABLE `books`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `category`
--
ALTER TABLE `category`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `channel`
--
ALTER TABLE `channel`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `books`
--
ALTER TABLE `books`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `channel`
--
ALTER TABLE `channel`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 4b87a105a472741c960b471175474f4278fbae03 | [
"SQL"
] | 3 | SQL | hipobali/phpmyadmin-data | 2f11aa00546221a0e86344dcb29c27b95f805abc | 418e863f83883629d58fe27eb90dd484689fcfb0 |
refs/heads/master | <repo_name>joaopaulogalvao/sead40_hw3<file_sep>/AuthService.swift
//
// AuthService.swift
// sead40_hw3
//
// Created by <NAME> on 8/19/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class AuthService {
class func performInitialRequest(){
UIApplication.sharedApplication().openURL(NSURL(string: "https://github.com/login/oauth/authorize?client_id=\(kClientID)&redirect_uri=sead40hw3://oauth&scope=user,repo")!)
}
class func exchangeCodeInURL(codeURL : NSURL) {
if let code = codeURL.query {
let request = NSMutableURLRequest(URL: NSURL(string: "https://github.com/login/oauth/access_token?\(code)&client_id=\(kClientID)&client_secret=\(kClientSecret)")!)
request.HTTPMethod = "POST"
//Response from GitHub / Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
println(httpResponse.statusCode)
var jsonError : NSError?
if let rootObject = NSJSONSerialization.JSONObjectWithData(data , options: nil, error: &jsonError) as? [String : AnyObject], token = rootObject["access_token"] as? String {
KeychainService.saveToken(token)
}
}
}).resume()
println(request.URL)
}
}
}
<file_sep>/sead40_hw3/CollectionViewUserCell.swift
//
// CollectionViewUserCell.swift
// sead40_hw3
//
// Created by <NAME> on 8/19/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class CollectionViewUserCell: UICollectionViewCell {
@IBOutlet weak var imageViewUser: UIImageView!
}
<file_sep>/sead40_hw3/GithubService.swift
//
// GithubService.swift
// sead40_hw3
//
// Created by <NAME> on 8/18/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import Foundation
class GithubService {
static let sharedService = GithubService()
private init() {}
//MARK: - My Profile
class func myProfileSearch(myProfileURL: String, completionHandler : (String?,User?) -> (Void)){
//var myUserResult : [User]!
let baseURL = "https://api.github.com/user"
let finalURL = baseURL
let request = NSMutableURLRequest(URL:NSURL(string: finalURL)!)
if let token = KeychainService.loadToken() {
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
}
// Create the url request
if let url = NSURL(string: finalURL) {
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data , response, error) -> Void in
if let error = error {
println("error")
completionHandler("Could not connect to server", nil)
} else if let httpResponse = response as? NSHTTPURLResponse {
println("http response: \(httpResponse.statusCode)")
switch httpResponse.statusCode {
case 200...299:
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
let myProfile = GithubJSONParser.myProfileJSONData(data)
completionHandler(nil, myProfile)
})
case 400...499:
completionHandler("This is our fault",nil)
case 500...599:
completionHandler("This is the servers fault",nil)
default:
completionHandler("Error occurred",nil)
}
}
}).resume()
}
}
//MARK: - Users Search
class func usersForSearchTerm(searchTerm : String , completionHandler : (String?, [User]?) -> (Void)){
var results : [User]!
let baseURL = "https://api.github.com/search/users"
let finalURL = baseURL + "?q=\(searchTerm)"
let request = NSMutableURLRequest(URL: NSURL(string: finalURL)!)
if let token = KeychainService.loadToken() {
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
}
//Create the url request
if let url = NSURL(string: finalURL) {
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if let error = error {
println("error")
completionHandler("Could not connect to server",nil)
} else if let httpResponse = response as? NSHTTPURLResponse {
println("http response: \(httpResponse.statusCode)")
switch httpResponse.statusCode {
case 200...299:
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
let gitAccounts = GithubJSONParser.userInfoFromJSONData(data)
completionHandler(nil,gitAccounts)
})
case 400...499:
completionHandler("this is our fault", nil)
case 500...599:
completionHandler("this is the servers fault", nil)
default:
completionHandler("error occurred", nil)
}
}
}).resume()
}
}
// MARK: - Repos Search
class func reposForSearchTerm(searchTerm: String, reposCallback : (String?, [Repos]?) -> (Void)){
var results : [Repos]!
let baseURL = "https://api.github.com/search/repositories"
let finalURL = baseURL + "?q=\(searchTerm)"
let request = NSMutableURLRequest(URL: NSURL(string: finalURL)!)
if let token = KeychainService.loadToken() {
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
}
if let url = NSURL(string: finalURL){
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if let error = error {
println("error")
reposCallback("Could not connect to server", nil)
} else if let httpResponse = response as? NSHTTPURLResponse {
println("repos response: \(httpResponse.statusCode)")
switch httpResponse.statusCode {
case 200...299:
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
let repos = GithubJSONParser.reposInfoFromJSONData(data)
reposCallback(nil,repos)
})
case 400...499:
reposCallback("this is our fault",nil)
case 500...599:
reposCallback("this is the servers fault", nil)
default:
reposCallback("error occured",nil)
}
}
}).resume()
}
}
}
<file_sep>/sead40_hw3/User_BASE_83432.swift
//
// User.swift
// sead40_hw3
//
// Created by <NAME> on 8/17/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import Foundation
class User {
}<file_sep>/sead40_hw3/RepoSearchViewController.swift
//
// RepoSearchViewController.swift
// sead40_hw3
//
// Created by <NAME> on 8/18/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class RepoSearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var userResults = [User]()
var repoResults = [Repos]()
@IBOutlet weak var tableviewSearch: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.tableviewSearch.dataSource = self
self.tableviewSearch.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showWebview" {
if let detailViewController = segue.destinationViewController as? WebViewController {
//let myIndexPath = self.tableviewSearch.indexPathForSelectedRow()
if let indexPath = self.tableviewSearch.indexPathForSelectedRow() {
// let selectedRow: AnyObject? = indexPath.first
let selectedRepo = self.repoResults[indexPath.row]
println("Row: \(indexPath.row) selected")
// println("Row \(indexPath.row) selected")
detailViewController.selectedRepo = selectedRepo
}
println("Detail Clicked")
}
}
}
}
extension RepoSearchViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
GithubService.reposForSearchTerm(self.searchBar.text) { (errorDescription, repos) -> (Void) in
if let repos = repos {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
println(repos)
self.repoResults = repos
self.tableviewSearch.reloadData()
})
}
}
}
}
extension RepoSearchViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.repoResults.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let userSearchCell = tableviewSearch.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) as! UITableViewCell
// userSearchCell.tag++
// let tag = userSearchCell.tag
var infoFromRepos = self.repoResults[indexPath.row]
userSearchCell.textLabel?.text = infoFromRepos.repoName
//tableviewSearch.reloadData()
return userSearchCell
}
}
/*
extension RepoSearchViewController : UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let repoWebView = storyboard.instantiateViewControllerWithIdentifier("WebRepo") as? WebViewController {
let selectedRepo = self.repoResults[indexPath.row]
println("Row: \(indexPath.row) selected")
repoWebView.selectedRepo = selectedRepo
//self.presentViewController(repoWebView, animated: true, completion: nil)
self.navigationController?.pushViewController(repoWebView, animated: true)
}
}
}
*/
<file_sep>/sead40_hw3/MenuTableViewController.swift
//
// MenuTableViewController.swift
// sead40_hw3
//
// Created by <NAME> on 8/18/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
//MARK: Properties
var myProfile : User!
let myProfileUserImageQueue = NSOperationQueue()
//MARK: Constants
let kSize2Width : Int = 160
let kSize2Height : Int = 160
let kSize3Width : Int = 240
let kSize3Height : Int = 240
let kSizeDefaultWidth : Int = 80
let kSizeDefaultHeight : Int = 80
//MARK: Outlets
@IBOutlet weak var imgViewMyProfile: UIImageView!
@IBOutlet weak var labelMyProfile: UILabel!
//MARK: Life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
AuthService.performInitialRequest()
let baseURL = "https://api.github.com/user"
GithubService.myProfileSearch(baseURL) { (errorDescription, myProfile) -> (Void) in
println("myProfileInfo to Menu: \(myProfile)")
self.labelMyProfile.text = myProfile?.username
if let profileImage = myProfile?.profileImage {
self.imgViewMyProfile.image = profileImage
} else {
self.myProfileUserImageQueue.addOperationWithBlock({ () -> Void in
//Check if there is an URL - set indexPath for each url / check Data and image
if let imageURL = NSURL(string: myProfile!.profileImageURL),
data = NSData(contentsOfURL: imageURL),
image = UIImage(data: data){
//Check for image size depending on resolution
var size : CGSize
switch UIScreen.mainScreen().scale {
case 2:
size = CGSize(width: self.kSize2Width, height: self.kSize2Height)
case 3:
size = CGSize(width: self.kSize3Width, height: self.kSize3Height)
println("Size 240")
default:
size = CGSize(width: self.kSizeDefaultWidth, height: self.kSizeDefaultHeight)
println("default")
}
let resizedImage = ImageSizer.resizeImage(image, size: size)
// Adjust rounded border
self.imgViewMyProfile.layer.masksToBounds = false
self.imgViewMyProfile.layer.cornerRadius = self.imgViewMyProfile.frame.height/2
self.imgViewMyProfile.clipsToBounds = true
self.imgViewMyProfile.image = resizedImage
//Only load when needed
// ImageService.fetchProfileImage(myProfile!.profileImageURL, imageQueue: self.myProfileUserImageQueue, completionHandler: { (image) -> () in
// if let profileImage = myProfile!.profileImage {
// //self.myProfile.profileImage = resizedImage
// self.imgViewMyProfile.image = resizedImage
// println("Resized Image:\(resizedImage)")
// }
// })
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/sead40_hw3/ImageService.swift
//
// ImageService.swift
// sead40_hw3
//
// Created by <NAME> on 8/20/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class ImageService {
class func fetchProfileImage(url : String, imageQueue : NSOperationQueue, completionHandler : (UIImage?) ->()) {
imageQueue.addOperationWithBlock { () -> Void in
if let url = NSURL(string: url) {
if let imageData = NSData(contentsOfURL: url) {
if let image = UIImage(data: imageData) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completionHandler(image)
})
}
}
}
}
}
}<file_sep>/sead40_hw3/GithubJSONParser.swift
//
// GithubJSONParser.swift
// sead40_hw3
//
// Created by <NAME> on 8/18/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import Foundation
class GithubJSONParser {
//MARK: - My profile data
class func myProfileJSONData (jsonData : NSData) -> User? {
var error: NSError?
var myProfileInfo : User?
if let myProfileDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? [String : AnyObject] {
if let myProfileURL = myProfileDict["avatar_url"] as? String, username = myProfileDict["name"] as? String, userLocation = myProfileDict["location"] as? String {
var myProfile = User(username: username, profileImage: nil, userLocation: userLocation, userEmail: nil, profileImageURL: myProfileURL)
println("myProfile: \(myProfile)")
myProfileInfo = myProfile
println("myProfileInfo: \(myProfileInfo)")
}
}
return myProfileInfo
}
//MARK: - User data
class func userInfoFromJSONData (jsonData : NSData) -> [User]? {
var error : NSError?
var gitUserInfo = [User]()
if let userDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? [String : AnyObject] {
if let items = userDict["items"] as? [[String : AnyObject]] {
for item in items {
if let username = item["login"] as? String, profileImageURL = item["avatar_url"] as? String, userLocation = item["url"] as? String, userEmail = item["repos_url"] as? String {
var gitUser = User(username: username, profileImage: nil, userLocation: userLocation, userEmail: userEmail, profileImageURL: profileImageURL)
gitUserInfo.append(gitUser)
println("gitUserInfo Array:\(gitUser)")
}
}
}
}
return gitUserInfo
}
//MARK: - Repos data
class func reposInfoFromJSONData (jsonData : NSData) -> [Repos]? {
var error : NSError?
var gitReposInfo = [Repos]()
if let reposDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? [String : AnyObject] {
if let items = reposDict["items"] as? [[String : AnyObject]] {
//Access the array of Dictionaries
for item in items {
if let repoName = item["name"] as? String, repoDescription = item["description"] as? String, repoURL = item["html_url"] as? String {
//Create Git Repo object
var gitRepo = Repos(repoName: repoName, repoDescription: repoDescription, repoURL : repoURL)
gitReposInfo.append(gitRepo)
}
}
}
}
return gitReposInfo
}
}
<file_sep>/sead40_hw3/Repos.swift
//
// Repos.swift
// sead40_hw3
//
// Created by <NAME> on 8/17/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import Foundation
struct Repos {
let repoName : String
let repoDescription : String
let repoURL : String
}<file_sep>/sead40_hw3/UserSearchViewController.swift
//
// UserSearchViewController.swift
// sead40_hw3
//
// Created by <NAME> on 8/19/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class UserSearchViewController: UIViewController, UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
var userResults = [User]()
var gitHubUser : User?
let userImageQueue = NSOperationQueue()
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var searchBarUser: UISearchBar!
let kCornerRadius : CGFloat = 50.0
//MARK: Life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.searchBarUser.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.delegate = nil
}
//MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "showDetailView" {
if let detailViewController = segue.destinationViewController as? DetailViewController {
let myIndexPath = self.collectionView.indexPathsForSelectedItems()
if let indexPath = self.collectionView?.indexPathsForSelectedItems() {
// let selectedRow: AnyObject? = indexPath.first
let selectedUser = self.userResults.first
// println("Row \(indexPath.row) selected")
detailViewController.selectedUserName = selectedUser
}
println("Detail Clicked")
}
}
}
}
//MARK: - UISearchBarDelegate
extension UserSearchViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
GithubService.usersForSearchTerm(self.searchBarUser.text) { (errorDescription, users) -> (Void) in
if let users = users {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
println(users)
self.userResults = users
self.collectionView.reloadData()
})
}
}
}
func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return text.validateForURL()
}
}
//MARK: - UICollectionViewDelegate
extension UserSearchViewController : UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let detailViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileView") as? DetailViewController {
let selectedUser = self.userResults[indexPath.row]
println("Row \(indexPath.row) selected")
//Pass selecteded user reference to next viewcontroller
detailViewController.selectedUserName = selectedUser
println(selectedUser)
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
}
//MARK: - UICollectionViewDataSource
extension UserSearchViewController : UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userResults.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("userCell", forIndexPath: indexPath) as! CollectionViewUserCell
cell.layer.cornerRadius = kCornerRadius
// Set the imageView for nil each time it dequeue a cell.
cell.imageViewUser.image = nil
cell.hidden = false
cell.alpha = 1.0
cell.tag++
let tag = cell.tag
var userImage = userResults[indexPath.row]
println("Users image:\(userImage)")
// If there is an image set an image for a user
if let profileImage = userImage.profileImage {
cell.imageViewUser.image = profileImage
} else {
//The reason Brad's is async is because in his service he made a queue
//Only load when needed
userImageQueue.addOperationWithBlock({ () -> Void in
//Check if there is an URL - set indexPath for each url / check Data and image
if let imageURL = NSURL(string: self.userResults[indexPath.row].profileImageURL),
data = NSData(contentsOfURL: imageURL),
image = UIImage(data: data){
//Check for image size depending on resolution
var size : CGSize
switch UIScreen.mainScreen().scale {
case 2:
size = CGSize(width: 160, height: 160)
case 3:
size = CGSize(width: 240, height: 240)
println("Size 240")
default:
size = CGSize(width: 80, height: 80)
println("default")
}
let resizedImage = ImageSizer.resizeImage(image, size: size)
// Send operation back to the main Queue
ImageService.fetchProfileImage(userImage.profileImageURL,imageQueue:self.userImageQueue, completionHandler: { (image) -> () in
userImage.profileImage = resizedImage
self.userResults[indexPath.row] = userImage
if cell.tag == tag {
cell.imageViewUser?.image = resizedImage
UIView.animateWithDuration(0.3, animations: { () -> Void in
cell.alpha = 1
// Adjust rounded border
cell.imageViewUser.layer.masksToBounds = false
cell.imageViewUser.layer.cornerRadius = cell.imageViewUser.frame.height/2
cell.imageViewUser.clipsToBounds = true
})
}
})
}
})
}
return cell
}
}
extension UserSearchViewController : UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return toVC is DetailViewController ? ToUserDetailAnimationController() : nil
}
}
<file_sep>/sead40_hw3/ImageSizer.swift
//
// ImageSizer.swift
// sead40_hw3
//
// Created by <NAME> on 8/20/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class ImageSizer {
class func resizeImage(image : UIImage, size : CGSize) -> UIImage {
UIGraphicsBeginImageContext(size)
image.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
}
<file_sep>/sead40_hw3/DetailViewController.swift
//
// DetailViewController.swift
// sead40_hw3
//
// Created by <NAME> on 8/20/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var selectedUserName : User?
var userImage : UIImage?
var user_name : String?
var users = [User]()
@IBOutlet weak var imgViewDetail: UIImageView!
@IBOutlet weak var labelUserDetail: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.labelUserDetail.text = self.selectedUserName?.username
self.imgViewDetail.image = self.selectedUserName?.profileImage
// Adjust rounded border
imgViewDetail.layer.masksToBounds = false
imgViewDetail.layer.cornerRadius = imgViewDetail.frame.height/2
imgViewDetail.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/sead40_hw3/ToUserDetailAnimation.swift
//
// ToUserDetailAnimation.swift
// sead40_hw3
//
// Created by <NAME> on 8/20/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
class ToUserDetailAnimationController: NSObject {
override init() {
}
}
extension ToUserDetailAnimationController : UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.4
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? UserSearchViewController,
toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? DetailViewController {
let containerView = transitionContext.containerView()
toVC.view.alpha = 0
containerView.addSubview(toVC.view)
let indexPath = fromVC.collectionView.indexPathsForSelectedItems().first as! NSIndexPath
let userCell = fromVC.collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewUserCell
let snapShot = userCell.imageViewUser.snapshotViewAfterScreenUpdates(false)
snapShot.frame = containerView.convertRect(userCell.imageViewUser.frame, fromCoordinateSpace: userCell.imageViewUser.superview!)
containerView.addSubview(snapShot)
userCell.hidden = true
//ensure that my destination image view is in place
toVC.view.layoutIfNeeded()
toVC.imgViewDetail.hidden = true
let destinationFrame = toVC.imgViewDetail.frame
UIView.animateWithDuration(0.4, animations: { () -> Void in
snapShot.frame = destinationFrame
toVC.view.alpha = 1
}, completion: { (finished) -> Void in
userCell.hidden = false
toVC.imgViewDetail.hidden = false
snapShot.removeFromSuperview()
if finished {
transitionContext.completeTransition(finished)
} else {
transitionContext.completeTransition(finished)
}
})
}
}
}
<file_sep>/sead40_hw3/User_REMOTE_83432.swift
//
// User.swift
// sead40_hw3
//
// Created by <NAME> on 8/17/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import Foundation
struct User {
let username : String
let name : String
let userLocation : String
let userEmail : String
}<file_sep>/sead40_hw3/WebViewController.swift
//
// WebViewController.swift
// sead40_hw3
//
// Created by <NAME> on 8/22/15.
// Copyright (c) 2015 jalvestech. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
var selectedRepo : Repos!
//@IBOutlet weak var webViewRepos: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
// Do any additional setup after loading the view.
// let baseURL = "https://api.github.com/search/repositories"
// let finalURL = baseURL + "?q=\(selectedRepo!.repoURL)"
// if let urlRequest = NSURL(string: selectedRepo!.repoURL){
let urlRequest = NSURLRequest(URL: NSURL(string: selectedRepo.repoURL)!)
webView.loadRequest(urlRequest)
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 08ff42c5e9b991a74f88a33589f856e8f25ddb6f | [
"Swift"
] | 15 | Swift | joaopaulogalvao/sead40_hw3 | 1cbebd2cab10010c89c087dc765d730b0d5e4d79 | da0a1b3ec48a2390078d24eee3efd0b00e7ac768 |
refs/heads/master | <file_sep>package demo.concurrent.optimizations;
/**
* Java concurency optimisations benchmark based on article:
* http://www.infoq.com/articles/java-threading-optimizations-p1
* http://www.infoq.com/articles/java-threading-optimizations-p2
*/
public class LockTest {
private static final int MAX = 20000000; // 20 million
public static void main(String[] args) throws InterruptedException {
// warm up the method cache
for (int i = 0; i < MAX; i++) {
concatBuffer("Josh", "James", "Duke");
concatBuilder("Josh", "James", "Duke");
}
System.gc();
Thread.sleep(1000);
System.out.println("Starting test");
long start = System.currentTimeMillis();
for (int i = 0; i < MAX; i++) {
concatBuffer("Josh", "James", "Duke");
}
long bufferCost = System.currentTimeMillis() - start;
System.out.println("StringBuffer: " + bufferCost + " ms.");
System.gc();
Thread.sleep(1000);
start = System.currentTimeMillis();
for (int i = 0; i < MAX; i++) {
concatBuilder("Josh", "James", "Duke");
}
long builderCost = System.currentTimeMillis() - start;
System.out.println("StringBuilder: " + builderCost + " ms.");
System.out.println("Thread safety overhead of StringBuffer: "
+ ((bufferCost * 10000 / (builderCost * 100)) - 100) + "%\n");
}
public static String concatBuffer(String s1, String s2, String s3) {
StringBuffer sb = new StringBuffer();
sb.append(s1);
sb.append(s2);
sb.append(s3);
return sb.toString();
}
public static String concatBuilder(String s1, String s2, String s3) {
StringBuilder sb = new StringBuilder();
sb.append(s1);
sb.append(s2);
sb.append(s3);
return sb.toString();
}
} | 052a77b54b6345bfa16132743216d036f3884816 | [
"Java"
] | 1 | Java | piczmar/JavaConcurrency | 91a95a2f7b1e4b382472a0e637753bd9f0c3293c | 2947900618853559ffe9a31ed245c5ad24b3cedd |
refs/heads/master | <repo_name>ShevtsovDmitriy/Monopoly<file_sep>/src/sample/MyGame/Field.java
package sample.MyGame;
import java.util.ArrayList;
/**
* Created by Дмитрий on 06.10.2014.
*/
public class Field {
public static Field GetGameField(){
if (gameField == null){
gameField = new Field();
}
return gameField;
}
private static Field gameField = null;
protected Field(){
startCell = new Cell(0, "Старт", Game.CellType.Start, 0, new ArrayList<Integer>(), 0, 0);
}
private Cell startCell;
public Cell getStartCell(){
return startCell;
}
private Cell prison = null;
public Cell getPrison() {
return prison;
}
public void SetPrison(Cell cell){
if (prison == null && (cell.getType() == Game.CellType.Prison)){
prison = cell;
}
}
public boolean GoToNextCell(Player player){
return true;
//TODO: create method to navigate on cells
}
public void SetNextCells(){
Cell buf = startCell;
System.out.print(startCell);
while (!CellFactory.isItEnd()){
buf.SetNextCell();
buf = buf.GoToNextCell();
}
}
//Поле хранится в текстовом файле
}
<file_sep>/src/sample/MyGame/Player.java
package sample.MyGame;
/**
* Created by Дмитрий on 06.10.2014.
*/
public class Player implements IPlayer {
public Player(){}
private Object playerInfo;
public boolean MakeMove(){
return true;
//TODO:
}
public boolean DoSomething(){
return true;
//TODO:
}
}
<file_sep>/src/sample/MyGame/IPlayer.java
package sample.MyGame;
/**
* Created by Дмитрий on 06.10.2014.
*/
public interface IPlayer {
public boolean MakeMove();
public boolean DoSomething();
}
<file_sep>/src/sample/MyGame/CellFactory.java
package sample.MyGame;
import java.io.*;
import java.util.ArrayList;
/**
* Created by Дмитрий on 06.10.2014.
*/
public class CellFactory {
private static File my_file = new File("Map.res");
private static BufferedReader in;
private static boolean itEnd = false;
public static boolean isItEnd() {
return itEnd;
}
public static Cell GetCell() {
String str = "";
if (in == null)
{
try {
in = new BufferedReader(new FileReader(my_file));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.print("File not found");
}
}
if (my_file.exists()) {
try {
str = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
else {System.out.print("File not found");}
if(str != null) {
Integer id = 0;
String name = "";
Game.CellType type;
int cost = 0;
ArrayList<Integer> rate = new ArrayList<Integer>();
int houseCost = 0;
int collateral = 0;
int i = 0;
String buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
id = new Integer(buf);
i++;
buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
name = buf;
i++;
buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
type = Game.CellType.valueOf(buf);
i++;
buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
cost = new Integer(buf);
i++;
buf = "";
while (str.charAt(i) != '/') {
while (str.charAt(i) != ' ') {
buf += str.charAt(i);
i++;
}
rate.add(new Integer(buf));
i++;
buf = "";
}
i++;
buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
houseCost = new Integer(buf);
i++;
buf = "";
while (str.charAt(i) != '/') {
buf += str.charAt(i);
i++;
}
collateral = new Integer(buf);
Cell cell = new Cell(id, name, type, cost, rate, houseCost, collateral );
return cell;
}
else
{
itEnd = true;
return Field.GetGameField().getStartCell();
}
}
}
<file_sep>/src/sample/MyGame/ICellFactory.java
package sample.MyGame;
/**
* Created by Дмитрий on 06.10.2014.
*/
public interface ICellFactory {
public Cell GetCell();
}
| 54f2169adfa8677db7d0a2e53fab59911ce4eea7 | [
"Java"
] | 5 | Java | ShevtsovDmitriy/Monopoly | e70d3ef338926c8c49db540fe734163df4676524 | 393ef7432727ab95b83b85f4e7ed047265fcf99b |
refs/heads/master | <repo_name>algo-88team/Hidato<file_sep>/Generator.cpp
#include <random>
//
// Created by thdtj on 2018-11-21.
//
#include "Generator.h"
#include "Cell.h"
#include <random>
#include <algorithm>
#define GET(map, p) (map[p.y * width2 + p.x])
Generator::~Generator() {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
direction[i][j].clear();
std::vector<Point>().swap(direction[i][j]);
}
delete[] direction[i];
}
delete[] direction;
startLoader.clear();
std::vector<Point>().swap(startLoader);
delete[] map;
}
Puzzle &Generator::Generate(Puzzle &puzzle, Puzzle& answer) {
width = puzzle.getWidth();
height = puzzle.getHeight();
width2 = width + 2;
height2 = height + 2;
numCells = puzzle.getNumCells();
// Change empty cells from 1 to -1
Invert(puzzle);
// Init map
init_map(puzzle);
// Init random direction
init_direction(puzzle);
// Init start
Init_startLoader();
bool result;
do {
if (startLoader.empty()) {
std::cout << "There is no way." << std::endl;
}
result = Recursive(*startLoader.begin(), 1);
startLoader.erase(startLoader.begin());
} while (!result);
copy_map(puzzle, true);
std::cout << "Filled Puzzle" << std::endl << puzzle << std::endl;
answer = puzzle;
init_cellLoader();
while (!cellLoader.empty()) {
Point pos = *cellLoader.begin();
cellLoader.erase(cellLoader.begin());
int value = GET(map, pos);
GET(map, pos) = -1;
int lower = 0;
int upper = numCells + 1;
Point lowerPoint;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
Point p(j, i);
int v = GET(map, p);
if (v < value) {
if (v > lower) {
lower = v;
lowerPoint = p;
}
}
else if (v < upper) {
upper = v;
}
}
}
if (is_UniquePath(lower, upper, lowerPoint) != 1) {
GET(map, pos) = value;
}
}
copy_map(puzzle);
return puzzle;
}
bool Generator::Recursive(Point pos, int n) {
if (n > numCells) {
return true;
}
if (GET(map, pos) != -1) {
return false;
}
GET(map, pos) = n;
std::vector<Point> &dir = direction[pos.y][pos.x];
for (int i = 0; i < 8; ++i) {
if (Recursive(pos + dir[i], n + 1)) {
return true;
}
}
GET(map, pos) = -1;
return false;
}
void Generator::Invert(Puzzle &puzzle) {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
puzzle[i][j] *= -1;
}
}
puzzle.setNumEmptyCells(puzzle.getNumCells());
}
void Generator::init_direction(const Puzzle &puzzle) {
std::vector<Point> dir = { { 0, -1 },
{ 1, -1 },
{ 1, 0 },
{ 1, 1 },
{ 0, 1 },
{ -1, 1 },
{ -1, 0 },
{ -1, -1 } };
direction = new std::vector<Point> *[height];
for (int i = 0; i < height; ++i) {
direction[i] = new std::vector<Point>[width];
for (int j = 0; j < width; ++j) {
Point p = { j, i };
if (puzzle[p] == -1) {
std::vector<Point> shuffled(dir);
std::shuffle(shuffled.begin(), shuffled.end(), std::mt19937(std::random_device()()));
direction[i][j].swap(shuffled);
}
}
}
}
void Generator::init_map(const Puzzle &puzzle) {
map = new int[(height2) * (width2)];
for (int i = 0; i < height2; ++i) {
for (int j = 0; j < width2; ++j) {
map[i * (width2)+j] = puzzle[i - 1][j - 1];
}
}
map = map + width2 + 1;
}
void Generator::Init_startLoader() {
std::vector<Point> EmptyCells;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
Point p(j, i);
if (GET(map, p) == -1) {
EmptyCells.emplace_back(p);
}
}
}
std::shuffle(EmptyCells.begin(), EmptyCells.end(), std::mt19937(std::random_device()()));
startLoader.swap(EmptyCells);
}
void Generator::init_cellLoader() {
std::vector<Point> FilledCells;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
Point p(j, i);
if (1 < GET(map, p) && GET(map, p) < numCells) {
FilledCells.emplace_back(p);
}
}
}
std::shuffle(FilledCells.begin(), FilledCells.end(), std::mt19937(std::random_device()()));
cellLoader.swap(FilledCells);
}
Puzzle &Generator::copy_map(Puzzle &puzzle, bool stay) {
map = map - width2 - 1;
for (int i = 0; i < height2; ++i) {
for (int j = 0; j < width2; ++j) {
puzzle[i - 1][j - 1] = map[i * (width2)+j];
}
}
if (stay) {
map = map + width2 + 1;
}
return puzzle;
}
int Generator::is_UniquePath(int num, const int goal, Point pos) {
std::vector<Point> &dir = direction[pos.y][pos.x];
for (int i = 0; i < 8; i++) {
Point next = pos + dir[i];
if (GET(map, next) == num + 1) {
if (num + 1 == goal) {
return 1;
}
return is_UniquePath(num + 1, goal, next);
}
}
if (num == goal - 1) {
return 0;
}
int count = 0;
for (int i = 0; i < 8; i++) {
if (count > 1) {
return count;
}
Point next = pos + dir[i];
if (GET(map, next) == -1) {
GET(map, next) = num + 1;
count += is_UniquePath(num + 1, goal, next);
GET(map, next) = -1;
}
}
return count;
}
Puzzle &Generator::GenerateWithCellGraph(Puzzle &puzzle) {
width = puzzle.getWidth();
height = puzzle.getHeight();
width2 = width + 2;
height2 = height + 2;
numCells = puzzle.getNumCells();
// Change empty cells from 1 to -1
Invert(puzzle);
// Init random direction
init_direction(puzzle);
// Create CellGraph
CellGraph graph(puzzle);
// Fill puzzle
Puzzle *result;
do {
Cell *randCell = graph.getRandCell(1);
if (randCell == nullptr) {
std::cout << "There are no way" << std::endl;
return puzzle;
}
randCell->setData(1);
result = Fill(puzzle, graph, *randCell);
if (result == nullptr) {
randCell->eraseCandidate(1);
graph.eraseRemainder(1, randCell);
randCell->setData(-1);
}
} while (result == nullptr);
puzzle = *result;
// Check puzzle
int checker = 0;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
checker ^= puzzle[i][j];
}
}
for (int n = 1; n < numCells + 1; ++n) {
checker ^= n;
}
if (checker) {
std::cout << "Fill failed." << std::endl;
return puzzle;
}
// Init map
init_map(puzzle);
// Init cellLoader
init_cellLoader();
while(!cellLoader.empty()) {
Point pos = *cellLoader.begin();
cellLoader.erase(cellLoader.begin());
int value = GET(map, pos);
GET(map, pos) = -1;
int lower = 0;
int upper = numCells + 1;
Point lowerPoint;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
Point p(j, i);
int v = GET(map, p);
if (v < value) {
if (v > lower) {
lower = v;
lowerPoint = p;
}
} else if (v < upper) {
upper = v;
}
}
}
if (is_UniquePath(lower, upper, lowerPoint) != 1) {
GET(map, pos) = value;
}
}
copy_map(puzzle);
return puzzle;
}
Puzzle *Generator::Fill(Puzzle puzzle, CellGraph graph, const Cell cell) {
if (!Update(puzzle, graph, cell)) {
return nullptr;
}
if (graph.is_finished()) {
return new Puzzle(puzzle);
}
Puzzle *result;
do {
Cell *randCell = graph.getNextRandCell();
if (randCell == nullptr) {
// std::cout << "There are no way " << graph.getRemaindersSetSize() << std::endl;
return nullptr;
}
int n = randCell->getData();
result = Fill(puzzle, graph, *randCell);
if (result == nullptr) {
randCell->eraseCandidate(n);
graph.eraseRemainder(n, randCell);
randCell->setData(-1);
}
} while (result == nullptr);
return result;
}
bool Generator::Update(Puzzle &puzzle, CellGraph &graph, const Cell cell) {
puzzle[cell.getPos()] = cell.getData();
graph.eraseCell(graph[cell.getPos()]);
graph.checkNeighbor(cell);
if (graph.is_finished()) {
return true;
}
if (!graph.checkMapping() || !graph.is_candidatesEmpty() || !graph.is_remaindersEmpty()) {
return false;
}
Cell *pCell = graph.find_onlyCandidate();
if (pCell == nullptr) {
pCell = graph.find_onlyRemainder();
if (pCell == nullptr) {
return true;
}
}
return Update(puzzle, graph, *pCell);
}
<file_sep>/Solver.h
//
// Created by thdtj on 2018-11-21.
//
#ifndef HIDATO_SOLVER_H
#define HIDATO_SOLVER_H
#include "Puzzle.h"
#include <utility>
class Solver {
public:
Puzzle & Solve(Puzzle &p, Puzzle &answer);
int hidato_solve(int num, const int goal, int position_x, int position_y, Puzzle &p);
int direction[8][2] = { {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1} };
int Answer_checking(Puzzle& p, Puzzle &answer);
};
class Stack {
public:
Stack();
int pop();
void push(int x, int y, int dir);
bool empty();
private:
int s[1000];
int top;
};
#endif //HIDATO_SOLVER_H
<file_sep>/Generator.h
//
// Created by thdtj on 2018-11-21.
//
#ifndef HIDATO_GENERATOR_H
#define HIDATO_GENERATOR_H
#include "Puzzle.h"
#include "CellGraph.h"
class Generator {
public:
Generator() : width(0), height(0), numCells(0) {}
Puzzle &Generate(Puzzle &puzzle, Puzzle& answer);
Puzzle &GenerateWithCellGraph(Puzzle &puzzle);
virtual ~Generator();
private:
int width;
int height;
int width2;
int height2;
int numCells;
int *map;
std::vector<Point> startLoader;
std::vector<Point> cellLoader;
std::vector<Point> **direction;
void init_direction(const Puzzle &puzzle);
void init_map(const Puzzle &puzzle);
void Init_startLoader();
void init_cellLoader();
bool Recursive(Point pos, int n);
Puzzle ©_map(Puzzle &puzzle, bool stay = false);
void Invert(Puzzle &puzzle);
int is_UniquePath(int num, const int goal, Point pos);
Puzzle *Fill(Puzzle puzzle, CellGraph graph, const Cell cell);
bool Update(Puzzle &puzzle, CellGraph &graph, const Cell cell);
};
#endif //HIDATO_GENERATOR_H
<file_sep>/Puzzle.cpp
//
// Created by thdtj on 2018-11-21.
//
#include "Generator.h"
#include "Puzzle.h"
#include <string.h>
#include <iomanip>
Puzzle::Puzzle() : width(0), height(0), map(nullptr), numCells(0), numEmptyCells(0) {};
Puzzle::Puzzle(int width, int height) : width(width), height(height), map(nullptr), numCells(0), numEmptyCells(0) {
map = new int *[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new int[width + 2];
}
memset(map[0], 0, (width + 2) * sizeof(int));
memset(map[height + 2 - 1], 0, (width + 2) * sizeof(int));
for (int i = 1; i < height + 1; ++i) {
map[i][0] = 0;
map[i][width + 1] = 0;
}
}
Puzzle::Puzzle(const Puzzle &p) {
width = p.width;
height = p.height;
numCells = p.numCells;
numEmptyCells = p.numEmptyCells;
if (width == 0 || height == 0 || p.map == nullptr) {
map = nullptr;
return;
}
map = new int *[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new int[width + 2];
memcpy(map[i], p.map[i], (width + 2) * sizeof(int));
}
}
Puzzle::~Puzzle() {
if (map != nullptr) {
for (int i = 0; i < height + 2; ++i) {
delete[] map[i];
}
delete[] map;
}
}
int *Puzzle::operator[](int i) const {
return map[i + 1] + 1;
}
int *Puzzle::operator[](int i) {
return map[i + 1] + 1;
}
int Puzzle::operator[](const Point &p) const {
return map[p.y + 1][p.x + 1];
}
int &Puzzle::operator[](const Point &p) {
return map[p.y + 1][p.x + 1];
}
Puzzle &Puzzle::operator=(const Puzzle &p) {
if (&p == this) {
return *this;
}
if (map != nullptr) {
for (int i = 0; i < height + 2; ++i) {
delete[] map[i];
}
delete[] map;
}
width = p.width;
height = p.height;
numCells = p.numCells;
numEmptyCells = p.numEmptyCells;
if (width == 0 || height == 0 || p.map == nullptr) {
map = nullptr;
return *this;
}
map = new int *[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new int[width + 2];
memcpy(map[i], p.map[i], (width + 2) * sizeof(int));
}
return *this;
}
std::ostream &operator<<(std::ostream &o, const Puzzle &p) {
#ifdef PRINT_EDGE
for (int i = -1; i < p.height+1; ++i) {
for (int j = -1; j < p.width+1; ++j) {
o << p[i][j] << " ";
}
o << std::endl;
}
#else
for (int i = 0; i < p.height; ++i) {
for (int j = 0; j < p.width; ++j) {
o << std::setw(4) << p[i][j] << " ";
}
o << std::endl;
}
#endif
return o;
}
std::istream &operator>>(std::istream &in, Puzzle &p) {
int width, height;
in >> width >> height;
p = Puzzle(width, height);
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
in >> p[i][j];
if (p[i][j]) {
++p.numCells;
if (p[i][j] < 0) {
++p.numEmptyCells;
}
}
}
}
return in;
}
Puzzle &Puzzle::LoadFormFile(const char *name) {
if (map != nullptr) {
for (int i = 0; i < height + 2; ++i) {
delete[] map[i];
}
delete[] map;
}
std::ifstream in;
in.open(name);
if (in.fail()) {
std::cerr << "file open error : " << name << std::endl;
return *this;
}
in >> *this;
return *this;
}
int Puzzle::getWidth() const {
return width;
}
int Puzzle::getHeight() const {
return height;
}
int Puzzle::getNumCells() const {
return numCells;
}
int Puzzle::getNumEmptyCells() const {
return numEmptyCells;
}
void Puzzle::setNumCells(int numCells) {
Puzzle::numCells = numCells;
}
void Puzzle::setNumEmptyCells(int numEmptyCells) {
Puzzle::numEmptyCells = numEmptyCells;
}
Point::Point(int x, int y) : x(x), y(y) {}
<file_sep>/main.cpp
//
// Created by thdtj on 2018-11-21.
//
#include <iostream>
#include "Puzzle.h"
#include "Generator.h"
#include "Solver.h"
#include <string>
#define RANDOM_SEED (time(nullptr))
int main() {
Generator generator;
Solver solver;
srand(static_cast<unsigned int>(RANDOM_SEED));
for (int i = 0; i < 5; i++) {
Puzzle puzzle, answer;
std::string s = "input" + std::to_string(i) + ".txt";
const char* c = s.c_str();
std::cout << "--------------------- testcase " << i + 1 << " ---------------------" << std::endl;
puzzle.LoadFormFile(c);
std::cout << "Input puzzle" << std::endl;
std::cout << puzzle << std::endl;
std::cout << "Generated puzzle" << std::endl;
std::cout << generator.Generate(puzzle, answer) << std::endl;
std::cout << "Solved puzzle" << std::endl;
std::cout << solver.Solve(puzzle, answer) << std::endl;
}
std::getchar();
return 0;
}<file_sep>/Cell.cpp
//
// Created by thdtj on 2018-12-13.
//
#include "Cell.h"
Cell::~Cell() {
candidates.clear();
std::set<int>().swap(candidates);
}
int Cell::getData() const {
return data;
}
void Cell::setData(int data) {
Cell::data = data;
}
void Cell::setDataCandidate() {
data = *candidates.begin();
}
int Cell::getCandidate() {
return *candidates.begin();
}
const Point &Cell::getPos() const {
return pos;
}
Cell &Cell::operator=(const Cell &c) {
data = c.data;
pos = c.pos;
candidates.clear();
candidates = c.candidates;
return *this;
}
void Cell::insertCandidate(int n) {
candidates.insert(n);
}
void Cell::eraseCandidate(int n) {
candidates.erase(n);
}
bool Cell::is_Neighbor(int x, int y) {
return abs(pos.x - x) <= 1 && abs(pos.y - y) <= 1;
}
bool Cell::is_Neighbor(const Point &p) {
return abs(pos.x - p.x) <= 1 && abs(pos.y - p.y) <= 1;
}
bool Cell::is_Neighbor(const Cell &c) {
return abs(pos.x - c.pos.x) <= 1 && abs(pos.y - c.pos.y) <= 1;
}
int Cell::getCandidatesSize() {
return static_cast<int>(candidates.size());
}
bool Cell::isCandidatesEmpty() {
return candidates.empty();
}
bool Cell::is_candidate(int n) {
return candidates.find(n) != candidates.end();
}
<file_sep>/CMakeLists.txt
# cmake_minimum_required(VERSION <specify CMake version here>)
project(Hidato)
set(CMAKE_CXX_STANDARD 14)
add_executable(Hidato main.cpp Puzzle.cpp Puzzle.h Generator.cpp Generator.h Solver.cpp Solver.h CellGraph.cpp CellGraph.h Cell.cpp Cell.h)<file_sep>/Solver.cpp
//
// Created by thdtj on 2018-11-21.
//
#include "Solver.h"
#include <time.h>
Stack::Stack() {
top = -1;
for (int i = 0; i < 1000; i++)
this->s[i] = 0;
}
int Stack::pop() {
if (empty()) {
return 0;
}
else {
return s[top--];
}
}
void Stack::push(int x, int y, int dir) {
s[++top] = x;
s[++top] = y;
s[++top] = dir;
}
bool Stack::empty() {
return (top == -1);
}
int Solver::hidato_solve(int num, const int goal, int position_x, int position_y, Puzzle& p) {
//***************************** Recursive *********************************************
if (num == goal)
return 1;
for (int i = 0; i < 8; i++) {
int next_x = position_x + this->direction[i][0];
int next_y = position_y + this->direction[i][1];
if (p[next_y][next_x] == num + 1) {
if (hidato_solve(num + 1, goal, next_x, next_y, p))
return 1;
}
}
for (int i = 0; i < 8; i++) {
int next_x = position_x + this->direction[i][0];
int next_y = position_y + this->direction[i][1];
if (p[next_y][next_x] == -1) {
p[next_y][next_x] = num + 1;
if (hidato_solve(num + 1, goal, next_x, next_y, p))
return 1;
p[next_y][next_x] = -1;
}
}
return 0;
/********************************** Stack **********************************************
Puzzle temp(p);
Stack s;
s.push(position_x, position_y, 0);
int found = 0;
while (!s.empty() && !found) {
int dir = s.pop();
int y = s.pop();
int x = s.pop();
while (dir < 8 && !found) {
int next_x = x + this->direction[dir][0];
int next_y = y + this->direction[dir][1];
if (num == goal)
found = 1;
else if (p[next_y][next_x] == num + 1 || p[next_y][next_x] == -1) {
if (p[next_y][next_x] == num + 1) { // if the next number exists
s.push(x, y, ++dir);
x = next_x; y = next_y; dir = 0;
++num;
}
else { // if blank
p[next_y][next_x] = ++num;
s.push(x, y, ++dir);
x = next_x; y = next_y; dir = 0;
}
}
else
dir++;
}
p[y][x] = temp[y][x];
num--;
}
return 0;
*/
}
int Solver::Answer_checking(Puzzle &p, Puzzle& answer) {
for (int i = 0; i < answer.getHeight(); i++) {
for (int j = 0; j < answer.getWidth(); j++) {
if (p[i][j] != answer[i][j]) {
std::cout << "Not correct" << std::endl;
return 0;
}
}
}
std::cout << "Correct" << std::endl;
return 0;
}
Puzzle &Solver::Solve(Puzzle &p, Puzzle& answer) {
// TODO
int goal = -1;
int position_x = 0, position_y = 0;
// find goal, find start_point
for (int i = 0; i < p.getHeight(); i++) {
for (int j = 0; j < p.getWidth(); j++) {
int temp = p[i][j];
if (temp != 0) {
if (temp > goal)
goal = temp;
if (temp == 1) {
position_x = j;
position_y = i;
}
}
}
}
//std::cout << goal << std::endl << position_x << " " << position_y << std::endl;
// solve_program
clock_t begin = clock();
hidato_solve(1, goal, position_x, position_y, p);
clock_t end = clock();
long msec1 = end - begin;
std::cout << msec1 * 0.001 << " sec" << "\n";
Answer_checking(p, answer);
return p;
}<file_sep>/Puzzle.h
//
// Created by thdtj on 2018-11-21.
//
#ifndef HIDATO_PUZZLE_H
#define HIDATO_PUZZLE_H
#include <iostream>
#include <fstream>
#include <ctime>
struct Point {
public:
Point() = default;
Point(int x, int y);
Point operator+(Point p) {
return { x + p.x, y + p.y };
}
bool operator==(const Point &rhs) const {
return x == rhs.x &&
y == rhs.y;
}
bool operator!=(const Point &rhs) const {
return !(rhs == *this);
}
bool operator<(const Point &rhs) const {
return x == rhs.x ? y < rhs.y : x < rhs.x;
}
friend std::ostream &operator<<(std::ostream &o, const Point &p) {
return o << p.x << " " << p.y;
}
friend std::istream &operator>>(std::istream &in, Point &p) {
return in >> p.x >> p.y;
}
int x;
int y;
};
class Puzzle {
public:
Puzzle();
Puzzle(int width, int height);
Puzzle(const Puzzle &p);
virtual ~Puzzle();
int *operator[](int i) const;
int *operator[](int i);
int operator[](const Point &p) const;
int &operator[](const Point &p);
Puzzle &operator=(const Puzzle &p);
friend std::ostream &operator<<(std::ostream &o, const Puzzle &p);
friend std::istream &operator>>(std::istream &in, Puzzle &p);
Puzzle &LoadFormFile(const char *name);
int getWidth() const;
int getHeight() const;
int getNumCells() const;
int getNumEmptyCells() const;
void setNumCells(int numCells);
void setNumEmptyCells(int numEmptyCells);
private:
int width;
int height;
int **map;
int numCells;
int numEmptyCells;
};
#endif //HIDATO_PUZZLE_H
<file_sep>/README.md
# Hidato
Hidato puzzle Generator and Solver
<file_sep>/CellGraph.h
//
// Created by thdtj on 2018-12-10.
//
#ifndef HIDATO_CELLGRAPH_H
#define HIDATO_CELLGRAPH_H
#include <vector>
#include <set>
#include <map>
#include "Puzzle.h"
#include "Cell.h"
class CellGraph {
public:
CellGraph() : width(0), height(0), map(nullptr) {}
CellGraph(const Puzzle &puzzle);
CellGraph(const CellGraph &cg);
virtual ~CellGraph();
Cell **operator[](int i) const;
Cell **operator[](int i);
Cell *operator[](const Point &p) const;
Cell *&operator[](const Point &p);
CellGraph &operator=(const CellGraph &cg);
Cell *getRandCell(int n) const;
Cell *getNextRandCell() const;
int getRemaindersSetSize();
void eraseRemainder(int n, Cell *pCell);
void eraseRemainders(int n);
void eraseCell(Cell *pCell);
void checkNeighbor(const Cell &c);
bool checkMapping();
bool is_candidatesEmpty();
bool is_remaindersEmpty();
bool is_finished();
Cell *find_onlyCandidate();
Cell *find_onlyRemainder();
private:
int width;
int height;
Cell ***map;
std::vector<Cell *> cells;
std::map<int, std::set<Cell *>> remaindersSet;
};
#endif //HIDATO_CELLGRAPH_H
<file_sep>/Cell.h
//
// Created by thdtj on 2018-12-13.
//
#ifndef HIDATO_CELL_H
#define HIDATO_CELL_H
#include <set>
#include "Puzzle.h"
class Cell {
public:
Cell() : data(0), pos(0, 0) {}
Cell(int data, const Point &p) : data(data), pos(p) {}
Cell(int data, int x, int y) : data(data), pos(x, y) {}
Cell(const Cell &c) = default;
virtual ~Cell();
int getData() const;
void setData(int data);
void setDataCandidate();
int getCandidate();
const Point &getPos() const;
Cell &operator=(const Cell &c);
void insertCandidate(int n);
void eraseCandidate(int n);
bool is_candidate(int n);
bool is_Neighbor(int x, int y);
bool is_Neighbor(const Point &p);
bool is_Neighbor(const Cell &c);
bool isCandidatesEmpty();
int getCandidatesSize();
private:
int data;
Point pos;
std::set<int> candidates;
};
#endif //HIDATO_CELL_H
<file_sep>/CellGraph.cpp
//
// Created by thdtj on 2018-12-10.
//
#include "CellGraph.h"
#include <random>
CellGraph::CellGraph(const Puzzle &puzzle) {
width = puzzle.getWidth();
height = puzzle.getHeight();
// Allocate map
map = new Cell **[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new Cell *[width + 2];
for (int j = 0; j < width + 2; ++j) {
map[i][j] = nullptr;
}
}
// Initialize remaindersSet
for (int n = 1; n < puzzle.getNumCells() + 1; ++n) {
remaindersSet.insert(std::pair<int, std::set<Cell *>>(n, std::set<Cell *>()));
}
// Create Cells
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int value = puzzle[i][j];
auto &p = (*this)[i][j];
if (value < 0) {
p = new Cell(value, j, i);
cells.emplace_back(p);
for (auto &remainders : remaindersSet) {
remainders.second.insert(p);
p->insertCandidate(remainders.first);
}
} else if (value > 0) {
auto &remainders = remaindersSet.find(value)->second;
remainders.clear();
std::set<Cell *>().swap(remainders);
remaindersSet.erase(value);
int prevValue = value - 1;
int nextValue = value + 1;
auto iter = remaindersSet.find(prevValue);
if (iter != remaindersSet.end()) {
auto &prevRemainders = iter->second;
for (auto prevRemainder = prevRemainders.begin(); prevRemainder != prevRemainders.end();) {
if (!prevRemainder.operator*()->is_Neighbor(j, i)) {
prevRemainder.operator*()->eraseCandidate(prevValue);
prevRemainder = prevRemainders.erase(prevRemainder);
} else {
++prevRemainder;
}
}
}
iter = remaindersSet.find(nextValue);
if (iter != remaindersSet.end()) {
auto &nextRemainders = iter->second;
for (auto nextRemainder = nextRemainders.begin(); nextRemainder != nextRemainders.end();) {
if (!nextRemainder.operator*()->is_Neighbor(j, i)) {
nextRemainder.operator*()->eraseCandidate(nextValue);
nextRemainder = nextRemainders.erase(nextRemainder);
} else {
++nextRemainder;
}
}
}
}
}
}
}
CellGraph::CellGraph(const CellGraph &cg) : width(cg.width), height(cg.height) {
// Allocate map
map = new Cell **[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new Cell *[width + 2];
for (int j = 0; j < width + 2; ++j) {
map[i][j] = cg.map[i][j] == nullptr ? nullptr : new Cell(*cg.map[i][j]);
}
}
// Mapping cells
for (auto &cgCell : cg.cells) {
cells.emplace_back((*this)[cgCell->getPos()]);
}
// Mapping remaindersSet
for (auto &cgRemainders : cg.remaindersSet) {
std::pair<std::map<int, std::set<Cell *>>::iterator, bool> remainders = remaindersSet.insert(
std::pair<int, std::set<Cell *>>(cgRemainders.first, std::set<Cell *>()));
for (auto &cgRemainder : cgRemainders.second) {
remainders.first->second.insert((*this)[cgRemainder->getPos()]);
}
}
}
CellGraph::~CellGraph() {
cells.clear();
std::vector<Cell *>().swap(cells);
for (auto &remainders : remaindersSet) {
remainders.second.clear();
std::set<Cell *>().swap(remainders.second);
}
remaindersSet.clear();
std::map<int, std::set<Cell *>>().swap(remaindersSet);
if (map != nullptr) {
for (int i = 0; i < height + 2; ++i) {
for (int j = 0; j < width + 2; ++j) {
if (map[i][j] != nullptr) {
delete map[i][j];
}
}
delete[] map[i];
}
delete[] map;
}
}
Cell **CellGraph::operator[](int i) const {
return map[i + 1] + 1;
}
Cell **CellGraph::operator[](int i) {
return map[i + 1] + 1;
}
Cell *CellGraph::operator[](const Point &p) const {
return map[p.y + 1][p.x + 1];
}
Cell *&CellGraph::operator[](const Point &p) {
return map[p.y + 1][p.x + 1];
}
CellGraph &CellGraph::operator=(const CellGraph &cg) {
cells.clear();
for (auto &remainders : remaindersSet) {
remainders.second.clear();
std::set<Cell *>().swap(remainders.second);
}
remaindersSet.clear();
if (map != nullptr) {
for (int i = 0; i < height + 2; ++i) {
for (int j = 0; j < width + 2; ++j) {
if (map[i][j] != nullptr) {
delete map[i][j];
}
}
delete[] map[i];
}
delete[] map;
}
width = cg.width;
height = cg.height;
cells = cg.cells;
// Allocate map
map = new Cell **[height + 2];
for (int i = 0; i < height + 2; ++i) {
map[i] = new Cell *[width + 2];
for (int j = 0; j < width + 2; ++j) {
map[i][j] = cg.map[i][j] == nullptr ? nullptr : new Cell(*cg.map[i][j]);
}
}
// Mapping cells
for (auto &cell : cells) {
cell = (*this)[cell->getPos()];
}
// Mapping remaindersSet
for (auto &cgRemainders : cg.remaindersSet) {
std::pair<std::map<int, std::set<Cell *>>::iterator, bool> remainders = remaindersSet.insert(
std::pair<int, std::set<Cell *>>(cgRemainders.first, std::set<Cell *>()));
for (auto &cgRemainder : cgRemainders.second) {
remainders.first->second.insert((*this)[cgRemainder->getPos()]);
}
}
return *this;
}
Cell *CellGraph::getRandCell(int n) const {
if (remaindersSet.empty()) {
return nullptr;
}
auto &remainders = remaindersSet.find(n)->second;
if (remainders.empty()) {
return nullptr;
}
unsigned long idx = rand() % remainders.size();
auto remainder = remainders.begin();
for (int i = 0; i < idx; ++i) {
++remainder;
}
return *remainder;
}
Cell *CellGraph::getNextRandCell() const {
if (remaindersSet.empty()) {
return nullptr;
}
auto iter = remaindersSet.begin();
auto &remainders = iter->second;
if (remainders.empty()) {
return nullptr;
}
unsigned long idx = rand() % remainders.size();
auto remainder = remainders.begin();
for (int i = 0; i < idx; ++i) {
++remainder;
}
((Cell *)*remainder)->setData(iter->first);
return *remainder;
}
int CellGraph::getRemaindersSetSize() {
return remaindersSet.size();
}
void CellGraph::eraseRemainder(int n, Cell *pCell) {
remaindersSet.find(n)->second.erase(pCell);
pCell->eraseCandidate(n);
}
void CellGraph::eraseRemainders(int n) {
auto iter = remaindersSet.find(n);
if (iter == remaindersSet.end()) {
return;
}
auto &remainders = iter->second;
for (auto &remainder : remainders) {
remainder->eraseCandidate(n);
}
remainders.clear();
std::set<Cell *>().swap(remainders);
remaindersSet.erase(iter);
}
void CellGraph::eraseCell(Cell *pCell) {
eraseRemainders(pCell->getData());
for (auto &remainders : remaindersSet) {
remainders.second.erase(pCell);
}
for (auto iter = cells.begin(); iter != cells.end(); ++iter) {
if (*iter == pCell) {
cells.erase(iter);
break;
}
}
(*this)[pCell->getPos()] = nullptr;
delete pCell;
}
void CellGraph::checkNeighbor(const Cell &c) {
int value = c.getData();
int prevValue = value - 1;
int nextValue = value + 1;
auto iter = remaindersSet.find(prevValue);
if (iter != remaindersSet.end()) {
auto &prevRemainders = iter->second;
for (auto prevRemainder = prevRemainders.begin(); prevRemainder != prevRemainders.end();) {
if (!prevRemainder.operator*()->is_Neighbor(c)) {
prevRemainder.operator*()->eraseCandidate(prevValue);
prevRemainder = prevRemainders.erase(prevRemainder);
} else {
++prevRemainder;
}
}
}
iter = remaindersSet.find(nextValue);
if (iter != remaindersSet.end()) {
auto &nextRemainders = iter->second;
for (auto nextRemainder = nextRemainders.begin(); nextRemainder != nextRemainders.end();) {
if (!nextRemainder.operator*()->is_Neighbor(c)) {
nextRemainder.operator*()->eraseCandidate(nextValue);
nextRemainder = nextRemainders.erase(nextRemainder);
} else {
++nextRemainder;
}
}
}
}
bool CellGraph::checkMapping() {
for (auto &cell : cells) {
if (cell != (*this)[cell->getPos()]) {
std::cerr << "Error : cells mapping was broken. " << cell->getPos() << std::endl;
return false;
}
}
for (auto &remainders : remaindersSet) {
for (auto &remainder : remainders.second) {
if (remainder != (*this)[remainder->getPos()]) {
std::cerr << "Error : remaindersSet mapping was broken. " << remainder->getPos() << std::endl;
return false;
}
}
}
return true;
}
bool CellGraph::is_candidatesEmpty() {
for (auto &cell : cells) {
if (cell->isCandidatesEmpty()) {
return false;
}
}
return true;
}
bool CellGraph::is_remaindersEmpty() {
for (auto &remainders : remaindersSet) {
if (remainders.second.empty()) {
return false;
}
}
return true;
}
bool CellGraph::is_finished() {
return cells.empty() && remaindersSet.empty();
}
Cell *CellGraph::find_onlyCandidate() {
for (auto &cell : cells) {
if (cell->getCandidatesSize() == 1) {
int data = cell->getCandidate();
auto itr = remaindersSet.find(data);
if (itr == remaindersSet.end() || itr->second.find(cell) == itr->second.end()) {
return nullptr;
}
cell->setDataCandidate();
return cell;
}
}
return nullptr;
}
Cell *CellGraph::find_onlyRemainder() {
for (auto &remainders : remaindersSet) {
if (remainders.second.size() == 1) {
Cell *cell = *remainders.second.begin();
if (cell->is_candidate(remainders.first)) {
return nullptr;
}
cell->setData(remainders.first);
return cell;
}
}
return nullptr;
}
| afd207e6e47887067e04d2aa2f903fbfbaf39d18 | [
"Markdown",
"CMake",
"C++"
] | 13 | C++ | algo-88team/Hidato | 6bfe5ea7660434d39c4bf69e75f7c436dbbf73d1 | f87e988d536ae7c9759fa54f81d9efd5aafa13a9 |
refs/heads/master | <repo_name>gavioto/gwt-polymer<file_sep>/src/main/java/br/com/rpa/client/_coreelements/CoreIconElement.java
package br.com.rpa.client._coreelements;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.TagName;
@TagName(CoreIconElement.TAG)
public class CoreIconElement extends Element {
public static final String TAG = "core-icon";
/**
* Assert that the given {@link Element} is compatible with this class and
* automatically typecast it.
*/
public static CoreIconElement as(final Element elem) {
assert elem.getTagName().equalsIgnoreCase(TAG);
return (CoreIconElement) elem;
}
protected CoreIconElement() {
}
public final native String getAlt() /*-{
return this.alt
}-*/;
public final native String getIcon() /*-{
return this.icon
}-*/;
public final native String getIconSrc() /*-{
return this.src
}-*/;
public final native void setAlt(String alt) /*-{
this.alt = alt;
}-*/;
public final native void setIcon(String icon) /*-{
this.icon = icon;
}-*/;
public final native void setIconSrc(String src) /*-{
this.src = src;
}-*/;
}
| 3f72e72ae54fc4c734cd929de613c5588cb09a47 | [
"Java"
] | 1 | Java | gavioto/gwt-polymer | e6f8fdf5ec9a35f747a348365f40507985299db5 | 87e50057bbc074b85b0fed53c97624487286ec11 |
refs/heads/master | <repo_name>Nareshbojja/Decra_serviceProvider<file_sep>/src/providers/generic/generic.ts
import { Injectable } from '@angular/core';
import { LoadingController, ToastController } from 'ionic-angular';
// import { StorageProvider } from '../storage/storage';
import firebase from 'firebase/app';
/*
Generated class for the GenericProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class GenericProvider {
public loading;
public reguser;
constructor(public toastCtrl: ToastController,public loadingCtrl: LoadingController,
// private storagePro: StorageProvider
) {
console.log('Hello GenericProvider Provider');
}
public getCurrentUserDetails(uid) {
return new Promise((resolve, reject) => {
let ref = "serviceProvider_details/" + uid
firebase.database().ref(ref).on('value', itemSnapshot => {
this.reguser = itemSnapshot.val();
resolve(this.reguser);
return false;
}, (error) => {
reject(error);
});
});
}
getMyOrders(myEmail){
return new Promise((resolve, reject) => {
firebase.database().ref('orders/').on('value', itemSnapshot => {
let orders = [];
//console.log(JSON.stringify(this.reguser));
itemSnapshot.forEach(itemSnap => {
if (myEmail == itemSnap.val().provider_email) {
console.log(itemSnap.val().provider_email);
orders.push(itemSnap.val());
}
return false;
});
resolve(orders);
}, (error) => {
reject(error);
});
});
}
getDriverEmails(){
return new Promise((resolve, reject) => {
firebase.database().ref('driver_details/').on('value', itemSnapshot => {
let drivers = [];
console.log(itemSnapshot.val());
itemSnapshot.forEach(itemSnap => {
if (itemSnap.val().avaialble === "yes") {
console.log(itemSnap.val().email);
// drivers.push(itemSnap.val().email);
drivers.push(itemSnap.val());
}
return false;
});
resolve(drivers);
}, (error) => {
reject(error);
});
});
}
updateStatus(order_id,driver){
let ref = "orders/"+order_id+"/";
return new Promise((resolve, reject) => {
firebase.database().ref(ref).on('value', itemSnapshot => {
firebase.database().ref(ref).update({
order_status: "on_the_way",
driver_info: driver
});
console.log(itemSnapshot.val());
resolve(true);
}, (error) => {
reject(error);
});
})
}
sendRejectmsg(order_id,msg){
let ref = "orders/"+order_id+"/";
return new Promise((resolve, reject) => {
firebase.database().ref(ref).on('value', itemSnapshot => {
firebase.database().ref(ref).update({
'reject_msg' : msg,
'order_status': "rejected"
})
console.log(itemSnapshot.val());
resolve(true);
}, (error) => {
reject(error);
});
})
}
updateDriver(order_id){
// let ref = "driverdetails/"+order_id+"/";
return new Promise((resolve, reject) => {
firebase.database().ref('driver_details/').orderByChild('email').equalTo(order_id).once('value', function (snapshot) {
var driverDetails = snapshot.val();
console.log(snapshot.key);
console.log(snapshot.val());
let obj = snapshot.val();
console.log(Object.keys(obj));
let key = Object.keys(obj);
let ref = "driver_details/"+key+"/";
console.log(ref);
// firebase.database().ref(ref).on('value', itemSnapshot => {
firebase.database().ref(ref).update({
avaialble: "no"
});
// })
resolve(driverDetails);
return false;
}, (error) => {
reject(error);
});
});
}
public showLoader() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...'
});
this.loading.present();
}
public hideLoader() {
this.loading.dismiss();
}
public presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 3000,
position: 'bottom'
});
toast.present();
}
}
<file_sep>/src/pages/moreinfo/moreinfo.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google: any;
import {TimerObservable} from "rxjs/observable/TimerObservable";
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/interval';
/**
* Generated class for the MoreinfoPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-moreinfo',
templateUrl: 'moreinfo.html',
})
export class MoreinfoPage {
order_det:any;
user_loc:any;
remainingSeconds: number;
runTimer: boolean;
hasStarted: boolean;
hasFinished: boolean;
displayTime: string;
myCount:any;
timeInSeconds: number;
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.order_det = navParams.get('vOrder');
console.log(this.order_det);
this.user_loc = this.order_det.u_latlng;
console.log("loc"+ this.user_loc);
this.tiner();
}
ionViewDidLoad() {
console.log('ionViewDidLoad MoreinfoPage');
}
tiner(){
setTimeout(start, 1000);
var i = 1;
// var num = document.getElementById('number');
function start() {
setInterval(increase, 1000);
}
function increase() {
if (i < 10000) {
i++;
this.myCount = i;
console.log(this.myCount);
}
}
}
ionViewDidEnter(){
//Set latitude and longitude of some place
let latLng = new google.maps.LatLng(-34.9290, 138.6010);
let mapOptions = {
center: this.user_loc,
zoom: 22,
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: false
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
console.log(this.order_det.u_latlng);
this.addMarker(this.order_det.u_latlng);
}
addMarker(latln){
let values = latln;
var latlng = new google.maps.LatLng(values);
console.log(values);
console.log(this.map.getCenter());
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
mapTypeId: google.maps.MapTypeId.ROADMAP,
position: this.user_loc,
mapTypeControl:false,
center: this.user_loc
});
//let content = "<h4>Information!</h4>";
//this.addInfoWindow(myMarker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
initTimer() {
if(!this.timeInSeconds) { this.timeInSeconds = 0; }
this.runTimer = false;
this.hasStarted = false;
this.hasFinished = false;
this.remainingSeconds = this.timeInSeconds;
this.displayTime = this.getSecondsAsDigitalClock(this.remainingSeconds);
}
startTimer() {
this.runTimer = true;
this.hasStarted = true;
this.timerTick();
}
timerTick() {
setTimeout(() => {
if (!this.runTimer) { return; }
this.remainingSeconds--;
this.displayTime = this.getSecondsAsDigitalClock(this.remainingSeconds);
if (this.remainingSeconds > 0) {
this.timerTick();
}
else {
this.hasFinished = true;
}
}, 1000);
}
getSecondsAsDigitalClock(inputSeconds: number) {
var sec_num = parseInt(inputSeconds.toString(), 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
var hoursString = '';
var minutesString = '';
var secondsString = '';
hoursString = (hours < 10) ? "0" + hours : hours.toString();
minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
return hoursString + ':' + minutesString + ':' + secondsString;
}
}
<file_sep>/src/providers/local-storage/local-storage.ts
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/Storage';
/*
Generated class for the LocalStorageProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class LocalStorageProvider {
constructor( public storage: Storage) {
console.log('Hello LocalStorageProvider Provider');
}
public setData(key,value){
console.log("data stored");
return this.storage.set(key,value);
}
public async getData(key){
return new Promise((resolve) => {
this.storage.get(key)
.then((data) =>{
console.log(data);
resolve(data),
error => resolve("")
});
});
}
public async remove(settingName){
console.log(settingName+"removed")
return await this.storage.remove(settingName);
}
public clearAll() {
this.storage.clear().then(() => {
console.log('all keys cleared');
});
}
}
<file_sep>/src/pages/main/main.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GenericProvider } from '../../providers/generic/generic';
import { LocalStorageProvider } from '../../providers/local-storage/local-storage';
import firebase from 'firebase/app';
import { SelectDriverPage } from '../select-driver/select-driver';
import { MoreinfoPage } from '../moreinfo/moreinfo';
import { OrderHistoryPage } from '../order-history/order-history';
import { RejectPage } from '../reject/reject';
/**
* Generated class for the MainPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-main',
templateUrl: 'main.html',
})
export class MainPage {
public myOrders: any;
public resEmail: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private genericPro: GenericProvider, private storagePro: LocalStorageProvider) {
// let myDetails:any = this.storagePro.getData('');
this.storagePro.getData('service_provier_details').then((val: any) => {
console.log("" + val);
this.resEmail = val.email;
// console.log("ooo" + this.resEmail);
this.getMYOrders(this.resEmail);
})
// let resEmail = JSON.stringify(myDetails.email);
}
myyynext(){
alert('ye8888ss');
}
getMYOrders(myEmail){
this.genericPro.showLoader();
firebase.database().ref('orders/').on('value', itemSnapshot => {
let orders = [];
console.log(itemSnapshot.val());
itemSnapshot.forEach(itemSnap => {
if (myEmail == itemSnap.val().provider_email) {
console.log(itemSnap.val().provider_email);
// let fromD = itemSnap.val().FromDate;
// let toD = itemSnap.val().ToDate;
// let dt1 = new Date(fromD);
// let dt2 = new Date(toD);
// let dif = Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()) ) /(1000 * 60 * 60 * 24));
// console.log(dif);
// itemSnap.val()['diff'] = dif;
orders.push(itemSnap.val());
//orders['difference'] = dif;
}
return false;
});
if(this.myOrders !== "" || this.myOrders !== null){
this.myOrders = orders;
}
else{
this.genericPro.presentToast("Sorry...You don't have any orders");
}
this.genericPro.hideLoader();
console.log("myyy"+JSON.stringify(this.myOrders));
})
}
reject(ordr_id){
this.navCtrl.push(RejectPage,{
'ordr' : ordr_id
});
}
selctDriver(o_id){
console.log(o_id);
//send status update as notification to the user
this.navCtrl.push(SelectDriverPage,{
'ordr' : o_id
});
}
viewMore(or_id){
// let viewOrd:any;
// console.log(order_id);
// this.myOrders.forEach(ord => {
// console.log(ord);
// if(order_id == ord.order_id){
// viewOrd = ord;
// }
// });
if(or_id){
let viewOrd:any;
for (var i=0; i < this.myOrders.length; i++) {
if (this.myOrders[i].order_id === or_id) {
console.log(this.myOrders[i]);
viewOrd = this.myOrders[i];
}
}
this.navCtrl.push(MoreinfoPage,{
'vOrder' : viewOrd
});
}
}
ordershist(){
this.navCtrl.push(OrderHistoryPage);
}
ionViewDidLoad() {
console.log('ionViewDidLoad MainPage');
}
}
<file_sep>/src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { GenericProvider } from '../../providers/generic/generic';
import { LocalStorageProvider } from '../../providers/local-storage/local-storage';
import firebase from 'firebase';
import { MainPage } from '../main/main'
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
sdata = {
"email": "<EMAIL>", "password": "<PASSWORD>"
}
loginData: any;
constructor(public navCtrl: NavController, private genericPro: GenericProvider, private localStorage: LocalStorageProvider) {
}
Login() {
if (this.sdata.email === undefined || this.sdata.email === "") {
this.genericPro.presentToast('Please enter your email ID');
}
else if (this.sdata.password === undefined || this.sdata.password === "") {
this.genericPro.presentToast('Please enter your password');
}
else {
this.genericPro.showLoader();
firebase.auth().signInWithEmailAndPassword(this.sdata.email, this.sdata.password).then(res => {
if (res) {
var resEmail;
console.log(res);
resEmail = res.email;
var de = firebase.auth().currentUser.uid;
//console.log(de);
this.genericPro.getCurrentUserDetails(de).then(result => {
console.log(result);
// this.storagePro.remove("user_data");
this.loginData = result;
this.genericPro.hideLoader();
if (this.loginData == null) {
this.genericPro.presentToast("Sorry, user not found");
}
else{
this.localStorage.setData("service_provier_details",this.loginData);
//this.events.publish('loggedin');
this.navCtrl.setRoot(MainPage);
}
}
)
}
else {
alert("Err");
this.genericPro.presentToast("Login failed");
}
}).catch(err => {
this.genericPro.hideLoader();
this.genericPro.presentToast(err);
})
}
}
}
<file_sep>/src/pages/order-history/order-history.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GenericProvider } from '../../providers/generic/generic';
import { LocalStorageProvider } from '../../providers/local-storage/local-storage';
import firebase from 'firebase/app';
/**
* Generated class for the OrderHistoryPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-order-history',
templateUrl: 'order-history.html',
})
export class OrderHistoryPage {
resEmail:any;
myOrders :any;
totolOrders:any;
noOrders:boolean = false;
constructor(public navCtrl: NavController, public navParams: NavParams, private genericPro: GenericProvider, private storagePro: LocalStorageProvider) {
this.storagePro.getData('service_provier_details').then((val: any) => {
console.log("" + val);
this.resEmail = val.email;
// console.log("ooo" + this.resEmail);
this.getMYOrders(this.resEmail);
})
}
getMYOrders(myEmail){
this.genericPro.showLoader();
firebase.database().ref('orders/').on('value', itemSnapshot => {
let orders = [];
console.log(itemSnapshot.val());
itemSnapshot.forEach(itemSnap => {
if (myEmail == itemSnap.val().provider_email) {
console.log(itemSnap.val().provider_email);
orders.push(itemSnap.val());
}
return false;
});
if(this.myOrders !== "" || this.myOrders !== null){
this.myOrders = orders;
this.totolOrders = orders;
}
else{
this.genericPro.presentToast("Sorry...You don't have any orders");
}
this.genericPro.hideLoader();
console.log("myyy"+JSON.stringify(this.myOrders));
})
}
ionViewDidLoad() {
console.log('ionViewDidLoad OrderHistoryPage');
}
next(){
alert('yesss');
}
accepted(){
console.log(this.totolOrders);
this.getFilter("on_the_way");
}
timeup(){
this.getFilter("time_up")
}
rejected(){
this.getFilter("rejected")
}
finished(){
this.getFilter("finished")
}
getFilter(status){
let checkorder = [];
for (var i=0; i < this.totolOrders.length; i++) {
if (this.totolOrders[i].order_status === status) {
console.log(this.totolOrders[i]);
checkorder.push(this.totolOrders[i])
console.log(checkorder);
this.noOrders= false;
}
}
this.myOrders = checkorder;
if(this.myOrders.length <= 0){
this.noOrders = true;
}
return this.myOrders;
}
}
<file_sep>/src/pages/reject/reject.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GenericProvider } from '../../providers/generic/generic';
/**
* Generated class for the RejectPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-reject',
templateUrl: 'reject.html',
})
export class RejectPage {
rejectmsg:any;
rorder_id :any;
constructor(public navCtrl: NavController, public navParams: NavParams, public genericPro: GenericProvider) {
this.rorder_id = navParams.get('ordr');
console.log(this.rorder_id);
}
ionViewDidLoad() {
console.log('ionViewDidLoad RejectPage');
}
doreject(){
console.log(this.rejectmsg);
this.genericPro.sendRejectmsg(this.rorder_id, this.rejectmsg);
}
}
<file_sep>/src/pages/select-driver/select-driver.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GenericProvider } from '../../providers/generic/generic';
import { LocalStorageProvider } from '../../providers/local-storage/local-storage';
import { MainPage } from '../main/main';
/**
* Generated class for the SelectDriverPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-select-driver',
templateUrl: 'select-driver.html',
})
export class SelectDriverPage {
driver_emails :any;
sel_mail:any;
drivers:any;
order_id:any;
sel_driver:any;
constructor(public navCtrl: NavController, public navParams: NavParams, private genericPro: GenericProvider, private localStorage: LocalStorageProvider) {
this.order_id = navParams.get('ordr');
console.log(this.order_id);
}
ionViewDidLoad() {
this.genericPro.getDriverEmails().then((driver)=>{
this.drivers = driver;
console.log(this.drivers);
this.driver_emails = this.drivers.map(a => a.email);
console.log(this.driver_emails);
if(this.driver_emails <= 0){
this.genericPro.presentToast('Currently all the drivers are busy');
}
})
console.log('ionViewDidLoad SelectDriverPage');
}
seldriver() {
console.log(this.sel_mail);
// console.log(this.category);
}
done(){
if(this.sel_mail){
for (var i=0; i < this.drivers.length; i++) {
if (this.drivers[i].email === this.sel_mail) {
console.log(this.drivers[i]);
this.sel_driver = this.drivers[i];
delete this.sel_driver.password;
delete this.sel_driver.avaialble;
}
}
this.genericPro.updateStatus(this.order_id, this.sel_driver);
this.genericPro.updateDriver(this.sel_mail).then(()=>{
this.navCtrl.push(MainPage);
})
}
else{
this.genericPro.presentToast('Please select driver');
}
}
}
<file_sep>/www/assets/globla.js
var ev;
console.log('hi');
var gflag = true;
var pos;
var user;
var token;
var selectedkey;
var orderId;
var myCart=[];
var myTotal = 0;
var orderChanges;
var locationChanges;
var hasOrder=false;
var changes;
var activeOrders=[];
var locationService;
var activeOrdersObject={};
var posUpdate;
var back={ "direction" : "right", // 'left|right|up|down', default 'left' (which is like 'next')
"slowdownfactor" : 2, // overlap views (higher number is more) or no overlap (1). -1 doesn't slide at all. Default 4
"fixedPixelsTop" : 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
"duration":300
};
var next={ "direction" : "left", // 'left|right|up|down', default 'left' (which is like 'next')
"slowdownfactor" : 1, // overlap views (higher number is more) or no overlap (1). -1 doesn't slide at all. Default 4
"slidePixels":0,
"andriddelay":200,
"iosdelay":200,
"fixedPixelsTop" : 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
"duration":350
};
firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "justbeep-d5636.firebaseapp.com",
databaseURL: "https://justbeep-d5636.firebaseio.com",
projectId: "justbeep-d5636",
storageBucket: "justbeep-d5636.appspot.com",
messagingSenderId: "49153713702"
});
var watch;
var db = firebase.firestore();
function watchPosition()
{
if(gflag)
{
console.log("watch started...");
watch= navigator.geolocation.watchPosition((p)=>{pos=p;
// console.log("watcher: " + p)
if(user)
{
}
console.log(pos);
//ev.publish("position Update");
}, (e)=>{console.log(e);}, {enableHighAccuracy:true});
gflag = false;
}
}
function stopWatch()
{
gflag= true;
navigator.geolocation.clearWatch(watch);
}
var tempOption=
{
combo:true,
name:'options test2',
img:"https://scontent-sea1-1.cdninstagram.com/t51.2885-15/e35/20393662_505900299745674_8460001815432265728_n.jpg?ig_cache_key=MTU2Njc5NTIzMzI4MjcxODMyOQ%3D%3D.2",
price:20,
options:[
{multi:false,desc:'your size choice.',default:'small',options:[{name:'small',price:0},{name:"large",price:3}]},
{multi:true,desc:'select addons.',options:[{name:'extra shot',price:3,selected:false},{name:"caramel",price:3,selected:false}]}
]
}
//db.collection("busienss/pizzaHutMadenahQurban/categories").doc().set({icon:'002',name:'cold drinks',items:[tempOption]},{merge:true});<file_sep>/platforms/ios/www/assets/scripts.js
var service ="";
var myLocation;
var rate = 0;
var currancy="";
var car="";
var back={ "direction" : "right", // 'left|right|up|down', default 'left' (which is like 'next')
"slowdownfactor" : 2, // overlap views (higher number is more) or no overlap (1). -1 doesn't slide at all. Default 4
"fixedPixelsTop" : 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
"duration":300
};
var next={ "direction" : "left", // 'left|right|up|down', default 'left' (which is like 'next')
"slowdownfactor" : 2, // overlap views (higher number is more) or no overlap (1). -1 doesn't slide at all. Default 4
"fixedPixelsTop" : 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
"duration":300
}; | ddd87607b8f5256ea35e1d600890c5d0e1d32c23 | [
"JavaScript",
"TypeScript"
] | 10 | TypeScript | Nareshbojja/Decra_serviceProvider | 07d1f526563de61999861bdfe8244fbeebd52139 | 79c74f6c2bde001b4911f7c9063251e9973e25c0 |
refs/heads/master | <repo_name>Udaypalmewada/spring_transaction<file_sep>/JDBCtransaction/src/com/app/txmgmt/TESTtxmgmt.java
package com.app.txmgmt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class TESTtxmgmt {
public static void main(String[] args) throws SQLException {
Scanner sc = null;
Connection con = null;
PreparedStatement psmt = null;
boolean rs;
String name = null;
int number = 0;
double amount = 0;
boolean flag = false;
String driverclassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "<PASSWORD>";
sc = new Scanner(System.in);
System.out.println("enter number");
number = sc.nextInt();
sc.nextLine();
System.out.println("enter name");
name = sc.nextLine();
System.out.println("enter amount");
amount = sc.nextDouble();
// con=Class.forName(driverclassName);
con = DriverManager.getConnection(url, username, password);
try {
if (con != null) {
psmt = (PreparedStatement) con.prepareStatement("INSERT INTO person VALUES (?,?,?)");
psmt.setInt(1, number);
psmt.setString(2, name);
psmt.setDouble(3, amount);
psmt.execute();
flag = true;
}
if (flag == false) {
System.out.println("commited not happend");
con.setAutoCommit(false);
System.out.println("roll back data");
con.rollback();
} else {
con.setAutoCommit(true);
System.out.println("data commited");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 03da93007624631fc0b3410f4ee50ab9151f2f02 | [
"Java"
] | 1 | Java | Udaypalmewada/spring_transaction | 5e7357fd99f18b7357a95913afbe8955b673658d | bb53806bbec225d740ba003d29355861e355a22e |
refs/heads/master | <file_sep>#!/usr/bin/env python
import telepot
import time
import sys
from pprint import pprint
class TheBot:
def __init__(self):
TOKEN = '<YOUR TOKEN>'
self.bot = telepot.Bot(TOKEN);
self.bot.notifyOnMessage(self.handle_msg)
def handle_msg(self,msg):
pprint( msg )
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'text':
response = self.get_response(msg)
self.bot.sendMessage(chat_id,response)
def get_response(self,msg):
command = msg['text']
if command == '/help':
return """Esta es la ayuda de nuestro bot
/help mostrara la ayuda
/start registra el usuario de nuevo en el sistema
/terminar elimina al usuario del sistema"""
elif command == '/start':
return 'Hola '+ msg['from']['first_name'] +', yo sere tu asistente cultural de Galicia, sera un placer informarte'
else:
return msg['text'][::-1]
def main():
theBot = TheBot()
while 1:
time.sleep(10)
if __name__ == '__main__':
main()
<file_sep>from TheBot import TheBot
| 4d9332d9b7488ba3492171577fac8fc893c652d4 | [
"Python"
] | 2 | Python | viticlick/teleBot | 79affbaf2290f1edbebdf55e39c684bb36ed70d7 | 572b5a68b245e4d539727c7d688f9596c2bcc7b0 |
refs/heads/master | <file_sep># 常用分词用具比较
hanlp jieba
# 集成要求
- 不能太大
- 内存不能太高
- java?python?<file_sep>package com.idss.demo;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.collection.AhoCorasick.AhoCorasickDoubleArrayTrie;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord;
import com.hankcs.hanlp.dictionary.CoreDictionary;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import com.hankcs.hanlp.dictionary.py.Pinyin;
import com.hankcs.hanlp.mining.word2vec.DocVectorModel;
import com.hankcs.hanlp.mining.word2vec.WordVectorModel;
import com.hankcs.hanlp.model.crf.CRFLexicalAnalyzer;
import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment;
import com.hankcs.hanlp.seg.NShort.NShortSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.suggest.Suggester;
import com.hankcs.hanlp.tokenizer.*;
import java.io.IOException;
import java.util.List;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ) throws IOException {
//tokenizerUsage();
//standardTokenizer();
nlp();
//index();
//nShortSegment();
//crf();
//highSpeedSegment();
//customDictionary();
//chineseName();
//translatedName();
//japaneseName();
//placeName();
//organizationName();
//keyword();
//extractSummary();
//extractPhrase();
//pinyin();
//traditional2Simplified();
//suggester();
//dependencyParser();
}
private static void standardTokenizer(){
String text = "你好,我住在苏州市工业园区锦溪苑小区,手机号码是15618297613,电话号码0512-88886666";
System.out.println(String.format("Demo: %s",StandardTokenizer.segment(text)));
}
private static void tokenizerUsage(){
String text = "你好,我住在苏州市工业园区锦溪苑小区,手机号码是15618297613,电话号码0512-88886666";
System.out.println(String.format("Demo: %s",HanLP.segment(text)));
System.out.println(String.format("StandardTokenizer: %s",StandardTokenizer.segment(text)));
System.out.println(String.format("BasicTokenizer: %s", BasicTokenizer.segment(text)));
System.out.println(String.format("IndexTokenizer: %s", IndexTokenizer.segment(text)));
System.out.println(String.format("NLPTokenizer: %s", NLPTokenizer.segment(text)));
System.out.println(String.format("NotionalTokenizer: %s", NotionalTokenizer.segment(text)));
System.out.println(String.format("SpeedTokenizer: %s", SpeedTokenizer.segment(text)));
System.out.println(String.format("TraditionalChineseTokenizer: %s", TraditionalChineseTokenizer.segment(text)));
System.out.println(String.format("URLTokenizer: %s", URLTokenizer.segment(text)));
}
private static void dependencyParser(){
CoNLLSentence sentence = HanLP.parseDependency("徐先生还具体帮助他确定了把画雄鹰、松鼠和麻雀作为主攻目标。");
System.out.println(sentence);
// 可以方便地遍历它
for (CoNLLWord word : sentence)
{
System.out.printf("%s --(%s)--> %s\n", word.LEMMA, word.DEPREL, word.HEAD.LEMMA);
}
// 也可以直接拿到数组,任意顺序或逆序遍历
CoNLLWord[] wordArray = sentence.getWordArray();
for (int i = wordArray.length - 1; i >= 0; i--)
{
CoNLLWord word = wordArray[i];
System.out.printf("%s --(%s)--> %s\n", word.LEMMA, word.DEPREL, word.HEAD.LEMMA);
}
// 还可以直接遍历子树,从某棵子树的某个节点一路遍历到虚根
CoNLLWord head = wordArray[12];
while ((head = head.HEAD) != null)
{
if (head == CoNLLWord.ROOT) System.out.println(head.LEMMA);
else System.out.printf("%s --(%s)--> ", head.LEMMA, head.DEPREL);
}
}
private static void word2Vec(){
/*WordVectorModel wordVectorModel = trainOrLoadModel();
printNearest("中国", wordVectorModel);
printNearest("美丽", wordVectorModel);
printNearest("购买", wordVectorModel);
// 文档向量
DocVectorModel docVectorModel = new DocVectorModel(wordVectorModel);
String[] documents = new String[]{
"山东苹果丰收",
"农民在江苏种水稻",
"奥运会女排夺冠",
"世界锦标赛胜出",
"中国足球失败",
};
System.out.println(docVectorModel.similarity(documents[0], documents[1]));
System.out.println(docVectorModel.similarity(documents[0], documents[4]));
for (int i = 0; i < documents.length; i++)
{
docVectorModel.addDocument(i, documents[i]);
}
printNearestDocument("体育", documents, docVectorModel);
printNearestDocument("农业", documents, docVectorModel);
printNearestDocument("我要看比赛", documents, docVectorModel);
printNearestDocument("要不做饭吧", documents, docVectorModel);*/
}
private static void suggester(){
Suggester suggester = new Suggester();
String[] titleArray =(
"威廉王子发表演说 呼吁保护野生动物\n" +
"《时代》年度人物最终入围名单出炉 普京马云入选\n" +
"“黑格比”横扫菲:菲吸取“海燕”经验及早疏散\n" +
"日本保密法将正式生效 日媒指其损害国民知情权\n" +
"英报告说空气污染带来“公共健康危机”"
).split("\\n");
for (String title : titleArray)
{
suggester.addSentence(title);
}
System.out.println(suggester.suggest("发言", 1)); // 语义
System.out.println(suggester.suggest("危机公共", 1)); // 字符
System.out.println(suggester.suggest("mayun", 1)); // 拼音
}
private static void traditional2Simplified(){
System.out.println(HanLP.convertToTraditionalChinese("用笔记本电脑写程序"));
System.out.println(HanLP.convertToSimplifiedChinese("「以後等妳當上皇后,就能買士多啤梨慶祝了」"));
}
private static void pinyin(){
String text = "重载不是重任";
List<Pinyin> pinyinList = HanLP.convertToPinyinList(text);
System.out.print("原文,");
for (char c : text.toCharArray())
{
System.out.printf("%c,", c);
}
System.out.println();
System.out.print("拼音(数字音调),");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin);
}
System.out.println();
System.out.print("拼音(符号音调),");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getPinyinWithToneMark());
}
System.out.println();
System.out.print("拼音(无音调),");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getPinyinWithoutTone());
}
System.out.println();
System.out.print("声调,");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getTone());
}
System.out.println();
System.out.print("声母,");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getShengmu());
}
System.out.println();
System.out.print("韵母,");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getYunmu());
}
System.out.println();
System.out.print("输入法头,");
for (Pinyin pinyin : pinyinList)
{
System.out.printf("%s,", pinyin.getHead());
}
System.out.println();
}
private static void extractPhrase(){
String text = "算法工程师\n" +
"算法(Algorithm)是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时间内获得所要求的输出。如果一个算法有缺陷,或不适合于某个问题,执行这个算法将不会解决这个问题。不同的算法可能用不同的时间、空间或效率来完成同样的任务。一个算法的优劣可以用空间复杂度与时间复杂度来衡量。算法工程师就是利用算法处理事物的人。\n" +
"\n" +
"1职位简介\n" +
"算法工程师是一个非常高端的职位;\n" +
"专业要求:计算机、电子、通信、数学等相关专业;\n" +
"学历要求:本科及其以上的学历,大多数是硕士学历及其以上;\n" +
"语言要求:英语要求是熟练,基本上能阅读国外专业书刊;\n" +
"必须掌握计算机相关知识,熟练使用仿真工具MATLAB等,必须会一门编程语言。\n" +
"\n" +
"2研究方向\n" +
"视频算法工程师、图像处理算法工程师、音频算法工程师 通信基带算法工程师\n" +
"\n" +
"3目前国内外状况\n" +
"目前国内从事算法研究的工程师不少,但是高级算法工程师却很少,是一个非常紧缺的专业工程师。算法工程师根据研究领域来分主要有音频/视频算法处理、图像技术方面的二维信息算法处理和通信物理层、雷达信号处理、生物医学信号处理等领域的一维信息算法处理。\n" +
"在计算机音视频和图形图像技术等二维信息算法处理方面目前比较先进的视频处理算法:机器视觉成为此类算法研究的核心;另外还有2D转3D算法(2D-to-3D conversion),去隔行算法(de-interlacing),运动估计运动补偿算法(Motion estimation/Motion Compensation),去噪算法(Noise Reduction),缩放算法(scaling),锐化处理算法(Sharpness),超分辨率算法(Super Resolution),手势识别(gesture recognition),人脸识别(face recognition)。\n" +
"在通信物理层等一维信息领域目前常用的算法:无线领域的RRM、RTT,传送领域的调制解调、信道均衡、信号检测、网络优化、信号分解等。\n" +
"另外数据挖掘、互联网搜索算法也成为当今的热门方向。\n" +
"算法工程师逐渐往人工智能方向发展。";
List<String> phraseList = HanLP.extractPhrase(text, 10);
System.out.println(phraseList);
}
private static void extractSummary(){
String document = "算法可大致分为基本算法、数据结构的算法、数论算法、计算几何的算法、图的算法、动态规划以及数值分析、加密算法、排序算法、检索算法、随机化算法、并行算法、厄米变形模型、随机森林算法。\n" +
"算法可以宽泛的分为三类,\n" +
"一,有限的确定性算法,这类算法在有限的一段时间内终止。他们可能要花很长时间来执行指定的任务,但仍将在一定的时间内终止。这类算法得出的结果常取决于输入值。\n" +
"二,有限的非确定算法,这类算法在有限的时间内终止。然而,对于一个(或一些)给定的数值,算法的结果并不是唯一的或确定的。\n" +
"三,无限的算法,是那些由于没有定义终止定义条件,或定义的条件无法由输入的数据满足而不终止运行的算法。通常,无限算法的产生是由于未能确定的定义终止条件。";
List<String> sentenceList = HanLP.extractSummary(document, 3);
System.out.println(sentenceList);
}
private static void keyword(){
String content = "程序员(英文Programmer)是从事程序开发、维护的专业人员。一般将程序员分为程序设计人员和程序编码人员,但两者的界限并不非常清楚,特别是在中国。软件从业人员分为初级程序员、高级程序员、系统分析员和项目经理四大类。";
List<String> keywordList = HanLP.extractKeyword(content, 5);
System.out.println(keywordList);
}
private static void organizationName(){
String[] testCase = new String[]{
"我在上海林原科技有限公司兼职工作,",
"我经常在台川喜宴餐厅吃饭,",
"偶尔去地中海影城看电影。",
"我的电脑号码是15618297613,邮箱是<EMAIL>"
};
Segment segment = HanLP.newSegment().enableOrganizationRecognize(true);
for (String sentence : testCase){
List<Term> termList = segment.seg(sentence);
System.out.println(termList);
}
}
private static void placeName(){
String[] testCase = new String[]{
"武胜县新学乡政府大楼门前锣鼓喧天",
"蓝翔给宁夏固原市彭阳县红河镇黑牛沟村捐赠了挖掘机",
"我的住址是苏州市工业园区锦溪街66号锦溪苑"
};
Segment segment = HanLP.newSegment().enablePlaceRecognize(true);
for (String sentence : testCase)
{
List<Term> termList = segment.seg(sentence);
System.out.println(termList);
}
}
private static void japaneseName(){
String[] testCase = new String[]{
"北川景子参演了林诣彬导演的《速度与激情3》",
"林志玲亮相网友:确定不是波多野结衣?",
};
Segment segment = HanLP.newSegment().enableJapaneseNameRecognize(true);
for (String sentence : testCase) {
List<Term> termList = segment.seg(sentence);
System.out.println(termList);
}
}
private static void translatedName(){
String[] testCase = new String[]{
"一桶冰水当头倒下,微软的比尔盖茨、Facebook的扎克伯格跟桑德博格、亚马逊的贝索斯、苹果的库克全都不惜湿身入镜,这些硅谷的科技人,飞蛾扑火似地牺牲演出,其实全为了慈善。",
"世界上最长的姓名是简森·乔伊·亚历山大·比基·卡利斯勒·达夫·埃利奥特·福克斯·伊维鲁莫·马尔尼·梅尔斯·帕特森·汤普森·华莱士·普雷斯顿。",
};
Segment segment = HanLP.newSegment().enableTranslatedNameRecognize(true);
for (String sentence : testCase){
List<Term> termList = segment.seg(sentence);
System.out.println(termList);
}
}
private static void chineseName(){
String[] testCase = new String[]{
"签约仪式前,秦光荣、李纪恒、仇和等一同会见了参加签约的企业家。",
"王国强、高峰、汪洋、张朝阳光着头、韩寒、小四",
"张浩和胡健康复员回家了",
"王总和小丽结婚了",
"编剧邵钧林和稽道青说",
"这里有关天培的有关事迹",
"龚学平等领导,邓颖超生前",
};
Segment segment = HanLP.newSegment()
.enableNameRecognize(true);
for (String sentence : testCase){
List<Term> termList = segment.seg(sentence);
System.out.println(termList);
}
}
private static void customDictionary(){
// 动态增加
CustomDictionary.add("攻城狮");
// 强行插入
CustomDictionary.insert("白富美", "nz 1024");
// 删除词语(注释掉试试)
CustomDictionary.remove("攻城狮");
System.out.println(CustomDictionary.add("单身狗", "nz 1024 n 1"));
System.out.println(CustomDictionary.get("单身狗"));
String text = "攻城狮逆袭单身狗,迎娶白富美,走上人生巅峰"; // 怎么可能噗哈哈!
// AhoCorasickDoubleArrayTrie自动机扫描文本中出现的自定义词语
final char[] charArray = text.toCharArray();
CustomDictionary.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute>() {
@Override
public void hit(int begin, int end, CoreDictionary.Attribute value) {
System.out.printf("[%d:%d]=%s %s\n", begin, end, new String(charArray, begin, end - begin), value);
}
});
// 自定义词典在所有分词器中都有效
System.out.println(HanLP.segment(text));
}
private static void highSpeedSegment(){
String text = "江西鄱阳湖干枯,中国最大淡水湖变成大草原";
System.out.println(SpeedTokenizer.segment(text));
long start = System.currentTimeMillis();
int pressure = 1000000;
for (int i = 0; i < pressure; ++i){
SpeedTokenizer.segment(text);
}
double costTime = (System.currentTimeMillis() - start) / (double)1000;
System.out.printf("分词速度:%.2f字每秒", text.length() * pressure / costTime);
}
private static void crf() throws IOException {
CRFLexicalAnalyzer analyzer = new CRFLexicalAnalyzer();
/*String[] tests = new String[]{
"商品和服务",
"上海华安工业(集团)公司董事长谭旭光和秘书胡花蕊来到美国纽约现代艺术博物馆参观",
"微软公司於1975年由比爾·蓋茲和保羅·艾倫創立,18年啟動以智慧雲端、前端為導向的大改組。" // 支持繁体中文
};*/
String[] tests = new String[]{
"签约仪式前,秦光荣、李纪恒、仇和等一同会见了参加签约的企业家。",
"王国强、高峰、汪洋、张朝阳光着头、韩寒、小四",
"张浩和胡健康复员回家了",
"王总和小丽结婚了",
"编剧邵钧林和稽道青说",
"这里有关天培的有关事迹",
"龚学平等领导,邓颖超生前",
};
for (String sentence : tests){
System.out.println(analyzer.analyze(sentence));
}
}
private static void nShortSegment(){
Segment nShortSegment = new NShortSegment()
.enableCustomDictionary(false)
.enablePlaceRecognize(true)
.enableOrganizationRecognize(true);
Segment shortestSegment = new DijkstraSegment()
.enableCustomDictionary(false)
.enablePlaceRecognize(true)
.enableOrganizationRecognize(true);
String[] testCase = new String[]{
"今天,刘志军案的关键人物,山西女商人丁书苗在市二中院出庭受审。",
"刘喜杰石国祥会见吴亚琴先进事迹报告团成员",
};
for (String sentence : testCase) {
System.out.println("N-最短分词:" + nShortSegment.seg(sentence) + "\n最短路分词:" + shortestSegment.seg(sentence));
}
}
private static void index(){
List<Term> termList = IndexTokenizer.segment("欢迎使用HanLP汉语处理包");
for(Term term:termList){
System.out.println(term + " [" + term.offset + ":" + (term.offset + term.word.length()) + "]");
}
}
private static void nlp(){
String[] tests = new String[]{
"签约仪式前,秦光荣、李纪恒、仇和等一同会见了参加签约的企业家。",
"王国强、高峰、汪洋、张朝阳光着头、韩寒、小四",
"张浩和胡健康复员回家了",
"王总和小丽结婚了",
"编剧邵钧林和稽道青说",
"这里有关天培的有关事迹",
"龚学平等领导,邓颖超生前",
"你好,我住在苏州市工业园区锦溪苑小区,手机号码是15618297613,电话号码0512-88886666,邮箱是<EMAIL>。qq邮箱是<EMAIL>"
};
for (String test:tests){
System.out.println(NLPTokenizer.segment(test));
}
}
}
| 87752022b77b787390fb1ab031d8188b05f9812c | [
"Markdown",
"Java"
] | 2 | Markdown | huoqubing/chineseanalysis | 5b5620d550379ef66a4510934563f91a4373e893 | 66c42ac74b0298f24002aea572c37ddcd17b7f38 |
refs/heads/master | <repo_name>NathansStuff/PlatformerGame<file_sep>/src/anims/index.js
export default anims => {
anims.create({
key: 'hit-effect',
frames: anims.generateFrameNumbers('hit-sheet', {
start: 0, end: 4
}), frameRate: 10, repeat: 0
})
} | 86491196d2ff400ff6a37660f3c22d967db7d3fb | [
"JavaScript"
] | 1 | JavaScript | NathansStuff/PlatformerGame | f6002411d6e50a22301f08195cf5aa2724df927b | fce1890c0d2d2d986e174aad4b422296b4b31134 |
refs/heads/master | <file_sep>console.log(process.argv);
// Protractor config
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
specs: ['spec/modularized.spec.js'],
capabilities: {
'browserName': 'chrome'
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
// add jasmine spec reporter
jasmine.getEnv().addReporter(new SpecReporter({
displaySpecDuration: true,
displaySuiteNumber: true,
prefixes: {
success: '[OK] ',
failure: '[ERR] '
}
}));
},
// Default params
params: {
file: 'specs.json',
mode: 'full',
index: 0
},
rootElement: 'html',
allScriptsTimeout: 100
}
<file_sep>/**
* Check element clickability
* @param {string} strIdentifier `string` for default type ID or `type=value` e.g. `id=string`
* @return {function} `it` spec block
*/
module.exports = function(strIdentifier) {
var helpers = global.specsAPI.helpers,
format = helpers.format;
if (!strIdentifier) {
console.log(format.formatError('Module [' + module.id + ']: Missing argument, either ' +
'string ID of an element or simple locator e.g. `id=string`, `linkText=string` etc.'));
return;
}
var locator = helpers.locators.getLocator(strIdentifier),
locatorName = locator.name,
locatorValue = locator.value;
return it('Checked clickability for ' +
format.formatModuleDetail('Element of type "' + locatorName + '", with value "' +
locatorValue + '"'), function() {
browser.wait(protractor.ExpectedConditions.elementToBeClickable(
element(by[locatorName](locatorValue))
), 1000, 'Element is not clickable!');
});
};
<file_sep>/**
* OJ Options name spec module
* @param {array} arrOptionNames Array with OJ option names, in order
* @return {function} `it` spec block
*/
module.exports = function(arrOptionNames) {
var format = global.specsAPI.helpers.format;
if (!arrOptionNames || !arrOptionNames.length) {
console.log(format.formatError('Module [' + module.id + ']: Missing the option names that ' +
'need checking in the OJ page: an array with at least one member.'));
return;
}
return it('The current OJ page should have the following option names: ' +
format.formatModuleDetail(format.getDetailFromArray(arrOptionNames)), function() {
var elemsUserChoice = element.all(by.css('input.radio'));
elemsUserChoice.each(function(elem, index) {
// Get the ID so we can associate it with a label - `input` elements are connected
// to their `label` element through the `id` and `for` HTML attributes
elem.getAttribute('id').then(function(strIdAttr) {
// Get the corresponding label for the current input
var elemCorrespondingLabel = element(by.xpath('//label[@for="' + strIdAttr + '"]'));
elemCorrespondingLabel.getText().then(function(strText) {
// We need to strip string of additional characters coming from
// the anchor's "Find out more" add-on
var strText = format.normalizeAndReplace(strText,
global.specsAPI.constants.common.anchorMoreText);
expect(strText).toBe(arrOptionNames[index]);
});
});
});
});
};
<file_sep>/**
* Complete input by locator spec module
* @param {Object} config Config object
* @param {string} [config.ID] Input element ID
* @param {string} [config.name] Input element name
* @param {string} [config.className] Input element class name
* @param {string} [config.text] Text that needs to be sent to the input
* @return {function} `it` spec block
*/
module.exports = function(config) {
var configID = config.ID,
configName = config.name,
configClassName = config.className,
configText = config.text,
helpers = global.specsAPI.helpers,
format = helpers.format,
elemLocator;
if ((!configID && !configName && !configClassName) || (!configText && configText !== '')) {
console.log(format.formatError('Module [' + module.id + ']: Missing argument, either ' +
'input ID, input name or input class name AND complete text are required!'));
return;
}
// Get correct first <input> element
if (configID) {
elemLocator = by.id(configID);
} else {
elemLocator = (configName) ? by.css('input[name="' + configName + '"]') :
by.css('input.' + configClassName);
}
// Module detail
var moduleDetail = format.formatModuleDetail(format.getDetailFromObject({
'ID': configID,
'Name': configName,
'Class name': configClassName
}));
return it('Completed the input ' + moduleDetail + ' with the following text content: ' +
format.formatModuleDetail(configText), function() {
var elemInputs = element.all(elemLocator);
elemInputs.each(function(elemInput, index) {
// Check if visible
// Find the first visible element
elemInput.isDisplayed().then(function(displayed) {
if(displayed) {
browser.executeScript(helpers.view.scrollIntoView, elemInput.getWebElement())
.then(function() {
// Send text to input element
elemInput.clear().sendKeys(configText);
});
// Early return
return;
}
});
});
});
};
<file_sep>var CONSTANTS = require('../spec-data/spec-constants.js');
module.exports = {
appendPOStyleNode: function appendPOStyleNode() {
var POSTYLE_NODE_ID = 'syncPOStyleNode',
STYLE_CONTENT = '#cookieNotification, #lpChatInvite { display: none !important; }';
if (document.getElementById(POSTYLE_NODE_ID)) {
// A bit of performance improvement,
// node already exists i.e. the current test didn't change URL
return;
}
var elemHead = document.getElementsByTagName('head')[0],
elemPOStyle = document.createElement('style');
elemPOStyle.id = POSTYLE_NODE_ID;
if (elemPOStyle.styleSheet){
elemPOStyle.styleSheet.cssText = STYLE_CONTENT;
} else {
elemPOStyle.appendChild(document.createTextNode(STYLE_CONTENT));
}
// Apend style overwrite node
elemHead.appendChild(elemPOStyle);
},
waitForLoader: function waitForLoader(elemLoader) {
var EC = protractor.ExpectedConditions;
// Wait until CC loader is removed from the <iframe> DOM
// `invisibilityOf` combines `stalenessOf` and `not.visibilityOf` expectancies,
// as behavior with presales/OJ loaders is inconsistent
return browser.wait(
EC.invisibilityOf(elemLoader),
50000,
'Expectation error: Timed out waiting for a loader to disappear!'
).catch(function(err) {
// Ignore `NoSuchElementError` and `StaleElementReferenceError` errors
if (CONSTANTS.common.arrErrLoaderDetectionIgnores.indexOf(err.name) >= 0) {
return null;
}
throw err;
});
}
};
<file_sep>module.exports = {
formatModuleDetail: function formatModuleDetail(strDetail) {
return '['.gray + strDetail.toString().white.bold + ']'.gray;
},
formatInfo: function formatInfo(strInfo) {
return '[i] '.blue.bold + strInfo.blue.bold;
},
formatInfoWithBg: function formatInfoWithBg(strInfo) {
return '[i] '.bold.inverse + strInfo.bold.inverse;
},
formatWarnInfo: function formatWarnInfo(strInfo) {
return '[!] '.yellow.bold + strInfo.yellow.bold;
},
formatInModuleInfo: function formatInModuleInfo(strInfo) {
return '> '.gray.bold + strInfo.gray.bold;
},
formatInModuleStartInfo: function formatInModuleStartInfo(strInfo) {
return '-> '.green.bold + strInfo.green.bold;
},
formatError: function formatError(strError) {
return '[ERR]: '.red.bold + strError.red.bold;
},
getDetailFromArray: function getDetailFromArray(arrDetails, strHeading) {
var moduleDetail = strHeading || '';
arrDetails.forEach(function(detail) {
moduleDetail += '"' + detail + '", ';
});
return moduleDetail.replace(/,(?=[^,]*$)/, '.').trim();
},
getDetailFromObject: function getDetailFromObject(objDetail) {
var moduleDetail = '';
for (var detailKey in objDetail) {
var detailValue = objDetail[detailKey];
if (objDetail.hasOwnProperty(detailKey) && detailValue) {
moduleDetail += detailKey + ': "' + detailValue + '"; ';
}
}
return moduleDetail.replace(/;(?=[^;]*$)/, '.').trim();
},
normalizeAndReplace: function normalizeAndReplace(strText, strAlsoReplace) {
var strText = strText.replace(/[\n\r\t]/g, '');
if (strAlsoReplace.length) {
strText = strText.replace(strAlsoReplace, '');
}
return strText.trim();
}
};
<file_sep>/**
* OJ Single Option select
* @param {string} strText `string` Text content of the OJ single selection
* @return {function} `it` spec block
*/
module.exports = function(strText) {
var helpers = global.specsAPI.helpers,
format = helpers.format;
if (!strText) {
console.log(format.formatError('Module [' + module.id + ']: You must pass a string ' +
'representing the text content of the OJ single selection!'));
return;
}
return it('Selected the ' + format.formatModuleDetail(strText) + ' OJ Single Selection',
function() {
// Search for a label with the provided text content
var elemNativeInputLabel = element(by.cssContainingText('label', strText));
elemNativeInputLabel.isPresent().then(function(isPresent) {
if (!isPresent) {
console.log(format.formatError('OJ Single Option input element not found!'));
return;
}
var elemNativeInput = null;
elemNativeInputLabel.getAttribute('for').then(function(forAttrValue) {
// Get the corresponding native <input /> element
elemNativeInput = element(by.id(forAttrValue));
}).then(function() {
browser.executeScript(helpers.view.scrollIntoView, elemNativeInput.getWebElement());
}).then(function() {
// And finally click it!
elemNativeInput.click();
});
});
});
};
<file_sep>/**
* Select option in native <select> element
* @param {Object} config Config object
* @param {string} [config.ID] Select element ID
* @param {string} [config.name] Select element name
* @param {string} [config.className] Select element class name
* @param {string|number} [config.optionIndex] Option element index
* @param {string} [config.optionText] Option element text
* @return {function} `it` spec block
*/
module.exports = function(config) {
var configID = config.ID,
configName = config.name,
configClassName = config.className,
configOptIndex = config.optionIndex,
configOptText = config.optionText,
helpers = global.specsAPI.helpers,
format = helpers.format,
optLocator;
if ((!configID && !configName && !configClassName) || (!configOptIndex && !configOptText)) {
console.log(format.formatError('Module [' + module.id + ']: Missing argument, either ' +
'select ID, select name or select class name AND option index or text are required!'));
return;
}
var _getDetailFromObject = function(obj) {
return format.formatModuleDetail(format.getDetailFromObject(obj));
};
// Module detail
var moduleDetail = _getDetailFromObject({
'ID': configID,
'Name': configName,
'Class name': configClassName
}),
// Module option detail
moduleOptDetail = _getDetailFromObject({
'Option index': configOptIndex,
'Option text': configOptText
});
return it('Selected option ' + moduleOptDetail + ' from native select element with the ' +
'following identifier details: ' + moduleDetail, function() {
var elemLocator;
// Get correct first <select> element
if (configID) {
elemLocator = by.id(configID);
} else {
elemLocator = (configName) ? by.css('select[name="' + configName + '"]') :
by.css('select.' + configClassName);
}
var elemSelect = element(elemLocator);
browser.executeScript(helpers.view.scrollIntoView, elemSelect.getWebElement())
.then(function() {
// Get final option element and click it
var elemOption = (configOptIndex) ?
elemSelect.$$('option').get(parseInt(configOptIndex, 10)) :
elemSelect.element(by.cssContainingText('option', configOptText));
elemOption.click();
});
});
};
<file_sep>/**
* Add-ons select spec module
* @param {array} arrAddonsID Add-on IDs to check for
* @return {function} `it` spec block
*/
module.exports = function(arrAddonsID) {
var format = global.specsAPI.helpers.format,
numLenAddonsArr = arrAddonsID.length,
moduleDetail = '',
clickedAddonsIndex = 0;
if (!arrAddonsID || !numLenAddonsArr) {
console.log(format.formatError('Module [' + module.id + ']: You need to select at ' +
'least one add-on!'));
return;
}
moduleDetail += format.getDetailFromArray(arrAddonsID);
return it('Selected the following add-ons: ' + format.formatModuleDetail(moduleDetail),
function() {
// Create Protractor promise
var deferred = protractor.promise.defer(),
promise = deferred.promise;
arrAddonsID.forEach(function(ID, index) {
var normalizedID = ID.replace(/-/g, '').toLowerCase(),
elemAddon = element(by.name(normalizedID)).element(by.xpath('..')),
elemAddonWebElem = elemAddon.getWebElement();
browser.executeScript(global.specsAPI.helpers.view.scrollIntoView, elemAddonWebElem)
.then(function() {
elemAddon.click().then(function() {
clickedAddonsIndex++;
if (index === numLenAddonsArr - 1) {
// Fulfill promise if this is the last element
deferred.fulfill();
}
});
});
});
// Queue after the above promise is fulfilled
promise.then(function() {
expect(clickedAddonsIndex).toBe(numLenAddonsArr);
});
});
};
<file_sep>/**
* Hub buttons count
* @param {number} numCount The hub buttons count
* @return {function} `it` spec block
*/
module.exports = function(numCount) {
var format = global.specsAPI.helpers.format;
if (!numCount && numCount !== 0) {
console.log(format.formatError('Module [' + module.id + ']: You need to set a count ' +
'value!'));
return;
}
return it('Should have ' + format.formatModuleDetail(numCount) + ' hub option buttons',
function() {
expect(element(by.className('hub-navigation')).$$('.gutter > ul > li').count())
.toBe(numCount);
});
};
<file_sep>module.exports = {
format: require('./format.spec-helper.js'),
locators: require('./locators.spec-helper.js'),
validation: require('./validation.spec-helper.js'),
view: require('./view.spec-helper.js'),
async: require('./async.spec-helper.js'),
browser: require('./browser.spec-helper.js')
};
<file_sep>module.exports = {
eachArray: function eachArray(arrMembers, fnEvaluator) {
// No need for recursion if the array has only one member
if (arrMembers.length === 1) {
return fnEvaluator(arrMembers[0]);
}
return fnEvaluator(arrMembers[0]).then(function() {
this.eachArray(arrMembers.slice(1, arrMembers.length), fnEvaluator);
}.bind(this));
}
};
<file_sep>/**
* Packages IDs spec module
* Verifies if certain packages are present into the page
* @param {array} arrPackageIDs Array of package IDs
* @return {function} `it` spec block
*/
module.exports = function(arrPackageIDs) {
var format = global.specsAPI.helpers.format,
moduleDetail = '';
if (!arrPackageIDs || !arrPackageIDs.length) {
console.log(format.formatError('Module [' + module.id + ']: You need to at least have ' +
'one package into the packages array!'));
return;
}
moduleDetail += format.getDetailFromArray(arrPackageIDs);
return it('Should have the following package shelves: ' + format.formatModuleDetail(moduleDetail),
function() {
arrPackageIDs.forEach(function(ID) {
// Verify that each package ID exists
expect(element.all(by.css('div.package-shelves[data-link-id="' + ID + '"]')).first()
.isDisplayed()).toBe(true);
});
});
};
<file_sep>#DT-E2E-CLI
## Digital Testing End to End - Command Line Interface
----------------------
### Please visit the [wiki](https://github.com/BTplc/DT-E2E-CLI/wiki) for installation notes and documentation.
<file_sep>#!/usr/bin/env node
const exec = require('child_process').exec,
colors = require('colors/safe'),
path = require('path'),
fs = require('fs');
// Some constants and command blocks with replaceable parameters
const EXEC_BASE = 'protractor ' + path.join(
path.dirname(fs.realpathSync(__filename)), 'protractor.config.js'
),
PARAMS_FILE_BASE = '--params.file $0',
PARAMS_MODE_BASE = '--params.mode $0',
PARAMS_INDEX_BASE = '--params.index $0',
FLAGS_BROWSER_BASE = '--browser $0',
NODE_EXEC_PARAM_DELIMITER = '=',
DT_CLI_FILE_PARAM_ID = 'file='
DT_CLI_ENABLE_LOGGING_FLAG = '--enable-logging',
DT_CLI_LOG_EXT = '.log',
DT_CLI_LOG_DIR_NAME = 'spec-logs',
BASH_TRASH_REGEXP = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
// Valid flags and their mapping
var arrValidFlags = ['file', 'mode', 'index', 'browser'],
objValidFlags = {
file: PARAMS_FILE_BASE,
mode: PARAMS_MODE_BASE,
index: PARAMS_INDEX_BASE,
browser: FLAGS_BROWSER_BASE
},
finalExecCmd = EXEC_BASE,
isLogWritingEnabled = (process.argv.indexOf(DT_CLI_ENABLE_LOGGING_FLAG) >= 0);
var dateObj = new Date();
// Logging suite - we always use logging
// - If log writing is disabled, only console log is used
// - If log writing is enabled, both console log and writing log file are used
var createLoggingSuite = function createLoggingSuite() {
if (!isLogWritingEnabled) {
return {
writer: { write: function write() { return void 0; } },
writeLog: function writeLog() { return void 0; },
displayLog: console.log
};
}
var logsDirPath = path.join(process.cwd(), DT_CLI_LOG_DIR_NAME);
// Try to access the future folder path
try {
fs.accessSync(logsDirPath, fs.R_OK | fs.W_OK)
} catch(e) {
// And create the folder if it doesn't exist
fs.mkdirSync(logsDirPath);
}
var strArgs = process.argv.join(' '),
argsFileParamIndex = strArgs.indexOf(DT_CLI_FILE_PARAM_ID),
extractedFileName = (argsFileParamIndex >= 0) ?
// If we do have a `file=value` in the arguments, extract the `value`
// and then strip any additional quotation marks
strArgs.slice(
// Numeric index value + length of key and delimiter
argsFileParamIndex + DT_CLI_FILE_PARAM_ID.length,
// Get the next matching space from substring + numeric length value of previous slice
strArgs.slice(argsFileParamIndex, strArgs.length).indexOf(' ') + argsFileParamIndex
).replace(/["']/g, '') :
// Same value as default `params.file` in `protractor.config.js`
// - TODO needs proper linking
'specs.json';
var writeStream = fs.createWriteStream(path.join(
// Saves in current running directory with added timestamp
logsDirPath, extractedFileName + '.' + dateObj.getTime() + DT_CLI_LOG_EXT
)),
writeLog = function writeLog(logContent) {
writeStream.write(logContent.replace(BASH_TRASH_REGEXP, ''));
},
displayLog = function displayLog(logContent) {
console.log(logContent);
writeLog('\n' + logContent + '\n');
};
return {
writer: writeStream,
writeLog: writeLog,
displayLog: displayLog
};
};
// Logging suite
var loggingSuite = createLoggingSuite(),
// A couple logging helpers
writeLog = loggingSuite.writeLog,
displayLog = loggingSuite.displayLog;
// Map our custom arguments and build the final command to execute
process.argv.forEach(function (arg, index) {
var numDelimiterIndex = arg.indexOf(NODE_EXEC_PARAM_DELIMITER),
strFlagName = arg.slice(0, numDelimiterIndex),
strFlagValue = arg.slice(numDelimiterIndex + 1, arg.length);
if (arrValidFlags.indexOf(strFlagName) > -1) {
finalExecCmd += ' ' + objValidFlags[strFlagName].replace('$0', '"' + strFlagValue + '"');
}
});
// Inform the user
displayLog(colors.green(dateObj, '\n\n', 'Executing: <<' + finalExecCmd + '>>'));
// Run the final command
var cliExec = exec(finalExecCmd, function (error, stdout, stderr) {
if (error !== null) {
// Inform on errors
displayLog(
colors.blue('START: STDOUT ERROR DETAILS\n') +
error +
colors.blue('END: STDOUT ERROR DETAILS\n') +
colors.red('Execution error: This could also mean the suite had been executed ' +
'successfully, but one or more tests failed! Please check further logs for clarification.')
);
}
displayLog(colors.green('DONE Executing: <<' + finalExecCmd + '>>'));
}),
cliExecStdOut = cliExec.stdout;
// Pipe the `stdout` output so we can also see live tests feedback
cliExecStdOut.pipe(process.stdout);
if (!isLogWritingEnabled) {
return;
}
// Write the log on each data chunk
cliExecStdOut.on('data', function(data) {
writeLog(data);
});
<file_sep>var http = require('http'),
path = require('path');
var helpers = require('../spec-helpers/index.spec-helpers.js'),
browserHelpers = helpers.browser,
format = helpers.format,
formatError = format.formatError,
formatInfo = format.formatInfo,
formatWarnInfo = format.formatWarnInfo,
validateArgs = helpers.validation.validateArgs,
constants = require('../spec-data/spec-constants.js');
var LOADER_DETECTION_ERRIGNORE_ARRAY = ['NoSuchElementError', 'StaleElementReferenceError'];
if (global.specsAPI) {
console.log(formatError('It seems the `specsAPI` namespace already exists!'));
return;
}
// Define the global namespace
global.specsAPI = {
helpers: helpers,
constants: constants,
collateOrderNumbers: []
};
module.exports = function() {
var specsDataPath = path.join(
process.cwd(), 'spec-data', browser.params.file
),
specsData = require(specsDataPath);
if (browser.params.mode === 'single') {
_parseSpecsData({specs:[specsData.specs[browser.params.index]]});
return;
}
// Parse specs
_parseSpecsData(specsData);
}();
function _parseSpecsData(data) {
data.specs.forEach(function(spec, index) {
var specName = spec.name,
globalUrl = spec.globalUrl,
startUrl = spec.startUrl,
testFor = spec.testFor,
isAfterLoaderDetectionOff = spec.isAfterLoaderDetectionOff,
isSpecExternal = spec.isExternal,
isSpecWindowMaximized = spec.isWindowMaximized;
if (!validateArgs(specName, (globalUrl || startUrl), (testFor.length > 0))) {
console.log(formatError('Spec [' + index + ']: While defining a spec, `name`, `globalUrl` ' +
'or `startUrl` and `testFor` configuration are all required.'));
return;
}
return describe(specName, function() {
var constantsByType = (globalUrl) ? constants.independent : constants.chained;
beforeAll(function() {
console.log(formatInfo(constantsByType.notifier));
console.log(formatInfo(constantsByType.description));
console.log(formatInfo(constantsByType.urlDescription + ' ' + (globalUrl || startUrl)));
// External spec flag
if (isSpecExternal) {
browser.ignoreSynchronization = true;
console.log(formatWarnInfo('Angular synchronization turned OFF for this test.'));
}
// After loader auto detection "off" flag
if (isAfterLoaderDetectionOff) {
console.log(formatWarnInfo('Auto \"after\" loader detection turned OFF for this test.'));
}
// Spec window maximized flag
if (isSpecWindowMaximized) {
browser.executeScript(function() {
return {
width: window.screen.availWidth,
height: window.screen.availHeight
};
}).then(function(result) {
var browserDriverManageWindow = browser.manage().window();
browserDriverManageWindow.setPosition(0, 0).then(function() {
browserDriverManageWindow.setSize(result.width, result.height);
});
});
}
if (startUrl) {
browser.get(startUrl);
}
});
beforeEach(function() {
if (globalUrl) {
browser.get(globalUrl);
}
// Append the Protractor Overwrites Style Node i.e. the `POStyleNode`
// This allows us to forcefully hide annoying pop-ups and boxes
browser.executeScript(helpers.browser.appendPOStyleNode);
// In case auto after loader detection is not needed
if (isAfterLoaderDetectionOff) {
return;
}
var elemLoader = element(by.css('.' + constants.common.presalesLoaderClassName +
', .' + constants.common.ojLoaderClassName));
// Wait until loader is removed from the DOM
// `invisibilityOf` combines `stalenessOf` and `not.visibilityOf` expectancies,
// as behavior with presales/OJ loaders is inconsistent
browserHelpers.waitForLoader(elemLoader);
});
testFor.forEach(function(testForBlock, index) {
for (var testModuleName in testForBlock) {
if (testForBlock.hasOwnProperty(testModuleName)) {
var testModule = require('../spec-modules/' + testModuleName + '.spec-module.js');
testModule(testForBlock[testModuleName]);
}
}
});
afterAll(function() {
if (isSpecExternal) {
browser.ignoreSynchronization = false;
console.log(formatWarnInfo('Angular synchronization turned back ON for the next test.'));
}
console.log(formatInfo(constants.common.executedTemplate.replace('$0', index + 1)
.replace('$1', data.specs.length)));
if (global.specsAPI.collateOrderNumbers.length > 0) {
console.log('**************************************************');
console.log('* Order Numbers *');
console.log('**************************************************');
for (var i = 0; i < global.specsAPI.collateOrderNumbers.length; i++) {
console.log('Your Order Number is = ' + global.specsAPI.collateOrderNumbers[i]);
}
}
});
});
});
}
<file_sep>/**
* Click then wait spec module
* @param {string} strIdentifier `string` for default type ID or `type=value` e.g. `id=string`
* @return {function} `it` spec block
*/
module.exports = function(strIdentifier) {
var helpers = global.specsAPI.helpers,
format = helpers.format;
if (!strIdentifier) {
console.log(format.formatError('Module [' + module.id + ']: Missing argument, either ' +
'string ID of an element or simple locator e.g. `id=string`, `linkText=string` etc.'));
return;
}
var locator = helpers.locators.getLocator(strIdentifier),
locatorName = locator.name,
locatorValue = locator.value;
return it('Clicked the ' + format.formatModuleDetail('link of type "' + locatorName +
'", with value "' + locatorValue + '"'), function() {
var scrollIntoView = global.specsAPI.helpers.view.scrollIntoView,
allClickElements = element.all(by[locatorName](locatorValue));
var elementToClick = allClickElements.filter(function(elem) {
return elem.isDisplayed().then(function(displayedElement){
return displayedElement;
});
}).first();
browser.executeScript(scrollIntoView, elementToClick.getWebElement()).then(function() {
// Click link
elementToClick.click();
return;
});
});
};
<file_sep>/**
* OJ Multiple (checkbox) Option select
* @param {array} arrOptionsText `Array` with OJ options text content
* @return {function} `it` spec block
*/
module.exports = function(arrOptionsText) {
var helpers = global.specsAPI.helpers,
format = helpers.format;
if (!arrOptionsText || !arrOptionsText.length) {
console.log(format.formatError('Module [' + module.id + ']: You must pass an array with ' +
'items representing the text content of the OJ selections you want to click!'));
return;
}
return it('Selected the ' + format.formatModuleDetail(format.getDetailFromArray(arrOptionsText)) +
' multiple OJ Selections', function() {
arrOptionsText.forEach(function(optionText, index) {
// Search for a label with the provided text content
var elemNativeInputLabel = element(by.cssContainingText('label', optionText));
elemNativeInputLabel.isPresent().then(function(isPresent) {
if (!isPresent) {
console.log(format.formatError('OJ Multiple Option input element not found!'));
return;
}
var elemNativeInput = null;
elemNativeInputLabel.getAttribute('for').then(function(forAttrValue) {
// Get the corresponding native <input /> element
elemNativeInput = element(by.id(forAttrValue));
}).then(function() {
browser.executeScript(helpers.view.scrollIntoView, elemNativeInput.getWebElement());
}).then(function() {
// And finally click it!
elemNativeInput.click();
});
});
});
});
};
<file_sep>/**
* Hub buttons secondary count spec module
* Clicks the link with the given text,
* then verifies for that section's secondary option buttons
* @param {Object} config Config object
* @param {string} config.primaryButtonText Primary button (click button) text
* @param {string} config.secondaryButtonsCount Secondary buttons count to check
* @return {function} `it` spec block
*/
module.exports = function(config) {
var helpers = global.specsAPI.helpers,
format = helpers.format,
formatModuleDetail = format.formatModuleDetail,
primaryButtonText = config.primaryButtonText,
secondaryButtonsCount = config.secondaryButtonsCount;
if (!helpers.validation.validateArgs(primaryButtonText, secondaryButtonsCount)) {
console.log(format.formatError('Module [' + module.id + ']: `config.primaryButtonText` ' +
'and `config.secondaryButtonsCount` are both required!'));
return;
}
return it('The ' + formatModuleDetail(primaryButtonText) + ' section should have ' +
formatModuleDetail(secondaryButtonsCount) + ' secondary option buttons', function() {
var elemPrimaryButton = element(by.className('hub-navigation')).
element(by.linkText(primaryButtonText)),
elemSecondaryButtonsList = elemPrimaryButton.element(by.xpath('following-sibling::ul[1]')),
scrollIntoView = global.specsAPI.helpers.view.scrollIntoView;
var clickThenWait = browser.executeScript(scrollIntoView, elemPrimaryButton.getWebElement())
.then(function() {
elemPrimaryButton.click().then(function() {
browser.driver.wait(elemSecondaryButtonsList.isDisplayed(), 10000);
});
});
clickThenWait.then(function() {
expect(elemSecondaryButtonsList.$$('li').count())
.toEqual(parseInt(secondaryButtonsCount, 10));
});
});
};
<file_sep>/**
* OJ Order Summary spec module
* @param {Object} config Config object
* @param {array} config.sections Array with section Objects
* @param {string} section.name Name of section in array
* @param {string} section.oneoff One-off value for the section
* @param {string} section.monthly Monthly value for the section
* @param {array} section.items Array of item Objects
@param {string} item.title Title of the subSection
@param {string} item.description Description of the subSection
@param {array} item.list array of string elements
* @param {Object} config.total Object with totals
* @param {string} config.total.oneoff Total one-off value
* @param {string} config.total.monthly Total monthly value
* @return {function} `it` spec block
*/
module.exports = function(config) {
var format = global.specsAPI.helpers.format;
if (!config || (!config.sections && !config.total)) {
console.log(format.formatError('Module [' + module.id + ']: You need a config object so you ' +
'can test the OJ Order Summary for sections or total!'));
return;
}
return it('Finished checking the OJ Order Summary', function() {
var summarySections = config.sections,
summaryTotal = config.total;
// In-module information, display start heading
console.log(format.formatInModuleStartInfo('Started checking the OJ Order Summary...'));
if (summarySections && summarySections.length) {
// Section headers and body - sibling elements
var elemsSectionHeaders = element.all(by.css('.sectionTitle.priceTableShort')),
elemsSectionBodies = element.all(by.css('.contentBlock.priceTableDetail'));
elemsSectionHeaders.each(function(elemHeader, sectionIndex) {
var elemHeading = elemHeader.$('h2.aside'),
configSection = summarySections[sectionIndex],
configSectionOneOff = configSection.oneoff,
configSectionMonthly = configSection.monthly;
// Log the section information
console.log(format.formatInModuleInfo('Checking section: ' +
format.getDetailFromObject(configSection)));
// Expect same header title
// h2.aside
expect(elemHeading.getText()).toBe(configSection.name);
// Get all section body headings and descriptions
var elemsSectionBodyHeadings = elemsSectionBodies.get(sectionIndex).$$('h4'),
elemsSectionBodyDescription = elemsSectionBodies.get(sectionIndex).$$('.description'),
elemsSectionRows = elemsSectionBodies.get(sectionIndex).$$('.option');
elemsSectionRows.each(function(sectionRow, rowIndex) {
var rowHeader = elemsSectionRows.get(rowIndex).$$('h4'),
rowDescription = elemsSectionRows.get(rowIndex).$$('.description'),
rowLists = elemsSectionRows.get(rowIndex).$$('ul.bulletList'),
itemToTest = configSection.items[rowIndex];
// Test the header of the rowIndex
rowHeader.getText().then(function(headingText) {
headingText = String(headingText);
var normalizedHeader = format.normalizeAndReplace(headingText, global.specsAPI.constants.common.anchorMoreText);
expect(normalizedHeader).toBe(itemToTest.title);
});
// Test the description if present
if (itemToTest.description) {
rowDescription.getText().then(function(description){
description = String(description);
var normalizedDescription = format.normalizeAndReplace(description, global.specsAPI.constants.common.anchorMoreText);
expect(description).toBe(itemToTest.description);
});
}
// Test list items if present
if (itemToTest.list) {
// Because the JSON has all the list items in one array we need a external counter (outside of the two loops)
var listLoopCount = 0;
rowLists.each(function(listContainer, outerListIndex) {
// Check whether the list container is displayed
listContainer.isDisplayed().then(function(displayed) {
if (displayed) {
var listItems = listContainer.$$('li');
listItems.each(function(listItem, innerListIndex) {
listItem.getInnerHtml().then(function(listHTMLContent) {
if (listHTMLContent.length > 0) {
// Checks for HTML content
expect(listHTMLContent).toBe(itemToTest.list[listLoopCount]);
}
listLoopCount++;
});
});
}
});
});
}
});
// Section one-off
if (configSectionOneOff) {
expect(elemHeader.$('td.col_oneOffCost').getText()).toBe(configSectionOneOff);
}
// Section monthly
if (configSectionMonthly) {
expect(elemHeader.$('td.col_monthlyCost').getText()).toBe(configSectionMonthly);
}
});
}
if (!summaryTotal) {
return;
}
var summaryOneOff = summaryTotal.oneoff,
summaryMonthly = summaryTotal.monthly;
// Check for total summary one-off charge value
if (summaryOneOff) {
console.log(format.formatInModuleInfo('Checking summary one-off...'));
var elemSummaryOneOff = element.all(by.css('.priceTable tr')).get(0).$('.numeric');
expect(elemSummaryOneOff.getText()).toBe(summaryOneOff);
}
// Check for total summary monthly cost value
if (summaryMonthly) {
console.log(format.formatInModuleInfo('Checking summary monthly...'));
var elemSummaryMonthly = element.all(by.css('.priceTable tr')).get(1).$('.numeric');
expect(elemSummaryMonthly.getText()).toBe(summaryMonthly);
}
});
};
<file_sep>/**
* Packages count spec module
* @param {number} numCount The hub buttons count
* @return {function} `it` spec block
*/
module.exports = function(numCount) {
var format = global.specsAPI.helpers.format;
if (!numCount && numCount !== 0) {
console.log(format.formatError('Module [' + module.id + ']: You need to set a count ' +
'value!'));
return;
}
return it('Should have a number of ' + format.formatModuleDetail(numCount) + ' package shelves',
function() {
// Shelves count
expect(element.all(by.className('package-shelves')).filter(function(elem) {
return elem.isDisplayed();
}).count()).toBe(numCount);
});
};
<file_sep>module.exports = {
independent: {
notifier: 'Independent test suite |->✓|->✗|->✓',
description: 'This means all tests are independent from eachother.',
urlDescription: 'Global URL:'
},
chained: {
notifier: 'Chained test suite |->✓->✗->✗',
description: 'This means all tests are dependent on eachother\'s actions and/or results.',
urlDescription: 'Start URL:'
},
common: {
executedTemplate: 'Executed spec $0/$1',
presalesLoaderClassName: 'page-loader',
ojLoaderClassName: 'progressBar',
arrErrLoaderDetectionIgnores: ['NoSuchElementError', 'StaleElementReferenceError'],
anchorMoreText: 'Find out more',
elemSelectName: 'select',
elemOptionName: 'option',
objCcPaymentFields: {
cardHolder: 'input',
cardNumber: 'input',
securityCode: 'input',
cardType: 'select',
expiryMonth: 'select',
expiryYear: 'select'
},
ccSecureCodeFieldName: 'visaSecureCode',
ccDetailsFrameName: 'payframe',
ccCodeFrameName: 'bankarea',
ccDetailsSubmitButtonId: 'submitBtn',
ccCodeSubmitButtonId: 'next',
ccLoaderSelector: '.blockPage',
ccLetterDigitsSelector: '.pwdInput',
ccLetterDigitsRegExp: /(,)|(and)/g,
ccPinInputBaseName: 'slotpin',
spacesPlusRegExp: /(\s+)/g,
objDigitsMapping: {
first: 1,
second: 2,
third: 3,
fourth: 4,
fifth: 5,
sixth: 6,
seventh: 7,
eighth: 8,
ninth: 9,
tenth: 10,
eleventh: 11,
twelfth: 12,
thirteenth: 13,
fourteenth: 14,
fifteenth: 15,
sixteenth: 16,
seventeenth: 17,
eighteenth: 18,
nineteenth: 19,
twentieth: 20
}
},
locators: {
separator: '=',
default: 'id'
},
errors: {
sc: {
noNumber: 'No address found with number "$0"! \r\n The SC check will proceed with ' +
'post-code-only check.'
}
}
};
<file_sep>/**
* Services checker spec module
* @param {Object} config Config Object
* @param {string} [config.landline] Landline number
* @param {string} config.postcode Post code
* @param {string} [config.addressID] Address ID
* @param {string} [config.number] Street number
* @return {function} `it` spec block
*/
module.exports = function(config) {
var specsAPI = global.specsAPI,
helpers = specsAPI.helpers,
format = helpers.format,
configLandline = config.landline,
configPostcode = config.postcode,
configAddressID = config.addressID,
configNumber = config.number,
moduleDetail = '';
if (!configPostcode) {
console.log(format.formatError('Module [' + module.id + ']: You need to at least provide ' +
'a post code to use in the check!'));
return;
}
var moduleDetail = format.formatModuleDetail(format.getDetailFromObject({
'Post code': configPostcode,
'Land line': configLandline,
'Address by ID': configAddressID,
'Street number': configNumber
}));
return it('Finished doing a Services Checker check using: ' + moduleDetail, function() {
var elemSc = element(by.id('serviceChecker')),
elemLPBox = element(by.id('need_help')),
elemStartAgain = elemSc.$('.back'),
elemsSteps = elemSc.$$('.blue-bg');
browser.executeScript(helpers.view.scrollIntoView, elemSc.getWebElement()).then(function() {
// Pre-check actions
var preChecks = elemLPBox.isPresent().then(function(isPresent) {
// Live Person box blocks the clicks, so we have to
// close it first if it's present on the screen.
if (isPresent) {
elemLPBox.click();
}
}).then(function() {
elemStartAgain.isDisplayed().then(function(isDisplayed) {
// If "Start again" is present (e.g. in a chained test), then
// click the link to clean the previous results
if (isDisplayed) {
elemStartAgain.click();
}
});
}).then(function() {
elemSc.$('.drop-box').isDisplayed().then(function(isDisplayed) {
if (!isDisplayed) {
// SC is collapsed, make it visible
elemSc.$('.drop-toggle').click();
}
});
});
preChecks.then(function() {
var elemLandline = element(by.id('txtLandline'));
// Landline number
if (configLandline) {
elemLandline.clear().sendKeys(configLandline);
} else {
elemLandline.isEnabled().then(function(isEnabled) {
if (isEnabled) {
// No landline validation
elemSc.$('.sm-hidden').$('.no-number').click();
}
});
}
// Post code
element(by.id('txtPostcode')).clear().sendKeys(configPostcode);
// Click the "Check Now" button
element(by.id('btnCheckServices')).click();
// Wait until it's finished loading
var elemLoading = element(by.css('.loading'));
browser.driver.wait(protractor.until.elementIsNotVisible(elemLoading));
element(by.id('selAddresses')).isDisplayed().then(function(isDisplayed) {
// If we had both a landline and postcode, it's possible the SC will display results.
// If that's the case, Address selection will not be shown and the SC check is over.
if (!isDisplayed) {
return;
}
// At this point we got the Address selection screen, so no results just yet.
// Create Protractor promise
var deferred = protractor.promise.defer(),
promise = deferred.promise;
var clickElem;
// Element selection based on the address ID - the most accurate.
if (configAddressID) {
clickElem = element(by.id(configAddressID));
deferred.fulfill();
} else if (configNumber) {
// Element selection based on a street number.
// This will return the first address (element) representing that street number.
element(by.id('selAddresses')).$$('a').each(function(elem, index) {
var numSeparatorLastIndex;
elem.getAttribute('id').then(function(attr) {
numSeparatorLastIndex = attr.lastIndexOf('|');
if (numSeparatorLastIndex >= 0 &&
attr.substring(numSeparatorLastIndex + 1, attr.length) === configNumber) {
clickElem = elem;
deferred.fulfill();
return;
}
});
});
if (!clickElem) {
console.log(format.formatError(specsAPI.constants.errors.sc.noNumber
.replace('$0', configNumber)));
}
}
// No address ID and no street number provided / street number not found
// Going ahead with simple post code check.
if (!clickElem) {
clickElem = elemsSteps.get(1).$('.no-number');
deferred.fulfill();
}
promise.then(function() {
// After promise is fulfilled, click the address and wait
// until the SC returns a result (loading element will disappear).
clickElem.click();
browser.driver.wait(protractor.until.elementIsNotVisible(elemLoading));
});
});
});
});
}, 50000);
};
<file_sep>/**
* Title checker spec module
* @param {array} arrSteps Array with step objects, which contain:
* @param {string} target Text of the click button
* @param {number} count Number of buttons you expect to see
* @param {array} arrButtonsText Array with texts for each button - in order (!)
* @return {function} `it` spec block
*/
module.exports = function(arrSteps) {
var RESERVED_NAV_TARGETS = ['back', 'start-again'],
helpers = global.specsAPI.helpers,
format = helpers.format,
bookmarkIndexes = {
current: 0,
last: 0
};
if (!arrSteps || !arrSteps.length) {
console.log(format.formatError('Module [' + module.id + ']: You need to pass an array with ' +
'one or multiple step objects in order to use this module!'));
return;
}
return it('Should be able to navigate the Manage Switcher and check for various content',
function() {
element(by.id('switcher')).isPresent().then(function(isPresent) {
if (!isPresent) {
console.log(format.formatError('This page does not have a Manage Switcher!'));
return;
}
helpers.async.eachArray(arrSteps, stepEvaluator);
});
});
function stepEvaluator(objStep) {
var switcherElem = element(by.id('switcher')),
stepTarget = objStep.target,
stepButtonsCount = parseInt(objStep.count, 10),
arrButtonsText = objStep.arrButtonsText,
deferred = protractor.promise.defer(),
localDeferred = protractor.promise.defer();
if (stepTarget) {
var elemCurrentSlide = element(by.css(
'.slide[data-index="' + bookmarkIndexes.current + '"]')),
clickElem = (RESERVED_NAV_TARGETS.indexOf(stepTarget) < 0) ?
// `by.linkText` locator is not accurate enough and there are inconsistencies
// between `element.getText()` and feeding that as a value for `linkText`
elemCurrentSlide.element(by.cssContainingText('a.btn-big', stepTarget)) :
element(by.id('switcher')).element(by.className(stepTarget));
clickElem.isPresent().then(function(isPresent) {
if (!isPresent) {
console.log(format.formatError('The click element is not present!'));
// Fulfilling the promise will throw errors in the test,
// because it will allow continuing to run the module
localDeferred.fulfill();
return;
}
browser.executeScript(helpers.view.scrollIntoView, clickElem.getWebElement())
.then(function() {
clickElem.getAttribute('data-click').then(function(attrIndexValue) {
clickElem.click().then(function() {
// Update last bookmark index, but only if we have a new value to set
if (attrIndexValue) {
bookmarkIndexes.last = bookmarkIndexes.current;
}
// Update bookmark index (in order to CSS select the step)
// and fullfill expectancy
bookmarkIndexes.current = attrIndexValue || bookmarkIndexes.last;
localDeferred.fulfill();
});
});
});
});
} else {
// No step target, fulfill expectancy
localDeferred.fulfill();
}
// Run the below only after the `target` has been clicked
// This means that whenever we have a `target`, count and buttons text are
// checked for the next screen (for the target screen itself)
localDeferred.promise.then(function() {
if (!stepButtonsCount && !arrButtonsText) {
deferred.fulfill();
return;
}
var elemCurrentSlide = element(by.css(
'.slide[data-index="' + bookmarkIndexes.current + '"]')),
elemsCurrentSlideButtons = elemCurrentSlide.$$('a.btn-big');
// Step buttons count
if (stepButtonsCount) {
expect(elemsCurrentSlideButtons.count()).toBe(stepButtonsCount);
}
if (!arrButtonsText) {
deferred.fulfill();
return;
}
// Step buttons text content AND order
elemsCurrentSlideButtons.each(function(elem, index) {
elem.getText().then(function(strTextContent) {
expect(strTextContent.trim().replace(/[\t\n\r]/g, '')).toBe(arrButtonsText[index]);
});
}).then(function() {
deferred.fulfill();
});
});
return deferred.promise;
}
};
<file_sep>/**
* Title checker spec module
* @param {string} strTitle Title to check for
* @return {function} `it` spec block
*/
module.exports = function(strTitle) {
var format = global.specsAPI.helpers.format;
if (!strTitle) {
console.log(format.formatError('Module [' + module.id + ']: You need to test for a ' +
'non-empty title!'));
return;
}
return it('Title should be ' + format.formatModuleDetail(strTitle), function() {
expect(browser.getTitle()).toEqual(strTitle);
});
};
<file_sep>/**
* Click-out then check title spec module
* @param {Object} config Config object
* @param {string} config.identifier `string` for default type ID or `type=value` e.g. `id=string`
* @param {string} config.outTitle The new title that needs checking
* @return {function} `it` spec block
*/
module.exports = function(config) {
var helpers = global.specsAPI.helpers,
format = helpers.format,
strIdentifier = config.identifier,
outTitle = config.outTitle;
if (!helpers.validation.validateArgs(strIdentifier, outTitle)) {
console.log(format.formatError('Module [' + module.id + ']: `config.identifier and` ' +
'`config.outTitle` are both required!'));
return;
}
var locator = helpers.locators.getLocator(strIdentifier),
locatorName = locator.name,
locatorValue = locator.value;
return it('Clicking the ' + format.formatModuleDetail('link of type "' + locatorName +
'", with value "' + locatorValue + '"') + ' should leave the page and check the new title ' +
'is now ' + format.formatModuleDetail(outTitle), function() {
var scrollIntoView = global.specsAPI.helpers.view.scrollIntoView,
elemByLocator = element(by[locatorName](locatorValue));
browser.executeScript(scrollIntoView, elemByLocator.getWebElement()).then(function() {
// Click link
elemByLocator.click().then(function() {
// Title check
expect(browser.getTitle()).toEqual(outTitle);
});
});
});
};
<file_sep>/**
* My BT Dashboard
* @param {Object} config Config object
* @param {array} config.sections Array with section Objects
* @param {array} section.myProducts Array of products listed
* @param {string} section.myProducts.title title of the product
* @param {array} section.myProducts.listItems Array of strings with items within the dropdown for products
* @param {array} section.myExtras Array of extras
* @return {function} `it` spec block
*/
module.exports = function(config) {
var format = global.specsAPI.helpers.format,
STATIC_STRINGS = {
"latest_bill" : "Your latest bill came to:",
"usage_since" : "Usage since"
};
if (!config) {
console.log(format.formatError('Module [' + module.id + ']: You need a config object so you ' +
'can test the My BT Dashboard!'));
return;
}
return it('Finished checking the My BT Dashboard', function() {
// In-module information, display start heading
console.log(format.formatInModuleStartInfo('Started checking the My BT Dashboard...'));
var elemsMyBillHeaders = element.all(by.css('.billPay')).$$('h3'),
elemsMyProductsSections = element.all(by.css('.myproduct-header')),
elemsMyProductDetails = element.all(by.css('.myproduct-container')).$$('.features_list'),
elemsMyExtrasSections = element.all(by.css('.tile-container')),
checkedLatestBill = false,
sections = config.sections,
scrollIntoView = global.specsAPI.helpers.view.scrollIntoView;
// Check the bill header sections
elemsMyBillHeaders.each(function(elemBillHeader, index) {
elemsMyBillHeaders.get(index).isDisplayed().then(function(displayed){
if (displayed) {
if (!checkedLatestBill) {
elemBillHeader.getText().then(function(latestText){
expect(latestText.indexOf(STATIC_STRINGS.latest_bill)).toBe(0, 'The Latest Bill text is incorrect');
});
checkedLatestBill = true;
} else {
elemBillHeader.getText().then(function(usageSince) {
expect(usageSince.indexOf(STATIC_STRINGS.usage_since)).toBe(0, 'The Usage Since text is incorrect');
});
}
}
});
});
// Check My Products
elemsMyProductsSections.each(function(elemProductSection, index) {
var productTitle = elemProductSection.$('.subtitle'),
productData = sections.myProducts[index];
// Check title is correct
browser.executeScript(scrollIntoView, productTitle.getWebElement()).then(function() {
expect(productTitle.getText()).toBe(productData.title);
});
if (productData.listItems) {
// Click the product header
browser.executeScript(scrollIntoView, elemProductSection.getWebElement()).then(function() {
elemsMyProductsSections.get(index).click().then(function() {
// Sleep to allow the accordian to open
browser.driver.sleep(2000).then(function(){
// Find the current visible extras
elemsMyProductDetails.each(function(elemProductDetails, index) {
elemsMyProductDetails.get(index).isDisplayed().then(function(displayed) {
if (displayed) {
// Check against this product details
var featureListItems = elemProductDetails.$('ul').$$('li');
featureListItems.each(function(listItem, listIndex) {
expect(listItem.getText()).toBe(productData.listItems[listIndex]);
});
}
});
});
});
});
});
}
});
var extraSectionsOnScreen = [];
// Check My extras
elemsMyExtrasSections.each(function(elemExtraSection, index) {
var extraHeader = elemsMyExtrasSections.get(index).$('h1');
extraHeader.getText().then(function(extraText) {
extraSectionsOnScreen.push(extraText);
expect(extraText).toBe(sections.myExtras[index]);
});
});
// Check the number of extra elements are correct
elemsMyExtrasSections.count().then(function(numberOfExtras) {
expect(numberOfExtras).toBe(sections.myExtras.length, 'There was an incorrect number of extra sections.\n' +
' Sections on screen: ' + extraSectionsOnScreen + '\n Sections expected: ' + sections.myExtras);
});
});
};
| 0b98ddc6221d026ee1e1450d9924f57ab73d0033 | [
"JavaScript",
"Markdown"
] | 27 | JavaScript | BTplc/AIS-E2E | f94d3d26036bcaba3a954687bdd885b6970ce1a4 | b4633f3b96c60df16b2f7ba04b714d8ce99682f0 |
refs/heads/master | <repo_name>irinfox/collocations<file_sep>/interface/index.php
<?php
//строки, кот. формируются по параметрам. 1ая для поиска файла (чтоб не считать, а сразу выдать), 2ая для запуска соотв. запросу программы
$filename = "";
$launch = "perl ";
$launchDict = "perl ../newProgr/freqs_count.pl -f ";
$launchDict1 = "perl ";
$dict1 = ""; //файл для поиска однословных частот для MI, tscore
$dict2 = ""; //файл для поиска Nсловных частот для MI, tscore
$coll2path = array(
'vz' => 'news/vz',
'ng' => 'news/ng',
'corp' => 'science/corp'
);
foreach ($_GET as $key => $value){
echo "$key = $value<br>";
}//test print
switch ($_GET['metricR']){
case "freqDict":
$launchDict;
break;
case "MI"://нужно проверять на существование ещё и другие файлы
$launch .= "../newProgr/MI.pl ";
break;
case "tscore":
$launch .= "../newProgr/tscore.pl ";
break;
}
switch ($_GET['collection']){
case "vz":
$filename .= "vz.ru_sport.txt.utf8.lemma";
break;
case "ng":
$filename .= "ng_all.txt.af.lemma_utf8";
break;
case "corp":
$filename .= "corp.txt.utf8.lemma";
break;
}
//где берём файлы?
$pathSrc = "../collections/texts/" . $coll2path[$_GET['collection']] . '/';
//строка запуска perl progName -f fileName с указанием пути программы и файла
$launchDict .= $pathSrc.$filename;
if ($_GET['param1'] == "lemm"){
$filename .= "_l";
}
else {
$filename .= "_w";
//здесь была проверка на то, что метрика - част. словарь
$launchDict .= " -w";
}
if ($_GET['dop'] == "lowcase"){
$filename .= "r";
if ($_GET['metricR']== "freqDict"){
$launchDict .= "-l ";
}
}
else{$filename .= "R";}
$dict1 .= $filename."_freqDict_1";
$dict2 .= $filename."_freqDict_";
$filename .= "_".$_GET['metricR'];//приписываем метрику (value, пришедшее из формы);
$launchDict1 = $launchDict;
if ($_GET['metricR'] == "freqDict" || $_GET['metricR'] == "MI"){
//$dict1 .= "_1";
if ($_GET['grams'] == ""){
$filename .= "_".$_GET['gram'];
$launchDict .= " -n".$_GET['gram'];
$dict2 .= $_GET['gram'];
}else {
$filename .= "_".$_GET['grams'];
//для запуска составления частотных словарей
//$launchDict1 = $launchDict;
$launchDict .= " -n".$_GET['grams'];
$dict2 .= $_GET['grams'];
}
}
if ($_GET['metricR'] == "tscore"){$dict2 .= "2";}
if ($_GET['metricR'] == "MI" || $_GET['metricR'] == "tscore"){
if ($_GET['metricR'] == "tscore"){$filename .= "_";}
$filename .= "b".$_GET['b'];
//$dict1 .= "b".$_GET['b'];
$tempStr = "а для MI и tscore проверим ещё и эти: $dict1 <br> $dict2 <br>";
}
//работа с файлами
//этап 0. Подключение к БД
$host = "localhost";
$login = "colloc";
$PWD = "<PASSWORD>";
$dbCon = mysql_connect($host,$login, $PWD);
//проверка
print "код ошибки: ". mysql_error();
print "<br>Connected with ID: ".$dbCon."<br>";
//к журналу
$dbName = "collocs";
mysql_select_DB($dbName, $dbCon);
echo "ищем файл: $filename<br>".$tempStr;
//где ищем?
$path = "../collections/metric/" . $coll2path[$_GET['collection']] . '/';
if (file_exists($path.$filename)){
echo "отдаю файл: $path.$filename";
}
else {
if ($_GET['metricR']== "freqDict"){
echo "запускаю программу и радуюсь: " .$launchDict;
//запись строки в журнал
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launchDict)."','".mysql_real_escape_string($path.$filename)."', 0)");
}
else {
if (file_exists($path.$dict1) && file_exists($path.$dict2)){//существуют оба частотных списка
$launch .= " -f $path$dict2 -h $path$dict1 -b".$_GET['b'];
echo "<br>три ".$launch;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launch)."','".mysql_real_escape_string($path.$filename)."', 0)");
}
if (file_exists($path.$dict1)&& !file_exists($path.$dict2)){//no nGram freqdict
if ($_GET['metricR'] == "tscore"){ $launchDict .= " -n2";}
echo "<br>запускаю программу раз и как-то сохраняю результат".$launchDict;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launchDict)."','".mysql_real_escape_string($path.$dict2)."', 0)");
$launch .= " -f $path$dict2 -h $path$dict1 ";//надо по dict1 прописать в перл. программе подсчёт частот
echo "<br>запускаю программу два ".$launch;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launch)."','".mysql_real_escape_string($path.$filename)."', 0)");
}
if (!file_exists($path.$dict1) && file_exists($path.$dict2)){ //no unigram freqDict
echo "<br>униграммный ".$launchDict1;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launchDict1)."','".mysql_real_escape_string($path.$dict1)."', 0)");
$launch .= " -f $path$dict2 -h $path$dict1 ";
echo "<br>запускаю программу два ".$launch;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launch)."','".mysql_real_escape_string($path.$filename)."', 0)");
}
if (!file_exists($path.$dict1)&& !file_exists($path.$dict2)){ //no both freqDict
echo "<br> вот же не повезло<br>";
if ($_GET['metricR'] == "tscore"){ $launchDict .= " -n2";}
echo "<br>раз ".$launchDict;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launchDict)."','".mysql_real_escape_string($path.$dict2)."', 0)");
// print "<br>код ошибки: ". mysql_error();
echo "<br>два ".$launchDict1;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launchDict1)."','".mysql_real_escape_string($path.$dict1)."', 0)");
// print "<br>код ошибки: ". mysql_error();
$launch .= " -f $path$dict2 -h $path$dict1 -b".$_GET['b'];
echo "<br>три ".$launch;
mysql_query("insert into journal values(NULL,'".mysql_real_escape_string($launch)."','".mysql_real_escape_string($path.$filename)."', 0)");
// print "<br>код ошибки: ". mysql_error();
}
}
}
//printing table
print "<br><br><b>This is how journal looks like:</b><br><br>";
$sql="select * from journal";
$result = mysql_query($sql);
$table="<form method='get' action='index.php'><table border=1><tr><td>ID<td>launch_path<td>res_path<td>mode";
while ($line = mysql_fetch_assoc($result)){
$iD = $line['numb']." ";
$launch_path = $line['launch']." ";
$res_path = $line['path']." ";
$mode = $line['mode'];
$table.= "<tr><td>$iD<td>$launch_path<td>$res_path<td>$mode";
};
print $table;
?>
<!--
<form method="get" action="index.php">
</form>
-->
<file_sep>/interface/showRes.php
<html>
<head>
<title>Collocations interface</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Author" content="<NAME>">
<meta name="keywords" content="collocations,MI,t-score,mutual information">
<meta name="description" content="Collocations">
<meta name="Generator" content="Notepad++">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div id="wrap">
<div id="header">
<ul class="top-menu">
<li><a href="main.html" title="Collocations main"><b>Выбор коллекции</b></a></li>
<li><a href="download.php" title="Download">Готовые файлы</a></li>
</ul>
<h1>Collocations</h1>
</div>
<div id="container">
<?php
if ($_GET['file']!=null){
//show existing file on the page
if($_GET['res']==""){
#echo "Файл уже обработан: <a href=".$_GET['file'].">".$_GET['file']."</a><br>";}
print "Файл уже обработан: <a href=saveFile.php?flname=".basename($_GET['file'])."&flpath=".$_GET['file'].">".basename($_GET['file'])."</a><br>";
}
else {
#echo "Файл уже обработан: <a href=".$_GET['file'].">".$_GET['res']."</a><br>";}
print "Файл уже обработан: <a href=saveFile.php?flname=".$_GET['res']."&flpath=".$_GET['file'].">".basename($_GET['file'])."</a><br>";
}
echo "Top 50: <br>";
$handle = @fopen($_GET['file'], "r");
if ($handle){
ini_set("auto_detect_line_endings", true); //instead of length parameter
while(($buffer = fgets($handle)) <= 50){
echo $buffer."<br>";
}
}
if (!feof($handle)){
echo "END OF FILE\n";
}
fclose($handle);
}
if($_GET['name']!=null){
echo $_GET['name'];
}
?>
</div>
<div id="bottom">
Все <a href="http://code.google.com/p/collocations/source/browse/#svn%2Ftrunk" title="Программы, SVN">программы</a> и <a href="http://code.google.com/p/collocations/wiki/Documentation" title="Wiki документация">документация к ним</a> находятся в открытом доступе.
<p>©<NAME></p>
</div>
</div>
</body>
</html>
<file_sep>/interface/download.php
<html>
<head>
<title>Collocations interface</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Author" content="<NAME>">
<meta name="keywords" content="collocations,MI,t-score,mutual information">
<meta name="description" content="Collocations">
<meta name="Generator" content="Notepad++">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div id="wrap">
<div id="header">
<ul class="top-menu">
<li><a href="main.html" title="Collocations main"><b>Выбор коллекции</b></a></li>
<li><a href="download.php" title="Download">Готовые файлы</a></li>
</ul>
<h1>Collocations</h1>
</div>
<div id="container">
<!--<form>
код для обращения к БД и выводу файлов с mode=2-->
<?php
$host = "localhost";
$login = "colloc";
$PWD = "<PASSWORD>";
$dbCon = mysql_connect($host,$login, $PWD);
//проверка
//print "код ошибки: ". mysql_error();
//print "<br>Connected with ID: ".$dbCon."<br>";
//к журналу
$dbName = "collocs";
mysql_select_DB($dbName, $dbCon);
$result = mysql_query("select * from journal where mode=2", $dbCon);
$result2 = mysql_query("SELECT * FROM journal WHERE mode=2", $dbCon);
print "<b>Обработанные файлы, доступные для скачивания:</b><br><br>";
while ($line = mysql_fetch_array($result)){
//$res_path = $line['path']." ";
//$res_path = $line[0];
//print $res_path."<br>";
if ($line['name'] == ''){
#print "<a href=".$line['path'].">".basename($line['path'])."</a><br>";
print "<a href=saveFile.php?flname=".basename($line['path'])."&flpath=".$line['path'].">".basename($line['path'])."</a><br>";
}else{
print "<a href=saveFile.php?flname=".$line['name']."&flpath=".$line['path'].">".$line['name']."</a><br>";
# header("Location:saveFile.php?flname=".$line['name']."&flpath=".$line['path']);#выводим пользовательское имя файла
}
}
?>
<!-- </form>-->
</div>
<div id="bottom">
Все <a href="http://code.google.com/p/collocations/source/browse/#svn%2Ftrunk" title="Программы, SVN">программы</a> и <a href="http://code.google.com/p/collocations/wiki/Documentation" title="Wiki документация">документация к ним</a> находятся в открытом доступе.
<p>©<NAME></p>
</div>
</div>
</body>
</html>
| 216062b63f10ab90329b687ed52340652dac22e4 | [
"PHP"
] | 3 | PHP | irinfox/collocations | 780a2154a0eeba1ae241deabc925a15d9f28c6ca | cb034563874ef310bebb33ded1f14573c81ce4c9 |
refs/heads/master | <repo_name>diegoalpin/SA-NETCore-Solution<file_sep>/SA-NETCore-Solution/Controllers/SearchController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SA_NETCore_Solution.Models;
namespace SA_NETCore_Solution.Controllers
{
public class SearchController : Controller
{
private DbSongs dbContext;
public SearchController(DbSongs dbContext)
{
this.dbContext = dbContext;
}
public IActionResult Duration(string mins,string secs)
{
int minutes = Convert.ToInt32(mins);
int seconds = Convert.ToInt32(secs);
List<Song> songs = dbContext.Songs.Where(x=>x.Mins>=minutes).ToList();
List<Song> SearchedSongs = new List<Song>();
foreach(Song song in songs)
{
if((song.Mins>minutes)||(song.Mins==minutes && song.Secs >= seconds))
{
SearchedSongs.Add(song);
}
}
List<Genre> genres = dbContext.Genres.ToList();
var songlist = from song in SearchedSongs
from genre in genres
where song.GenreId == genre.Id
orderby (song.Mins.ToString() + song.Secs.ToString()) descending
select new
{
song.Title,
Length = song.Mins.ToString() + ":" + song.Secs.ToString(),
genre.Name
};
List<FinalSongs> toReturnSongs = new List<FinalSongs>();
foreach(var song in songlist)
{
toReturnSongs.Add(new FinalSongs{
Title = song.Title,
Length = song.Length,
Name = song.Name
});
}
ViewData["SongList"] =toReturnSongs;
ViewData["mins"] = mins;
ViewData["secs"] = secs;
return View();
}
}
}
<file_sep>/SA-NETCore-Solution/Models/Song.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SA_NETCore_Solution.Models
{
public class Song
{
public Song()
{
Id = new Guid();
}
public Guid Id { get; set; }
public string Title { get; set; }
public int Mins { get; set; }
public int Secs { get; set; }
public virtual Guid GenreId { get; set; }
}
}
<file_sep>/SA-NETCore-Solution/Models/Genre.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SA_NETCore_Solution.Models
{
public class Genre
{
public Genre()
{
Id = new Guid();
Songs = new List<Song>();
}
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; }
}
}
<file_sep>/SA-NETCore-Solution/DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SA_NETCore_Solution.Models;
namespace SA_NETCore_Solution
{
public class DB
{
private DbSongs dbContext;
public DB(DbSongs dbContext)
{
this.dbContext = dbContext;
}
public void Seed()
{
SeedGenre();
SeedSongs();
}
public void SeedGenre()
{
dbContext.Add(new Genre
{
Name = "Classical"
});
dbContext.Add(new Genre
{
Name = "Pop"
});
dbContext.SaveChanges();
}
public void SeedSongs()
{
Genre classical = dbContext.Genres.FirstOrDefault(x => x.Name == "Classical");
Genre pop = dbContext.Genres.FirstOrDefault(x => x.Name == "Pop");
dbContext.Add(new Song
{
Title = "Fly Me To The Moon",
Mins = 5,
Secs = 42,
GenreId = pop.Id
});
dbContext.Add(new Song
{
Title = "Canon In D",
Mins = 5,
Secs = 11,
GenreId = classical.Id
});
dbContext.Add(new Song
{
Title = "Let It Be",
Mins = 5,
Secs = 58,
GenreId = pop.Id
});
dbContext.Add(new Song
{
Title = "Somewhere Out There",
Mins = 4,
Secs = 48,
GenreId = pop.Id
});
dbContext.Add(new Song
{
Title = "Hallelujah",
Mins = 4,
Secs = 15,
GenreId = classical.Id
}); ;
dbContext.SaveChanges();
}
}
}
<file_sep>/SA-NETCore-Solution/Models/DbSongs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace SA_NETCore_Solution.Models
{
public class DbSongs : DbContext
{
public DbSongs(DbContextOptions<DbSongs> options) : base(options)
{
}
public DbSet<Song> Songs { get; set; }
public DbSet<Genre> Genres { get; set; }
}
}
| ff051a9e390837ab76002f15a89b3cc8299d67c9 | [
"C#"
] | 5 | C# | diegoalpin/SA-NETCore-Solution | e8ae136f7032ce97636db46b053c17999da056c2 | 5c27043ae1e5ff8b16e7544ba35d87c3660925f4 |
refs/heads/master | <repo_name>mgarlanger/VirtualH89<file_sep>/VirtualH89/Src/Terminal.h
/// \file Terminal.h
///
/// \date Apr 12, 2009
/// \author <NAME>
///
#ifndef TERMINAL_H_
#define TERMINAL_H_
#include "SerialPortDevice.h"
/// \class Terminal
///
/// \brief Base %Terminal.
///
/// Base class for generic terminal.
///
class Terminal: public SerialPortDevice
{
public:
Terminal();
virtual ~Terminal() override;
virtual void init() = 0;
virtual void reset() = 0;
virtual void processCharacter(char ch) = 0;
virtual void display() = 0;
virtual void keypress(char ch) = 0;
virtual bool checkUpdated() = 0;
private:
};
#endif // TERMINAL_H_
<file_sep>/VirtualH89/Src/VirtualH89Frame.h
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: VirtualH89Frame.h
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 17:02:50 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _VIRTUALH89FRAME_H_
#define _VIRTUALH89FRAME_H_
/*!
* Includes
*/
////@begin includes
#include "wx/frame.h"
////@end includes
#include <wx/bitmap.h>
#include <wx/timer.h>
#include <vector>
/*!
* Forward declarations
*/
////@begin forward declarations
class H19TextFrame;
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_VIRTUALH89FRAME 10000
#define ID_MENUITEM_FileExit 10002
#define ID_MENUITEM_ViewConfig 10004
#define ID_MENUITEM_HelpAbout 10003
#define SYMBOL_VIRTUALH89FRAME_STYLE wxCAPTION|wxSYSTEM_MENU|wxMINIMIZE_BOX|wxCLOSE_BOX
#define SYMBOL_VIRTUALH89FRAME_TITLE _("Virtual Heathkit H-89 All-in-One Computer")
#define SYMBOL_VIRTUALH89FRAME_IDNAME ID_VIRTUALH89FRAME
#define SYMBOL_VIRTUALH89FRAME_SIZE wxSize(400, 300)
#define SYMBOL_VIRTUALH89FRAME_POSITION wxDefaultPosition
////@end control identifiers
/*!
* VirtualH89Frame class declaration
*/
class VirtualH89Frame: public wxFrame
{
DECLARE_CLASS( VirtualH89Frame )
DECLARE_EVENT_TABLE()
public:
/// Constructors
VirtualH89Frame();
VirtualH89Frame( wxWindow* parent, wxWindowID id = SYMBOL_VIRTUALH89FRAME_IDNAME, const wxString& caption = SYMBOL_VIRTUALH89FRAME_TITLE, const wxPoint& pos = SYMBOL_VIRTUALH89FRAME_POSITION, const wxSize& size = SYMBOL_VIRTUALH89FRAME_SIZE, long style = SYMBOL_VIRTUALH89FRAME_STYLE );
bool Create( wxWindow* parent, wxWindowID id = SYMBOL_VIRTUALH89FRAME_IDNAME, const wxString& caption = SYMBOL_VIRTUALH89FRAME_TITLE, const wxPoint& pos = SYMBOL_VIRTUALH89FRAME_POSITION, const wxSize& size = SYMBOL_VIRTUALH89FRAME_SIZE, long style = SYMBOL_VIRTUALH89FRAME_STYLE );
/// Destructor
~VirtualH89Frame();
/// Initialises member variables
void Init();
/// Creates the controls and sizers
void CreateControls();
////@begin VirtualH89Frame event handler declarations
/// wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_FileExit
void OnMENUITEMFileExitClick( wxCommandEvent& event );
/// wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_HelpAbout
void OnMENUITEMHelpAboutClick( wxCommandEvent& event );
////@end VirtualH89Frame event handler declarations
////@begin VirtualH89Frame member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end VirtualH89Frame member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin VirtualH89Frame member variables
H19TextFrame* m_H19TextFrame;
////@end VirtualH89Frame member variables
};
extern VirtualH89Frame *TheFrame;
extern std::vector<wxBitmap> FontBitmaps;
#endif
// _VIRTUALH89FRAME_H_
#endif
<file_sep>/VirtualH89/Src/h89-timer.h
/// \file h89-timer.h
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#ifndef H89TIMER_H_
#define H89TIMER_H_
#include "EventHandler.h"
#include "GppListener.h"
/// \cond
#include <pthread.h>
/// \endcond
class CPU;
class Computer;
class InterruptController;
///
/// \class H89Timer
///
/// \brief %H89 2 mSec timer
///
///
class H89Timer: public EventHandler, public GppListener
{
public:
H89Timer(Computer* computer,
CPU* cpu,
unsigned char intlvl = 1);
virtual ~H89Timer() override;
virtual int handleSignal(int signum) override;
void reset();
void start();
private:
virtual void gppNewValue(BYTE gpo) override;
static const BYTE h89timer_gpp2msIntEnBit_c = 0b00000010;
Computer* computer_m;
CPU* cpu_m;
bool intEnabled_m;
unsigned long count_m;
unsigned char intLevel;
pthread_t thread;
};
#endif // H89TIMER_H_
<file_sep>/VirtualH89/Src/SerialPortDevice.h
/// \file SerialPortDevice.h
///
/// \date Apr 23, 2009
/// \author <NAME>
///
#ifndef SERIALPORTDEVICE_H_
#define SERIALPORTDEVICE_H_
#include "h89Types.h"
class INS8250;
/// \class SerialPortDevice
///
/// \brief Base class for devices that connect to a Serial Port
///
///
class SerialPortDevice
{
public:
SerialPortDevice();
virtual ~SerialPortDevice();
virtual void receiveData(BYTE data) = 0;
virtual bool sendReady();
virtual bool sendData(BYTE data);
virtual void attachPort(INS8250* port);
virtual unsigned int getBaudRate() = 0;
static const int DISABLE_BAUD_CHECK = -1;
private:
INS8250* port_m;
};
#endif // SERIALPORTDEVICE_H_
<file_sep>/VirtualH89/Src/GUI.h
///
/// \name GUI.h
///
/// GUI base class. It defines the interface between the H19 terminal class and an abstract GUI.
/// It also houses the character generator ROM, which is needed by any GUI implementation.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#ifndef GUI_H_
#define GUI_H_
// Ensure exactly one GUI defined.
#undef __GUIDefined__
#if defined(__GUIglut__)
#define __GUIDefined__
#endif
#if defined(__GUIwx__) && defined(__GUIDefined__)
#error Configured for more than 1 GUI. Choices are -D__GUIglut__ and -D__GUIwx__. Please choose exactly 1.
#elif defined(__GUIwx__)
#define __GUIDefined__
#endif
// More checks as other GUIs added go here>
//#if defined(__GUI??__) && defined(__GUIDefined__)
//#error Configured for more than 1 GUI. Choices are -D__GUIglut__, -D__GUIwx__, .... Please choose exactly 1.
//#elif defined(__GUI??__)
//#define __GUIDefined__
//#endif
typedef void (* tKeyboardFunc)(unsigned char Key);
typedef void (* tDisplayFunc)(void);
typedef void (* tTimerFunc)(void);
#include <iostream>
class GUI
{
public:
GUI();
virtual ~GUI();
// Interface functions.
public:
virtual void GUIDisplay(void) = 0;
virtual void InitGUI(void) = 0;
virtual void SetKeyboardFunc(tKeyboardFunc KeyboardFunc) = 0;
virtual void SetDisplayFunc(tDisplayFunc KeyboardFunc) = 0;
virtual void SetTimerFunc(unsigned int ms, tTimerFunc TimerFunc) = 0;
virtual void StartGUI(void) = 0;
};
// All client GUI access is through this pointer to the base GUI class.
// Access is achieved by adding #include "GUI.h". The include gives the access.
extern GUI* TheGUI;
extern const unsigned char fontTableForward[];
extern const unsigned char fontTableInverted[];
#endif /* GUI_H_ */
<file_sep>/VirtualH89/Src/HardSectoredDisk.cpp
///
/// \file HardSectoredDisk.cpp
///
///
/// \date Sep 9, 2012
/// \author <NAME>
///
#include "HardSectoredDisk.h"
#include "logger.h"
/// \cond
#include <cstring>
/// \endcond
HardSectoredDisk::HardSectoredDisk(const char* name)
{
FILE* file;
initialized_m = true;
memset(rawImage_m, 0, maxHeads_c * bytesPerTrack_c * maxTracksPerSide_c);
if ((file = fopen(name, "r")) != nullptr)
{
unsigned long readCount;
int trk = 0;
int head = 0;
do
{
if (trk == 80)
{
// Check to see if we read both sides.
if (head == 1)
{
break;
}
trk = 0;
head++;
}
if ((readCount =
fread(&rawImage_m[head][trk][0], bytesPerTrack_c, 1, file)) == 1)
{
trk++;
}
else if ((trk == 0) && (head == 1))
{
// check to see if we have to adjust side and track.
head = 0;
trk = 80;
}
}
while (readCount == 1);
tracks_m = trk;
sides_m = head + 1;
debugss(ssFloppyDisk, ALL, "Sides: %d Tracks: %d\n", sides_m, tracks_m);
fclose(file);
}
else
{
debugss(ssFloppyDisk, ERROR, "unable to open file - %s\n", name);
initialized_m = false;
}
if (initialized_m)
{
debugss(ssFloppyDisk, INFO, "Success %s\n", name);
}
}
HardSectoredDisk::HardSectoredDisk()
{
debugss(ssFloppyDisk, ALL, "blank disk\n");
// clear disk
bzero(rawImage_m, maxHeads_c * bytesPerTrack_c * maxTracksPerSide_c);
tracks_m = maxTracksPerSide_c;
sides_m = maxHeads_c;
initialized_m = true;
setWriteProtect(false);
}
HardSectoredDisk::~HardSectoredDisk()
{
}
bool
HardSectoredDisk::readData(BYTE side,
BYTE track,
unsigned long pos,
BYTE& data)
{
debugss(ssFloppyDisk, ALL, "maxTrack (%d) tracks_m(%d)\n", maxTrack_m,
tracks_m);
// Currently only 40 and 80 are supported.
if ((maxTrack_m != 40) && (maxTrack_m != 80))
{
debugss(ssFloppyDisk, ERROR, "Invalid maxTrack: %d\n", maxTrack_m);
return false;
}
if (maxTrack_m != tracks_m)
{
if ((maxTrack_m == 80) && (tracks_m == 40))
{
debugss(ssFloppyDisk, INFO, "max - 80 trk_m - 40 | track - %d newTrack - %d\n",
track, track / 2);
track /= 2;
}
else if ((maxTrack_m == 40) && (tracks_m == 80))
{
debugss(ssFloppyDisk, INFO, "max - 40 trk_m - 80\n");
track *= 2;
}
}
if (initialized_m)
{
if ((track < maxTracksPerSide_c) && (pos < bytesPerTrack_c))
{
debugss(ssFloppyDisk, INFO, "side(%d) track(%d) pos(%lu) = %d\n",
side, track, pos, rawImage_m[side][track][pos]);
data = rawImage_m[side][track][pos];
return true;
}
else
{
debugss(ssFloppyDisk, ERROR, "range error: track(%d) pos(%lu)\n", track, pos);
return false;
}
}
else
{
debugss(ssFloppyDisk, ERROR, "disk not initialized\n");
return false;
}
}
bool
HardSectoredDisk::writeData(BYTE side,
BYTE track,
unsigned long pos,
BYTE data)
{
debugss(ssFloppyDisk, ALL, "maxTrack (%d) tracks_m(%d)\n", maxTrack_m, tracks_m);
// Currently only 40 and 80 are supported.
if ((maxTrack_m != 40) && (maxTrack_m != 80))
{
debugss(ssFloppyDisk, ERROR, "Invalid maxTrack: %d\n", maxTrack_m);
return false;
}
if (maxTrack_m != tracks_m)
{
if ((maxTrack_m == 80) && (tracks_m == 40))
{
debugss(ssFloppyDisk, INFO, "max - 80 trk_m - 40\n");
track /= 2;
}
else if ((maxTrack_m == 40) && (tracks_m == 80))
{
debugss(ssFloppyDisk, INFO, "max - 40 trk_m - 80\n");
track *= 2;
}
}
if (initialized_m)
{
// if we write beyond the current max, update it, since it's likely
// being formatted.
if (side == sides_m)
{
sides_m = side + 1;
}
/* \TODO have to handle 80/40 tracks on drive vs disk better.
if (track == tracks_m && tracks_m == 40)
{
tracks_m = 80;
}*/
if ((track < maxTracksPerSide_c) && (pos < bytesPerTrack_c))
{
rawImage_m[side][track][pos] = data;
debugss(ssFloppyDisk, ALL, "side (%d) track(%d) pos(%lu) = %d\n",
side,
track,
pos, rawImage_m[side][track][pos]);
return true;
}
else
{
debugss(ssFloppyDisk, ERROR, "Out of Range - track(%d) pos(%lu)\n", track, pos);
return false;
}
}
else
{
debugss(ssFloppyDisk, ERROR, "disk not initialized\n");
return false;
}
}
void
HardSectoredDisk::getControlInfo(unsigned long pos,
bool& hole,
bool& writeProtect)
{
if (initialized_m)
{
hole = defaultHoleStatus(pos);
writeProtect = checkWriteProtect();
}
else
{
// No disk in drive so hole light is on.
hole = true;
// write protect sensor is not blocked.
writeProtect = false;
}
}
bool
HardSectoredDisk::defaultHoleStatus(unsigned long pos)
{
debugss(ssFloppyDisk, ALL, "pos = %lu ", pos);
// check for a sector hole
if ((pos % 320) < 64)
{
debugss_nts(ssFloppyDisk, ALL, "sector hole\n");
return true;
}
// check for index hole
if ((pos > 3040) && (pos < 3104))
{
debugss_nts(ssFloppyDisk, ALL, "index hole\n");
return true;
}
debugss_nts(ssFloppyDisk, ALL, "no hole\n");
return false;
}
void
HardSectoredDisk::dump()
{
debugss(ssFloppyDisk, ERROR, "Not Implemented\n");
}
void
HardSectoredDisk::eject(const char* name)
{
FILE* file;
debugss(ssFloppyDisk, ALL, "Save: %s\n", name);
if ((file = fopen(name, "wb")) != nullptr)
{
unsigned long readCount;
for (int head = 0; head < sides_m; head++)
{
for (int track = 0; track < tracks_m; track++)
{
if ((readCount =
fwrite(&rawImage_m[head][track][0], bytesPerTrack_c, 1, file)) != 1)
{
debugss(ssFloppyDisk, ERROR, "Unable to save file: %s head: %d track: %d\n",
name, head, track);
}
}
}
fclose(file);
}
else
{
debugss(ssFloppyDisk, WARNING, "unable to save file - %s\n", name);
}
}
bool
HardSectoredDisk::readSectorData(BYTE side,
BYTE track,
BYTE sector,
WORD pos,
BYTE& data)
{
debugss(ssFloppyDisk, ERROR, "Not Implemented\n");
return false;
}
<file_sep>/VirtualH89/Src/cpu.h
/// \file cpu.h
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#ifndef CPU_H_
#define CPU_H_
#include "h89Types.h"
/// \cond
#include <string>
/// \endcond
class AddressBus;
class IOBus;
///
/// \brief Abstract processor.
///
/// Basic processor abstraction class.
///
class CPU
{
public:
static const unsigned long NO_INTR_INST = ((unsigned long) -1);
typedef unsigned long intrCheck (void* arg,
int level);
private:
public:
CPU();
virtual ~CPU();
virtual void addClockTicks(void) = 0;
virtual BYTE execute(WORD numInst = 0) = 0;
virtual void reset(void) = 0;
virtual BYTE step(void) = 0;
virtual void raiseINT(void) = 0;
virtual void lowerINT(void) = 0;
virtual void raiseNMI(void) = 0;
virtual void setIOBus(IOBus* io) = 0;
virtual void setAddressBus(AddressBus* ab) = 0;
virtual void continueRunning(void) = 0;
virtual void waitState(void) = 0;
virtual std::string dumpDebug() = 0;
virtual void setSpeedup(int factor) = 0;
virtual void enableFast(void) = 0;
};
#endif // CPU_H_
<file_sep>/VirtualH89/Src/IODevice.cpp
/// \file IODevice.cpp
///
/// \date Apr 20, 2009
/// \author <NAME>
///
#include "IODevice.h"
IODevice::IODevice(BYTE base,
BYTE numPorts): baseAddress_m(base),
numPorts_m(numPorts)
{
}
IODevice::~IODevice()
{
}
BYTE
IODevice::getBaseAddress(void)
{
return (baseAddress_m);
}
BYTE
IODevice::getNumPorts(void)
{
return (numPorts_m);
}
bool
IODevice::verifyPort(BYTE addr)
{
return ((addr >= baseAddress_m) && (addr < (baseAddress_m + numPorts_m)));
}
BYTE
IODevice::getPortOffset(BYTE addr)
{
return (addr - baseAddress_m);
}
<file_sep>/VirtualH89/Src/MemoryDecoder.h
///
/// \file MemoryDecoder.h
///
/// Base class for memory decoders, which implement various layouts of
/// the address space along with switching between them.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef MEMORYDECODER_H_
#define MEMORYDECODER_H_
#include "GppListener.h"
#include "MemoryLayout.h"
#include "Memory8K.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class SystemMemory8K;
class MemoryDecoder;
typedef std::shared_ptr<MemoryDecoder> MemoryDecoder_ptr;
class MemoryDecoder: public GppListener
{
public:
static MemoryDecoder_ptr createMemoryDecoder(std::string type,
std::shared_ptr<SystemMemory8K> sysMem,
MemoryLayout::MemorySize_t memSize);
MemoryDecoder(int numLayouts,
BYTE gppBits);
virtual ~MemoryDecoder();
virtual void reset();
virtual void addLayout(int ix,
MemoryLayout_ptr lo);
inline MemoryLayout_ptr getLayout(int ix)
{
return layouts_m[ix & layoutMask_m];
}
inline int numLayouts();
inline int getCurrentLayoutNum()
{
return curLayoutNum_m;
}
inline BYTE readByte(int ix,
WORD addr)
{
return getLayout(ix)->getPageByAddress(addr)->readByte(addr);
}
inline void writeByte(int ix,
WORD addr,
BYTE val)
{
getLayout(ix)->getPageByAddress(addr)->writeByte(addr, val);
}
inline BYTE readByte(WORD address)
{
return curLayout_m->getPageByAddress(address)->readByte(address);
}
inline void writeByte(WORD address,
BYTE val)
{
curLayout_m->getPageByAddress(address)->writeByte(address, val);
}
protected:
BYTE curLayoutNum_m;
int layoutMask_m;
int numLayouts_m;
std::vector<MemoryLayout_ptr> layouts_m;
MemoryLayout_ptr curLayout_m;
virtual void updateCurLayout(BYTE layout);
};
#endif // MEMORYDECODER_H_
<file_sep>/VirtualH89/Src/NilMemory8K.h
///
/// \file NilMemory8K.h
///
/// Implementation of an 8K page of non-existent memory. Reads 0, writes ignored.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef NILMEMORY8K_H_
#define NILMEMORY8K_H_
#include "Memory8K.h"
class NilMemory8K: public Memory8K
{
public:
NilMemory8K(WORD base): Memory8K(base)
{
}
virtual ~NilMemory8K() override
{
}
void writeByte(WORD adr, BYTE val) override
{
}
};
#endif // NILMEMORY8K_H_
<file_sep>/VirtualH89/Src/DiskController.cpp
/// \file DiskController.cpp
///
/// A wrapper for an IODevice that allows it to be distinguished from other,
/// non-storage, I/O Devices. Requires some methods for handling mounted media.
///
/// \date Feb 8, 2016
/// \author <NAME>
///
#include "DiskController.h"
/// \cond
#include <sstream>
/// \endcond
DiskController::DiskController(BYTE base,
BYTE numPorts): IODevice(base, numPorts)
{
}
DiskController::~DiskController()
{
}
std::string
DiskController::getDriveName(int index)
{
std::ostringstream name;
name << getDeviceName() << '-' << (index + 1);
return name.str();
}
<file_sep>/VirtualH89/Src/Z47Controller.cpp
///
/// \name Z47Controller.cpp
///
/// Controller card for the Z-47 external 8" drives. The card is physically located
/// on the Master Remex Drive.
///
/// \date Aug 12, 2013
/// \author <NAME>
///
#include "Z47Controller.h"
#include "logger.h"
#include "ParallelLink.h"
/// \cond
#include <string.h>
/// \endcond
Z47Controller::Z47Controller(): curDisk(invalidDisk_c),
curLinkState(st_Link_Undefined_c),
curState(st_None_c),
statePosition_m(0),
countDown_m(0),
linkToHost_m(0),
readyState(0),
sectorCount(1),
driveNotReady_m(false),
diskWriteProtected_m(false),
deletedData_m(false),
noRecordFound_m(false),
crcError_m(false),
lateData_m(false),
invalidCommandReceived_m(false),
badTrackOverflow_m(false),
dataToTransmit_m(0),
drive_m(0),
side_m(0),
track_m(0),
sector_m(0),
diskOffset(0),
bytesToTransfer(0),
sectorSize(128)
{
}
Z47Controller::~Z47Controller()
{
}
void
Z47Controller::loadDisk()
{
debugss(ssH47, VERBOSE, "Entering\n");
FILE* file;
if ((file = fopen("8in.dsk", "r")) != nullptr)
{
int i = 0;
for (; i < 26 * 77; i++)
{
if ((fread(&diskData[i * 128], 128, 1, file)) != 1)
{
debugss(ssH47, INFO, "File ended early: %d\n", i);
}
else
{
debugss(ssH47, ALL, "File was read\n");
break;
}
}
for (; i < 26 * 77; i++)
{
memset(&diskData[i * 128], 0, 128);
}
fclose(file);
}
else
{
debugss(ssH47, ERROR, "unable to open file\n");
}
}
void
Z47Controller::reset()
{
curDisk = invalidDisk_c;
curState = st_None_c;
linkToHost_m = 0;
}
const char*
Z47Controller::getStateStr(ControllerState state)
{
switch (curState)
{
case st_None_c:
return ("None");
case st_Boot_c:
return ("Boot");
case st_ReadCntrlStat_c:
return ("ReadCntrlStat");
case st_ReadAuxStat_c:
return ("ReadAuxStat");
case st_LoadSectorCount_c:
return ("LoadSectorCount");
case st_ReadLastAddr_c:
return ("ReadLastAddr");
case st_ReadSectors_c:
return ("ReadSectors");
case st_WriteSectors_c:
return ("WriteSectors");
case st_ReadSectorsBuffered_c:
return ("ReadSectorsBuffered");
case st_WriteSectorsBuffered_c:
return ("WriteSectorsBuffered");
case st_WriteSectorsAndDelete_c:
return ("WriteSectorsAndDelete");
case st_WriteSectorsBufferedAndDelete_c:
return ("WriteSectorsBufferedAndDelete");
case st_Copy_c:
return ("Copy");
case st_FormatIBM_SD_c:
return ("FormatIBM_SD");
case st_Format_SD_c:
return ("Format_SD");
case st_FormatIBM_DD_c:
return ("FormatIBM_DD");
case st_Format_DD_c:
return ("Format_DD");
case st_ReadReadyStatus_c:
return ("ReadReadyStatus");
default:
break;
}
return ("Unknown");
}
void
Z47Controller::transitionLinkToReady()
{
curLinkState = st_Link_Ready_c;
if (linkToHost_m)
{
linkToHost_m->setBusy(false);
linkToHost_m->setDTR(true);
}
}
void
Z47Controller::transitionLinkToAwaitingReceive()
{
curLinkState = st_Link_AwaitingToReqReceive_c;
if (linkToHost_m)
{
linkToHost_m->setBusy(false);
linkToHost_m->setDTR(true);
}
}
void
Z47Controller::transitionLinkToTransmit()
{
curLinkState = st_Link_AwaitingToTransmit_c;
if (linkToHost_m)
{
linkToHost_m->setBusy(false);
linkToHost_m->setDTR(true);
}
}
void
Z47Controller::processReadControlStatus(void)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 2)
{
commandComplete();
return;
}
if (statePosition_m != 1)
{
debugss(ssH47, ERROR, "Unexpected position\n");
}
if (linkToHost_m)
{
dataToTransmit_m = 0;
if (driveNotReady_m)
{
debugss(ssH47, INFO, "set Drive not Ready\n");
dataToTransmit_m |= stat_Cntrl_Drive_Not_Ready_c;
driveNotReady_m = false;
}
if (diskWriteProtected_m)
{
debugss(ssH47, INFO, "set Disk Write Protected\n");
dataToTransmit_m |= stat_Cntrl_Write_Protected_c;
diskWriteProtected_m = false;
}
if (deletedData_m)
{
debugss(ssH47, INFO, "set Deleted Data\n");
dataToTransmit_m |= stat_Cntrl_Deleted_Data_c;
deletedData_m = false;
}
if (noRecordFound_m)
{
debugss(ssH47, INFO, "set No Record Found\n");
dataToTransmit_m |= stat_Cntrl_No_Record_Found_c;
noRecordFound_m = false;
}
if (crcError_m)
{
debugss(ssH47, INFO, "set CRC Error\n");
dataToTransmit_m |= stat_Cntrl_CRC_Error_c;
crcError_m = false;
}
if (lateData_m)
{
debugss(ssH47, INFO, "set Late Data\n");
dataToTransmit_m |= stat_Cntrl_Late_Data_c;
lateData_m = false;
}
if (invalidCommandReceived_m)
{
debugss(ssH47, INFO, "set Invalid Command Received\n");
dataToTransmit_m |= stat_Cntrl_Illegal_Command_c;
invalidCommandReceived_m = false;
}
if (badTrackOverflow_m)
{
debugss(ssH47, INFO, "set Bad Track Overflow\n");
dataToTransmit_m |= stat_Cntrl_Bad_Track_Overflow_c;
badTrackOverflow_m = false;
}
debugss(ssH47, INFO, "cmd_ReadCntrlStat_c - 0x%02x\n", dataToTransmit_m);
curLinkState = st_Link_AwaitingToTransmit_c;
}
else
{
/// \todo assert or make the top check an assert
debugss(ssH47, FATAL, "Link not connected\n");
}
}
void
Z47Controller::processReadAuxStatus(BYTE val)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 3)
{
commandComplete();
return;
}
if (statePosition_m == 2)
{
// val passed in is drive and side.
decodeSideDriveSector(val);
// based on side_m and drive_m set value to return (by asking drive - which asks disk)
// but for now just say single sided, single density, and sector length byte of 128
// (which is hopefully 0);
dataToTransmit_m = stat_Aux_Side1_Available_c;
curLinkState = st_Link_AwaitingToTransmit_c;
countDown_m = 10;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processLoadSectorCount(BYTE val)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 3)
{
sectorCount |= val;
debugss(ssH47, ALL, "sector Count = %d\n", sectorCount);
commandComplete();
return;
}
if (statePosition_m == 2)
{
// val passed in is MSB of sector count.
sectorCount = (val << 8);
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processReadSectorsBufffered(BYTE val)
{
statePosition_m++;
debugss(ssH47, ALL, "statePosition: %d\n", statePosition_m);
if (bytesToTransfer == 0)
{
debugss(ssH47, ALL, "All Sectors Read\n");
commandComplete();
return;
}
if (statePosition_m > 3)
{
dataToTransmit_m = diskData[diskOffset++];
bytesToTransfer--;
curLinkState = st_Link_AwaitingToTransmit_c;
countDown_m = 10;
return;
}
if (statePosition_m == 3)
{
// val passed in is drive and side.
decodeSideDriveSector(val);
diskOffset = track_m * (sectorSize * 26) + ((sector_m - 1) * sectorSize);
bytesToTransfer = sectorCount * sectorSize - 1;
// reset sector count
sectorCount = 1;
dataToTransmit_m = diskData[diskOffset++];
curLinkState = st_Link_AwaitingToTransmit_c;
countDown_m = 10;
return;
}
if (statePosition_m == 2)
{
decodeTrack(val);
// based on side_m and drive_m set value to return (by asking drive - which asks disk)
// but for now just say single sided, single density, and sector length byte of 128
// (which is hopefully 0);
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processWriteSectorsBufffered(BYTE val)
{
statePosition_m++;
debugss(ssH47, ALL, "statePosition: %d\n", statePosition_m);
if (bytesToTransfer == 0)
{
diskData[diskOffset++] = val;
debugss(ssH47, ALL, "All Sectors written\n");
commandComplete();
return;
}
if (statePosition_m > 3)
{
diskData[diskOffset++] = val;
bytesToTransfer--;
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
return;
}
if (statePosition_m == 3)
{
// val passed in is drive and side.
decodeSideDriveSector(val);
diskOffset = track_m * (sectorSize * 26) + ((sector_m - 1) * sectorSize);
bytesToTransfer = sectorCount * sectorSize - 1;
// reset sector count
sectorCount = 1;
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
return;
}
if (statePosition_m == 2)
{
decodeTrack(val);
// based on side_m and drive_m set value to return (by asking drive - which asks disk)
// but for now just say single sided, single density, and sector length byte of 128
// (which is hopefully 0);
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processFormatSingleDensity(BYTE val)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 3)
{
commandComplete();
return;
}
if (statePosition_m == 2)
{
//
decodeSideDriveSector(val);
countDown_m = 10000;
memset(&diskData[0], 0xe5, 256256);
curLinkState = st_Link_AwaitingControllerComplete_c;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processFormatIBMDoubleDensity(BYTE val)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 3)
{
commandComplete();
return;
}
if (statePosition_m == 2)
{
//
decodeSideDriveSector(val);
countDown_m = 10000;
memset(&diskData[0], 0xe5, 256256);
curLinkState = st_Link_AwaitingControllerComplete_c;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processFormatDoubleDensity(BYTE val)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 3)
{
commandComplete();
return;
}
if (statePosition_m == 2)
{
//
decodeSideDriveSector(val);
countDown_m = 10000;
memset(&diskData[0], 0xe5, 256256);
curLinkState = st_Link_AwaitingControllerComplete_c;
return;
}
if (statePosition_m == 1)
{
// val invalid.
curLinkState = st_Link_AwaitingToReqReceive_c;
countDown_m = 10;
}
}
void
Z47Controller::processReadReadyStatus(void)
{
debugss(ssH47, ALL, "\n");
statePosition_m++;
if (statePosition_m == 2)
{
commandComplete();
return;
}
if (statePosition_m != 1)
{
debugss(ssH47, ERROR, "Unexpected position\n");
}
dataToTransmit_m = readyState;
curLinkState = st_Link_AwaitingToTransmit_c;
countDown_m = 10;
// after reading the status, the changed status bits must be reset.
readyState &= ~(stat_Ready_Drive0ReadyChanged_c |
stat_Ready_Drive1ReadyChanged_c |
stat_Ready_Drive2ReadyChanged_c |
stat_Ready_Drive3ReadyChanged_c);
}
void
Z47Controller::processTransmitted()
{
if (linkToHost_m)
{
linkToHost_m->setDTR(false);
}
switch (curState)
{
case st_Boot_c:
debugss(ssH47, ERROR, "Unsupported - st_Boot_c\n");
break;
case st_ReadCntrlStat_c:
debugss(ssH47, INFO, "st_ReadCntrlStat_c\n");
processReadControlStatus();
break;
case st_ReadAuxStat_c:
debugss(ssH47, INFO, "st_ReadAuxStat_c\n");
processReadAuxStatus();
break;
case st_LoadSectorCount_c:
debugss(ssH47, ERROR, "st_LoadSectorCount_c\n");
processLoadSectorCount();
break;
case st_ReadLastAddr_c:
debugss(ssH47, ERROR, "Unsupported - st_ReadLastAddr_c\n");
break;
case st_ReadSectors_c:
debugss(ssH47, ERROR, "Unsupported - st_ReadSectors_c\n");
break;
case st_WriteSectors_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectors_c\n");
break;
case st_ReadSectorsBuffered_c:
debugss(ssH47, INFO, "st_ReadSectorsBuffered_c\n");
// bytesToTransfer = sectorSize;
processReadSectorsBufffered();
break;
case st_WriteSectorsBuffered_c:
debugss(ssH47, INFO, "st_WriteSectorsBuffered_c\n");
processReadSectorsBufffered();
break;
case st_WriteSectorsAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectorsAndDelete_c\n");
break;
case st_WriteSectorsBufferedAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectorsBufferedAndDelete_c\n");
break;
case st_Copy_c:
debugss(ssH47, ERROR, "Unsupported - st_Copy_c\n");
break;
case st_FormatIBM_SD_c:
debugss(ssH47, ERROR, "Unsupported - st_FormatIBM_SD_c\n");
break;
case st_Format_SD_c:
debugss(ssH47, ERROR, "Unsupported - st_Format_SD_c\n");
break;
case st_FormatIBM_DD_c:
debugss(ssH47, ERROR, "Unsupported - st_FormatIBM_DD_c\n");
break;
case st_Format_DD_c:
debugss(ssH47, ERROR, "Unsupported - st_Format_DD_c\n");
break;
case st_ReadReadyStatus_c:
debugss(ssH47, INFO, "st_ReadReadyStatus_c\n");
processReadReadyStatus();
break;
case st_WaitingToComplete_c:
debugss(ssH47, ERROR, "Unsupported - st_WaitingToComplete_c\n");
break;
default:
debugss(ssH47, ERROR, "default: - %d\n", curState);
break;
}
}
void
Z47Controller::processCmd(BYTE cmd)
{
debugss(ssH47, ALL, "=============START of CMD=============\n");
debugss(ssH47, ALL, "state - %s: cmd - 0x%02x\n", getStateStr(curState), cmd);
countDown_m = coundDown_Default_c;
statePosition_m = 0;
curLinkState = st_Link_Ready_c;
// first lower DTR, and set busy
if (linkToHost_m)
{
linkToHost_m->setDTR(false);
linkToHost_m->setBusy(true);
}
switch (cmd)
{
case cmd_Boot_c:
debugss(ssH47, ERROR, "Unsupported - cmd_Boot_c %d\n", cmd);
// not sure if this is used by heathkit boot. Likes like they just read
// the first 10 sectors.
curState = st_Boot_c;
break;
case cmd_ReadCntrlStat_c:
debugss(ssH47, INFO, "cmd_ReadCntrlStat_c\n");
curState = st_ReadCntrlStat_c;
processReadControlStatus();
break;
case cmd_ReadAuxStat_c:
debugss(ssH47, INFO, "Read Aux Status\n");
curState = st_ReadAuxStat_c;
processReadAuxStatus();
countDown_m = 20;
break;
case cmd_LoadSectorCount_c:
debugss(ssH47, INFO, "cmd_LoadSectorCount_c\n");
curState = st_LoadSectorCount_c;
processLoadSectorCount();
countDown_m = 20;
break;
case cmd_ReadLastAddr_c:
debugss(ssH47, ERROR, "Unsupported - cmd_ReadLastAddr_c %d\n", cmd);
break;
case cmd_ReadSectors_c:
debugss(ssH47, ERROR, "Unsupported - cmd_ReadSectors_c %d\n", cmd);
break;
case cmd_WriteSectors_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteSectors_c %d\n", cmd);
break;
case cmd_ReadSectorsBuffered_c:
debugss(ssH47, INFO, "cmd_ReadSectorsBuffered_c %d\n", cmd);
curState = st_ReadSectorsBuffered_c;
bytesToTransfer = sectorSize;
processReadSectorsBufffered();
break;
case cmd_WriteSectorsBuffered_c:
debugss(ssH47, INFO, "cmd_WriteSectorsBuffered_c %d\n", cmd);
curState = st_WriteSectorsBuffered_c;
bytesToTransfer = sectorSize;
processReadSectorsBufffered();
break;
case cmd_WriteSectorsAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteSectorsAndDelete_c %d\n", cmd);
break;
case cmd_WriteSectorsBufferedAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteSectorsBufferedAndDelete_c %d\n", cmd);
break;
case cmd_Copy_c:
debugss(ssH47, ERROR, "Unsupported - cmd_Copy_c %d\n", cmd);
break;
case cmd_FormatIBM_SD_c:
debugss(ssH47, ERROR, "Unsupported - cmd_FormatIBM_SD_c %d\n", cmd);
break;
case cmd_Format_SD_c:
debugss(ssH47, INFO, "cmd_Format_SD_c %d\n", cmd);
curState = st_Format_SD_c;
processFormatSingleDensity();
break;
case cmd_FormatIBM_DD_c:
debugss(ssH47, INFO, "cmd_FormatIBM_DD_c %d\n", cmd);
curState = st_FormatIBM_DD_c;
processFormatIBMDoubleDensity();
break;
case cmd_Format_DD_c:
debugss(ssH47, ERROR, "Unsupported - cmd_Format_DD_c %d\n", cmd);
curState = st_Format_DD_c;
processFormatDoubleDensity();
break;
case cmd_ReadReadyStatus_c:
debugss(ssH47, INFO, "Read Ready Status\n");
curState = st_ReadReadyStatus_c;
processReadReadyStatus();
break;
case cmd_SpecialFunction1_c:
case cmd_SpecialFunction2_c:
case cmd_SpecialFunction3_c:
case cmd_SpecialFunction4_c:
case cmd_SpecialFunction5_c:
debugss(ssH47, ERROR, "Unsupported - cmd_SpecialFunctionx_c %d\n", cmd);
break;
case cmd_SetDriveCharacteristics_c:
debugss(ssH47, ERROR, "Unsupported - cmd_SetDriveCharacteristics_c %d\n", cmd);
break;
case cmd_SeekToTrack_c:
debugss(ssH47, ERROR, "Unsupported - cmd_SeekToTrack_c %d\n", cmd);
break;
case cmd_DiskStatus_c:
debugss(ssH47, ERROR, "Unsupported - cmd_DiskStatus_c %d\n", cmd);
break;
case cmd_ReadLogical_c:
debugss(ssH47, ERROR, "Unsupported - cmd_ReadLogical_c %d\n", cmd);
break;
case cmd_WriteLogical_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteLogical_c %d\n", cmd);
break;
case cmd_ReadBufferedLogical_c:
debugss(ssH47, ERROR, "Unsupported - cmd_ReadBufferedLogical_c %d\n",
cmd);
break;
case cmd_WriteBufferedLogical_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteBufferedLogical_c %d\n", cmd);
break;
case cmd_WriteDeletedDataLogical:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteDeletedDataLogical %d\n", cmd);
break;
case cmd_WriteBufferedDeletedDataLogical_c:
debugss(ssH47, ERROR, "Unsupported - cmd_WriteBufferedDeletedDataLogical_c %d\n", cmd);
break;
default:
debugss(ssH47, ERROR, "Unknown command - default %d\n", cmd);
invalidCommandReceived_m = true;
if (linkToHost_m)
{
linkToHost_m->setError(true);
}
commandComplete();
break;
}
switch (curLinkState)
{
case st_Link_Undefined_c:
debugss(ssH47, ERROR, "Unexpected Undefined link state\n");
break;
case st_Link_Ready_c:
debugss(ssH47, INFO, "link ready state - do nothing\n");
break;
case st_Link_AwaitingToReqReceive_c:
debugss(ssH47, INFO, "link awaiting receive state\n");
break;
case st_Link_AwaitingToTransmit_c:
debugss(ssH47, INFO, "link transmit state\n");
break;
default:
debugss(ssH47, ERROR, "Unknown command - default %d\n",
curLinkState);
}
}
bool
Z47Controller::connectDrive(BYTE unitNum,
DiskDrive* drive)
{
debugss(ssH47, ALL, "%d - %p\n", unitNum, drive);
if (unitNum < numDrives_c)
{
if (drives_m[unitNum] == 0)
{
drives_m[unitNum] = drive;
}
else
{
debugss(ssH47, ERROR, "drive conflict - %d.\n", unitNum);
return false;
}
}
else
{
debugss(ssH47, ERROR, "invalid drive - %d\n", unitNum);
return false;
}
return true;
}
bool
Z47Controller::removeDrive(BYTE unitNum)
{
debugss(ssH47, ALL, "\n");
if (unitNum < numDrives_c)
{
if (drives_m[unitNum] == 0)
{
debugss(ssH47, WARNING, "no drive to remove - %d.\n", unitNum);
}
drives_m[unitNum] = 0;
debugss(ssH47, ERROR, " disk already in use - %d.\n", unitNum);
}
else
{
debugss(ssH47, ERROR, "invalid drive - %d\n", unitNum);
}
return true;
}
void
Z47Controller::notification(unsigned int cycleCount)
{
switch (curLinkState)
{
case st_Link_Undefined_c:
// debugss(ssH47, ERROR, "Unexpected Undefined link state\n");
return;
case st_Link_Ready_c:
// debugss(ssH47, INFO, "link ready state - do nothing\n");
return;
case st_Link_AwaitingToReqReceive_c:
debugss(ssH47, INFO, "link awaiting to request receive state\n");
break;
case st_Link_AwaitingToReceive_c:
// debugss(ssH47, INFO, "link to receive - do nothing\n");
// get data when dtak is asserted.
return;
case st_Link_AwaitingToTransmit_c:
debugss(ssH47, INFO, "link transmit state\n");
break;
case st_Link_AwaitingTransmitComplete_c:
return;
case st_Link_HoldingDTR_c:
processTransmitted();
return;
case st_Link_AwaitingReadyState_c:
break;
case st_Link_AwaitingControllerComplete_c:
break;
}
if (countDown_m > cycleCount)
{
countDown_m -= cycleCount;
return;
}
countDown_m = 0;
switch (curLinkState)
{
case st_Link_AwaitingToReqReceive_c:
debugss(ssH47, INFO, "link awaiting receive state\n");
// just set the flags and wait for the host to send;
if (linkToHost_m)
{
linkToHost_m->setDTR(true);
}
curLinkState = st_Link_AwaitingToReceive_c;
return;
case st_Link_AwaitingToTransmit_c:
debugss(ssH47, INFO, "link transmit state\n");
if (linkToHost_m)
{
linkToHost_m->sendHostData(dataToTransmit_m);
}
curLinkState = st_Link_AwaitingTransmitComplete_c;
return;
case st_Link_AwaitingReadyState_c:
debugss(ssH47, INFO, "link awaiting ready state\n");
// just set the flags and wait for the host to send;
if (linkToHost_m)
{
linkToHost_m->setDTR(true);
}
curLinkState = st_Link_AwaitingToReceive_c;
return;
default:
debugss(ssH47, ERROR, "Unknown command - default %d\n", curLinkState);
}
if (curState == st_None_c)
{
debugss(ssH47, ERROR, "Unexpected st_None_c\n");
return;
}
switch (curState)
{
case st_Boot_c:
debugss(ssH47, ERROR, "Unsupported - st_Boot_c\n");
break;
case st_ReadCntrlStat_c:
debugss(ssH47, INFO, "st_ReadCntrlStat_c\n");
processReadControlStatus();
break;
case st_ReadAuxStat_c:
debugss(ssH47, INFO, "st_ReadAuxStat_c\n");
processReadReadyStatus();
break;
case st_LoadSectorCount_c:
debugss(ssH47, ERROR, "st_LoadSectorCount_c\n");
processLoadSectorCount();
break;
case st_ReadLastAddr_c:
debugss(ssH47, ERROR, "Unsupported - st_ReadLastAddr_c\n");
break;
case st_ReadSectors_c:
debugss(ssH47, ERROR, "Unsupported - st_ReadSectors_c\n");
break;
case st_WriteSectors_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectors_c\n");
break;
case st_ReadSectorsBuffered_c:
debugss(ssH47, ERROR, "Unsupported - st_ReadSectorsBuffered_c\n");
break;
case st_WriteSectorsBuffered_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectorsBuffered_c\n");
break;
case st_WriteSectorsAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectorsAndDelete_c\n");
break;
case st_WriteSectorsBufferedAndDelete_c:
debugss(ssH47, ERROR, "Unsupported - st_WriteSectorsBufferedAndDelete_c\n");
break;
case st_Copy_c:
debugss(ssH47, ERROR, "Unsupported - st_Copy_c\n");
break;
case st_FormatIBM_SD_c:
debugss(ssH47, ERROR, "Unsupported - st_FormatIBM_SD_c\n");
break;
case st_Format_SD_c:
debugss(ssH47, INFO, "st_Format_SD_c\n");
processFormatSingleDensity();
break;
case st_FormatIBM_DD_c:
debugss(ssH47, INFO, "st_FormatIBM_DD_c\n");
processFormatIBMDoubleDensity();
break;
case st_Format_DD_c:
debugss(ssH47, ERROR, "Unsupported - st_Format_DD_c\n");
processFormatDoubleDensity();
break;
case st_WaitingToComplete_c:
debugss(ssH47, ERROR, "Unsupported - st_WaitingToComplete_c\n");
break;
default:
debugss(ssH47, ERROR, "Unknown command - default %d\n", curState);
}
}
void
Z47Controller::connectHostLink(ParallelLink* link)
{
debugss(ssH47, ALL, "\n");
linkToHost_m = link;
if (linkToHost_m)
{
linkToHost_m->registerDevice(this);
}
else
{
debugss(ssH47, ERROR, "link invalid\n");
}
}
void
Z47Controller::processData(BYTE val)
{
debugss(ssH47, ALL, "0x%02x\n", val);
switch (curState)
{
case st_None_c:
debugss(ssH47, ALL, "st_None_c\n");
processCmd(val);
break;
case st_Boot_c:
debugss(ssH47, ERROR, "st_Boot_c\n");
break;
case st_ReadCntrlStat_c:
debugss(ssH47, ERROR, "Invalid state st_ReadCntrlStat_c\n");
// processReadControlStatus();
break;
case st_ReadAuxStat_c:
debugss(ssH47, INFO, "st_ReadAuxStat_c - 0x%02x\n", val);
processReadAuxStatus(val);
break;
case st_LoadSectorCount_c:
debugss(ssH47, INFO, "st_LoadSectorCount_c\n");
processLoadSectorCount(val);
break;
case st_ReadLastAddr_c:
debugss(ssH47, ERROR, "st_ReadLastAddr_c\n");
break;
case st_ReadSectors_c:
debugss(ssH47, ERROR, "st_ReadSectors_c\n");
break;
case st_WriteSectors_c:
debugss(ssH47, ERROR, "st_WriteSectors_c\n");
break;
case st_ReadSectorsBuffered_c:
debugss(ssH47, INFO, "st_ReadSectorsBuffered_c\n");
processReadSectorsBufffered(val);
break;
case st_WriteSectorsBuffered_c:
debugss(ssH47, INFO, "st_WriteSectorsBuffered_c\n");
processWriteSectorsBufffered(val);
break;
case st_WriteSectorsAndDelete_c:
debugss(ssH47, ERROR, "st_WriteSectorsAndDelete_c\n");
break;
case st_WriteSectorsBufferedAndDelete_c:
debugss(ssH47, ERROR, "st_WriteSectorsBufferedAndDelete_c\n");
break;
case st_Copy_c:
debugss(ssH47, ERROR, "st_Copy_c\n");
break;
case st_FormatIBM_SD_c:
debugss(ssH47, ERROR, "st_FormatIBM_SD_c\n");
break;
case st_Format_SD_c:
debugss(ssH47, INFO, "st_Format_SD_c\n");
processFormatSingleDensity(val);
break;
case st_FormatIBM_DD_c:
debugss(ssH47, INFO, "st_FormatIBM_DD_c\n");
processFormatIBMDoubleDensity(val);
break;
case st_Format_DD_c:
debugss(ssH47, ERROR, "st_Format_DD_c\n");
processFormatDoubleDensity(val);
break;
default:
debugss(ssH47, ERROR, "Unknown state\n");
break;
}
}
void
Z47Controller::raiseSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
switch (sigType)
{
// Master Reset (Host to Disk System)
case st_MasterReset:
// Handle a reset
debugss(ssH47, INFO, "Master Reset received.\n");
// Set reset flag.
readyState = stat_Ready_Drive0ReadyChanged_c |
stat_Ready_Drive1ReadyChanged_c;
curLinkState = st_Link_AwaitingToReceive_c;
if (linkToHost_m)
{
linkToHost_m->setBusy(false);
linkToHost_m->setDTR(true);
}
// clear the errors
driveNotReady_m = false;
diskWriteProtected_m = false;
deletedData_m = false;
noRecordFound_m = false;
crcError_m = false;
lateData_m = false;
invalidCommandReceived_m = false;
badTrackOverflow_m = false;
break;
// Data Acknowledge (Host to Disk System)
case st_DTAK:
// Handle data acknowledge.
debugss(ssH47, INFO, "DTAK received.\n");
if (curLinkState == st_Link_AwaitingTransmitComplete_c)
{
curLinkState = st_Link_HoldingDTR_c;
countDown_m = 1;
}
else if (curLinkState == st_Link_AwaitingToReceive_c)
{
BYTE val = 0;
if (linkToHost_m)
{
linkToHost_m->readDataBusByDrive(val);
}
processData(val);
}
break;
// Data Ready (Disk System to Host)
case st_DTR:
debugss(ssH47, ERROR, "Invalid DTR received.\n");
break;
// Disk Drive Out (Disk System to Host)
case st_DDOUT:
debugss(ssH47, ERROR, "Invalid DDOUT received.\n");
break;
// Busy (Disk System to Host)
case st_Busy:
// Not valid
debugss(ssH47, ERROR, "Invalid Busy received.\n");
break;
// Error (Disk System to Host)
case st_Error:
debugss(ssH47, ERROR, "Invalid error received.\n");
break;
default:
debugss(ssH47, ERROR, "Invalid sigType received.\n");
break;
}
}
void
Z47Controller::lowerSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
switch (sigType)
{
// Master Reset (Host to Disk System)
case st_MasterReset:
// Handle a reset
debugss(ssH47, INFO, "Master Reset received.\n");
break;
// Data Acknowledge (Host to Disk System)
case st_DTAK:
// Handle data acknowledge.
// Computer acknowledged the transfer to it, or has valid data
// available for the disk system to receive.
debugss(ssH47, INFO, "DTAK received.\n");
break;
// Data Ready (Disk System to Host)
case st_DTR:
// This signal only goes to the host
debugss(ssH47, ERROR, "Invalid DTR received.\n");
break;
// Disk Drive Out (Disk System to Host)
case st_DDOUT:
// This signal only goes to the host
debugss(ssH47, ERROR, "Invalid DDOUT received.\n");
break;
// Busy (Disk System to Host)
case st_Busy:
// This signal only goes to the host
debugss(ssH47, ERROR, "Invalid Busy received.\n");
break;
// Error (Disk System to Host)
case st_Error:
// This signal only goes to the host
debugss(ssH47, ERROR, "Invalid error received.\n");
break;
default:
debugss(ssH47, ERROR, "Invalid sigType received.\n");
break;
}
}
void
Z47Controller::pulseSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
raiseSignal(sigType);
lowerSignal(sigType);
}
void
Z47Controller::commandComplete(void)
{
debugss(ssH47, ALL, "state: %s\n", getStateStr(curState));
curState = st_None_c;
curLinkState = st_Link_AwaitingReadyState_c;
countDown_m = 120;
if (linkToHost_m)
{
linkToHost_m->setBusy(false);
// linkToHost_m->setDTR(true);
}
debugss(ssH47, ALL, "=============END of CMD============\n");
}
void
Z47Controller::decodeSideDriveSector(BYTE val)
{
side_m = (val & sideMask_c) >> sideShift_c;
drive_m = (val & driveMask_c) >> driveShift_c;
sector_m = (val & sectorMask_c) >> sectorShift_c;
debugss(ssH47, ALL, "side: %d drive: %d sector: %d\n", side_m, drive_m, sector_m);
}
void
Z47Controller::decodeTrack(BYTE val)
{
track_m = (val & trackMask_c) >> trackShift_c;
debugss(ssH47, ALL, "track: %d\n", track_m);
}
<file_sep>/VirtualH89/Src/AboutVirtualH89.cpp
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: aboutvirtualh89.cpp
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 17:10:14 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include "AboutVirtualH89.h"
////@begin XPM images
////@end XPM images
/*
* AboutVirtualH89 type definition
*/
IMPLEMENT_DYNAMIC_CLASS( AboutVirtualH89, wxDialog )
/*
* AboutVirtualH89 event table definition
*/
BEGIN_EVENT_TABLE( AboutVirtualH89, wxDialog )
////@begin AboutVirtualH89 event table entries
////@end AboutVirtualH89 event table entries
END_EVENT_TABLE()
/*
* AboutVirtualH89 constructors
*/
AboutVirtualH89::AboutVirtualH89()
{
Init();
}
AboutVirtualH89::AboutVirtualH89( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create(parent, id, caption, pos, size, style);
}
/*
* AboutVirtualH89 creator
*/
bool AboutVirtualH89::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin AboutVirtualH89 creation
SetExtraStyle(wxWS_EX_VALIDATE_RECURSIVELY|wxWS_EX_BLOCK_EVENTS);
wxDialog::Create( parent, id, caption, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end AboutVirtualH89 creation
return true;
}
/*
* AboutVirtualH89 destructor
*/
AboutVirtualH89::~AboutVirtualH89()
{
////@begin AboutVirtualH89 destruction
////@end AboutVirtualH89 destruction
}
/*
* Member initialisation
*/
void AboutVirtualH89::Init()
{
////@begin AboutVirtualH89 member initialisation
////@end AboutVirtualH89 member initialisation
}
/*
* Control creation for AboutVirtualH89
*/
void AboutVirtualH89::CreateControls()
{
////@begin AboutVirtualH89 content construction
AboutVirtualH89* itemDialog1 = this;
wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
itemDialog1->SetSizer(itemBoxSizer2);
wxTextCtrl* itemTextCtrl3 = new wxTextCtrl( itemDialog1, ID_TEXTCTRL_AboutText, _("Virtual H89\n\n # # ### #### ##### # # # # # # ### ### \n # # # # # # # # # # # # # # # # #\n # # # # # # # # # # # # # # # # #\n # # # #### # # # ##### # ##### ### ####\n # # # # # # # # # # # # # # # #\n # # # # # # # # # # # # # # # # #\n # ### # # # ### # # ##### # # ### ### \n\nPortions derived from Z80Pack Release 1.17- Copyright (C) 1987-2008 by Udo Munk\nVirtual H89 - Copyright (C) 2009-2016 by Mark Garlanger\nRelease 1.93\n"), wxDefaultPosition, wxSize(670, 230), wxTE_MULTILINE|wxTE_READONLY );
itemTextCtrl3->SetFont(wxFont(10, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Courier")));
itemBoxSizer2->Add(itemTextCtrl3, 1, wxGROW|wxALL, 2);
////@end AboutVirtualH89 content construction
}
/*
* Should we show tooltips?
*/
bool AboutVirtualH89::ShowToolTips()
{
return true;
}
/*
* Get bitmap resources
*/
wxBitmap AboutVirtualH89::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin AboutVirtualH89 bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end AboutVirtualH89 bitmap retrieval
}
/*
* Get icon resources
*/
wxIcon AboutVirtualH89::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin AboutVirtualH89 icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end AboutVirtualH89 icon retrieval
}
#endif
<file_sep>/VirtualH89/Src/INS8250.h
/// \file INS8250.h
///
/// \brief Virtual 8250 Serial UART
///
/// \date Apr 4, 2009
/// \author <NAME>
///
#ifndef INS8250_H_
#define INS8250_H_
#include "IODevice.h"
class SerialPortDevice;
class Computer;
///
/// \brief Serial Port
///
/// 8250 Serial Port
///
class INS8250: public IODevice
{
public:
INS8250(Computer* computer,
BYTE baseAddr,
int IntLevel = -1);
virtual ~INS8250() override;
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual bool attachDevice(SerialPortDevice* dev);
virtual bool receiveReady();
virtual void receiveData(BYTE data);
void reset() override;
// TODO - add all the status, both for the device to set it's status
// and for the port to set the status.
private:
Computer* computer_m;
int intLevel_m;
void raiseInterrupt();
void lowerInterrupt();
/// Line Control variables:
bool DLAB_m; // Divisor Latch Access bit
BYTE bits_m;
bool stopBits_m;
bool parityEnable_m;
bool evenParity_m;
bool stickParity_m;
bool break_m;
bool ERBFI_m;
bool receiveInterruptPending;
// Modem Control variables
/// Data Terminal Ready
bool DTR_m;
/// Request to Send
bool RTS_m;
bool OUT1_m;
bool OUT2_m;
/// Loopback
bool Loop_m;
// Line Status variables
/// Data Ready
bool DR_m;
/// Overrun Error
bool OE_m;
/// Parity Error
bool PE_m;
/// Framing Error
bool FE_m;
/// Break Interrupt
bool BI_m;
/// Transmitter Holding Register Empty
bool THRE_m;
/// Transmitter Shift Register Empty
bool TSRE_m;
SerialPortDevice* device_m;
bool rxByteAvail;
BYTE RecvBuf;
bool txByteAvail;
BYTE TransHolding;
BYTE lsBaudDiv;
BYTE msBaudDiv;
WORD baud_m;
unsigned long lastTransmit;
/// Interrupt Enable Register
BYTE saveIER;
/// Interrupt Identification Register
BYTE saveIIR;
/// Line Control Register
BYTE saveLCR;
/// Modem Control Register
BYTE saveMCR;
/// Line Status Register
BYTE saveLSR;
/// Modem Status Register
BYTE saveMSR;
///
/// Register offsets from the base address.
///
enum RegisterOffsets
{
/// Receiver Buffer Register (Read Only)
RBR = 0,
/// Transmitter Holding Register (Write Only)
THR = 0,
/// Divisor Latch (Low - LS)
DLL = 0,
/// Interrupt Enable Register
IER = 1,
/// Divisor Latch (High - MS)
DLH = 1,
/// Interrupt Identification Register
IIR = 2,
/// Line Control Register
LCR = 3,
/// Modem Control Register
MCR = 4,
/// Line Status Register
LSR = 5,
/// Modem Status Register
MSR = 6,
/// SCratch Register
SCR = 7
};
///
/// Interrupt Enable Register Bits
///
/// Interrupt Enable Register - Receive Data
static const BYTE IER_ReceiveData = 0x01;
/// Interrupt Enable Register - Transmit Holding Register Empty
static const BYTE IER_TransmitHoldingEmpty = 0x02;
/// Interrupt Enable Register - Line Status
static const BYTE IER_LineStatus = 0x04;
/// Interrupt Enable Register - Receive Data
static const BYTE IER_ModemStatus = 0x08;
//
// Interrupt Identification Register
//
/// Interrupt Identification Register - No Interrupt Pending
static const BYTE IIR_NoInterruptPending = 0x01;
/// Interrupt Identification Register - Line Status
static const BYTE IIR_LineStatus = 0x06;
/// Interrupt Identification Register - Data Available
static const BYTE IIR_DataAvailable = 0x04;
/// Interrupt Identification Register - Transmitter Empty
static const BYTE IIR_TransmitterEmpty = 0x02;
/// Interrupt Identification Register - Modem Status
static const BYTE IIR_ModemStatus = 0x00;
//
// Line Control Register Bits
//
/// Line Control Register - Word Length
static const BYTE LCR_WordLength = 0x03;
/// Line Control Register - Stop Bits
static const BYTE LCR_NumberOfStopBits = 0x04;
/// Line Control Register - Parity Enable
static const BYTE LCR_ParityEnable = 0x08;
/// Line Control Register - Even Parity
static const BYTE LCR_EvenParitySelect = 0x10;
/// Line Control Register - Stick Parity
static const BYTE LCR_StickParity = 0x20;
/// Line Control Register - Set Break
static const BYTE LCR_SetBreak = 0x40;
/// Line Control Register - Divisor Latch Access
static const BYTE LCR_DivisorLatchAccess = 0x80;
//
// Line Status Register Bits
//
/// Line Status Register - Data Ready
static const BYTE LSB_DataReady = 0x01;
/// Line Status Register - Overrun
static const BYTE LSB_Overrun = 0x02;
/// Line Status Register - Parity Error
static const BYTE LSB_ParityError = 0x04;
/// Line Status Register - Framing Error
static const BYTE LSB_FramingError = 0x08;
/// Line Status Register - Break Interrupt
static const BYTE LSB_BreakInterrupt = 0x10;
/// Line Status Register - Transmitting Holding Register Empty
static const BYTE LSB_THRE = 0x20;
/// Line Status Register - Transmitting Shift Register Empty
static const BYTE LSB_TSRE = 0x40;
//
// Modem Status Register Bits
//
/// Modem Status Register - Delta Clear to Send
static const BYTE MSB_DeltaClearToSend = 0x01;
/// Modem Status Register - Delta Data Set Ready
static const BYTE MSB_DeltaDataSetReady = 0x02;
/// Modem Status Register - Trailing Edge Ring Indicator
static const BYTE MSB_TrailingEdgeRI = 0x04;
/// Modem Status Register - Delta Receive Line Signal Detect
static const BYTE MSB_DeltaReceiveLineSignalDetect = 0x08;
/// Modem Status Register - Clear to Send
static const BYTE MSB_ClearToSend = 0x10;
/// Modem Status Register - Data Set Ready
static const BYTE MSB_DataSetReady = 0x20;
/// Modem Status Register - Ring Indicator
static const BYTE MSB_RingIndicator = 0x40;
/// Modem Status Register - Received Line Signal Detect
static const BYTE MSB_ReceivedLineSignalDetect = 0x80;
};
#endif // INS8250_H_
<file_sep>/VirtualH89/Src/H89.cpp
/// \file H89.cpp
///
/// \date Mar 8, 2009
/// \author <NAME>
///
#include "H89.h"
#include "H89-roms.h"
#include "ROM.h"
#include "SystemMemory8K.h"
#include "MemoryLayout.h"
#include "MemoryDecoder.h"
#include "z80.h"
#include "AddressBus.h"
#include "InterruptController.h"
#include "H37InterruptController.h"
#include "MMS316IntrCtrlr.h"
#include "h89-timer.h"
#include "h89-io.h"
#include "NMIPort.h"
#include "GeneralPurposePort.h"
#include "INS8250.h"
#include "h17.h"
#include "h37.h"
#include "Z47Interface.h"
#include "Z47Controller.h"
#include "mms77316.h"
#include "mms77320.h"
#include "ParallelLink.h"
#include "h-17-1.h"
#include "h-17-4.h"
#include "H47Drive.h"
#include "HardSectoredDisk.h"
// #include "SoftSectoredDisk.h"
// #include "EightInchDisk.h"
#include "CPNetDevice.h"
#include "Console.h"
#include "logger.h"
#include "propertyutil.h"
/// \cond
#include <vector>
/// \endcond
using namespace std;
H89::H89(): Computer()
{
pthread_mutex_init(&h89_mutex, nullptr);
}
void
H89::buildSystem(Console* console, PropertyUtil::PropertyMapT props)
{
this->console = console;
string s; // for general property queries.
// TODO: use properties to configure rest of hardware.
// Possibly set defaults and write/create file.
interruptController = nullptr;
ab = nullptr;
cpu = new Z80(this, cpuClockRate_c, clockInterruptPerSecond_c);
h89io = new H89_IO;
cpu->setIOBus(h89io);
s = props["sw501"];
if (!s.empty())
{
gpp = new GeneralPurposePort(this, s);
}
else
{
gpp = new GeneralPurposePort(this);
}
h89io->addDevice(gpp);
ROM* monitorROM = nullptr;
s = props["monitor_rom"];
if (!s.empty())
{
monitorROM = ROM::getROM(s.c_str(), 0);
}
if (monitorROM == nullptr)
{
monitorROM = new ROM(4096);
monitorROM->setBaseAddress(0);
monitorROM->initialize(&MTR90_2_ROM[0], 4096);
}
ROM* h17ROM = new ROM(2048);
h17ROM->setBaseAddress(6 * 1024);
h17ROM->initialize(&H17_ROM[0], 2048);
vector<string> memslots = {"slot_p501", "slot_p502", "slot_p503"};
bool memorySpecified = false;
bool haveMMS77318 = false;
bool ORG_Zero = true;
MemoryLayout::MemorySize_t memSize = MemoryLayout::Mem_48k;
s = props["ORG0"];
// Allow config file to turn off ORG-0, but default to true;
if (s.compare("False") == 0)
{
ORG_Zero = false;
memorySpecified = true;
}
s = props["CPU_Memory"];
if (s.compare("16K") == 0)
{
memSize = MemoryLayout::Mem_16k;
memorySpecified = true;
}
else if (s.compare("32K") == 0)
{
memSize = MemoryLayout::Mem_32k;
memorySpecified = true;
}
else if (s.compare("48K") == 0)
{
memSize = MemoryLayout::Mem_48k;
memorySpecified = true;
}
else if (s.compare("64K") == 0)
{
memSize = MemoryLayout::Mem_64k;
memorySpecified = true;
// \todo error if ORG_Zero
}
// only P503 can contain the 16K/128K add-on board.
//
for (int x = 0; x < memslots.size(); ++x)
{
if (memslots[x] == "slot_p503")
{
s = props[memslots[x]];
if (s.compare("MMS77311") == 0 || s.compare("WH-88-16") == 0)
{
memSize = MemoryLayout::Mem_64k;
}
else if (s.compare("MMS77318") == 0)
{
haveMMS77318 = true;
}
else if (s.compare("Empty") == 0)
{
// do nothing.
}
else
{
// default to 64k if config didn't specify memory size
if (!memorySpecified)
{
memSize = MemoryLayout::Mem_64k;
}
}
}
}
// default to no speedup.
unsigned long speedup = 0;
s = props["z80_speedup_option"];
if (!s.empty())
{
speedup = strtoul(s.c_str(), nullptr, 10);
if (speedup > 40)
{
debugss(ssH89, ERROR, "Illegal CPU speedup factor %d, disabling\n", speedup);
speedup = 0;
}
else if (haveMMS77318)
{
debugss(ssH89, ERROR, "CPU speedup incompatible with MMS77318, disabling\n");
speedup = 0;
}
}
if ((speedup > 1) && (!haveMMS77318))
{
cpu->setSpeedup((unsigned) speedup);
cpu->enableFast();
}
sysMem = make_shared<SystemMemory8K>();
sysMem->installROM(monitorROM);
sysMem->installROM(h17ROM);
sysMem->enableRAM(0x1400, 1024);
// H17
H17* h17 = nullptr;
// Z37
Z_89_37* h37 = nullptr;
// Z47
z47If = nullptr;
z47Cntrl = nullptr;
z47Link = nullptr;
driveUnitE0 = nullptr;
driveUnitE1 = nullptr;
eight0 = nullptr;
eight1 = nullptr;
MMS77316* m316 = nullptr;
MMS77320* m320 = nullptr;
CPNetDevice* cpn = CPNetDevice::install_CPNetDevice(props);
if (cpn != nullptr)
{
h89io->addDevice(cpn);
}
// TODO: not all slots are identical, handle restrictions...
// Could have a Slot object with more details...
vector<string> devslots = {"slot_p504", "slot_p505", "slot_p506"};
bool dev_slots = false;
bool ser_slots = true;
for (int x = 0; x < devslots.size(); ++x)
{
s = props[devslots[x]];
if (s.compare("MMS77316") == 0)
{
interruptController = new MMS316IntrCtrlr(cpu);
m316 = MMS77316::install_MMS77316(interruptController,
props,
devslots[x]);
h89io->addDiskDevice(m316);
dev_slots = true;
}
else if (s.compare("MMS77320") == 0)
{
// Also includes (auxiliary) serial ports... TODO
m320 = MMS77320::install_MMS77320(props, devslots[x]);
h89io->addDiskDevice(m320);
}
else if (s.compare("H17") == 0)
{
// TODO - should only support slot p506
h17 = H17::install_H17(H17_BaseAddress_c, props, devslots[x]);
h89io->addDiskDevice(h17);
dev_slots = true;
}
else if (s.compare("H37") == 0)
{
// TODO make sure only one of H37 or MMS77316 is configured.
interruptController = new H37InterruptController(cpu);
// TODO - should only be supported on p504 (and maybe p505 - check schematics)
h37 = Z_89_37::install_H37(this,
H37_BaseAddress_c,
interruptController,
props,
devslots[x]);
h89io->addDiskDevice(h37);
dev_slots = true;
}
else if (s.compare("H47") == 0)
{
// Not functional
// select port based on slot - p504 -> 0170 p506 -> 0174
z47If = new Z47Interface(devslots[x].compare("slot_p506") == 0 ?
Z47_BaseAddress_2_c : Z47_BaseAddress_1_c);
z47Cntrl = new Z47Controller();
z47Link = new ParallelLink();
z47If->connectDriveLink(z47Link);
z47Cntrl->connectHostLink(z47Link);
driveUnitE0 = new H47Drive;
driveUnitE1 = new H47Drive;
s = props["z47_disk1"];
if (s.empty())
{
s = "diskA.eightdisk";
}
// eight0 = new EightInchDisk(s.c_str(), EightInchDisk::dif_8RAW);
s = props["z47_disk2"];
if (s.empty())
{
s = "diskB.eightdisk";
}
// eight1 = new EightInchDisk(s.c_str(), EightInchDisk::dif_8RAW);
}
else if (s.compare("H_88_3") == 0)
{
// 3-port serial board
// \todo make sure it's on P504 or P505.
lpPort = new INS8250(this, Serial_LpPort_c);
modemPort = new INS8250(this, Serial_ModemPort_c);
auxPort = new INS8250(this, Serial_AuxPort_c);
h89io->addDevice(lpPort);
h89io->addDevice(auxPort);
h89io->addDevice(modemPort);
ser_slots = true;
}
}
// if no interrupt created with the soft-sectored controllers, create the default one
if (interruptController == nullptr)
{
interruptController = new InterruptController(cpu);
}
ab = new AddressBus(interruptController);
cpu->setAddressBus(ab);
timer = new H89Timer(this, cpu);
h89io->addDevice(new NMIPort(cpu, NMI_BaseAddress_1_c, NMI_NumPorts_1_c));
h89io->addDevice(new NMIPort(cpu, NMI_BaseAddress_2_c, NMI_NumPorts_2_c));
string memDecoderType;
if (haveMMS77318)
{
memDecoderType = "MMS77318";
}
else if (ORG_Zero)
{
memDecoderType = "H89";
}
else
{
memDecoderType = "H88";
}
ab->installMemory(MemoryDecoder::createMemoryDecoder(memDecoderType,
sysMem,
memSize));
if (!dev_slots)
{
h17 = new H17(H17_BaseAddress_c);
// create the floppy drives for the hard-sectored controller.
shared_ptr<DiskDrive> driveUnitH0 = make_shared<H_17_1>();
shared_ptr<DiskDrive> driveUnitH1 = make_shared<H_17_1>();
shared_ptr<DiskDrive> driveUnitH2 = make_shared<H_17_1>();
s = props["h17_disk1"];
if (s.empty())
{
s = "diskA.tmpdisk";
}
shared_ptr<HardSectoredDisk> hard0 = make_shared<HardSectoredDisk>(s.c_str());
s = props["h17_disk2"];
if (s.empty())
{
s = "diskB.tmpdisk";
}
shared_ptr<HardSectoredDisk> hard1 = make_shared<HardSectoredDisk>(s.c_str());
s = props["h17_disk3"];
if (s.empty())
{
s = "diskC.tmpdisk";
}
shared_ptr<HardSectoredDisk> hard2 = make_shared<HardSectoredDisk>(s.c_str());
h89io->addDiskDevice(h17);
// Connect all the floppy drives for the hard-sectored controller.
h17->connectDrive(0, driveUnitH0);
h17->connectDrive(1, driveUnitH1);
h17->connectDrive(2, driveUnitH2);
// Insert all the the disks into the drives.
driveUnitH0->insertDisk(hard0);
driveUnitH1->insertDisk(hard1);
driveUnitH2->insertDisk(hard2);
}
// Serial Ports.
consolePort = new INS8250(this, Serial_Console_c, Serial_Console_Interrupt_c);
consolePort->attachDevice(console);
h89io->addDevice(consolePort);
if (!ser_slots)
{
lpPort = new INS8250(this, Serial_LpPort_c);
modemPort = new INS8250(this, Serial_ModemPort_c);
auxPort = new INS8250(this, Serial_AuxPort_c);
h89io->addDevice(lpPort);
h89io->addDevice(auxPort);
h89io->addDevice(modemPort);
}
}
H89::~H89()
{
// Acquire system mutex before starting to tear-down
// everything. This avoids a race where the CPU might be using
// objects that are being destroyed.
//
systemMutexAcquire();
// eject all the disk files
for (DiskController* dev : h89io->getDiskDevices())
{
if (dev != nullptr)
{
dev->~DiskController();
}
}
}
void
H89::reset()
{
cpu->reset();
ab->reset();
console->reset();
h89io->reset();
timer->reset();
}
void
H89::init()
{
console->init();
if (z47Cntrl != nullptr)
{
z47Cntrl->loadDisk();
}
}
void
H89::writeProtectH17RAM()
{
sysMem->writeProtect(0x1400, 1024);
}
void
H89::writeEnableH17RAM()
{
sysMem->writeEnable(0x1400, 1024);
}
void
H89::raiseNMI(void)
{
cpu->raiseNMI();
}
void
H89::systemMutexAcquire()
{
pthread_mutex_lock(&h89_mutex);
}
void
H89::systemMutexRelease()
{
pthread_mutex_unlock(&h89_mutex);
}
void
H89::raiseINT(int level)
{
debugss(ssH89, VERBOSE, "level - %d\n", level);
interruptController->raiseInterrupt(level);
}
void
H89::lowerINT(int level)
{
debugss(ssH89, VERBOSE, "level - %d\n", level);
interruptController->lowerInterrupt(level);
}
void
H89::continueCPU(void)
{
cpu->continueRunning();
}
void
H89::waitCPU(void)
{
cpu->waitState();
}
H89_IO&
H89::getIO()
{
return (*h89io);
}
BYTE
H89::run()
{
cpu->reset();
timer->start();
return (cpu->execute());
}
AddressBus&
H89::getAddressBus()
{
return (*ab);
}
CPU&
H89::getCPU()
{
return (*cpu);
}
string
H89::dumpDebug()
{
string ret = gpp->dumpDebug();
// Note: INT should be part of H89 (or InterruptController), not CPU...
// And... the signals are not actually latched on motherboard, only in
// respective I/O adapters. But for convenience they should be latched
// somewhere, or else we need to ask every device whether it has an interrupt.
ret += PropertyUtil::sprintf("INT=%02x\n", 0);
return ret;
}
// DEPRECATED
void
H89::keypress(BYTE ch)
{
}
void
H89::display()
{
}
<file_sep>/VirtualH89/Src/HardSectoredDisk.h
///
/// \file HardSectoredDisk.h
///
///
/// \date Sep 9, 2012
/// \author <NAME>
///
#ifndef HARDSECTOREDDISK_H_
#define HARDSECTOREDDISK_H_
#include "FloppyDisk.h"
/// \class HardSectoredDisk
///
/// \brief Virtual hard-sectored disk
///
/// This class implements a virtual hard-sectored disk. It models the entire track
/// such as the headers and gaps, not only the data portion.
///
class HardSectoredDisk: public FloppyDisk
{
public:
HardSectoredDisk(const char* name);
HardSectoredDisk();
virtual ~HardSectoredDisk() override;
virtual bool readData(BYTE side,
BYTE track,
unsigned long pos,
BYTE& data) override;
virtual bool writeData(BYTE side,
BYTE track,
unsigned long pos,
BYTE data) override;
virtual void getControlInfo(unsigned long pos,
bool& hole,
bool& writeProtect) override;
void dump() override;
virtual bool readSectorData(BYTE side,
BYTE track,
BYTE sector,
WORD pos,
BYTE& data) override;
virtual void eject(const char* name) override;
private:
// Hard sectored disks on Heath, only support single density (FM encoding)
static const unsigned int bytesPerTrack_c = 3200;
/// \todo make the tracks (and sides) runtime set, so that double sided and 80 track
/// hard-sectored disks can be used
static const unsigned int maxHeads_c = 2;
static const unsigned int maxTracksPerSide_c = 80;
BYTE rawImage_m[maxHeads_c][maxTracksPerSide_c][bytesPerTrack_c];
bool initialized_m = false;
unsigned int tracks_m = 80;
unsigned int sides_m = 2;
bool defaultHoleStatus(unsigned long pos);
};
#endif // HARDSECTOREDDISK_H_
<file_sep>/VirtualH89/Src/Track.h
///
/// \name Track.h
///
///
/// \date Jun 21, 2013
/// \author <NAME>
///
#ifndef TRACK_H_
#define TRACK_H_
#include "h89Types.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class Sector;
class Track
{
public:
enum DataRate
{
dr_Unknown,
dr_250kbps,
dr_300kbps,
dr_500kbps
};
enum Density
{
density_Unknown,
singleDensity,
FM = singleDensity,
doubleDensity,
MFM = doubleDensity
};
private:
BYTE sideNum_m;
BYTE trackNum_m;
std::vector <std::shared_ptr<Sector> > sectors_m;
Density density_m;
DataRate dataRate_m;
enum FormattingState
{
fs_none,
fs_waitingForIndex,
fs_writingGap,
fs_writingIdRecord,
fs_writingUserData
};
FormattingState formattingMode_m;
public:
Track(BYTE sideNum,
BYTE trackNum);
virtual ~Track();
BYTE getTrackNumber();
BYTE getSideNumber();
bool addSector(std::shared_ptr<Sector> sector);
void setDensity(Density density);
void setDataRate(DataRate datarate);
void dump();
std::shared_ptr<Sector> findSector(BYTE sector);
void startFormat();
};
#endif // TRACK_H_
<file_sep>/VirtualH89/Src/IMDFloppyDisk.h
///
/// \file IMDFloppyDisk.h
///
/// \author <NAME>
/// \date April, 17 2016
///
#ifndef IMDFLOPPYDISK_H_
#define IMDFLOPPYDISK_H_
#include "GenericFloppyDisk.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class DiskSide;
class Track;
class Sector;
class IMDFloppyDisk: public GenericFloppyDisk
{
public:
IMDFloppyDisk(std::vector<std::string> argv);
virtual ~IMDFloppyDisk() override;
virtual bool readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data) override;
virtual bool writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result) override;
virtual bool isReady() override;
virtual void eject(const std::string name) override;
virtual void dump(void) override;
bool findSector(BYTE side,
BYTE track,
BYTE sector) override;
static GenericFloppyDisk_ptr getDiskette(std::vector<std::string> argv);
private:
const std::string imageName_m;
static const unsigned int maxHeads_c = 2;
std::vector <std::shared_ptr<Track> > tracks_m[maxHeads_c];
std::vector<std::shared_ptr<DiskSide> > sideData_m;
std::shared_ptr<Sector> curSector_m;
int dataPos_m;
int sectorLength_m;
BYTE secLenCode_m;
bool ready_m;
// int gapLen_m;
// int indexGapLen_m;
// unsigned long writePos_m;
// bool trackWrite_m;
protected:
bool readIMD(const char* name);
};
#endif // IMDFLOPPYDISK_H_
<file_sep>/VirtualH89/Src/AddressBus.cpp
/// \file AddressBus.cpp
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#include "AddressBus.h"
#include "logger.h"
#include "MemoryDecoder.h"
#include "InterruptController.h"
using namespace std;
AddressBus::AddressBus(InterruptController* ic): ic_m(ic),
mem_m(nullptr)
{
debugss(ssAddressBus, INFO, "\n");
}
AddressBus::~AddressBus()
{
debugss(ssAddressBus, INFO, "\n");
}
BYTE
AddressBus::readByte(WORD addr,
bool interruptAck)
{
if (interruptAck)
{
debugss(ssAddressBus, ALL, "interrupt\n");
return ic_m->readDataBus();
}
debugss(ssAddressBus, ALL, "addr(%d)\n", addr);
return mem_m->readByte(addr);
}
void
AddressBus::writeByte(WORD addr,
BYTE val)
{
debugss(ssAddressBus, ALL, "addr(%d) = %d\n", addr, val);
mem_m->writeByte(addr, val);
}
void
AddressBus::installMemory(MemoryDecoder_ptr memory)
{
mem_m = memory;
}
void
AddressBus::reset()
{
if (mem_m != nullptr)
{
mem_m->reset();
}
}
<file_sep>/VirtualH89/Src/H89Operator.h
/// \file H89Operator.h
///
/// The VirtualH89-side implementation of the H89 Operator's interface, for
/// standard functions such as RESET and diskette muont/unmount, but also
/// providing virtual features like debugging.
///
/// \date Feb 9, 2016
/// \author <NAME>
///
#ifndef H89OPERATOR_H_
#define H89OPERATOR_H_
/// \cond
#include <assert.h>
#include <string>
/// \endcond
class GenericDiskDrive;
class DiskController;
/// \brief H89Operator
///
///
class H89Operator
{
public:
H89Operator();
virtual ~H89Operator();
std::string handleCommand(std::string cmd);
private:
std::string executeCommand(std::string cmd);
GenericDiskDrive* findDrive(std::string name);
DiskController* findDiskCtrlr(std::string name);
std::string cleanse(std::string resp);
};
#endif // H89OPERATOR_H_
<file_sep>/VirtualH89/Src/h-17-1.cpp
/// \file DiskDrive.cpp
///
/// \date May 2, 2009
/// \author <NAME>
///
#include "h-17-1.h"
#include "logger.h"
#include "FloppyDisk.h"
H_17_1::H_17_1(): DiskDrive(maxTracks_c)
{
}
H_17_1::~H_17_1()
{
}
void
H_17_1::getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect)
{
// Track info comes from the drive, the hole and write-protect is determined
// by the actual disk
debugss(ssH17_1, INFO, "pos: %ld\n", pos);
trackZero = (track_m == 0);
if (disk_m)
{
disk_m->getControlInfo(pos, hole, writeProtect);
}
else
{
debugss(ssH17_1, INFO, "no disk_m\n");
hole = true;
writeProtect = false;
}
}
void
H_17_1::step(bool direction)
{
if (direction)
{
if (track_m < 39)
{
++track_m;
}
debugss(ssH17_1, INFO, "in(up) (%d)\n", track_m);
}
else
{
if (track_m)
{
--track_m;
}
debugss(ssH17_1, INFO, "out(down) (%d)\n", track_m);
}
}
void
H_17_1::selectSide(BYTE side)
{
// Since the H-17-1 is single-sided, this is a NOP.
}
BYTE
H_17_1::readData(unsigned long pos)
{
BYTE data = 0;
if ((disk_m) && (disk_m->readData(head_c, track_m, pos, data)))
{
debugss(ssH17_1, INFO, "read passed - pos(%lu) data(%d)\n", pos, data);
}
else
{
debugss(ssH17_1, WARNING, "read failed - pos(%lu)\n", pos);
}
return data;
}
void
H_17_1::writeData(unsigned long pos,
BYTE data)
{
if ((disk_m) && (!disk_m->writeData(head_c, track_m, pos, data)))
{
debugss(ssH17_1, WARNING, "pos(%lu)\n", pos);
}
}
BYTE
H_17_1::readSectorData(BYTE sector,
unsigned long pos)
{
BYTE data = 0;
if ((disk_m) && (disk_m->readSectorData(0, track_m, sector, pos, data)))
{
debugss(ssH17_1, INFO, "read passed - pos(%lu) data(%d)\n", pos, data);
}
else
{
debugss(ssH17_1, WARNING, "read failed - pos(%lu)\n", pos);
}
return data;
}
<file_sep>/VirtualH89/Src/RawFloppyImage.cpp
/// \file RawFloppyImage.cpp
///
/// \brief virtual Floppy Disk implementation for soft-sectored media.
/// Supports media image files that have a simplified raw-track format.
///
/// \date Feb 2, 2016
/// \author <NAME>
///
#include "RawFloppyImage.h"
#include "logger.h"
#include "GenericFloppyFormat.h"
#include "GenericDiskDrive.h"
/// \cond
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
/// \endcond
void
RawFloppyImage::getAddrMark(BYTE* tp,
int nbytes,
int& id_tk,
int& id_sd,
int& id_sc,
int& id_sl)
{
id_tk = -1;
id_sd = -1;
int indexes = 0;
while (nbytes > 0)
{
if (*tp == GenericFloppyFormat::INDEX_AM_BYTE)
{
if (indexes > 1)
{
// error...
debugss(ssRawFloppyImage, WARNING, "no sectors found\n");
break;
}
++indexes;
}
else if (*tp == GenericFloppyFormat::ID_AM_BYTE)
{
id_tk = tp[1];
id_sd = tp[2];
id_sc = tp[3];
id_sl = tp[4];
break;
}
++tp;
--nbytes;
}
}
void
RawFloppyImage::eject(const std::string file)
{
// flush data...
cacheTrack(-1, -1);
close(imageFd_m);
imageFd_m = -1;
}
void
RawFloppyImage::dump()
{
}
// TODO: If constructor fails, the drive should not mount this disk!
RawFloppyImage::RawFloppyImage(GenericDiskDrive* drive,
std::vector<std::string> argv): GenericFloppyDisk(),
imageName_m(nullptr),
imageFd_m(-1),
trackBuffer_m(nullptr),
bufferedTrack_m(-1),
bufferedSide_m(-1),
bufferOffset_m(0),
bufferDirty_m(false),
hypoTrack_m(false),
hyperTrack_m(false),
interlaced_m(false),
gapLen_m(0),
indexGapLen_m(0),
writePos_m(-1),
trackWrite_m(false),
dataPos_m(0),
dataLen_m(0)
{
if (argv.size() < 1)
{
debugss(ssRawFloppyImage, WARNING, "no file specified\n");
return;
}
const char* name = strdup(argv[0].c_str());
// Now look for hints on disk format...
bool sd = false, dd = false;
bool ss = false, ds = false;
bool st = false, dt = false;
int media = 0;
for (int x = 1; x < argv.size(); ++x)
{
if (argv[x].compare("sd") == 0)
{
sd = true;
}
else if (argv[x].compare("dd") == 0)
{
dd = true;
}
else if (argv[x].compare("ss") == 0)
{
ss = true;
}
else if (argv[x].compare("ds") == 0)
{
ds = true;
}
else if (argv[x].compare("st") == 0)
{
st = true;
}
else if (argv[x].compare("dt") == 0)
{
dt = true;
}
else if (argv[x].compare("5") == 0)
{
media = 5;
}
else if (argv[x].compare("8") == 0)
{
media = 8;
}
else if (argv[x].compare("rw") == 0)
{
writeProtect_m = false;
}
else
{
debugss(ssRawFloppyImage, WARNING, "unrecognized hint - %s\n", argv[x].c_str());
}
}
if (!writeProtect_m && access(name, W_OK) != 0)
{
debugss(ssRawFloppyImage, WARNING, "Image not writeable: %s\n", name);
writeProtect_m = true;
}
int fd = open(name, writeProtect_m ? O_RDONLY : O_RDWR);
if (fd < 0)
{
debugss(ssRawFloppyImage, ERROR, "unable to open file - %s\n", name);
free((void*) name);
return;
}
// First examine at least one track, but we don't know the format...
// So get enough data for 1.5 DD tracks on this drive...
long nbytes = drive->getRawBytesPerTrack() * 2;
nbytes += nbytes / 2;
trackBuffer_m = new BYTE[nbytes];
if (trackBuffer_m == nullptr)
{
debugss(ssRawFloppyImage, ERROR, "unable to allocate track buffer of %ld bytes\n", nbytes);
close(fd);
free((void*) name);
return;
}
long n = read(fd, trackBuffer_m, nbytes);
if (n != nbytes)
{
debugss(ssRawFloppyImage, ERROR, "unable to read a track\n");
close(fd);
free((void*) name);
return;
}
BYTE* tp = trackBuffer_m;
BYTE* idx = nullptr;
BYTE* dat = nullptr;
BYTE* end = nullptr;
unsigned trklen = 0;
int seclen = 0;
int numsec = 0;
unsigned idxgap = 0;
unsigned gaplen = 0;
int id_tk = -1;
int id_sd = -1;
int id_sc = -1;
int id_sl = -1;
while (nbytes > 0)
{
if (*tp == GenericFloppyFormat::INDEX_AM_BYTE)
{
if (idx == nullptr)
{
idx = tp;
}
else
{
trklen = (unsigned) (tp - idx);
// We could continue into next track, and check how side-1
// is handled.
break;
}
}
else if (*tp == GenericFloppyFormat::ID_AM_BYTE)
{
if (id_tk == -1)
{
id_tk = tp[1];
}
else if (id_tk != tp[1])
{
debugss(ssRawFloppyImage, WARNING, "inconsistent track number %d (%d)\n", tp[1],
id_tk);
}
if (id_sd == -1)
{
id_sd = tp[2];
}
else if (id_sd != tp[2])
{
debugss(ssRawFloppyImage, WARNING, "inconsistent side number %d (%d)\n", tp[2],
id_sd);
}
int sl = tp[4] & 0x03;
sl = (128 << sl);
if (seclen != 0 && sl != seclen)
{
debugss(ssRawFloppyImage, WARNING, "inconsistent sector length %d (%d)\n", sl,
seclen);
}
seclen = sl;
}
else if (*tp == GenericFloppyFormat::DATA_AM_BYTE)
{
if (dat == nullptr)
{
dat = tp + 1;
idxgap = (unsigned) (dat - trackBuffer_m);
}
else if (gaplen == 0)
{
gaplen = (unsigned) (tp + 1 - end);
}
else if (gaplen != tp + 1 - end)
{
debugss(ssRawFloppyImage, WARNING, "inconsistent data gap %ld (%ld)\n",
tp + 1 - end, gaplen);
}
++numsec;
tp += seclen;
nbytes -= seclen;
end = tp + 1;
}
++tp;
--nbytes;
}
if (trklen == 0 || seclen == 0 || gaplen == 0 || numsec == 0 ||
id_tk != 0 || id_sd != 0)
{
debugss(ssRawFloppyImage, ERROR, "format not recognized\n");
free((void*) name);
close(fd);
return;
}
// Now check next track (we have partial, at least) at first ID_AM and see
// about any clues to track/side arrangement.
if (nbytes > 0 && *tp == GenericFloppyFormat::INDEX_AM_BYTE)
{
++tp;
--nbytes;
}
getAddrMark(tp, (int) nbytes, id_tk, id_sd, id_sc, id_sl);
// it's really an error if not found... must be more than one track.
if (id_tk >= 0 && id_sd >= 0)
{
if (id_tk == 1 && id_sd == 0)
{
// either SS or image has side 2 in last half...
interlaced_m = false; // already done.
}
else if (id_tk == 0 && id_sd == 1)
{
// interlaced image.
debugss(ssRawFloppyImage, INFO, "setting interlaced \n");
interlaced_m = true;
numSides_m = 2;
}
else
{
debugss(ssRawFloppyImage, ERROR, "invalid track/side layout\n");
}
}
trackLen_m = trklen;
struct stat stb;
fstat(fd, &stb);
long long est_trks = stb.st_size / trackLen_m;
debugss(ssRawFloppyImage, INFO, "estimated number of tracks %lld, trklen=%ld\n",
est_trks, trackLen_m);
if (est_trks == 77 || est_trks == 154)
{
// if interlaced, we know already.
mediaSize_m = 8;
numTracks_m = 77;
if (est_trks > 77)
{
numSides_m = 2;
}
else
{
numSides_m = 1;
}
}
else if (est_trks == 40 || est_trks == 80 || est_trks == 160)
{
mediaSize_m = 5;
if (est_trks > 80)
{
numSides_m = 2;
numTracks_m = 80;
}
else if (est_trks < 80)
{
numSides_m = 1;
numTracks_m = 40;
}
}
else
{
debugss(ssRawFloppyImage, ERROR, "invalid image size\n");
}
imageFd_m = fd; // need this for cacheTrack()...
if (mediaSize_m == 5 && est_trks == 80 && !interlaced_m)
{
// hypoTrack_m, hyperTrack_m still false, numTracks_m == 0, but must have trackLen_m
if (cacheTrack(0, 40))
{
tp = trackBuffer_m;
nbytes = trackLen_m;
getAddrMark(tp, (int) nbytes, id_tk, id_sd, id_sc, id_sl);
if (id_tk >= 0 && id_sd >= 0)
{
if (id_tk == 40 && id_sd == 0)
{
// must be SS 80-trk media...
numSides_m = 1;
numTracks_m = 80;
}
else if (id_tk == 0 && id_sd == 1)
{
// non-interlaced double-sided media...
numSides_m = 2;
numTracks_m = 40;
}
else
{
debugss(ssRawFloppyImage, ERROR, "invalid track/side layout\n");
}
}
else
{
// probably an error.
numSides_m = 2;
numTracks_m = 40;
}
}
}
numSectors_m = numsec;
gapLen_m = gaplen;
indexGapLen_m = idxgap;
secSize_m = seclen;
nbytes = drive->getRawBytesPerTrack();
if (nbytes == trackLen_m)
{
doubleDensity_m = false;
}
else if (nbytes * 2 == trackLen_m)
{
doubleDensity_m = true;
}
else if (dd)
{
doubleDensity_m = true;
}
else if (sd)
{
doubleDensity_m = false;
}
else
{
debugss(ssRawFloppyImage, ERROR, "invalid track length\n");
}
if (numTracks_m == 0)
{
if (dt && mediaSize_m == 5)
{
numTracks_m = 80;
}
else if (st && mediaSize_m == 5)
{
numTracks_m = 40;
}
else if (st && mediaSize_m == 8)
{
numTracks_m = 77;
}
else
{
debugss(ssRawFloppyImage, ERROR, "can't determine number of tracks\n");
}
}
if (numSides_m == 0)
{
if (ds)
{
numSides_m = 2;
}
else if (ss)
{
numSides_m = 1;
}
else
{
debugss(ssRawFloppyImage, ERROR, "can't determine number of sides\n");
}
}
// TODO: keep oversized buffer or free and alloc exact size needed?
imageName_m = name;
bufferedTrack_m = -1;
bufferedSide_m = -1;
bufferDirty_m = false;
debugss(ssRawFloppyImage, ERROR,
"mounted %d\" floppy %s: sides=%d tracks=%d spt=%d DD=%s R%s\n",
mediaSize_m, imageName_m, numSides_m, numTracks_m, numSectors_m,
doubleDensity_m ? "yes" : "no", writeProtect_m ? "O" : "W");
}
RawFloppyImage::~RawFloppyImage()
{
if (imageFd_m < 0)
{
return;
}
debugss(ssRawFloppyImage, INFO, "unmounted %s\n", imageName_m);
free((void*) imageName_m);
// flush data...
cacheTrack(-1, -1);
close(imageFd_m); // check errors?
imageFd_m = -1;
}
bool
RawFloppyImage::cacheTrack(int side,
int track)
{
if (bufferedSide_m == side && bufferedTrack_m == track)
{
return true;
}
if (imageFd_m < 0)
{
return false;
}
if (bufferDirty_m && bufferedSide_m != -1 && bufferedTrack_m != -1)
{
// Must write to disk...
lseek(imageFd_m, bufferOffset_m, SEEK_SET);
long rd = write(imageFd_m, trackBuffer_m, trackLen_m);
if (rd != trackLen_m)
{
debugss(ssRawFloppyImage, ERROR, "Unable to write to file %s\n", imageName_m);
}
bufferDirty_m = false;
}
if (side < 0 || track < 0)
{
// just flush only.
return true;
}
if (hypoTrack_m)
{
if ((track & 1) != 0)
{
return false;
}
track /= 2;
}
else if (hyperTrack_m)
{
track *= 2;
}
if (interlaced_m)
{
bufferOffset_m = (track * numSides_m + side) * trackLen_m;
}
else
{
bufferOffset_m = (side * numTracks_m + track) * trackLen_m;
}
lseek(imageFd_m, bufferOffset_m, SEEK_SET);
long rd = read(imageFd_m, trackBuffer_m, trackLen_m);
if (rd != trackLen_m)
{
bufferedSide_m = -1;
bufferedTrack_m = -1;
return false;
}
headPos_m = 0;
bufferedSide_m = side;
bufferedTrack_m = track;
return true;
}
bool
RawFloppyImage::findMark(int mark)
{
int indexCount = 0;
while (indexCount < 2)
{
BYTE d = trackBuffer_m[headPos_m++];
if (headPos_m >= trackLen_m)
{
// in most cases, should never hit this since
// we started at the address fields (there must be
// sector data after any address field, before index).
headPos_m = 0;
++indexCount;
continue;
}
if (d == GenericFloppyFormat::ID_AM_BYTE)
{
if (mark == GenericFloppyFormat::ID_AM)
{
return true;
}
headPos_m += 6;
}
else if (d == GenericFloppyFormat::DATA_AM_BYTE)
{
if (mark == GenericFloppyFormat::DATA_AM)
{
return true;
}
headPos_m += secSize_m + 2;
if (mark == GenericFloppyFormat::CRC)
{
return true;
}
// should never get here, should always start before addr,
// and find what we're looknig for before this.
break;
}
}
return false;
}
bool
RawFloppyImage::locateSector(BYTE track,
BYTE side,
BYTE sector)
{
if (findMark(GenericFloppyFormat::ID_AM))
{
if (track != trackBuffer_m[headPos_m] ||
side != trackBuffer_m[headPos_m + 1] ||
sector != trackBuffer_m[headPos_m + 2])
{
headPos_m += 6;
findMark(GenericFloppyFormat::CRC);
return false;
}
headPos_m += 6;
if (findMark(GenericFloppyFormat::DATA_AM))
{
return true;
}
}
return false;
}
bool
RawFloppyImage::findSector(BYTE sideNum,
BYTE trackNum,
BYTE sectorNum)
{
if (!cacheTrack(sideNum, trackNum))
{
return false;
}
return locateSector(sideNum, trackNum, sectorNum);
// return cacheSector(sideNum, trackNum, sectorNum);
}
bool
RawFloppyImage::readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data)
{
if (!cacheTrack(side, track))
{
// Just treat like unformatted disk/track.
return false;
}
if (inSector < 0)
{
if (sector == 0xfd) // read address
{
if (findMark(GenericFloppyFormat::ID_AM))
{
dataPos_m = headPos_m;
dataLen_m = dataPos_m + 6;
data = GenericFloppyFormat::ID_AM;
findMark(GenericFloppyFormat::CRC);
debugss(ssRawFloppyImage, INFO, "read address %d %d\n", dataPos_m, dataLen_m);
return true;
}
data = GenericFloppyFormat::ERROR;
return true;
}
else if (sector == 0xff) // read track
{
dataPos_m = 0;
dataLen_m = trackLen_m;
data = GenericFloppyFormat::INDEX_AM;
debugss(ssRawFloppyImage, INFO, "read track %d %d\n", dataPos_m, dataLen_m);
return true;
}
else if (locateSector(track, side, sector))
{
dataPos_m = headPos_m;
headPos_m += secSize_m + 2;
dataLen_m = dataPos_m + secSize_m;
data = GenericFloppyFormat::DATA_AM;
return true;
}
data = GenericFloppyFormat::NO_DATA;
return true;
}
if (dataPos_m < dataLen_m)
{
data = trackBuffer_m[dataPos_m++];
}
else
{
debugss(ssRawFloppyImage, INFO, "data done %d %d %d\n", track, side, sector);
data = GenericFloppyFormat::CRC;
}
return true;
}
bool
RawFloppyImage::writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result)
{
if (checkWriteProtect())
{
return false;
}
if (trackWrite_m)
{
return false;
}
if (!cacheTrack(side, track))
{
// Just treat like unformatted disk/track.
return false;
}
if (inSector < 0)
{
if (sector == 0xff || sector == 0xfe) // write track
{
#if 0
// density is in 'sector' LSB... use to handle proper track size, etc.
// This does actually work, in the sense that the pattern is
// written to the file. But, we have to re-mount the image
// in order to use it, and we have to deal with changes in density
// (not to mention other aspects of disk geometry). This all gets
// trickier if we need to handle formatting a single track and
// reading back sectors to verify. Really need to significantly
// rework this paradigm in order to make it work just like a
// real disk/controller. Right now, it does not handle changing
// format on-the-fly let alone track-by-track.
dataPos_m = 0;
dataLen_m = trackLen_m;
result = GenericFloppyFormat::INDEX_AM;
debugss(ssRawFloppyImage, INFO, "write track %d %d\n", dataPos_m, dataLen_m);
return true;
#else
result = GenericFloppyFormat::ERROR;
return true;
#endif
}
else if (locateSector(track, side, sector))
{
dataPos_m = headPos_m;
headPos_m += secSize_m + 2;
dataLen_m = dataPos_m + secSize_m;
result = GenericFloppyFormat::DATA_AM;
return true;
}
result = GenericFloppyFormat::NO_DATA;
return true;
}
if (dataPos_m < dataLen_m)
{
if (!dataReady)
{
result = GenericFloppyFormat::NO_DATA;
}
else
{
trackBuffer_m[dataPos_m++] = data;
bufferDirty_m = true;
result = data;
}
}
else
{
result = GenericFloppyFormat::CRC;
}
debugss(ssRawFloppyImage, INFO, "writeData pos=%d data=%02x\n", inSector, data);
return true;
}
bool
RawFloppyImage::isReady()
{
return (imageFd_m >= 0);
}
std::string
RawFloppyImage::getMediaName()
{
if (imageName_m == nullptr)
{
return "BAD";
}
return imageName_m;
}
<file_sep>/VirtualH89/Src/h89Types.h
/// \file h89Types.h
///
/// \date Mar 7, 2009
/// \author <NAME>
///
///
#ifndef H89_TYPES_H_
#define H89_TYPES_H_
/// \cond
#include <inttypes.h>
/// \endcond
///
/// \typedef WORD
///
/// 16-bit unsigned integer
///
typedef uint16_t WORD;
///
/// \typedef SWORD
///
/// 16-bit signed integer
///
typedef int16_t SWORD;
///
/// \typedef BYTE
///
/// 8-bit unsigned integer
///
typedef uint8_t BYTE;
///
/// \typedef SBYTE
///
/// 8-bit signed integer
///
typedef int8_t SBYTE;
#endif // H89_TYPES_H_
<file_sep>/VirtualH89/Src/DiskSide.h
///
/// \file DiskSide.h
///
/// \author <NAME>
///
/// \date June 27, 2016
///
#ifndef DISK_SIDE_H_
#define DISK_SIDE_H_
#include "h89Types.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class Track;
class Sector;
class DiskSide
{
public:
DiskSide(BYTE sideNum);
~DiskSide();
bool addTrack(std::shared_ptr<Track> track);
std::shared_ptr<Sector> findSector(BYTE trackNum, BYTE sectorNum);
private:
BYTE sideNum_m;
std::vector <std::shared_ptr<Track> > trackData_m;
};
#endif // DISK_SIDE_H_
<file_sep>/VirtualH89/Src/MemoryDecoder.cpp
///
/// \file MemoryDecoder.cpp
///
/// \author <NAME>
/// \date May 8, 2016
///
#include "MemoryDecoder.h"
#include "H88MemoryDecoder.h"
#include "H89MemoryDecoder.h"
#include "MMS77318MemoryDecoder.h"
/// \cond
#include <string>
#include <memory>
/// \endcond
using namespace std;
MemoryDecoder::MemoryDecoder(int numLayouts,
BYTE gppBits): GppListener(gppBits),
curLayoutNum_m(0),
layoutMask_m(numLayouts - 1),
numLayouts_m(numLayouts),
curLayout_m(nullptr)
{
GppListener::addListener(this);
layouts_m.resize(numLayouts);
for (MemoryLayout_ptr layout : layouts_m)
{
layout = nullptr;
}
curLayout_m = layouts_m[curLayoutNum_m];
}
MemoryDecoder::~MemoryDecoder()
{
}
void
MemoryDecoder::reset()
{
updateCurLayout(0);
}
void
MemoryDecoder::addLayout(int ix,
MemoryLayout_ptr lo)
{
if (ix >= 0 && ix < numLayouts_m)
{
layouts_m[ix] = lo;
}
curLayout_m = layouts_m[curLayoutNum_m];
}
void
MemoryDecoder::updateCurLayout(BYTE layout)
{
curLayoutNum_m = layout;
curLayout_m = layouts_m[curLayoutNum_m];
}
shared_ptr<MemoryDecoder>
MemoryDecoder::createMemoryDecoder(string type,
shared_ptr<SystemMemory8K> sysMem,
MemoryLayout::MemorySize_t memSize)
{
shared_ptr<MemoryDecoder> memDecoder = nullptr;
if (type == "MMS77318")
{
memDecoder = make_shared<MMS77318MemoryDecoder>(sysMem);
}
else if (type == "H89")
{
memDecoder = make_shared<H89MemoryDecoder>(sysMem, memSize);
}
else
{
memDecoder = make_shared<H88MemoryDecoder>(sysMem, memSize);
}
return memDecoder;
}
int
MemoryDecoder::numLayouts()
{
return numLayouts_m;
}
<file_sep>/VirtualH89/Src/ClockUser.cpp
///
/// \name clockUser.cpp
///
/// \brief notification class for clock ticks
///
/// \date Aug 11, 2012
/// \author <NAME>
///
#include "ClockUser.h"
#include "WallClock.h"
ClockUser::ClockUser()
{
WallClock::instance()->registerUser(this);
}
ClockUser::~ClockUser()
{
WallClock::instance()->unregisterUser(this);
}
<file_sep>/VirtualH89/Src/SystemMemory8K.h
///
/// \file SystemMemory8K.h
///
/// 8K page of ROM and RAM for HDOS (H88). Tracks R/O and uninstalled segments of 1K.
/// Implements "write under ROM" if an 8K RAM page is added.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef SYSTEMMEMORY8K_H_
#define SYSTEMMEMORY8K_H_
#include "RAMemory8K.h"
class ROM;
class SystemMemory8K: public RAMemory8K
{
public:
SystemMemory8K();
void overlayRAM(std::shared_ptr<Memory8K> ram);
void enableRAM(WORD base, WORD len);
void writeProtect(WORD adr, WORD len);
void writeEnable(WORD adr, WORD len);
void installROM(ROM* rom);
void writeByte(WORD adr, BYTE val) {
// "write under ROM" accesses both DRAM and H17-RAM
if (RAM != nullptr)
{
RAM->writeByte(adr, val);
}
if (maskRO)
{
int a = (adr >> 10) & 0x07;
if ((maskRO & (1 << a)) != 0 || (maskInstalled & (1 << a)) == 0)
{
return;
}
}
RAMemory8K::writeByte(adr, val);
}
private:
unsigned int maskRO;
unsigned int maskInstalled;
std::shared_ptr<Memory8K> RAM;
};
typedef std::shared_ptr<SystemMemory8K> systemMem_ptr;
#endif // SYSTEMMEMORY8K_H_
<file_sep>/VirtualH89/Src/H89MemoryDecoder.cpp
///
/// \file H89MemoryDecoder.cpp
///
/// H89 56K+ROM or 64K layout
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#include "H89MemoryDecoder.h"
#include "RAMemory8K.h"
#include "SystemMemory8K.h"
using namespace std;
H89MemoryDecoder::H89MemoryDecoder(shared_ptr<SystemMemory8K> systemRam,
MemoryLayout::MemorySize_t memSize): MemoryDecoder(2,
h89_gppOrg0Bit_c)
{
// Two different Memory Layout for the H89 ORG-0 configuration
MemoryLayout_ptr h89_0 = make_shared<MemoryLayout>();
MemoryLayout_ptr h89_1 = make_shared<MemoryLayout>();
// Add the ROMs/Floppydisk RAM
h89_0->addPage(systemRam);
// determine the number of banks based on memSize
int numBanks = 0;
switch (memSize)
{
case MemoryLayout::Mem_16k:
numBanks = 2;
break;
case MemoryLayout::Mem_32k:
numBanks = 4;
break;
case MemoryLayout::Mem_48k:
numBanks = 6;
break;
case MemoryLayout::Mem_64k:
numBanks = 8;
break;
case MemoryLayout::Mem_None:
default:
// \todo abort.
break;
}
// Add all the fixed memory to both memory layouts
for (int x = 1; x < numBanks; x++)
{
shared_ptr<Memory8K> mem = make_shared<RAMemory8K>(x << 13);
h89_0->addPage(mem);
h89_1->addPage(mem);
}
// handle the bank that handles bank 0 in the ORG-0 mode
if (memSize == MemoryLayout::Mem_64k)
{
// With a full 64k, the 8K bank both backfills the ROM area (writes to
// ROM cause write to the RAM) and is the first bank in the second layout.
// lowest memory
shared_ptr<Memory8K> rd6_0 = make_shared<RAMemory8K>(0x0000);
// make sure it backfills the ROM area
systemRam->overlayRAM(rd6_0);
// add it to the second bank.
h89_1->addPage(rd6_0);
}
else
{
// the last bank is either at the top of memory or at 0 depending on layout
// now add the last memory bank that also is at address 0 when ORG 0 is enabled.
shared_ptr<Memory8K> topMem = make_shared<RAMemory8K>(numBanks << 13);
h89_0->addPage(topMem);
// add to second layout at address 0.
h89_1->addPageAt(topMem, 0);
}
// Store the memory layouts
addLayout(0, h89_0);
addLayout(1, h89_1);
updateCurLayout(0);
}
H89MemoryDecoder::~H89MemoryDecoder()
{
}
void
H89MemoryDecoder::gppNewValue(BYTE gpo)
{
updateCurLayout((gpo & h89_gppOrg0Bit_c) ? 1 : 0);
}
<file_sep>/VirtualH89/Src/h37.cpp
/// \file h37.cpp
///
/// \date May 13, 2009
/// \author <NAME>
///
#include "h37.h"
#include "logger.h"
#include "wd1797.h"
#include "InterruptController.h"
#include "GenericFloppyDrive.h"
#include "computer.h"
#include "GenericFloppyDisk.h"
using namespace std;
Z_89_37::Z_89_37(Computer* computer,
int baseAddr,
InterruptController* ic): DiskController(baseAddr,
H37_NumPorts_c),
computer_m(computer),
ic_m(ic),
interfaceReg_m(0),
controlReg_m(0),
motorOn_m(false),
dataReady_m(false),
lostDataStatus_m(false),
sectorTrackAccess_m(false),
curDiskDrive_m(numDisks_c),
intrqAllowed_m(false),
drqAllowed_m(false),
cycleCount_m(0)
{
wd1797_m = new WD1797(this);
genericDrives_m[ds0] = nullptr;
genericDrives_m[ds1] = nullptr;
genericDrives_m[ds2] = nullptr;
genericDrives_m[ds3] = nullptr;
}
Z_89_37::~Z_89_37()
{
}
void
Z_89_37::reset(void)
{
interfaceReg_m = 0;
controlReg_m = 0;
sectorTrackAccess_m = false;
intrqAllowed_m = false;
drqAllowed_m = false;
motorOn_m = false;
dataReady_m = false;
lostDataStatus_m = false;
wd1797_m->reset();
}
Z_89_37*
Z_89_37::install_H37(Computer* computer,
BYTE baseAddr,
InterruptController* ic,
PropertyUtil::PropertyMapT& props,
string slot)
{
string s;
Z_89_37* z37 = new Z_89_37(computer, baseAddr, ic);
debugss(ssH37, INFO, "entering\n");
for (BYTE i = 0; i < numDisks_c; ++i)
{
string prop = "h37_drive";
prop += ('0' + i + 1);
s = props[prop];
if (!s.empty())
{
GenericFloppyDrive* drive = GenericFloppyDrive::getInstance(s);
if (drive)
{
z37->connectDrive(i, drive);
prop = "h37_disk";
prop += ('0' + i + 1);
s = props[prop];
if (!s.empty())
{
drive->insertDisk(GenericFloppyDisk::loadDiskImage(PropertyUtil::splitArgs(s)));
}
}
}
}
return z37;
}
BYTE
Z_89_37::in(BYTE addr)
{
BYTE offset = getPortOffset(addr);
BYTE val = 0;
debugss(ssH37, ALL, "(%d)\n", addr);
switch (offset)
{
case ControlPort_Offset_c:
debugss(ssH37, INFO, "(ControlPort) - %d\n", controlReg_m);
val = controlReg_m;
break;
case InterfaceControl_Offset_c:
debugss(ssH37, INFO, "(InterfaceControl) - %d\n", sectorTrackAccess_m);
val = interfaceReg_m;
break;
case StatusPort_Offset_c:
debugss(ssH37, INFO, "(%sPort)\n", sectorTrackAccess_m ? "Sector" : "Status");
val = wd1797_m->in(
sectorTrackAccess_m ? WD1797::SectorPort_Offset_c : WD1797::StatusPort_Offset_c);
break;
case DataPort_Offset_c:
debugss(ssH37, INFO, "(%sPort)\n", sectorTrackAccess_m ? "Track" : "Data");
val = wd1797_m->in(
sectorTrackAccess_m ? WD1797::TrackPort_Offset_c : WD1797::DataPort_Offset_c);
break;
default:
debugss(ssH37, ERROR, "(Unknown - 0x%02x)", addr);
break;
}
return val;
}
void
Z_89_37::out(BYTE addr,
BYTE val)
{
debugss(ssH37, ALL, "(%d, %d (0x%x))\n", addr, val, val);
BYTE offset = getPortOffset(addr);
switch (offset)
{
case ControlPort_Offset_c:
debugss(ssH37, INFO, "(ControlPort)");
controlReg_m = val;
if (val & ctrl_EnableIntReq_c)
{
debugss_nts(ssH37, INFO, " EnableIntReq");
intrqAllowed_m = true;
// setAllowIntrq(true);
}
else
{
debugss_nts(ssH37, INFO, " DisableIntReq");
intrqAllowed_m = false;
// setAllowIntrq(false);
}
if (val & ctrl_EnableDrqInt_c)
{
debugss_nts(ssH37, INFO, " EnableDrqInt");
drqAllowed_m = true;
// setAllowDrq(true);
}
else
{
debugss_nts(ssH37, INFO, " DisableDrqReq");
drqAllowed_m = false;
// setAllowDrq(false);
}
if (val & ctrl_SetMFMRecording_c)
{
debugss_nts(ssH37, INFO, " SetMFM");
wd1797_m->setDoubleDensity(true);
}
else
{
wd1797_m->setDoubleDensity(false);
}
motorOn(val & ctrl_MotorsOn_c);
if (val & ctrl_MotorsOn_c)
{
debugss_nts(ssH37, INFO, " MotorsOn");
}
// Only allow one to be set.
if (val & ctrl_Drive_0_c)
{
debugss_nts(ssH37, INFO, " Drive0");
curDiskDrive_m = ds0;
}
else if (val & ctrl_Drive_1_c)
{
debugss_nts(ssH37, INFO, " Drive1");
curDiskDrive_m = ds1;
}
else if (val & ctrl_Drive_2_c)
{
debugss_nts(ssH37, INFO, " Drive2");
curDiskDrive_m = ds2;
}
else if (val & ctrl_Drive_3_c)
{
debugss_nts(ssH37, INFO, " Drive3");
curDiskDrive_m = ds3;
}
else
{
debugss_nts(ssH37, INFO, " no Drive");
curDiskDrive_m = numDisks_c;
}
wd1797_m->setCurrentDrive(getCurrentDrive());
debugss_nts(ssH37, INFO, "\n");
// this APPEARS to be how the controller handles this.
ic_m->blockInterrupts(drqAllowed_m);
break;
case InterfaceControl_Offset_c:
debugss(ssH37, INFO, "(InterfaceControl) - ");
interfaceReg_m = val;
if ((val & if_SelectSectorTrack_c) == if_SelectSectorTrack_c)
{
debugss_nts(ssH37, INFO, "Sector/Track Access\n");
sectorTrackAccess_m = true;
}
else
{
debugss_nts(ssH37, INFO, "Control/Data Access\n");
sectorTrackAccess_m = false;
}
break;
case CommandPort_Offset_c:
debugss(ssH37, INFO, "(%sPort): %d\n", sectorTrackAccess_m ? "Sector" : "Command",
val);
wd1797_m->out(
sectorTrackAccess_m ? WD1797::SectorPort_Offset_c : WD1797::CommandPort_Offset_c,
val);
break;
case DataPort_Offset_c:
debugss(ssH37, INFO, "(%sPort): %d\n", sectorTrackAccess_m ? "Track" : "Data",
val);
wd1797_m->out(
sectorTrackAccess_m ? WD1797::TrackPort_Offset_c : WD1797::DataPort_Offset_c,
val);
break;
default:
debugss(ssH37, ERROR, "(Unknown - 0x%02x): %d\n", addr, val);
break;
}
}
void
Z_89_37::motorOn(bool motor)
{
if (motor != motorOn_m)
{
motorOn_m = motor;
for (int drive = ds0; drive < numDisks_c; drive++)
{
if (genericDrives_m[drive])
{
genericDrives_m[drive]->motor(motorOn_m);
}
}
}
}
GenericFloppyDrive*
Z_89_37::getCurrentDrive()
{
if (curDiskDrive_m < numDisks_c)
{
return genericDrives_m[curDiskDrive_m];
}
return nullptr;
}
bool
Z_89_37::connectDrive(BYTE unitNum,
GenericFloppyDrive* drive)
{
bool retVal = false;
debugss(ssH37, INFO, "unit (%d), drive (%p)\n", unitNum, drive);
if (unitNum < numDisks_c)
{
if (genericDrives_m[unitNum] == 0)
{
genericDrives_m[unitNum] = drive;
retVal = true;
}
else
{
debugss(ssH37, ERROR, "drive already connect\n");
}
}
else
{
debugss(ssH37, ERROR, "Invalid unit number (%d)\n", unitNum);
}
return (retVal);
}
bool
Z_89_37::removeDrive(BYTE unitNum)
{
// \todo implement
return (false);
}
void
Z_89_37::raiseIntrq()
{
// check if IRQs are allowed.
debugss(ssH37, INFO, "\n");
if (intrqAllowed_m)
{
ic_m->setIntrq(true);
computer_m->continueCPU();
return;
}
}
void
Z_89_37::raiseDrq()
{
debugss(ssH37, INFO, "\n");
// check if DRQ is allowed.
if (drqAllowed_m)
{
ic_m->setDrq(true);
computer_m->continueCPU();
return;
}
debugss(ssH37, INFO, "not allowed.\n");
}
void
Z_89_37::lowerIntrq()
{
debugss(ssH37, INFO, "\n");
// not sure but with this check, at least CP/M does not boot.
// if (!intrqAllowed_m)
// {
ic_m->setIntrq(false);
// }
}
void
Z_89_37::lowerDrq()
{
debugss(ssH37, INFO, "\n");
// not sure but with this check, at least CP/M does not boot.
// if (!drqAllowed_m)
// {
ic_m->setDrq(false);
// }
}
bool
Z_89_37::readReady()
{
// the H-37 has this line tied to +5V.
return true;
}
int
Z_89_37::getClockPeriod()
{
return 1000;
}
<file_sep>/VirtualH89/Src/MMS316IntrCtrlr.h
///
/// \name MMS316IntrCtrlr.h
///
/// Implementation of the H89 interrupt controller circuits, when augmented by the
/// MMS 77316 floppy disk controller. Used only if the MMS77316 is installed.
///
/// \date Feb 8, 2016
/// \author <NAME>
///
#ifndef MMS316INTRCTRLR_H_
#define MMS316INTRCTRLR_H_
#include "InterruptController.h"
class CPU;
/// \class MMS316IntrCtrlr
///
/// \brief Daisy-chaining Interrupt Controller Logic
///
///
class MMS316IntrCtrlr: public InterruptController
{
protected:
bool drqRaised_m;
bool intrqRaised_m;
public:
MMS316IntrCtrlr(CPU* cpu);
virtual ~MMS316IntrCtrlr() override;
void setINTLine() override;
// reading instructions for interrupts
virtual BYTE readDataBus() override;
virtual void setDrq(bool raise) override;
virtual void setIntrq(bool raise) override;
};
#endif // MMS316INTRCTRLR_H_
<file_sep>/VirtualH89/Src/GenericSASIDrive.cpp
/// \file GenericSASIDrive.cpp
///
/// Implementation of a generic SASI disk drive and controller. Media is separate.
/// Currently based on a XEBEC controller (only documentation available).
///
/// \date Feb 2, 2016
/// \author <NAME>
///
#include "GenericSASIDrive.h"
#include "logger.h"
/// \cond
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
/// \endcond
/* Expected drive characteristic by drive: (XEBEC S1410 manual)
* Drive cyl hd red-wr precomp
* CM5206 256 2 256 256
* CM5410 256 4 256 256
* CM5616 256 6 256 256
* HD561 180 2 128 180
* HD562 180 2 128 180
* RMS503 153 2 77 77
* RMS506 153 4 77 77
* RMS512 153 8 77 77
* ST506 153 4 128 64
* ST412 306 4 128 64
* TM602S 153 4 128 153
* TM603S 153 6 128 153
* TM603SE 230 6 128 128
* TI5.25+ 153 4 64 64
* RO101 192 2 96 0
* RO102 192 4 96 0
* RO103 192 6 96 0
* RO104 192 8 96 0
* RO201 321 2 132 0
* RO202 321 4 132 0
* RO203 321 6 132 0
* RO204 321 8 132 0
* MS1-006 306 2 153 0
* MS1-012 306 4 153 0
*/
// Grrr... C++ and no designated initializers
#if 0
int GenericSASIDrive::params[NUM_DRV_TYPE][4]
{
[XEBEC_ST506] = {153, 4, 128, 64},
[XEBEC_ST412] = {306, 4, 128, 64},
[XEBEC_CM5206] = {256, 2, 256, 256},
[XEBEC_CM5410] = {256, 4, 256, 256},
[XEBEC_CM5616] = {256, 6, 256, 256},
[XEBEC_RO201] = {321, 2, 132, 0},
[XEBEC_RO202] = {321, 4, 132, 0},
[XEBEC_RO203] = {321, 6, 132, 0},
[XEBEC_RO204] = {321, 8, 132, 0},
};
#endif
int GenericSASIDrive::params[NUM_DRV_TYPE][4]
{
/* INVALID=0 */ {0, 0, 0, 0},
/*[XEBEC_ST506] */ {153, 4, 128, 64},
/*[XEBEC_ST412] */ {306, 4, 128, 64},
/*[XEBEC_CM5206]*/ {256, 2, 256, 256},
/*[XEBEC_CM5410]*/ {256, 4, 256, 256},
/*[XEBEC_CM5616]*/ {256, 6, 256, 256},
/*[XEBEC_RO201] */ {321, 2, 132, 0},
/*[XEBEC_RO202] */ {321, 4, 132, 0},
/*[XEBEC_RO203] */ {321, 6, 132, 0},
/*[XEBEC_RO204] */ {321, 8, 132, 0},
};
bool
GenericSASIDrive::checkHeader(BYTE* buf, int n)
{
BYTE* b = buf;
int m = 0;
while (*b != '\n' && *b != '\0' && b - buf < n)
{
BYTE* e;
unsigned p = (unsigned) strtoul((char*) b, (char**) &e, 0);
// TODO: removable flag, others?
// NOTE: removable media requires many more changes.
switch (tolower(*e))
{
case 'c':
m |= 0x01;
mediaCyl = p;
break;
case 'h':
m |= 0x02;
mediaHead = p;
break;
case 'z':
m |= 0x04;
mediaSsz = p;
break;
case 'p':
m |= 0x08;
mediaSpt = p;
break;
case 'l':
m |= 0x10;
mediaLat = p;
break;
default:
return false;
}
b = e + 1;
}
return (m == 0x1f);
}
GenericSASIDrive::GenericSASIDrive(DriveType type,
std::string media,
int cnum,
int sectorSize):
curState(IDLE),
driveFd(-1),
driveSecLen(0),
sectorsPerTrack(0),
capacity(0),
dataOffset(0),
driveCode(0),
driveCnum(0),
driveMedia(nullptr),
driveType(INVALID),
mediaSpt(0),
mediaSsz(0),
mediaCyl(0),
mediaHead(0),
mediaLat(0),
cmdIx(0),
senseIx(0),
dcbIx(0),
stsIx(0),
dataBuf(nullptr),
dataLength(0),
dataIx(0)
{
driveType = type;
driveMedia = strdup(media.c_str());
driveCnum = cnum;
driveSecLen = sectorSize;
if (sectorSize == 256)
{
sectorsPerTrack = 32;
}
else if (sectorSize == 512)
{
sectorsPerTrack = 17;
}
else
{
// not supported, but do something...
if (sectorSize == 0)
{
sectorsPerTrack = 0;
}
else
{
sectorsPerTrack = 8192 / sectorSize;
}
}
capacity = params[type][0] * params[type][1] * sectorsPerTrack * sectorSize;
dataBuf = new BYTE[sectorSize + 4]; // space for ECC for "long" commands
dataLength = sectorSize;
driveFd = open(driveMedia, O_RDWR | O_CREAT, 0666);
if (driveFd < 0)
{
debugss(ssMMS77320, ERROR, "Unable to open media %s: %d\n", driveMedia, errno);
return;
}
dataOffset = 0;
BYTE buf[128];
off_t end = lseek(driveFd, (off_t) 0, SEEK_END);
// special case: 0 (EOF) means new media - initialize it.
if (end == 0)
{
mediaCyl = params[type][0];
mediaHead = params[type][1];
mediaSsz = sectorSize;
mediaSpt = sectorsPerTrack;
mediaLat = 1;
memset(buf, 0, sizeof(buf));
int l = sprintf((char*) buf, "%ldc%ldh%ldz%ldp%ldl\n", mediaCyl, mediaHead,
mediaSsz, mediaSpt, mediaLat);
// NOTE: 'buf' includes a '\n'...
debugss(ssMMS77320, ERROR, "Initializing new media %s as %s", driveMedia, buf);
ftruncate(driveFd, capacity + sizeof(buf));
lseek(driveFd, capacity, SEEK_SET); // i.e. END - sizeof(buf)
write(driveFd, buf, l);
}
else
{
// first, trying reading the last 128 bytes...
lseek(driveFd, end - sizeof(buf), SEEK_SET);
ssize_t x = read(driveFd, buf, sizeof(buf));
bool done = (x == sizeof(buf) && checkHeader(buf, sizeof(buf)));
if (!done)
{
lseek(driveFd, (off_t) 0, SEEK_SET);
x = read(driveFd, buf, sizeof(buf));
done = (x == sizeof(buf) && checkHeader(buf, sizeof(buf)));
dataOffset = mediaSsz;
}
if (!done)
{
debugss(ssMMS77320, ERROR, "Bad media header: %s\n", driveMedia);
close(driveFd);
driveFd = -1;
return;
}
if (mediaSpt != sectorsPerTrack || mediaSsz != driveSecLen ||
params[type][0] != mediaCyl || params[type][1] != mediaHead)
{
// TODO: fatal or warning?
debugss(ssMMS77320, ERROR, "Media/Drive mismatch: %s\n", driveMedia);
close(driveFd);
driveFd = -1;
return;
}
debugss(ssMMS77320, ERROR, "Mounted existing media %s as %s", driveMedia, buf);
}
}
GenericSASIDrive*
GenericSASIDrive::getInstance(std::string type,
std::string media,
int cnum)
{
DriveType etype;
if (type.compare("XEBEC_ST506") == 0)
{
etype = XEBEC_ST506;
}
else if (type.compare("XEBEC_ST412") == 0)
{
etype = XEBEC_ST412;
}
else if (type.compare("XEBEC_CM5206") == 0)
{
etype = XEBEC_CM5206;
}
else if (type.compare("XEBEC_CM5410") == 0)
{
etype = XEBEC_CM5410;
}
else if (type.compare("XEBEC_CM5616") == 0)
{
etype = XEBEC_CM5616;
}
else if (type.compare("XEBEC_RO201") == 0)
{
etype = XEBEC_RO201;
}
else if (type.compare("XEBEC_RO202") == 0)
{
etype = XEBEC_RO202;
}
else if (type.compare("XEBEC_RO203") == 0)
{
etype = XEBEC_RO203;
}
else if (type.compare("XEBEC_RO204") == 0)
{
etype = XEBEC_RO204;
}
else
{
debugss(ssMMS77320, ERROR, "Invalid controller/drive combination: %s\n", type.c_str());
return nullptr;
}
/*
* port determination based on SW501...
324 MVI B,7CH
325 IN GPIO ; READ SWITCH 501
326 ANI 00000011B ; WHAT'S PORT 7C SET FOR ?
327 CPI 00000010B ; IF Z67, THEN THIS IS IT
328 JRZ GOTPRT
329 MVI B,78H
330 IN GPIO ; READ SWITCH 501
331 ANI 00001100B ; WHAT'S PORT 78 SET FOR ?
332 CPI 00001000B ; IF Z67, THEN THIS IS IT
333 RNZ
*/
// DB 0,153,4,0,128,0,64,11 ; DRIVE CHARACTERISTIC DATA
// = 0099, 04, 0080, 0064, 0b
// = 153 cyl, 4 heads, 128 red-wr, 100 wr-pre, 11 ecc-burst
// = 612 trk. (~16 spt, 512B ea, ?)
// ssz = jumper_W2 ? 512 : 256; // XEBEC jumper "W2" a.k.a. "SS" pos "2" or "5"
int ssz = 512;
return new GenericSASIDrive(etype, media, cnum, ssz);
}
GenericSASIDrive::~GenericSASIDrive()
{
if (driveFd < 0)
{
return;
}
close(driveFd);
driveFd = -1;
}
/*
Typical sequence:
"Hail" controller:
wait !BSY (while poking data reg)
SEL
wait BSY
RUN
Send command:
wait until REQ+CMD+POUT+BSY
out next cmd byte
loop
Read command Write command
if loose POUT, goto status
wait for !CMD (loop)
inir 128 bytes outir 128 bytes
loop
Status phase:
check MSG+REQ+CMD+POUT
if REQ+CMD then input data and loop
if not MSG+REQ+CMD loop (no data read)
input (discard) data
return previous data byte (has error status)
MSG REQ CMD POUT BSY
---------------------------------
X X X X - OK to begin
SEL
X X X X BSY controller ready
RUN
X REQ CMD POUT BSY OK to send command
OUT cmd byte (ACK)
loop
X REQ CMD - BSY done with data (status begins)
X REQ - X BSY OK to send/get data (bulk 128 bytes)
IN/OUT data byte (ACK)
- REQ CMD - X OK get status byte
IN status byte (ACK)
MSG REQ CMD - X OK last status byte (prev has error)
IN status byte (ACK)
presumably resturns to:
X REQ CMD POUT BSY OK to send command.
*/
void
GenericSASIDrive::deselect(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
// User is switch controllers/drive, do any cleanup.
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl &= ~ctl_Req_o_c;
ctrl &= ~ctl_Busy_o_c;
curState = IDLE;
}
void
GenericSASIDrive::ack(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
ctrl &= ~ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
if (curState == COMMAND)
{
cmdBuf[cmdIx++] = dataOut;
if (cmdIx >= cmdLength)
{
curState = IDLE; // default? should get set to something else.
ctrl &= ~ctl_Cmd_o_c;
cmdIx = 0;
blockCount = 0;
debugss(ssGenericSASIDrive, INFO, "Command: %02x %02x %02x %02x %02x %02x\n",
cmdBuf[0], cmdBuf[1], cmdBuf[2], cmdBuf[3], cmdBuf[4], cmdBuf[5]);
// this further modifies 'ctrl' and sets curState.
processCmd(dataIn, dataOut, ctrl);
return;
}
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
}
else if (curState == STATUS)
{
if (stsIx < stsLength)
{
dataIn = stsBuf[stsIx++];
if (stsIx >= stsLength)
{
ctrl |= ctl_Msg_o_c;
}
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
return;
}
// must start over at SEL again...
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Busy_o_c; // it sppears this must go low...
ctrl &= ~ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl &= ~ctl_Req_o_c;
curState = IDLE;
}
else if (curState == SENSE)
{
if (senseIx < senseLength)
{
dataIn = senseBuf[senseIx++];
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
return;
}
senseIx = 0;
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
}
else if (curState == DATA_IN)
{
if (dataIx < dataLength)
{
dataIn = dataBuf[dataIx++];
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
return;
}
// We must either put some data in the reg or lower BSY...
dataIx = 0;
if (++blockCount < cmdBuf[4])
{
processCmd(dataIn, dataOut, ctrl);
return;
}
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
}
else if (curState == DRIVECB)
{
dcbBuf[dcbIx++] = dataOut;
if (dcbIx >= dcbLength)
{
dcbIx = 0;
processDCB(dataIn, dataOut, ctrl);
return;
}
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
}
else if (curState == DATA_OUT)
{
dataBuf[dataIx++] = dataOut;
if (dataIx >= dataLength)
{
dataIx = 0;
processData(dataIn, dataOut, ctrl);
return;
}
ctrl |= ctl_Req_o_c;
ctrl &= ~ctl_Ack_i_c;
}
else
{
// must be IDLE, and host is trying to sync-up with us.
// make everything look like we are not here...
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl &= ~ctl_Req_o_c;
ctrl &= ~ctl_Busy_o_c;
}
}
void
GenericSASIDrive::resetSASI(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl &= ~ctl_Req_o_c;
ctrl &= ~ctl_Busy_o_c;
curState = IDLE;
}
void
GenericSASIDrive::select(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
// validate data bit with cnum...
int i = ffs(dataOut);
if (i == 0)
{
return;
}
if (i - 1 == driveCnum)
{
ctrl |= ctl_Busy_o_c;
}
}
void
GenericSASIDrive::run(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
ctrl |= ctl_Busy_o_c;
ctrl |= ctl_Cmd_o_c;
ctrl |= ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
cmdIx = 0;
curState = COMMAND;
}
void
GenericSASIDrive::startStatus(BYTE& ctrl)
{
stsIx = 0;
curState = STATUS;
ctrl &= ~ctl_Msg_o_c;
ctrl |= ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
}
void
GenericSASIDrive::startSense(BYTE& ctrl)
{
senseIx = 0;
curState = SENSE;
ctrl &= ~ctl_Msg_o_c;
ctrl |= ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
}
void
GenericSASIDrive::startDataIn(BYTE& ctrl)
{
dataIx = 0;
curState = DATA_IN;
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl &= ~ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
}
void
GenericSASIDrive::startDataOut(BYTE& ctrl)
{
dataIx = 0;
curState = DATA_OUT;
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl |= ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
}
void
GenericSASIDrive::startError(BYTE& ctrl,
BYTE err)
{
stsBuf[0] = 0b00000010;
stsBuf[1] = 0;
senseBuf[0] = err;
startStatus(ctrl);
}
void
GenericSASIDrive::startDCB(BYTE& ctrl)
{
dcbIx = 0;
curState = DRIVECB;
ctrl &= ~ctl_Msg_o_c;
ctrl &= ~ctl_Cmd_o_c;
ctrl |= ctl_Out_o_c;
ctrl |= ctl_Req_o_c;
}
void
GenericSASIDrive::processCmd(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
off_t off;
long e;
if (cmdBuf[0] != cmd_ReqSense_c)
{
memset(senseBuf, 0, 4);
}
switch (cmdBuf[0])
{
case cmd_TestDriveReady_c:
case cmd_Recal_c:
case cmd_RAMDiag_c:
case cmd_DriveDiag_c:
case cmd_CtrlIntDiag_c:
// no-op: just return success
stsBuf[0] = 0;
stsBuf[1] = 0;
stsIx = 0;
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
break;
case cmd_ReqSense_c:
// sense data was set by previous command...
senseIx = 0;
startSense(ctrl);
ack(dataIn, dataOut, ctrl);
break;
case cmd_Read_c:
case cmd_ReadLong_c:
if (driveFd < 0)
{
startError(ctrl, 0x84); // drive not ready + addr valid
ack(dataIn, dataOut, ctrl);
break;
}
memcpy(senseBuf + 1, cmdBuf + 1, 3);
off = ((((((cmdBuf[1] & 0x1f) << 8) | cmdBuf[2]) << 8) | cmdBuf[3]) +
blockCount) * driveSecLen;
if (off >= capacity)
{
startError(ctrl, 0x21); // illegal disk address
ack(dataIn, dataOut, ctrl);
break;
}
lseek(driveFd, off + dataOffset, SEEK_SET);
e = read(driveFd, dataBuf, dataLength);
if (e != dataLength)
{
startError(ctrl, 0x94); // target sector not found + addr valid
ack(dataIn, dataOut, ctrl);
break;
}
dataLength = driveSecLen;
if (cmdBuf[0] == cmd_ReadLong_c)
{
dataLength += 4;
// TODO: must we compute ECC?
dataBuf[dataIx++] = 0;
dataBuf[dataIx++] = 0;
dataBuf[dataIx++] = 0;
dataBuf[dataIx++] = 0;
}
startDataIn(ctrl);
dataIx = 0;
// a little risky to recurse here, but startDataIn() should
// ensure we can't loop.
ack(dataIn, dataOut, ctrl);
break;
case cmd_Write_c:
case cmd_WriteLong_c:
if (driveFd < 0)
{
startError(ctrl, 0x84); // drive not ready + addr valid
ack(dataIn, dataOut, ctrl);
break;
}
memcpy(senseBuf + 1, cmdBuf + 1, 3);
dataLength = driveSecLen;
if (cmdBuf[0] == cmd_ReadLong_c)
{
dataLength += 4;
}
dataIx = 0;
// could validate address...
startDataOut(ctrl);
break;
case cmd_WriteSecBuf_c:
dataIx = 0;
dataLength = driveSecLen;
startDataOut(ctrl);
break;
case cmd_ReadSecBuf_c:
dataIx = 0;
dataLength = driveSecLen;
startDataIn(ctrl);
ack(dataIn, dataOut, ctrl);
break;
case cmd_InitDriveChar_c:
startDCB(ctrl);
break;
case cmd_FormatDrive_c:
case cmd_FormatTrack_c:
case cmd_FormatBadTrack_c:
case cmd_CheckTrackFmt_c:
case cmd_Seek_c:
case cmd_FormatAltTrack_c:
// validate address, but otherwise just return success.
blockCount = 0;
off = ((((((cmdBuf[1] & 0x1f) << 8) | cmdBuf[2]) << 8) | cmdBuf[3]) +
blockCount) * driveSecLen;
if (off >= capacity)
{
startError(ctrl, 0x21); // illegal disk address
ack(dataIn, dataOut, ctrl);
break;
}
stsBuf[0] = 0;
stsBuf[1] = 0;
stsIx = 0;
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
break;
case cmd_ReadECCLen_c:
// TODO: transfer 1 data byte, but this command is only valid
// after a correctable ECC data error 0x18, which we never return.
stsBuf[0] = 0;
stsBuf[1] = 0;
stsIx = 0;
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
break;
default:
break;
}
}
void
GenericSASIDrive::processData(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
off_t off;
long e;
switch (cmdBuf[0])
{
case cmd_Write_c:
off = ((((((cmdBuf[1] & 0x1f) << 8) | cmdBuf[2]) << 8) | cmdBuf[3]) +
blockCount) * driveSecLen;
if (off >= capacity)
{
startError(ctrl, 0x21); // illegal disk address
ack(dataIn, dataOut, ctrl);
break;
}
lseek(driveFd, off + dataOffset, SEEK_SET);
e = write(driveFd, dataBuf, dataLength);
if (e != dataLength)
{
startError(ctrl, 0x94); // target sector not found + addr valid
ack(dataIn, dataOut, ctrl);
break;
}
if (++blockCount >= cmdBuf[4])
{
startStatus(ctrl);
break;
}
break;
case cmd_WriteSecBuf_c:
// just leave sector buf with data for subsequent command(s)
startStatus(ctrl);
break;
case cmd_WriteLong_c:
break;
default:
break;
}
}
void
GenericSASIDrive::processDCB(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl)
{
switch (cmdBuf[0])
{
case cmd_InitDriveChar_c:
{
// validate? update params?
int cyl = (dcbBuf[0] << 8) | dcbBuf[1];
int hds = dcbBuf[2] & 0x0f;
int rwc = (dcbBuf[3] << 8) | dcbBuf[4];
int wpc = (dcbBuf[5] << 8) | dcbBuf[6];
int ebl = dcbBuf[7] & 0x0f;
if (cyl != params[driveType][0] || hds != params[driveType][1] ||
rwc != params[driveType][2] ||
wpc != params[driveType][3])
{
debugss(ssMMS77320, ERROR, "Host drive characteristics "
" mismatch\n");
debugss(ssMMS77320, ERROR, "cyl: %d, hds: %d, rwc: %d, wpc: %d, ebl: %d",
cyl, hds, rwc, wpc, ebl);
// TODO: what to do. Host will be sending commands based
// on a different geometry. Can we return an error?
// startError(ctrl, 0x??);
}
startStatus(ctrl);
ack(dataIn, dataOut, ctrl);
}
break;
default:
break;
}
}
std::string
GenericSASIDrive::getMediaName()
{
return (driveMedia != nullptr ? driveMedia : "");
}
<file_sep>/VirtualH89/Src/WD179xUserIf.h
///
/// \name WD179xUserIf.h
///
/// \date April 9, 2016
/// \author <NAME>
///
#ifndef WD179X_USER_IF_H_
#define WD179X_USER_IF_H_
class WD179xUserIf
{
public:
WD179xUserIf();
virtual ~WD179xUserIf();
virtual void raiseIntrq() = 0;
virtual void raiseDrq() = 0;
virtual void lowerIntrq() = 0;
virtual void lowerDrq() = 0;
virtual void loadHead(bool load);
virtual int getClockPeriod() = 0;
virtual bool readReady() = 0;
};
#endif // WD179X_USER_IF_H_
<file_sep>/VirtualH89/Src/NetworkServer.cpp
/// \file NetworkServer.cpp
///
/// Interface for network servers used with CPNetDevice.
/// First implementation was HostFileBdos.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#include "NetworkServer.h"
NetworkServer::NetworkServer()
{
}
NetworkServer::~NetworkServer()
{
}
<file_sep>/VirtualH89/Src/StdioConsole.h
/// \file StdioConsole.h
///
/// \date Feb 6, 2016
/// \author <NAME>
///
#ifndef STDIOCONSOLE_H_
#define STDIOCONSOLE_H_
#include "Console.h"
/// \cond
#include <assert.h>
/// \endcond
/// \brief StdioConsole
///
///
class StdioConsole: public Console
{
public:
StdioConsole(int argc,
char** argv);
virtual ~StdioConsole() override;
virtual void init() override;
virtual void reset() override;
virtual void display() override;
virtual void processCharacter(char ch) override;
virtual void keypress(char ch) override;
virtual void receiveData(BYTE) override;
virtual bool checkUpdated() override;
virtual unsigned int getBaudRate() override;
virtual void run() override;
private:
};
#endif // STDIOCONSOLE_H_
<file_sep>/VirtualH89/Src/h19.h
/// \file h19.h
///
/// \date Apr 12, 2009
/// \author <NAME>
///
#ifndef H19_H_
#define H19_H_
#include "Console.h"
#include "ClockUser.h"
// H19 needs access to the GUI engine.
#include "GUI.h"
/// \cond
#include <queue>
/// \endcond
/// \brief Virtual %H19 %Terminal Screen Buffer
///
/// The screen buffer is shared between the GUI and H19 logic.
/// This class abstracts the screen buffer from the H19 logic.
///
class H19Screen
{
public:
H19Screen(void): curCursor_m(false) {
return;
}
~H19Screen(void) {
return;
}
public:
// screen size
static const unsigned int cols_c = 80;
static const unsigned int rows_c = 25;
static const unsigned int rowsMain_c = 24;
// Will be removed when display() is abstracted.
unsigned int screen_m[cols_c][rows_c + 1]; // extra row for GLUT wraparound.
bool curCursor_m;
unsigned int posX_m, posY_m;
static const unsigned int screenRefresh_c = 1000 / 60;
bool cursorBlock_m;
bool cursorOff_m;
};
/// \brief Virtual %H19 %Terminal
///
/// Virtual Heathkit H19 Terminal logic that renders a pixel accurate emulation of the terminal.
/// Uses "TheGUI" abstraction for GUI.
///
class H19: public Console, public ClockUser, public H19Screen // , public BaseThread
{
public:
H19(std::string sw401 = "10001100", std::string sw402 = "00000101");
virtual ~H19();
virtual void init();
virtual void reset();
virtual void display();
virtual void processCharacter(char ch);
virtual void keypress(char ch);
virtual void receiveData(BYTE);
virtual bool checkUpdated();
virtual unsigned int getBaudRate();
virtual void run();
void notification(unsigned int cycleCount);
virtual bool sendData(BYTE data);
inline static H19* GetH19(void) {
return h19;
};
private:
static void GUIDisplay();
static void timer(void);
static void keyboard(unsigned char key);
static H19* h19; // for static callback funcs
static unsigned int screenRefresh_m;
void consoleLog(std::string message);
// state variables
enum InputMode
{
Normal,
Escape,
DCA_1,
DCA_2,
SetMode,
ResetMode
};
InputMode mode_m;
bool updated_m;
BYTE sw401_m;
BYTE sw402_m;
std::queue<BYTE> charToSend;
unsigned long countdownToSend_m;
unsigned long characterDelay_m;
// display modes
bool reverseVideo_m;
bool graphicMode_m;
bool insertMode_m;
bool line25_m;
bool holdScreen_m;
bool wrapEOL_m;
bool autoLF_m;
bool autoCR_m;
bool keyboardEnabled_m;
bool keyClick_m;
bool keypadShifted_m;
bool altKeypadMode_m;
bool offline_m;
unsigned int saveX_m, saveY_m;
//
// internal routines to handle control characters.
//
// character handling
virtual void processBS();
virtual void processTAB();
inline virtual void scroll()
{
for (unsigned int y = 0; y < (rowsMain_c - 1); ++y)
{
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][y] = screen_m[x][y + 1];
}
}
eraseLine(rowsMain_c - 1);
};
//
// internal routines to handle ESC sequences.
//
// Cursor
virtual void cursorHome();
virtual void cursorForward();
// virtual void cursorBackward(); // unneeded same as processBS.
virtual void cursorDown();
virtual void cursorUp();
virtual void reverseIndex();
virtual void cursorPositionReport();
virtual void saveCursorPosition();
virtual void restoreCursorPosition();
// Erasing and Editing
virtual void clearDisplay();
virtual void eraseBOD();
virtual void eraseEOP();
virtual void eraseEL();
virtual void eraseBOL();
virtual void eraseEOL();
virtual void insertLine();
virtual void deleteLine();
virtual void deleteChar();
virtual void eraseLine(unsigned int line);
//
virtual void processLF();
virtual void processCR();
virtual void processEnableLine25();
virtual void transmitLines(int start,
int end);
virtual void transmitLine25();
virtual void transmitPage();
virtual void displayCharacter(unsigned int ch);
inline bool onLine25()
{
return (posX_m == (rows_c - 1));
};
virtual void bell(void);
const BYTE RefreshRate_c = 0x80;
const BYTE KeypadMode_c = 0x40;
const BYTE TerminalMode_c = 0x20;
const BYTE AutoCR_c = 0x10;
const BYTE AutoLF_c = 0x08;
const BYTE WrapEOL_c = 0x04;
const BYTE KeyClick_c = 0x02;
const BYTE BlockCursor = 0x01;
void setSW401(BYTE sw401);
void setSW402(BYTE sw402);
};
#endif // H19_H_
<file_sep>/VirtualH89/Src/Z47Controller.h
///
/// \name Z47Controller.h
///
///
/// \date Aug 12, 2013
/// \author <NAME>
///
#ifndef Z47CONTROLLER_H_
#define Z47CONTROLLER_H_
#include "ClockUser.h"
#include "ParallelPortConnection.h"
class DiskDrive;
class ParallelLink;
class Z47Controller: virtual public ClockUser, virtual public ParallelPortConnection
{
public:
Z47Controller();
virtual ~Z47Controller() override;
bool removeDrive(BYTE unitNum);
bool connectDrive(BYTE unitNum,
DiskDrive* drive);
virtual void notification(unsigned int cycleCount) override;
void connectHostLink(ParallelLink* link);
virtual void raiseSignal(SignalType sigType) override;
virtual void lowerSignal(SignalType sigType) override;
virtual void pulseSignal(SignalType sigType) override;
void loadDisk(void);
private:
/// Format commands
/// CP/M
/// SD - Single Density, 26 sectors, 128 bytes
/// DD - IBM Double Density, 26 sectors, 256 bytes
/// ED - IBM Double Density, 8 sectors, 1024 bytes
///
/// Commands
///
/// Bootstrap (BOOT) Command
///
/// Transfers Track 00 Sectors 1 and 2 of unit 0, side 0 to host.
///
/// Byte Direction Value
/// 0 to H47 0x00
///
static const BYTE cmd_Boot_c = 0x00;
/// Read Controller Status (RSTS) Command
///
/// Transfer status to host.
///
/// Byte Direction Value
/// 0 to H47 0x01
/// 1 to Host <Status>
///
static const BYTE cmd_ReadCntrlStat_c = 0x01;
/// Bad Track Overflow - (after initialize) More than 2 bad tracks found on media.
static const BYTE stat_Cntrl_Bad_Track_Overflow_c = 0x01;
/// Illegal Command - CMD code specified is not in defined set.
static const BYTE stat_Cntrl_Illegal_Command_c = 0x02;
/// Late Data - Host did not respond in time to DTR*. Data was lost
static const BYTE stat_Cntrl_Late_Data_c = 0x04;
/// CRC Error - CRC computation error on ID or data field
static const BYTE stat_Cntrl_CRC_Error_c = 0x08;
/// No Record Found - Track or Sector not found in 2 revolutions.
static const BYTE stat_Cntrl_No_Record_Found_c = 0x10;
/// Deleted Data - Data field with deleted data mark encountered during last read.
static const BYTE stat_Cntrl_Deleted_Data_c = 0x20;
/// Write Protected - Attempt made to write on a protected media.
static const BYTE stat_Cntrl_Write_Protected_c = 0x40;
/// Drive Not Ready - Operation was attempted on a drive that was not ready, or ready
/// was lost during an operation
static const BYTE stat_Cntrl_Drive_Not_Ready_c = 0x80;
/// Read Auxiliary Status Command
///
/// Transfer Auxiliary Status to host.
///
/// Byte Direction Value
/// 0 to H47 0x02
/// 1 to H47 <side/drive>
/// 2 to Host <Auxilliary Status>
///
static const BYTE cmd_ReadAuxStat_c = 0x02;
/// Return data
/// Sector Length bits from I.D. field (TRK 1 - 76)
static const BYTE stat_Aux_SectorLengthId_Trk01_Mask_c = 0x03;
/// Sector Length bits from I.D. field (TRK 0)
static const BYTE stat_Aux_SectorLengthId_Trk00_Mask_c = 0x0C;
/// Side 1 Available
static const BYTE stat_Aux_Side1_Available_c = 0x10;
/// Double Density (TRK 1 - 76)
static const BYTE stat_Aux_DoubleDensity_Trk01_c = 0x20;
/// Double Density (TRK 0)
static const BYTE stat_Aux_DoubleDensity_Trk00_c = 0x40;
/// Load Sector Count Command (LDSC)
///
/// Load 2 byte sector count for next operation.
///
/// Count = 1 to 65535
///
/// Count = 0 is illegal
///
/// Absence of this command, means a count of 1.
///
/// Byte Direction Value
/// 0 to H47 0x03
/// 1 to H47 <Sector Count MSB>
/// 2 to H47 <Sector Count LSB>
///
static const BYTE cmd_LoadSectorCount_c = 0x03;
/// Read Last Address Command (RADR)
///
/// Transfers to host the last track/side/Unit Sector accessed by
/// disk subsystem.
///
/// Byte Direction Value
/// 0 to H47 0x04
/// 1 to Host <Track>
/// 2 to Host <Side/Drive/Sector>
///
static const BYTE cmd_ReadLastAddr_c = 0x04;
/// Read Sectors (RD) Command
///
/// Transfers data directly to host. Number of sectors transferred depends
/// on previous LDSC. If LDSC is not specified, one sector is read.
///
/// * - Number of bytes(sectors) specified by LDSC
///
/// Byte Direction Value
/// 0 to H47 0x05
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// * to Host <Data>
///
static const BYTE cmd_ReadSectors_c = 0x05;
/// Write Sectors Command
///
/// Transfers data directly, or through buffer, with or without deleted data
/// mark to subsystem. Number of sectors written depends on previous LDSC. If
/// LDSC is not specified, one sector is written.
///
/// Byte Direction Value
/// 0 to H47 0x06
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// 3 to H47 <Data>
///
static const BYTE cmd_WriteSectors_c = 0x06;
/// Read Sectors Buffered (RDB) Command
///
/// Transfers data through buffer to host. Number of sectors transferred depends
/// on previous LDSC. If LDSC is not specified, one sector is read.
///
/// * - Number of bytes(sectors) specified by LDSC
///
/// Byte Direction Value
/// 0 to H47 0x07
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// * to Host <Data>
///
static const BYTE cmd_ReadSectorsBuffered_c = 0x07;
/// Write Sectors Buffered Command
///
/// Transfers data directly, or through buffer, with or without deleted data
/// mark to subsystem. Number of sectors written depends on previous LDSC. If
/// LDSC is not specified, one sector is written.
///
/// Byte Direction Value
/// 0 to H47 0x08
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// * to H47 <Data>
///
static const BYTE cmd_WriteSectorsBuffered_c = 0x08;
/// Write Sectors and Delete Command
///
/// Transfers data directly, or through buffer, with or without deleted data
/// mark to subsystem. Number of sectors written depends on previous LDSC. If
/// LDSC is not specified, one sector is written.
///
/// Byte Direction Value
/// 0 to H47 0x09
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// * to H47 <Data>
///
static const BYTE cmd_WriteSectorsAndDelete_c = 0x09;
/// Write Sectors and Delete Buffered Command
///
/// Transfers data directly, or through buffer, with or without deleted data
/// mark to subsystem. Number of sectors written depends on previous LDSC. If
/// LDSC is not specified, one sector is written.
///
/// Byte Direction Value
/// 0 to H47 0x0a
/// 1 to H47 <Track>
/// 2 to H47 <Side/Drive/Sector>
/// * to H47 <Data>
///
static const BYTE cmd_WriteSectorsBufferedAndDelete_c = 0x0a;
/// Copy Command
///
/// Copy number of sectors specified by LDSC from source (Track/Side/Drive/Sector)
/// to destination (Track/Side/Drive/Sector)
///
/// Byte Direction Value
/// 0 to H47 0x0b
/// 1 to H47 <Source Track>
/// 2 to H47 <Source Side/Drive/Sector>
/// 3 to H47 <Destination Track>
/// 4 to H47 <Destination Side/Drive/Sector>
///
static const BYTE cmd_Copy_c = 0x0b;
/// Format IBM Single Density Command
///
/// Formats media as follows:
/// Track 00, Side: 0: 26 sectors single density
/// Track 00, Side: 1: 26 sectors double density \todo determine if this a manual error
/// Tracks 01-76, sides 0 and 1: 26, 15, or 8 sectors (as specified), single density
///
/// Byte Direction Value
/// 0 to H47 0x0c
/// 1 to H47 <Side/Drive/Number Sectors in TK01-TK76>
///
static const BYTE cmd_FormatIBM_SD_c = 0x0c;
/// Format Single Density Command
///
/// Formats media as follows:
/// Tracks 00-76, sides 0 and 1: 26, 15, or 8 sectors (as specified), single density
/// 128, 256, 512 bytes per sector
/// 1 side/77 tracks/26 sectors/128 bytes = 256256
/// 2 side/77 tracks/26 sectors/128 bytes = 512512
/// 1 side/77 tracks/15 sectors/256 bytes = 295680
/// 2 side/77 tracks/15 sectors/256 bytes = 591360
/// 1 side/77 tracks/8 sectors/512 bytes = 315392
/// 2 side/77 tracks/8 sectors/512 bytes = 630784
///
/// Byte Direction Value
/// 0 to H47 0x0d
/// 1 to H47 <Side/Drive/Number Sectors in TK00-TK76>
///
static const BYTE cmd_Format_SD_c = 0x0d;
/// Format IBM Double Density Command
///
/// Formats media as follows:
/// Track 00, Side: 0: 26 sectors single density
/// Track 00, Side: 1: 26 sectors double density
/// Tracks 01-76, sides 0 and 1: 26, 15, or 8 sectors (as specified), double density
///
/// Byte Direction Value
/// 0 to H47 0x0e
/// 1 to H47 <Side/Drive/Number Sectors in TK01-TK76>
///
static const BYTE cmd_FormatIBM_DD_c = 0x0e;
/// Format Double Density Command
///
/// Formats media as follows:
/// Tracks 00-76, sides 0 and 1: 26, 15, or 8 sectors (as specified), double density
/// 256, 512 1024 bytes per sector
/// 1 side/77 tracks/26 sectors/256 bytes = 512512
/// 2 side/77 tracks/26 sectors/256 bytes = 1025024
/// 1 side/77 tracks/15 sectors/512 bytes = 591360
/// 2 side/77 tracks/15 sectors/512 bytes = 1182720
/// 1 side/77 tracks/8 sectors/1024 bytes = 630784
/// 2 side/77 tracks/8 sectors/1024 bytes = 1261568
///
/// Byte Direction Value
/// 0 to H47 0x0f
/// 1 to H47 <Side/Drive/Number Sectors in TK00-TK76>
///
static const BYTE cmd_Format_DD_c = 0x0f;
static const BYTE cmd_ReadReadyStatus_c = 0x10;
static const BYTE stat_Ready_Drive0NotReady_c = 0x01;
static const BYTE stat_Ready_Drive1NotReady_c = 0x02;
static const BYTE stat_Ready_Drive2NotReady_c = 0x04;
static const BYTE stat_Ready_Drive3NotReady_c = 0x08;
static const BYTE stat_Ready_Drive0ReadyChanged_c = 0x10;
static const BYTE stat_Ready_Drive1ReadyChanged_c = 0x20;
static const BYTE stat_Ready_Drive2ReadyChanged_c = 0x40;
static const BYTE stat_Ready_Drive3ReadyChanged_c = 0x80;
// special debug commands
/// Special Debug Function 0 Command
/// Read Ready Status
/// Note the overlap with Read Ready Status.
static const BYTE cmd_SpecialFunction0_c = 0x10;
/// Special Debug Function 1 Command
static const BYTE cmd_SpecialFunction1_c = 0x11;
/// Special Debug Function 2 Command
static const BYTE cmd_SpecialFunction2_c = 0x12;
/// Special Debug Function 3 Command
static const BYTE cmd_SpecialFunction3_c = 0x13;
/// Special Debug Function 4 Command
static const BYTE cmd_SpecialFunction4_c = 0x14;
/// Special Debug Function 5 Command
static const BYTE cmd_SpecialFunction5_c = 0x15;
// special Heath Functions
/// Heath's Set Drive Characteristics Command
static const BYTE cmd_SetDriveCharacteristics_c = 0x80;
/// Heath's Seek to Track Command
static const BYTE cmd_SeekToTrack_c = 0x81;
/// Heath's Disk Status Command
static const BYTE cmd_DiskStatus_c = 0x82;
/// Heath's Read Logical Command
static const BYTE cmd_ReadLogical_c = 0x83;
/// Heath's Write Logical Command
static const BYTE cmd_WriteLogical_c = 0x84;
/// Heath's Read Buffered Logical Command
static const BYTE cmd_ReadBufferedLogical_c = 0x85;
/// Heath's Write Buffered Logical Command
static const BYTE cmd_WriteBufferedLogical_c = 0x86;
/// Heath's Write Deleted Data Logical Command
static const BYTE cmd_WriteDeletedDataLogical = 0x87;
/// Heath's Write Buffered Deleted Data Logical Command
static const BYTE cmd_WriteBufferedDeletedDataLogical_c = 0x88;
/// Dipswitch 0
static const BYTE ds_sw0_c = 0x02;
/// Dipswitch 1
static const BYTE ds_sw1_c = 0x04;
/// Dipswitch 2
static const BYTE ds_sw2_c = 0x08;
/// Dipswitch 3
static const BYTE ds_sw3_c = 0x10;
enum Drives
{
ds0 = 0,
ds1 = 1,
ds2 = 2,
ds3 = 3,
numDrives_c = 4,
invalidDisk_c = numDrives_c
};
Drives curDisk;
static const WORD sectorSize128_c = 128;
static const WORD sectorSize256_c = 256;
static const WORD sectorSize512_c = 512;
static const WORD sectorSize1024_c = 1024;
static const WORD sectorSizeMax_c = sectorSize1024_c;
enum LinkState
{
st_Link_Undefined_c,
st_Link_Ready_c,
st_Link_AwaitingToReqReceive_c,
st_Link_AwaitingToReceive_c,
st_Link_AwaitingToTransmit_c,
st_Link_AwaitingTransmitComplete_c,
st_Link_AwaitingReadyState_c,
st_Link_AwaitingControllerComplete_c,
st_Link_HoldingDTR_c // - manual says that DTR is held for 80 nSec, but that must be for
// a hardware requirement, since at 2 MHz, 80 nSec is much less than
// one cpu clock. But to avoid calling back on the host as it is calling
// on the drive we will lower it on the next notification.
};
LinkState curLinkState;
void transitionLinkToReady();
void transitionLinkToAwaitingReceive();
void transitionLinkToTransmit();
enum ControllerState
{
st_None_c,
st_Boot_c,
st_ReadCntrlStat_c,
st_ReadAuxStat_c,
st_LoadSectorCount_c,
st_ReadLastAddr_c,
st_ReadSectors_c,
st_WriteSectors_c,
st_ReadSectorsBuffered_c,
st_WriteSectorsBuffered_c,
st_WriteSectorsAndDelete_c,
st_WriteSectorsBufferedAndDelete_c,
st_Copy_c,
st_FormatIBM_SD_c,
st_Format_SD_c,
st_FormatIBM_DD_c,
st_Format_DD_c,
st_ReadReadyStatus_c,
st_WaitingToComplete_c,
st_MaxState_c
};
ControllerState curState;
unsigned int statePosition_m;
unsigned long long countDown_m;
static const unsigned long coundDown_Default_c = 200;
void processCmd(BYTE val);
const char* getStateStr(ControllerState state);
void reset();
DiskDrive* drives_m[numDrives_c];
ParallelLink* linkToHost_m;
BYTE readyState;
WORD sectorCount;
bool driveNotReady_m;
bool diskWriteProtected_m;
bool deletedData_m;
bool noRecordFound_m;
bool crcError_m;
bool lateData_m;
bool invalidCommandReceived_m;
bool badTrackOverflow_m;
BYTE dataToTransmit_m;
// Specified drive/side/track from host.
BYTE drive_m;
BYTE side_m;
BYTE track_m;
BYTE sector_m;
void decodeSideDriveSector(BYTE val);
static const BYTE sideMask_c = 0x80;
static const BYTE sideShift_c = 7;
static const BYTE driveMask_c = 0x60;
static const BYTE driveShift_c = 5;
static const BYTE sectorMask_c = 0x1F;
static const BYTE sectorShift_c = 0;
void decodeTrack(BYTE val);
static const BYTE trackMask_c = 0xFF;
static const BYTE trackShift_c = 0;
void processReadControlStatus(void);
void processReadReadyStatus(void);
void processLoadSectorCount(BYTE val = 0);
void processReadAuxStatus(BYTE val = 0);
void processReadSectorsBufffered(BYTE val = 0);
void processWriteSectorsBufffered(BYTE val = 0);
void processFormatSingleDensity(BYTE val = 0);
void processFormatDoubleDensity(BYTE val = 0);
void processFormatIBMDoubleDensity(BYTE val = 0);
void processTransmitted(void);
void commandComplete(void);
void processData(BYTE val);
BYTE diskData[256256];
int diskOffset;
int bytesToTransfer;
WORD sectorSize;
};
#endif // Z47CONTROLLER_H_
<file_sep>/VirtualH89/Src/H89MemoryDecoder.h
///
/// \file H89MemoryDecoder.h
///
/// H89 56K+ROM or 64K layout
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef H89MEMORYDECODER_H_
#define H89MEMORYDECODER_H_
#include "MemoryDecoder.h"
class SystemMemory8K;
class H89MemoryDecoder: public MemoryDecoder
{
public:
H89MemoryDecoder(std::shared_ptr<SystemMemory8K> systemRam,
MemoryLayout::MemorySize_t memSize = MemoryLayout::Mem_64k);
virtual ~H89MemoryDecoder() override;
private:
virtual void gppNewValue(BYTE gpo) override;
static const BYTE h89_gppOrg0Bit_c = 0b00100000;
};
#endif // H89MEMORYDECODER_H_
<file_sep>/VirtualH89/Src/HostFileBdos.cpp
/// \file HostFileBdos.cpp
///
/// Virtual access to host filesystem via CP/Net-style I/O device.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#include "HostFileBdos.h"
#ifdef __H89__
#include "logger.h"
#else
enum logLevel
{
FATAL = 0,
ERROR,
WARNING,
INFO,
VERBOSE,
ALL,
};
#ifndef CUR_LOG_LEVEL
#define CUR_LOG_LEVEL ERROR
#endif
#ifndef LOG_FILE
#define LOG_FILE stderr
#endif
#define debugss(subsys, level, args ...) \
if (level <= CUR_LOG_LEVEL){ \
fprintf(LOG_FILE, args); \
}
#endif // !H89
/// \cond
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <fnmatch.h>
#include <stdlib.h>
/// \endcond
HostFileBdos::HostFileBdos(PropertyUtil::PropertyMapT& props,
std::vector<std::string> args, uint8_t srvId, uint8_t cltId):
NetworkServer(),
dir(nullptr),
serverId(srvId),
clientId(cltId),
curDsk(-1),
curUsr(0),
curROVec(0),
curLogVec(0)
{
memset(&curSearch, 0, sizeof(curSearch));
memset(&curDpb, 0, sizeof(curDpb));
memset(openFiles, -1, sizeof(openFiles));
memset(&sFcb, 0, sizeof(sFcb));
sFcb.drv = 0x21;
curDpb.spt = 64; // some number
curDpb.bsh = DEF_BLS_SH - 7;
curDpb.blm = (1 << curDpb.bsh) - 1;
curDpb.dsm = DEF_NBLOCKS - 1;
curDpb.drm = 63; // some number
if (curDpb.dsm >= 256)
{
curDpb.exm = (1 << (curDpb.bsh - 4)) - 1;
phyExt = 8 << curDpb.bsh;
}
else
{
curDpb.exm = (1 << (curDpb.bsh - 3)) - 1;
phyExt = 16 << curDpb.bsh;
}
curDpb.cks = 0; // perhaps should be non-zero, as
// files can change without notice.
// But clients shouldn't be handling that.
// args[0] is our class name, like argv[0] in main().
std::string s;
if (args.size() > 1)
{
s = args[1];
}
else
{
s = props["hostfilebdos_root_dir"];
}
if (s.empty())
{
s = getenv("HOME");
s += "/HostFileBdos";
}
int rc = mkdir(s.c_str(), 0777);
if (rc != 0 && errno != EEXIST)
{
debugss(ssHostFileBdos, ERROR, "Cannot create root directory %s\n", s.c_str());
// what to do... all future accesses will likely return errors.
}
debugss(ssHostFileBdos, ERROR, "Creating HostFileBdos device with root dir %s\n", s.c_str());
dir = strdup(s.c_str());
}
HostFileBdos::~HostFileBdos()
{
int x;
for (x = 0; x < DEF_NFILE; ++x)
{
if (openFiles[x] >= 0)
{
close(openFiles[x]);
openFiles[x] = -1;
}
}
if (curSearch.find.dir)
{
closedir(curSearch.find.dir);
curSearch.find.dir = nullptr;
}
if (dir != nullptr)
{
free(dir);
dir = nullptr;
}
}
int
HostFileBdos::checkRecvMsg(uint8_t clientId, uint8_t* msgbuf, int len)
{
// For HostFileBdos, this indicates an error. The client did not
// get the response we posted from sendMsg().
return 0;
}
int
HostFileBdos::sendMsg(uint8_t* msgbuf, int len)
{
struct NetworkServer::ndos* hdr = (struct NetworkServer::ndos*) msgbuf;
uint8_t* msg = msgbuf + sizeof(*hdr);
if (bdosFunctions[hdr->mfunc] == nullptr)
{
msg[0] = 255;
msg[1] = 12;
return 2;
}
return bdosFunctions[hdr->mfunc](this, msg, len - sizeof(*hdr));
}
int
HostFileBdos::getDPB(uint8_t* msgbuf, int len)
{
memcpy(msgbuf, &curDpb, sizeof(curDpb));
return sizeof(curDpb);
}
int
HostFileBdos::writeProt(uint8_t* msgbuf, int len)
{
curROVec |= (1 << (msgbuf[0] & 0x0f));
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::resetDrive(uint8_t* msgbuf, int len)
{
curROVec &= ~(1 << (msgbuf[0] & 0x0f));
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::getROVec(uint8_t* msgbuf, int len)
{
msgbuf[0] = (curROVec & 0x0ff);
msgbuf[1] = ((curROVec >> 8) & 0x0ff);
return 2;
}
int
HostFileBdos::getAllocVec(uint8_t* msgbuf, int len)
{
// TODO: is there anything here?
memset(msgbuf, 0, 256);
return 256;
}
int
HostFileBdos::getLoginVec(uint8_t* msgbuf, int len)
{
msgbuf[0] = (curLogVec & 0x0ff);
msgbuf[1] = ((curLogVec >> 8) & 0x0ff);
return 2;
}
int
HostFileBdos::selectDisk(uint8_t* msgbuf, int len)
{
uint8_t d = msgbuf[0];
msgbuf[0] = 0;
if (curDsk == d)
{
return 1;
}
curDsk = d;
struct stat stb;
cpmDrive(fileName, d);
int rc = stat(fileName, &stb);
if (rc < 0 && errno == ENOENT)
{
debugss(ssHostFileBdos, INFO, "Mkdir %s\n", fileName);
rc = mkdir(fileName, 0777);
if (rc == 0)
{
stb.st_mode |= S_IFDIR;
}
}
if (rc < 0 || !S_ISDIR(stb.st_mode))
{
debugss(ssHostFileBdos, INFO, "Seldisk error (%d) %s\n", errno, fileName);
curLogVec &= ~(1 << d);
msgbuf[0] = 255;
return 1;
}
debugss(ssHostFileBdos, INFO, "Seldisk: %s\n", fileName);
curLogVec |= (1 << d);
return 1;
}
int
HostFileBdos::openFile(uint8_t* msgbuf, int len)
{
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
// ignore password...
int rc = openFileFcb(fcb, u);
if (rc < 0)
{
msgbuf[0] = 255; // a.k.a. File Not Found
return 1;
}
else
{
return 37;
}
}
int
HostFileBdos::closeFile(uint8_t* msgbuf, int len)
{
int rc;
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
int fd = getFileFcb(fcb);
if (fd < 0)
{
msgbuf[0] = 255;
return 1;
}
msgbuf[0] = 0;
if (!fcb->s1[1])
{
// special truncate for SUBMIT (CCP)
off_t len = fcb->rc;
len *= 128;
rc = ftruncate(fd, len);
if (rc < 0)
{
debugss(ssHostFileBdos, ERROR, "ftruncate\n");
}
}
rc = closeFileFcb(fcb);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
else
{
return 37;
}
}
int
HostFileBdos::searchNext(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[1] & 0x1f;
if (curSearch.full)
{
int dc = curSearch.iter & 0x03;
if (curSearch.iter < curSearch.lastit)
{
++curSearch.iter;
msgbuf[0] = dc;
return 1;
}
if (curSearch.iter < curSearch.endit)
{
msgbuf[0] = 255;
return 1;
}
// force iter to next record
curSearch.iter = (curSearch.iter + 0x03) & ~0x03;
}
const char* name = doSearch(&curSearch);
if (!name)
{
msgbuf[0] = 255;
return 1;
}
if (curSearch.full)
{
// curSearch.iter is 0, must be. We know at least one exists.
msgbuf[0] = fullSearch(&msgbuf[1], &curSearch, name); // fill the dma buf, if possible.
return 129;
}
else
{
msgbuf[0] = copyOutSearch(&msgbuf[1], name);
return 33;
}
}
// CP/M 3 DIR uses fcb->drv == '?' to do full listing,
// and older CP/M STAT uses fcb->ext == '?'.
// However, fcb->drv == '?' is documented in older CP/M
// so we cannot assume CP/M 3 based on that.
int
HostFileBdos::searchFirst(uint8_t* msgbuf, int len)
{
// uint8_t d = msgbuf[0] & 0x0f; // should be curDsk...
uint8_t u = msgbuf[1] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[2];
if ((fcb->drv & 0x7f) == '?')
{
// This means return every dir entry...
debugss(ssHostFileBdos, ERROR, "Search with drv = '?'\n");
memset(&fcb->name[0], '?', 12);
}
const char* f = startSearch(fcb, &curSearch, u);
if (f == nullptr)
{
if (errno == ENXIO)
{
// no drive present...
curLogVec &= ~(1 << curSearch.drv);
}
else
{
curLogVec |= (1 << curSearch.drv);
}
msgbuf[0] = 255;
return 1;
}
curLogVec |= (1 << curSearch.drv);
if (curSearch.full)
{
// curSearch.iter is 0, must be. We know at least one exists.
msgbuf[0] = fullSearch(&msgbuf[1], &curSearch, f); // fill the dma buf, if possible.
return 129;
}
else
{
msgbuf[0] = copyOutSearch(&msgbuf[1], f);
return 33;
}
}
// TODO: if this is an open file, then close it?
int
HostFileBdos::deleteFile(uint8_t* msgbuf, int len)
{
struct search era;
uint8_t u = msgbuf[0] & 0x1f;
msgbuf[0] = 0;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
if (fcb->drv == '?')
{
msgbuf[0] = 255;
msgbuf[1] = 9;
return 2;
}
if ((fcb->name[4] & 0x80) != 0) // check F5'
{ // no XFCBs in this implementation,
// do not remove timestamps.
return 1;
}
fcb->ext = 0; // in case it was '?'
memset(&era, 0, sizeof(era));
errno = 0;
const char* name = startSearch(fcb, &era, u);
int rc = 0;
while (name)
{
++rc;
unlink(cpmPathFound(&era.find));
name = doSearch(&era);
}
if (rc == 0)
{
msgbuf[0] = 255;
if (errno == ENXIO)
{
curLogVec &= ~(1 << era.drv);
}
return 1;
}
curLogVec |= (1 << era.drv);
return 1;
}
int
HostFileBdos::readSeq(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd < 0)
{
msgbuf[0] = 9;
return 1;
}
if ((fcb->ext == 0 && fcb->cr == 0) ||
fcb->cr != fcb->s1[0])
{
off_t len = fcb->cr;
len *= 128;
lseek(fd, len, SEEK_SET);
}
ssize_t rc = read(fd, &msgbuf[37], 128);
if (fcb->cr > 127)
{
fcb->cr = 0;
++fcb->ext;
fcb->ext &= 0x1f;
}
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
if (rc == 0)
{
msgbuf[0] = 1;
return 1;
}
++fcb->cr;
fcb->s1[0] = fcb->cr;
// fill any partial "sector" with Ctrl-Z, in case it's text.
memset(&msgbuf[37 + rc], 0x1a, 128 - rc);
// detect media change?
return 165;
}
int
HostFileBdos::writeSeq(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd <= 0)
{
msgbuf[0] = 9;
return 1;
}
ssize_t rc = write(fd, &msgbuf[37], 128);
if (fcb->cr > 127)
{
fcb->cr = 0;
fcb->rc = 0;
++fcb->ext;
fcb->ext &= 0x1f;
}
++fcb->cr;
if (fcb->rc < fcb->cr)
{
fcb->rc = fcb->cr;
}
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
if (rc == 0)
{
msgbuf[0] = 1;
return 1;
}
// fcb->s1[1] = 0; // don't need this here...
// detect media change?
return 37;
}
// File is open on successful return.
int
HostFileBdos::createFile(uint8_t* msgbuf, int len)
{
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int rc = makeFileFcb(fcb, u);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
return 37;
}
int
HostFileBdos::renameFile(uint8_t* msgbuf, int len)
{
char newn[sizeof(pathName)];
uint8_t d;
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
getFileName(fileName, fcb);
d = fcb->drv;
if (!d)
{
d = curDsk;
}
else
{
--d;
}
cpmPath(pathName, d, u, fileName);
fcb = (struct fcb*) &msgbuf[17];
getFileName(fileName, fcb);
cpmPath(newn, d, u, fileName);
int rc = rename(pathName, newn);
if (rc < 0)
{
if (errno == ENOENT)
{
curLogVec &= ~(1 << d);
}
// todo: decode errno...
msgbuf[0] = 255;
return 1;
}
curLogVec |= (1 << d);
return 1;
}
int
HostFileBdos::readRand(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd < 0)
{
msgbuf[0] = 9;
return 1;
}
seekFile(fcb);
ssize_t rc = read(fd, &msgbuf[37], 128);
seekFile(fcb);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
if (rc == 0)
{
msgbuf[0] = 1;
return 1;
}
memset(&msgbuf[37 + rc], 0x1a, 128 - rc);
// detect media change?
return 37 + 128;
}
int
HostFileBdos::writeRand(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd < 0)
{
msgbuf[0] = 9;
return 1;
}
seekFile(fcb);
ssize_t rc = write(fd, &msgbuf[37], 128);
seekFile(fcb);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
if (rc == 0)
{
msgbuf[0] = 1;
return 1;
}
// detect media change?
return 37;
}
int
HostFileBdos::setRandRec(uint8_t* msgbuf, int len)
{
// uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd < 0)
{
msgbuf[0] = 9;
return 1;
}
off_t r = lseek(fd, (off_t) 0, SEEK_CUR);
if (r > 0x03ffff * 128)
{
r = 0x03ffff;
}
else
{
r = (r + 127) / 128;
}
fcb->rr[0] = r & 0x0ff;
r >>= 8;
fcb->rr[1] = r & 0x0ff;
r >>= 8;
fcb->rr[2] = r & 0x0ff;
return 37;
}
int
HostFileBdos::compFileSize(uint8_t* msgbuf, int len)
{
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd < 0)
{
int rc = openFileFcb(fcb, u);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
fd = getFileFcb(fcb);
}
struct stat stb;
int rc = fstat(fd, &stb);
if (rc < 0)
{
msgbuf[0] = 255;
return 1;
}
off_t r = stb.st_size;
if (r > 0x03ffff * 128)
{
r = 0x03ffff;
}
else
{
r = (r + 127) / 128;
}
fcb->rr[0] = r & 0x0ff;
r >>= 8;
fcb->rr[1] = r & 0x0ff;
r >>= 8;
fcb->rr[2] = r & 0x003;
return 37;
}
int
HostFileBdos::setFileAttrs(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::accessDrive(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::freeDrive(uint8_t* msgbuf, int len)
{
curDsk = -1; // do this?
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::writeRandZF(uint8_t* msgbuf, int len)
{
// Linux zero-fills for us...
return writeRand(msgbuf, len);
}
int
HostFileBdos::lockRec(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 37;
}
int
HostFileBdos::unlockRec(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 37;
}
int
HostFileBdos::getFreeSp(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
msgbuf[1] = 0xff; // inifinte space available
msgbuf[2] = 0xff;
msgbuf[3] = 0xff;
return 4;
}
int
HostFileBdos::flushBuf(uint8_t* msgbuf, int len)
{
// nothing to do for us?
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::freeBlks(uint8_t* msgbuf, int len)
{
// nothing to do for us?
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::truncFile(uint8_t* msgbuf, int len)
{
int rc;
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
int fd = getFileFcb(fcb);
if (fd >= 0)
{
msgbuf[0] = 0xff;
msgbuf[1] = 0;
return 2;
}
uint8_t d = fcb->drv;
if (!d)
{
d = curDsk;
}
else
{
--d;
}
getFileName(fileName, fcb);
cpmPath(pathName, d, u, fileName);
if (access(pathName, W_OK) != 0)
{
msgbuf[0] = 0xff;
msgbuf[1] = errno == ENOENT ? 0x00 : 0x03;
return 2;
}
struct stat stb;
stat(pathName, &stb);
off_t r = fcb->rr[0] | (fcb->rr[1] << 8) | ((fcb->rr[2] & 0x03) << 16);
if (r > stb.st_size)
{
msgbuf[0] = 0xff;
msgbuf[1] = 0x00;
return 2;
}
rc = truncate(pathName, r);
if (rc < 0)
{
msgbuf[0] = 0xff;
msgbuf[1] = 0xff;
return 2;
}
// TODO: need to update ext,rc,cr? file is not open... as far as we know.
return 37;
}
int
HostFileBdos::login(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::logoff(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::setCompAttrs(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::getServCfg(uint8_t* msgbuf, int len)
{
// TODO: implement this if needed...
memset(msgbuf, 0, 17);
return 17;
}
int
HostFileBdos::setDefPwd(uint8_t* msgbuf, int len)
{
msgbuf[0] = 0;
return 1;
}
int
HostFileBdos::getDirLab(uint8_t* msgbuf, int len)
{
// CP/M 3 DIR.COM uses full-search, not this, to
// detect timestamps.
msgbuf[0] = dirMode;
return 1;
}
// Get timestamp for given file
int
HostFileBdos::readFStamps(uint8_t* msgbuf, int len)
{
uint8_t u = msgbuf[0] & 0x1f;
struct fcb* fcb = (struct fcb*) &msgbuf[1];
msgbuf[0] = 0;
uint8_t d = fcb->drv;
if (!d)
{
d = curDsk;
}
else
{
--d;
}
getFileName(fileName, fcb);
cpmPath(pathName, d, u, fileName);
if (access(pathName, F_OK) != 0)
{
msgbuf[0] = 0xff;
msgbuf[1] = 0x00;
return 2;
}
struct stat stb;
stat(pathName, &stb);
fcb->ext = 0; // no passwords
// order is important, overwrites seconds field (not present in CP/M 3 timestamps).
unix2cpmdate(stb.st_atime, (struct cpmdate*) &fcb->d0[8]);
unix2cpmdate(stb.st_mtime, (struct cpmdate*) &fcb->d0[12]);
fcb->cr = 0;
return 37;
}
int
HostFileBdos::getTime(uint8_t* msgbuf, int len)
{
time_t now = time(nullptr);
struct cpmdate* cpm = (struct cpmdate*) &msgbuf[0];
unix2cpmdate(now, cpm);
debugss(ssHostFileBdos, INFO, "getTime: %04x %02x %02x %02x\n",
msgbuf[0] | (msgbuf[1] << 8), msgbuf[2], msgbuf[3], msgbuf[4]);
return 5;
}
// *INDENT-OFF*
// '0' means not supported (returns error if called)
int(*HostFileBdos::bdosFunctions[256])(HostFileBdos *, uint8_t *, int) = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // (0-13)
selectDisk, openFile, closeFile, searchFirst, searchNext, // 14-18
deleteFile, readSeq, writeSeq, createFile, renameFile, // 19-23
getLoginVec, // 24
0, 0, // (25-26)
getAllocVec, writeProt, getROVec, setFileAttrs, getDPB, // 27-31
0, // (32)
readRand, writeRand, compFileSize, setRandRec, resetDrive, // 33-37
accessDrive, freeDrive, writeRandZF, // 38-40
0, // (41)
lockRec, unlockRec, // 42-43
0, 0, // (44-45)
getFreeSp, // 46
0, // (47)
flushBuf, // 48
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // (49-63)
login, logoff, // 64, 65: not implemented but must not return error.
0, 0, 0, 0, // (66-69)
setCompAttrs, getServCfg, // 70, 71
0, 0, 0, 0, 0, 0, 0, 0, // (72-79)
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // (80-95)
0, 0, // (96-97)
freeBlks, truncFile, // 98-99
0, getDirLab, readFStamps, 0, 0, // (100-104)
getTime, // 105: local convenience
setDefPwd, // 106: not really implemented...
0
};
// *INDENT-ON*
int
HostFileBdos::cpmDrive(char* buf, int drive)
{
drive &= 0x0f;
return sprintf(buf, "%s/%c", dir, drive + 'a');
}
int
HostFileBdos::cpmFilename(char* buf, int user, char* file)
{
int x = 0;
user &= 0x1f;
if (user)
{
x += sprintf(buf + x, "%d:", user);
}
x += sprintf(buf + x, "%s", file);
return x;
}
int
HostFileBdos::cpmPath(char* buf, int drive, int user, char* file)
{
int x = cpmDrive(buf, drive);
buf[x++] = '/';
x += cpmFilename(buf + x, user, file);
return x;
}
char*
HostFileBdos::cpmNameFound(struct search::find* find)
{
return find->path + find->dirlen + 1;
}
char*
HostFileBdos::cpmPathFound(struct search::find* find)
{
return find->path;
}
// Not used, as init is automatic on Search First.
void
HostFileBdos::cpmFindInit(struct search::find* find, int drive, char* pattern)
{
if (find->dir)
{
closedir(find->dir);
}
strncpy(find->pat, pattern, sizeof(find->pat));
find->pat[sizeof(find->pat) - 1] = '\0';
find->dirlen = cpmDrive(find->path, drive);
find->dir = opendir(find->path);
// nullptr check done later...
if (!find->dir)
{
debugss(ssHostFileBdos, INFO, "no dir: %s\n", find->path);
}
}
const char*
HostFileBdos::cpmFind(struct search::find* find)
{
struct dirent* de;
if (!find->dir)
{
errno = ENXIO;
return nullptr;
}
do
{
de = readdir(find->dir);
if (!de)
{
errno = ENOENT;
return nullptr;
}
if (de->d_name[0] == '.')
{
continue;
}
debugss(ssHostFileBdos, INFO, "looking at %s... %s\n", de->d_name, find->pat);
// need to prevent "*.*" from matching all users!
if (fnmatch(find->pat, de->d_name, 0) == 0)
{
break;
}
}
while (1);
sprintf(find->path + find->dirlen, "/%s", de->d_name);
return cpmNameFound(find);
}
void
HostFileBdos::getFileName(char* dst, struct fcb* fcb)
{
int x;
for (x = 0; x < 8 && (fcb->name[x] & 0x7f) != ' '; ++x)
{
*dst++ = tolower(fcb->name[x] & 0x7f);
}
for (x = 8; x < 11 && (fcb->name[x] & 0x7f) != ' '; ++x)
{
if (x == 8)
{
*dst++ = '.';
}
*dst++ = tolower(fcb->name[x] & 0x7f);
}
*dst++ = '\0';
}
void
HostFileBdos::getAmbFileName(char* dst, struct fcb* fcb, uint8_t usr)
{
int x;
char buf[16];
char* s = buf;
int sawQ = 0;
for (x = 0; x < 8 && (fcb->name[x] & 0x7f) != ' '; ++x)
{
if ((fcb->name[x] & 0x7f) == '?')
{
*s++ = '*';
sawQ = 1;
break;
}
*s++ = tolower(fcb->name[x] & 0x7f);
}
for (x = 8; x < 11 && (fcb->name[x] & 0x7f) != ' '; ++x)
{
if (x == 8)
{
if ((fcb->name[x] & 0x7f) == '?')
{
// special case, need "*.*" to be just "*"
if (sawQ)
{
break;
}
}
*s++ = '.';
}
if ((fcb->name[x] & 0x7f) == '?')
{
*s++ = '*';
break;
}
*s++ = tolower(fcb->name[x] & 0x7f);
}
*s++ = '\0';
cpmFilename(dst, usr, buf);
}
void
HostFileBdos::copyOutDir(uint8_t* dma, const char* name)
{
struct fcb* fcb = (struct fcb*) dma;
const char* t;
t = strchr(name, ':');
uint8_t u;
if (t)
{
u = atoi(name);
++t;
}
else
{
u = 0;
t = name;
}
fcb->drv = u; // user code , not drive
int x = 0;
while (*t && *t != '.' && x < 8)
{
fcb->name[x++] = toupper(*t++);
}
while (x < 8)
{
fcb->name[x++] = ' ';
}
while (*t && *t != '.')
{
++t;
}
if (*t == '.')
{
++t;
}
while (*t && *t != '.' && x < 11)
{
fcb->name[x++] = toupper(*t++);
}
while (x < 11)
{
fcb->name[x++] = ' ';
}
fcb->ext = 0;
fcb->s1[0] = 0;
fcb->s1[1] = 0;
fcb->rc = 0;
memset(fcb->d0, 0, sizeof(fcb->d0));
}
int
HostFileBdos::copyOutSearch(uint8_t* buf, const char* name)
{
if (*name == ' ') // DIR LABEL
{
struct dirl* dirLab = (struct dirl*) buf;
sprintf((char*) &dirLab->name[0], "SERVER%02x%c ",
serverId, curSearch.drv + 'A');
dirLab->ext = dirMode;
dirLab->drv = 0x20;
// nothing meaningful for timestamps?
return curSearch.iter++ & 0x03; // should be "0" (iter == 0)
}
else if (*name == '!') // SFCB (already populated)
{ // this should never happen...
debugss(ssHostFileBdos, ERROR, "Copy Out SFCB in wrong place\n");
memcpy(buf, &sFcb, 32);
return curSearch.iter++ & 0x03; // should be "3"
}
copyOutDir(buf, name);
struct fcb* fcb = (struct fcb*) buf;
// curSearch.size is only valid if curSearch.ext == '?'.
if (curSearch.ext == '?')
{
// create fake info in FCB to fool caller into
// thinking the file is of about the right size.
// This does not account for sparse files.
off_t len = curSearch.size; // len in bytes
if (len < phyExt * 128)
{
curSearch.size = 0;
}
else
{
curSearch.size -= phyExt * 128;
}
len = (len + 127) / 128; // len in records
// STAT only cares about (ext & exm), so actually ext can wrap.
// But, (ext & exm) must reflect the number of
// logical extents in this dirent.
int nb = 16, x;
if (len <= phyExt)
{
nb = (int) ((len + curDpb.blm) >> curDpb.bsh);
fcb->ext = len / 128; // num logical extents
fcb->rc = len & 0x7f;
if (len > 0 && fcb->rc == 0)
{
fcb->rc = 128;
}
}
else
{
fcb->ext = curDpb.exm; // should have advancing num in hi bits
fcb->rc = 128;
}
for (x = 0; x < nb; ++x)
{
// just need a non-zero value...
fcb->d0[x] = 1;
}
}
// Generally, no one (STAT) cares if this is always 0.
// CP/Net will place this in a DMA buffer for us.
return curSearch.iter++ & 0x03;
}
const char*
HostFileBdos::commonSearch(struct search* search)
{
if (search->full && search->cpm3)
{
if (search->iter == 0) // DIR LABEL
{
return " ";
}
else if ((search->iter & 0x03) == 0x03) // SFCB
{
return "!";
}
}
if (search->ext == '?' && search->size > 0)
{
// copyOutSearch() should ensure we don't keep landing here,
// but caller MUST invoke copyOutSearch() each time.
return cpmNameFound(&search->find);
}
const char* f = cpmFind(&search->find);
if (!f)
{
return nullptr;
}
if (search->ext == '?') // this includes search->full
{ // return size of file... by some definition...
struct stat stb;
stat(cpmPathFound(&search->find), &stb);
search->size = stb.st_size;
if (search->full && search->cpm3)
{
// SFCB timestamps are only used if the
// matching FCB is for extent 0. However,
// we just populate it anyway, especially since
// extent info is not computed until copyOut.
int x = search->iter & 0x03; // 0, 1, 2 only
// order is imperative, overwrite seconds field
unix2cpmdate(stb.st_atime,
(struct cpmdate*) &sFcb.fcbs[x].atim);
unix2cpmdate(stb.st_mtime,
(struct cpmdate*) &sFcb.fcbs[x].utim);
sFcb.fcbs[x].pwmode = 0; // clear seconds overrun
}
}
return f;
}
int
HostFileBdos::fullSearch(uint8_t* dirbuf, struct search* search, const char* ff)
{
int ix = 0; // by definition, we are starting with DIRENT 0.
int saveIter = search->iter;
search->endit = search->iter + curSearch.maxdc;
do
{
(void) copyOutSearch(dirbuf, ff);
dirbuf += 32;
++ix;
ff = doSearch(search);
}
while (ff != nullptr && ix < search->maxdc); // never includes SFCB
search->lastit = search->iter; // if >= saveIter+maxdc then no error
search->iter = saveIter;
while (ix < 4)
{
if (ix == search->maxdc) // can only happen for SFCB
{
memcpy(dirbuf, &sFcb, 32);
}
else
{
dirbuf[0] = 0xe5;
}
dirbuf += 32;
++ix;
}
return search->iter++ & 0x03;
}
const char*
HostFileBdos::doSearch(struct search* search)
{
return commonSearch(search);
}
const char*
HostFileBdos::startSearch(struct fcb* fcb, struct search* search, uint8_t u)
{
char pat[16];
uint8_t d = fcb->drv & 0x7f;
search->iter = 0;
if (d == '?')
{
search->full = 1;
search->cpm3 = ((fcb->drv & 0x80) != 0); // CP/M 3 sets hi bit
search->ext = '?';
search->maxdc = (search->cpm3 ? 3 : 4);
d = curDsk;
pat[0] = '*';
pat[1] = '\0';
}
else
{
search->full = 0;
search->cpm3 = 0; // don't care if !full
search->ext = fcb->ext; // might still be '?' (e.g. CP/M 2 STAT.COM)
if (!d)
{
d = curDsk;
}
else
{
--d;
}
getAmbFileName(pat, fcb, u);
}
search->drv = d;
search->usr = u;
cpmFindInit(&search->find, search->drv, pat);
return commonSearch(search);
}
void
HostFileBdos::seekFile(struct fcb* fcb)
{
int fd = getFileFcb(fcb);
if (fd < 0)
{
return;
}
off_t r = fcb->rr[0] | (fcb->rr[1] << 8) | ((fcb->rr[2] & 0x03) << 16);
r *= 128;
(void) lseek(fd, r, SEEK_SET);
fcb->s1[0] = fcb->cr;
}
int
HostFileBdos::newFileFcb()
{
int x;
for (x = 0; x < DEF_NFILE; ++x)
{
if (openFiles[x] < 0)
{
break;
}
}
if (x >= DEF_NFILE)
{
return -1;
}
return x;
}
int
HostFileBdos::locFileFcb(struct fcb* fcb)
{
if ((fcb->fd ^ fcb->fd_) != 0xffff)
{
return -1;
}
int x = fcb->fd;
if (x < 0 || x >= DEF_NFILE)
{
fcb->fd = fcb->fd_ = 0;
return -1;
}
return x;
}
void
HostFileBdos::putFileFcb(struct fcb* fcb, int ix, int fd)
{
openFiles[ix] = fd;
if (fd < 0)
{
fcb->fd = fcb->fd_ = 0;
}
else
{
fcb->fd = ix;
fcb->fd_ = ~ix;
}
// Always put file ID in FCB, the
// NDOS decides whether to copy it out.
// In the case of Close, the File Id returned
// is no longer valid.
fcb->rr[0] = ix & 0x0ff;
fcb->rr[1] = (ix >> 8) & 0x0ff;
}
// Returns Unix file descriptor, not CP/M File ID...
int
HostFileBdos::getFileFcb(struct fcb* fcb)
{
int x = locFileFcb(fcb);
if (x < 0)
{
return -1;
}
return openFiles[x];
}
// Returns CP/M File Id, or -1 on error.
int
HostFileBdos::closeFileFcb(struct fcb* fcb)
{
int x = locFileFcb(fcb);
if (x < 0)
{
return -1;
}
int fd = openFiles[x];
putFileFcb(fcb, x, -1);
int rc = close(fd);
return rc < 0 ? -1 : x;
}
// Returns CP/M File Id, or -1 on error.
int
HostFileBdos::openFileFcb(struct fcb* fcb, uint8_t u)
{
uint8_t d;
int x = newFileFcb();
if (x < 0)
{
return -1;
}
getFileName(fileName, fcb);
d = fcb->drv;
if (!d)
{
d = curDsk;
}
else
{
--d;
}
cpmPath(pathName, d, u, fileName);
debugss(ssHostFileBdos, INFO, "Opening %s\n", pathName);
int flags;
if (access(pathName, F_OK) < 0 && u)
{
cpmPath(pathName, d, 0, fileName);
}
if (access(pathName, W_OK) == 0)
{
flags = O_RDWR;
}
else
{
flags = O_RDONLY;
}
// NOTE: for this function, file must exist already.
int fd = open(pathName, flags);
if (fd < 0)
{
debugss(ssHostFileBdos, INFO, "Fail to open %s (%d)\n", pathName, errno);
// don't know exactly why... curLogVec &= ~(1 << d);
return -1;
}
putFileFcb(fcb, x, fd);
curLogVec |= (1 << d); // drive must be valid
fcb->ext = 0;
fcb->oflags = flags;
struct stat stb;
fstat(fd, &stb);
off_t len = stb.st_size;
len = (len + 127) / 128; // num records
fcb->rc = len > 127 ? 128 : (len & 0x7f);
fcb->s1[0] = 0;
fcb->s1[1] = 0x80; // flag if close needs to update...
return x;
}
// Returns CP/M File Id, or -1 on error.
int
HostFileBdos::makeFileFcb(struct fcb* fcb, uint8_t u)
{
uint8_t d;
int x = newFileFcb();
if (x < 0)
{
return -1;
}
getFileName(fileName, fcb);
d = fcb->drv;
if (!d)
{
d = curDsk;
}
else
{
--d;
}
cpmPath(pathName, d, u, fileName);
int flags = O_RDWR | O_CREAT | O_EXCL;
int fd = open(pathName, flags, 0666);
if (fd < 0)
{
if (errno == ENOENT)
{
curLogVec &= ~(1 << d);
}
return -1;
}
putFileFcb(fcb, x, fd);
curLogVec |= (1 << d);
fcb->ext = 0;
fcb->rc = 0;
fcb->oflags = flags;
fcb->s1[1] = 0x80; // flag to update on close
return x;
}
void
HostFileBdos::unix2cpmdate(time_t unx, struct cpmdate* cpm)
{
struct tm tmv;
localtime_r(&unx, &tmv);
// date is UTC, time is local, need to reconcile them...
unx += tmv.tm_gmtoff;
cpm->date = unx / 86400 - 2922 + 1;
// the rest are BCD fields...
cpm->hour = ((tmv.tm_hour / 10) << 4) | (tmv.tm_hour % 10);
cpm->min = ((tmv.tm_min / 10) << 4) | (tmv.tm_min % 10);
cpm->sec = ((tmv.tm_sec / 10) << 4) | (tmv.tm_sec % 10);
}
<file_sep>/VirtualH89/Src/InterruptController.h
///
/// \name InterruptController.h
///
///
/// \date Feb 7, 2016
/// \author <NAME>
///
#ifndef INTERRUPTCONTROLLER_H_
#define INTERRUPTCONTROLLER_H_
#include "h89Types.h"
/// \class InterruptController
///
/// \brief Interrupt Controller Logic
///
/// Although the H89 did not have an interrupt chip, it had special logic to generate
/// an RST xx instruction for each interrupt. Heath's soft-sectored controller and
/// MMS's 77316 both modified the logic to either generate an RST for interrupts
/// and an EI instruction when DRQ has been raised.
///
class CPU;
class InterruptController
{
protected:
BYTE intLevel_m;
CPU* cpu_m;
virtual void setINTLine();
public:
InterruptController(CPU* cpu);
virtual ~InterruptController();
virtual void raiseInterrupt(BYTE level);
virtual void lowerInterrupt(BYTE level);
virtual void setDrq(bool raise);
virtual void setIntrq(bool raise);
virtual void blockInterrupts(bool block);
// reading instructions for interrupts
virtual BYTE readDataBus();
};
#endif // INTERRUPTCONTROLLER_H_
<file_sep>/VirtualH89/Src/z80.cpp
/// \file z80.cpp
///
/// \brief Implements a virtual Zilog Z80 CPU.
///
/// \date Mar 7, 2009
///
/// \author <NAME>
///
#include "z80.h"
#include "logger.h"
#include "computer.h"
#include "AddressBus.h"
#include "WallClock.h"
#include "disasm.h"
#include "IOBus.h"
#include "propertyutil.h"
#include "config.h"
/// \cond
#include <ctime>
#include <cassert>
#include <strings.h>
#include <unistd.h>
/// \endcond
using namespace std;
/// Precalculated flag values for Z, S, & P
///
/// Since 8 bit values are all we have to check, setting up a table
/// is much more efficient than recalculating these values
/// up to 500,000 times a sec (at 2Mhz).
const BYTE Z80::ZSP[256] =
{
0x44, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x00, 0x04, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04,
0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x04, 0x00,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x84, 0x80, 0x80, 0x84, 0x80, 0x84, 0x84, 0x80,
0x80, 0x84, 0x84, 0x80, 0x84, 0x80, 0x80, 0x84
};
const Z80::opCodeMethod Z80::op_code[256] =
{
&Z80::op_nop, /* 0x00 - 000 */
&Z80::op_ld_xx_nn, /* 0x01 - 001 */
&Z80::op_ld_ibc_a, /* 0x02 - 002 */
&Z80::op_inc_xx, /* 0x03 - 003 */
&Z80::op_inc_x, /* 0x04 - 004 */
&Z80::op_dec_x, /* 0x05 - 005 */
&Z80::op_ld_x_n, /* 0x06 - 006 */
&Z80::op_rlc_a, /* 0x07 - 007 */
&Z80::op_ex_af_af, /* 0x08 - 010 */
&Z80::op_add_hl_xx, /* 0x09 - 011 */
&Z80::op_ld_a_ibc, /* 0x0a - 012 */
&Z80::op_dec_xx, /* 0x0b - 013 */
&Z80::op_inc_x, /* 0x0c - 014 */
&Z80::op_dec_x, /* 0x0d - 015 */
&Z80::op_ld_x_n, /* 0x0e - 016 */
&Z80::op_rrc_a, /* 0x0f - 017 */
&Z80::op_djnz, /* 0x10 - 020 */
&Z80::op_ld_xx_nn, /* 0x11 - 021 */
&Z80::op_ld_ide_a, /* 0x12 - 022 */
&Z80::op_inc_xx, /* 0x13 - 023 */
&Z80::op_inc_x, /* 0x14 - 024 */
&Z80::op_dec_x, /* 0x15 - 025 */
&Z80::op_ld_x_n, /* 0x16 - 026 */
&Z80::op_rl_a, /* 0x17 - 027 */
&Z80::op_jr, /* 0x18 - 030 */
&Z80::op_add_hl_xx, /* 0x19 - 031 */
&Z80::op_ld_a_ide, /* 0x1a - 032 */
&Z80::op_dec_xx, /* 0x1b - 033 */
&Z80::op_inc_x, /* 0x1c - 034 */
&Z80::op_dec_x, /* 0x1d - 035 */
&Z80::op_ld_x_n, /* 0x1e - 036 */
&Z80::op_rr_a, /* 0x1f - 037 */
&Z80::op_jr_nz, /* 0x20 - 040 */
&Z80::op_ld_xx_nn, /* 0x21 - 041 */
&Z80::op_ld_inn_xx, /* 0x22 - 042 */
&Z80::op_inc_xx, /* 0x23 - 043 */
&Z80::op_inc_x, /* 0x24 - 044 */
&Z80::op_dec_x, /* 0x25 - 045 */
&Z80::op_ld_x_n, /* 0x26 - 046 */
&Z80::op_daa, /* 0x27 - 047 */
&Z80::op_jr_z, /* 0x28 - 050 */
&Z80::op_add_hl_xx, /* 0x29 - 051 */
&Z80::op_ld_xx_inn, /* 0x2a - 052 */
&Z80::op_dec_xx, /* 0x2b - 053 */
&Z80::op_inc_x, /* 0x2c - 054 */
&Z80::op_dec_x, /* 0x2d - 055 */
&Z80::op_ld_x_n, /* 0x2e - 056 */
&Z80::op_cpl, /* 0x2f - 057 */
&Z80::op_jr_nc, /* 0x30 - 060 */
&Z80::op_ld_xx_nn, /* 0x31 - 061 */
&Z80::op_ld_inn_a, /* 0x32 - 062 */
&Z80::op_inc_xx, /* 0x33 - 063 */
&Z80::op_inc_ihl, /* 0x34 - 064 */
&Z80::op_dec_ihl, /* 0x35 - 065 */
&Z80::op_ld_ihl_n, /* 0x36 - 066 */
&Z80::op_scf, /* 0x37 - 067 */
&Z80::op_jr_c, /* 0x38 - 070 */
&Z80::op_add_hl_xx, /* 0x39 - 071 */
&Z80::op_ld_a_inn, /* 0x3a - 072 */
&Z80::op_dec_xx, /* 0x3b - 073 */
&Z80::op_inc_x, /* 0x3c - 074 */
&Z80::op_dec_x, /* 0x3d - 075 */
&Z80::op_ld_x_n, /* 0x3e - 076 */
&Z80::op_ccf, /* 0x3f - 077 */
&Z80::op_ld_x_x, /* 0x40 - 100 */
&Z80::op_ld_x_x, /* 0x41 - 101 */
&Z80::op_ld_x_x, /* 0x42 - 102 */
&Z80::op_ld_x_x, /* 0x43 - 103 */
&Z80::op_ld_x_x, /* 0x44 - 104 */
&Z80::op_ld_x_x, /* 0x45 - 105 */
&Z80::op_ld_x_ihl, /* 0x46 - 106 */
&Z80::op_ld_x_x, /* 0x47 - 107 */
&Z80::op_ld_x_x, /* 0x48 - 110 */
&Z80::op_ld_x_x, /* 0x49 - 111 */
&Z80::op_ld_x_x, /* 0x4a - 112 */
&Z80::op_ld_x_x, /* 0x4b - 113 */
&Z80::op_ld_x_x, /* 0x4c - 114 */
&Z80::op_ld_x_x, /* 0x4d - 115 */
&Z80::op_ld_x_ihl, /* 0x4e - 116 */
&Z80::op_ld_x_x, /* 0x4f - 117 */
&Z80::op_ld_x_x, /* 0x50 - 120 */
&Z80::op_ld_x_x, /* 0x51 - 121 */
&Z80::op_ld_x_x, /* 0x52 - 122 */
&Z80::op_ld_x_x, /* 0x53 - 123 */
&Z80::op_ld_x_x, /* 0x54 - 124 */
&Z80::op_ld_x_x, /* 0x55 - 125 */
&Z80::op_ld_x_ihl, /* 0x56 - 126 */
&Z80::op_ld_x_x, /* 0x57 - 127 */
&Z80::op_ld_x_x, /* 0x58 - 130 */
&Z80::op_ld_x_x, /* 0x59 - 131 */
&Z80::op_ld_x_x, /* 0x5a - 132 */
&Z80::op_ld_x_x, /* 0x5b - 133 */
&Z80::op_ld_x_x, /* 0x5c - 134 */
&Z80::op_ld_x_x, /* 0x5d - 135 */
&Z80::op_ld_x_ihl, /* 0x5e - 136 */
&Z80::op_ld_x_x, /* 0x5f - 137 */
&Z80::op_ld_x_x, /* 0x60 - 140 */
&Z80::op_ld_x_x, /* 0x61 - 141 */
&Z80::op_ld_x_x, /* 0x62 - 142 */
&Z80::op_ld_x_x, /* 0x63 - 143 */
&Z80::op_ld_x_x, /* 0x64 - 144 */
&Z80::op_ld_x_x, /* 0x65 - 145 */
&Z80::op_ld_x_ihl, /* 0x66 - 146 */
&Z80::op_ld_x_x, /* 0x67 - 147 */
&Z80::op_ld_x_x, /* 0x68 - 150 */
&Z80::op_ld_x_x, /* 0x69 - 151 */
&Z80::op_ld_x_x, /* 0x6a - 152 */
&Z80::op_ld_x_x, /* 0x6b - 153 */
&Z80::op_ld_x_x, /* 0x6c - 154 */
&Z80::op_ld_x_x, /* 0x6d - 155 */
&Z80::op_ld_x_ihl, /* 0x6e - 156 */
&Z80::op_ld_x_x, /* 0x6f - 157 */
&Z80::op_ld_ihl_x, /* 0x70 - 160 */
&Z80::op_ld_ihl_x, /* 0x71 - 161 */
&Z80::op_ld_ihl_x, /* 0x72 - 162 */
&Z80::op_ld_ihl_x, /* 0x73 - 163 */
&Z80::op_ld_ihl_x, /* 0x74 - 164 */
&Z80::op_ld_ihl_x, /* 0x75 - 165 */
&Z80::op_halt, /* 0x76 - 166 */
&Z80::op_ld_ihl_x, /* 0x77 - 167 */
&Z80::op_ld_x_x, /* 0x78 - 170 */
&Z80::op_ld_x_x, /* 0x79 - 171 */
&Z80::op_ld_x_x, /* 0x7a - 172 */
&Z80::op_ld_x_x, /* 0x7b - 173 */
&Z80::op_ld_x_x, /* 0x7c - 174 */
&Z80::op_ld_x_x, /* 0x7d - 175 */
&Z80::op_ld_x_ihl, /* 0x7e - 176 */
&Z80::op_ld_x_x, /* 0x7f - 177 */
&Z80::op_add_x, /* 0x80 - 200 */
&Z80::op_add_x, /* 0x81 - 201 */
&Z80::op_add_x, /* 0x82 - 202 */
&Z80::op_add_x, /* 0x83 - 203 */
&Z80::op_add_x, /* 0x84 - 204 */
&Z80::op_add_x, /* 0x85 - 205 */
&Z80::op_add_ihl, /* 0x86 - 206 */
&Z80::op_add_x, /* 0x87 - 207 */
&Z80::op_adc_x, /* 0x88 - 210 */
&Z80::op_adc_x, /* 0x89 - 211 */
&Z80::op_adc_x, /* 0x8a - 212 */
&Z80::op_adc_x, /* 0x8b - 213 */
&Z80::op_adc_x, /* 0x8c - 214 */
&Z80::op_adc_x, /* 0x8d - 215 */
&Z80::op_adc_ihl, /* 0x8e - 216 */
&Z80::op_adc_x, /* 0x8f - 217 */
&Z80::op_sub_x, /* 0x90 - 220 */
&Z80::op_sub_x, /* 0x91 - 221 */
&Z80::op_sub_x, /* 0x92 - 222 */
&Z80::op_sub_x, /* 0x93 - 223 */
&Z80::op_sub_x, /* 0x94 - 224 */
&Z80::op_sub_x, /* 0x95 - 225 */
&Z80::op_sub_ihl, /* 0x96 - 226 */
&Z80::op_sub_x, /* 0x97 - 227 */
&Z80::op_sbc_x, /* 0x98 - 230 */
&Z80::op_sbc_x, /* 0x99 - 231 */
&Z80::op_sbc_x, /* 0x9a - 232 */
&Z80::op_sbc_x, /* 0x9b - 233 */
&Z80::op_sbc_x, /* 0x9c - 234 */
&Z80::op_sbc_x, /* 0x9d - 235 */
&Z80::op_sbc_ihl, /* 0x9e - 236 */
&Z80::op_sbc_x, /* 0x9f - 237 */
&Z80::op_and_x, /* 0xa0 - 240 */
&Z80::op_and_x, /* 0xa1 - 241 */
&Z80::op_and_x, /* 0xa2 - 242 */
&Z80::op_and_x, /* 0xa3 - 243 */
&Z80::op_and_x, /* 0xa4 - 244 */
&Z80::op_and_x, /* 0xa5 - 245 */
&Z80::op_and_ihl, /* 0xa6 - 246 */
&Z80::op_and_x, /* 0xa7 - 247 */
&Z80::op_xor_x, /* 0xa8 - 250 */
&Z80::op_xor_x, /* 0xa9 - 251 */
&Z80::op_xor_x, /* 0xaa - 252 */
&Z80::op_xor_x, /* 0xab - 253 */
&Z80::op_xor_x, /* 0xac - 254 */
&Z80::op_xor_x, /* 0xad - 255 */
&Z80::op_xor_ihl, /* 0xae - 256 */
&Z80::op_xor_x, /* 0xaf - 257 */
&Z80::op_or_x, /* 0xb0 - 260 */
&Z80::op_or_x, /* 0xb1 - 261 */
&Z80::op_or_x, /* 0xb2 - 262 */
&Z80::op_or_x, /* 0xb3 - 263 */
&Z80::op_or_x, /* 0xb4 - 264 */
&Z80::op_or_x, /* 0xb5 - 265 */
&Z80::op_or_ihl, /* 0xb6 - 266 */
&Z80::op_or_x, /* 0xb7 - 267 */
&Z80::op_cp_x, /* 0xb8 - 270 */
&Z80::op_cp_x, /* 0xb9 - 271 */
&Z80::op_cp_x, /* 0xba - 272 */
&Z80::op_cp_x, /* 0xbb - 273 */
&Z80::op_cp_x, /* 0xbc - 274 */
&Z80::op_cp_x, /* 0xbd - 275 */
&Z80::op_cp_ihl, /* 0xbe - 276 */
&Z80::op_cp_x, /* 0xbf - 277 */
&Z80::op_ret_cc, /* 0xc0 - 300 */
&Z80::op_pop_xx, /* 0xc1 - 301 */
&Z80::op_jp_cc, /* 0xc2 - 302 */
&Z80::op_jp, /* 0xc3 - 303 */
&Z80::op_call_cc, /* 0xc4 - 304 */
&Z80::op_push_xx, /* 0xc5 - 305 */
&Z80::op_add_n, /* 0xc6 - 306 */
&Z80::op_rst, /* 0xc7 - 307 */
&Z80::op_ret_cc, /* 0xc8 - 310 */
&Z80::op_ret, /* 0xc9 - 311 */
&Z80::op_jp_cc, /* 0xca - 312 */
&Z80::op_cb_handle, /* 0xcb - 313 - prefix*/
&Z80::op_call_cc, /* 0xcc - 314 */
&Z80::op_call, /* 0xcd - 315 */
&Z80::op_adc_n, /* 0xce - 316 */
&Z80::op_rst, /* 0xcf - 317 */
&Z80::op_ret_cc, /* 0xd0 - 320 */
&Z80::op_pop_xx, /* 0xd1 - 321 */
&Z80::op_jp_cc, /* 0xd2 - 322 */
&Z80::op_out, /* 0xd3 - 323 */
&Z80::op_call_cc, /* 0xd4 - 324 */
&Z80::op_push_xx, /* 0xd5 - 325 */
&Z80::op_sub_n, /* 0xd6 - 326 */
&Z80::op_rst, /* 0xd7 - 327 */
&Z80::op_ret_cc, /* 0xd8 - 330 */
&Z80::op_exx, /* 0xd9 - 331 */
&Z80::op_jp_cc, /* 0xda - 332 */
&Z80::op_in, /* 0xdb - 333 */
&Z80::op_call_cc, /* 0xdc - 334 */
&Z80::op_dd_handle, /* 0xdd - 335 - prefix */
&Z80::op_sbc_n, /* 0xde - 336 */
&Z80::op_rst, /* 0xdf - 337 */
&Z80::op_ret_cc, /* 0xe0 - 340 */
&Z80::op_pop_xx, /* 0xe1 - 341 */
&Z80::op_jp_cc, /* 0xe2 - 342 */
&Z80::op_ex_isp_hl, /* 0xe3 - 343 */
&Z80::op_call_cc, /* 0xe4 - 344 */
&Z80::op_push_xx, /* 0xe5 - 345 */
&Z80::op_and_n, /* 0xe6 - 346 */
&Z80::op_rst, /* 0xe7 - 347 */
&Z80::op_ret_cc, /* 0xe8 - 350 */
&Z80::op_jp_hl, /* 0xe9 - 351 */
&Z80::op_jp_cc, /* 0xea - 352 */
&Z80::op_ex_de_hl, /* 0xeb - 353 */
&Z80::op_call_cc, /* 0xec - 354 */
&Z80::op_ed_handle, /* 0xed - 355 - prefix*/
&Z80::op_xor_n, /* 0xee - 356 */
&Z80::op_rst, /* 0xef - 357 */
&Z80::op_ret_cc, /* 0xf0 - 360 */
&Z80::op_pop_xx, /* 0xf1 - 361 */
&Z80::op_jp_cc, /* 0xf2 - 362 */
&Z80::op_di, /* 0xf3 - 363 */
&Z80::op_call_cc, /* 0xf4 - 364 */
&Z80::op_push_xx, /* 0xf5 - 365 */
&Z80::op_or_n, /* 0xf6 - 366 */
&Z80::op_rst, /* 0xf7 - 367 */
&Z80::op_ret_cc, /* 0xf8 - 370 */
&Z80::op_ld_sp_hl, /* 0xf9 - 371 */
&Z80::op_jp_cc, /* 0xfa - 372 */
&Z80::op_ei, /* 0xfb - 373 */
&Z80::op_call_cc, /* 0xfc - 374 */
&Z80::op_fd_handle, /* 0xfd - 375 - prefix */
&Z80::op_cp_n, /* 0xfe - 376 */
&Z80::op_rst /* 0xff - 377 */
};
const Z80::opCodeMethod Z80::op_cb[256] =
{
&Z80::op_rlc_x, /* 0x00 */
&Z80::op_rlc_x, /* 0x01 */
&Z80::op_rlc_x, /* 0x02 */
&Z80::op_rlc_x, /* 0x03 */
&Z80::op_rlc_x, /* 0x04 */
&Z80::op_rlc_x, /* 0x05 */
&Z80::op_rlc_ihl, /* 0x06 */
&Z80::op_rlc_x, /* 0x07 */
&Z80::op_rrc_x, /* 0x08 */
&Z80::op_rrc_x, /* 0x09 */
&Z80::op_rrc_x, /* 0x0a */
&Z80::op_rrc_x, /* 0x0b */
&Z80::op_rrc_x, /* 0x0c */
&Z80::op_rrc_x, /* 0x0d */
&Z80::op_rrc_ihl, /* 0x0e */
&Z80::op_rrc_x, /* 0x0f */
&Z80::op_rl_x, /* 0x10 */
&Z80::op_rl_x, /* 0x11 */
&Z80::op_rl_x, /* 0x12 */
&Z80::op_rl_x, /* 0x13 */
&Z80::op_rl_x, /* 0x14 */
&Z80::op_rl_x, /* 0x15 */
&Z80::op_rl_ihl, /* 0x16 */
&Z80::op_rl_x, /* 0x17 */
&Z80::op_rr_x, /* 0x18 */
&Z80::op_rr_x, /* 0x19 */
&Z80::op_rr_x, /* 0x1a */
&Z80::op_rr_x, /* 0x1b */
&Z80::op_rr_x, /* 0x1c */
&Z80::op_rr_x, /* 0x1d */
&Z80::op_rr_ihl, /* 0x1e */
&Z80::op_rr_x, /* 0x1f */
&Z80::op_sla_x, /* 0x20 */
&Z80::op_sla_x, /* 0x21 */
&Z80::op_sla_x, /* 0x22 */
&Z80::op_sla_x, /* 0x23 */
&Z80::op_sla_x, /* 0x24 */
&Z80::op_sla_x, /* 0x25 */
&Z80::op_sla_ihl, /* 0x26 */
&Z80::op_sla_x, /* 0x27 */
&Z80::op_sra_x, /* 0x28 */
&Z80::op_sra_x, /* 0x29 */
&Z80::op_sra_x, /* 0x2a */
&Z80::op_sra_x, /* 0x2b */
&Z80::op_sra_x, /* 0x2c */
&Z80::op_sra_x, /* 0x2d */
&Z80::op_sra_ihl, /* 0x2e */
&Z80::op_sra_x, /* 0x2f */
&Z80::op_sll_x, /* 0x30 - undoc */
&Z80::op_sll_x, /* 0x31 - undoc */
&Z80::op_sll_x, /* 0x32 - undoc */
&Z80::op_sll_x, /* 0x33 - undoc */
&Z80::op_sll_x, /* 0x34 - undoc */
&Z80::op_sll_x, /* 0x35 - undoc */
&Z80::op_sll_ihl, /* 0x36 - undoc */
&Z80::op_sll_x, /* 0x37 - undoc */
&Z80::op_srl_x, /* 0x38 */
&Z80::op_srl_x, /* 0x39 */
&Z80::op_srl_x, /* 0x3a */
&Z80::op_srl_x, /* 0x3b */
&Z80::op_srl_x, /* 0x3c */
&Z80::op_srl_x, /* 0x3d */
&Z80::op_srl_ihl, /* 0x3e */
&Z80::op_srl_x, /* 0x3f */
&Z80::op_tb_n_x, /* 0x40 */
&Z80::op_tb_n_x, /* 0x41 */
&Z80::op_tb_n_x, /* 0x42 */
&Z80::op_tb_n_x, /* 0x43 */
&Z80::op_tb_n_x, /* 0x44 */
&Z80::op_tb_n_x, /* 0x45 */
&Z80::op_tb_n_ihl, /* 0x46 */
&Z80::op_tb_n_x, /* 0x47 */
&Z80::op_tb_n_x, /* 0x48 */
&Z80::op_tb_n_x, /* 0x49 */
&Z80::op_tb_n_x, /* 0x4a */
&Z80::op_tb_n_x, /* 0x4b */
&Z80::op_tb_n_x, /* 0x4c */
&Z80::op_tb_n_x, /* 0x4d */
&Z80::op_tb_n_ihl, /* 0x4e */
&Z80::op_tb_n_x, /* 0x4f */
&Z80::op_tb_n_x, /* 0x50 */
&Z80::op_tb_n_x, /* 0x51 */
&Z80::op_tb_n_x, /* 0x52 */
&Z80::op_tb_n_x, /* 0x53 */
&Z80::op_tb_n_x, /* 0x54 */
&Z80::op_tb_n_x, /* 0x55 */
&Z80::op_tb_n_ihl, /* 0x56 */
&Z80::op_tb_n_x, /* 0x57 */
&Z80::op_tb_n_x, /* 0x58 */
&Z80::op_tb_n_x, /* 0x59 */
&Z80::op_tb_n_x, /* 0x5a */
&Z80::op_tb_n_x, /* 0x5b */
&Z80::op_tb_n_x, /* 0x5c */
&Z80::op_tb_n_x, /* 0x5d */
&Z80::op_tb_n_ihl, /* 0x5e */
&Z80::op_tb_n_x, /* 0x5f */
&Z80::op_tb_n_x, /* 0x60 */
&Z80::op_tb_n_x, /* 0x61 */
&Z80::op_tb_n_x, /* 0x62 */
&Z80::op_tb_n_x, /* 0x63 */
&Z80::op_tb_n_x, /* 0x64 */
&Z80::op_tb_n_x, /* 0x65 */
&Z80::op_tb_n_ihl, /* 0x66 */
&Z80::op_tb_n_x, /* 0x67 */
&Z80::op_tb_n_x, /* 0x68 */
&Z80::op_tb_n_x, /* 0x69 */
&Z80::op_tb_n_x, /* 0x6a */
&Z80::op_tb_n_x, /* 0x6b */
&Z80::op_tb_n_x, /* 0x6c */
&Z80::op_tb_n_x, /* 0x6d */
&Z80::op_tb_n_ihl, /* 0x6e */
&Z80::op_tb_n_x, /* 0x6f */
&Z80::op_tb_n_x, /* 0x70 */
&Z80::op_tb_n_x, /* 0x71 */
&Z80::op_tb_n_x, /* 0x72 */
&Z80::op_tb_n_x, /* 0x73 */
&Z80::op_tb_n_x, /* 0x74 */
&Z80::op_tb_n_x, /* 0x75 */
&Z80::op_tb_n_ihl, /* 0x76 */
&Z80::op_tb_n_x, /* 0x77 */
&Z80::op_tb_n_x, /* 0x78 */
&Z80::op_tb_n_x, /* 0x79 */
&Z80::op_tb_n_x, /* 0x7a */
&Z80::op_tb_n_x, /* 0x7b */
&Z80::op_tb_n_x, /* 0x7c */
&Z80::op_tb_n_x, /* 0x7d */
&Z80::op_tb_n_ihl, /* 0x7e */
&Z80::op_tb_n_x, /* 0x7f */
&Z80::op_rb_n_x, /* 0x80 */
&Z80::op_rb_n_x, /* 0x81 */
&Z80::op_rb_n_x, /* 0x82 */
&Z80::op_rb_n_x, /* 0x83 */
&Z80::op_rb_n_x, /* 0x84 */
&Z80::op_rb_n_x, /* 0x85 */
&Z80::op_rb_n_ihl, /* 0x86 */
&Z80::op_rb_n_x, /* 0x87 */
&Z80::op_rb_n_x, /* 0x88 */
&Z80::op_rb_n_x, /* 0x89 */
&Z80::op_rb_n_x, /* 0x8a */
&Z80::op_rb_n_x, /* 0x8b */
&Z80::op_rb_n_x, /* 0x8c */
&Z80::op_rb_n_x, /* 0x8d */
&Z80::op_rb_n_ihl, /* 0x8e */
&Z80::op_rb_n_x, /* 0x8f */
&Z80::op_rb_n_x, /* 0x90 */
&Z80::op_rb_n_x, /* 0x91 */
&Z80::op_rb_n_x, /* 0x92 */
&Z80::op_rb_n_x, /* 0x93 */
&Z80::op_rb_n_x, /* 0x94 */
&Z80::op_rb_n_x, /* 0x95 */
&Z80::op_rb_n_ihl, /* 0x96 */
&Z80::op_rb_n_x, /* 0x97 */
&Z80::op_rb_n_x, /* 0x98 */
&Z80::op_rb_n_x, /* 0x99 */
&Z80::op_rb_n_x, /* 0x9a */
&Z80::op_rb_n_x, /* 0x9b */
&Z80::op_rb_n_x, /* 0x9c */
&Z80::op_rb_n_x, /* 0x9d */
&Z80::op_rb_n_ihl, /* 0x9e */
&Z80::op_rb_n_x, /* 0x9f */
&Z80::op_rb_n_x, /* 0xa0 */
&Z80::op_rb_n_x, /* 0xa1 */
&Z80::op_rb_n_x, /* 0xa2 */
&Z80::op_rb_n_x, /* 0xa3 */
&Z80::op_rb_n_x, /* 0xa4 */
&Z80::op_rb_n_x, /* 0xa5 */
&Z80::op_rb_n_ihl, /* 0xa6 */
&Z80::op_rb_n_x, /* 0xa7 */
&Z80::op_rb_n_x, /* 0xa8 */
&Z80::op_rb_n_x, /* 0xa9 */
&Z80::op_rb_n_x, /* 0xaa */
&Z80::op_rb_n_x, /* 0xab */
&Z80::op_rb_n_x, /* 0xac */
&Z80::op_rb_n_x, /* 0xad */
&Z80::op_rb_n_ihl, /* 0xae */
&Z80::op_rb_n_x, /* 0xaf */
&Z80::op_rb_n_x, /* 0xb0 */
&Z80::op_rb_n_x, /* 0xb1 */
&Z80::op_rb_n_x, /* 0xb2 */
&Z80::op_rb_n_x, /* 0xb3 */
&Z80::op_rb_n_x, /* 0xb4 */
&Z80::op_rb_n_x, /* 0xb5 */
&Z80::op_rb_n_ihl, /* 0xb6 */
&Z80::op_rb_n_x, /* 0xb7 */
&Z80::op_rb_n_x, /* 0xb8 */
&Z80::op_rb_n_x, /* 0xb9 */
&Z80::op_rb_n_x, /* 0xba */
&Z80::op_rb_n_x, /* 0xbb */
&Z80::op_rb_n_x, /* 0xbc */
&Z80::op_rb_n_x, /* 0xbd */
&Z80::op_rb_n_ihl, /* 0xbe */
&Z80::op_rb_n_x, /* 0xbf */
&Z80::op_sb_n_x, /* 0xc0 */
&Z80::op_sb_n_x, /* 0xc1 */
&Z80::op_sb_n_x, /* 0xc2 */
&Z80::op_sb_n_x, /* 0xc3 */
&Z80::op_sb_n_x, /* 0xc4 */
&Z80::op_sb_n_x, /* 0xc5 */
&Z80::op_sb_n_ihl, /* 0xc6 */
&Z80::op_sb_n_x, /* 0xc7 */
&Z80::op_sb_n_x, /* 0xc8 */
&Z80::op_sb_n_x, /* 0xc9 */
&Z80::op_sb_n_x, /* 0xca */
&Z80::op_sb_n_x, /* 0xcb */
&Z80::op_sb_n_x, /* 0xcc */
&Z80::op_sb_n_x, /* 0xcd */
&Z80::op_sb_n_ihl, /* 0xce */
&Z80::op_sb_n_x, /* 0xcf */
&Z80::op_sb_n_x, /* 0xd0 */
&Z80::op_sb_n_x, /* 0xd1 */
&Z80::op_sb_n_x, /* 0xd2 */
&Z80::op_sb_n_x, /* 0xd3 */
&Z80::op_sb_n_x, /* 0xd4 */
&Z80::op_sb_n_x, /* 0xd5 */
&Z80::op_sb_n_ihl, /* 0xd6 */
&Z80::op_sb_n_x, /* 0xd7 */
&Z80::op_sb_n_x, /* 0xd8 */
&Z80::op_sb_n_x, /* 0xd9 */
&Z80::op_sb_n_x, /* 0xda */
&Z80::op_sb_n_x, /* 0xdb */
&Z80::op_sb_n_x, /* 0xdc */
&Z80::op_sb_n_x, /* 0xdd */
&Z80::op_sb_n_ihl, /* 0xde */
&Z80::op_sb_n_x, /* 0xdf */
&Z80::op_sb_n_x, /* 0xe0 */
&Z80::op_sb_n_x, /* 0xe1 */
&Z80::op_sb_n_x, /* 0xe2 */
&Z80::op_sb_n_x, /* 0xe3 */
&Z80::op_sb_n_x, /* 0xe4 */
&Z80::op_sb_n_x, /* 0xe5 */
&Z80::op_sb_n_ihl, /* 0xe6 */
&Z80::op_sb_n_x, /* 0xe7 */
&Z80::op_sb_n_x, /* 0xe8 */
&Z80::op_sb_n_x, /* 0xe9 */
&Z80::op_sb_n_x, /* 0xea */
&Z80::op_sb_n_x, /* 0xeb */
&Z80::op_sb_n_x, /* 0xec */
&Z80::op_sb_n_x, /* 0xed */
&Z80::op_sb_n_ihl, /* 0xee */
&Z80::op_sb_n_x, /* 0xef */
&Z80::op_sb_n_x, /* 0xf0 */
&Z80::op_sb_n_x, /* 0xf1 */
&Z80::op_sb_n_x, /* 0xf2 */
&Z80::op_sb_n_x, /* 0xf3 */
&Z80::op_sb_n_x, /* 0xf4 */
&Z80::op_sb_n_x, /* 0xf5 */
&Z80::op_sb_n_ihl, /* 0xf6 */
&Z80::op_sb_n_x, /* 0xf7 */
&Z80::op_sb_n_x, /* 0xf8 */
&Z80::op_sb_n_x, /* 0xf9 */
&Z80::op_sb_n_x, /* 0xfa */
&Z80::op_sb_n_x, /* 0xfb */
&Z80::op_sb_n_x, /* 0xfc */
&Z80::op_sb_n_x, /* 0xfd */
&Z80::op_sb_n_ihl, /* 0xfe */
&Z80::op_sb_n_x /* 0xff */
};
const Z80::opCodeMethod Z80::op_ed[256] =
{
&Z80::op_ed_nop, /* 0x00 */
&Z80::op_ed_nop, /* 0x01 */
&Z80::op_ed_nop, /* 0x02 */
&Z80::op_ed_nop, /* 0x03 */
&Z80::op_ed_nop, /* 0x04 */
&Z80::op_ed_nop, /* 0x05 */
&Z80::op_ed_nop, /* 0x06 */
&Z80::op_ed_nop, /* 0x07 */
&Z80::op_ed_nop, /* 0x08 */
&Z80::op_ed_nop, /* 0x09 */
&Z80::op_ed_nop, /* 0x0a */
&Z80::op_ed_nop, /* 0x0b */
&Z80::op_ed_nop, /* 0x0c */
&Z80::op_ed_nop, /* 0x0d */
&Z80::op_ed_nop, /* 0x0e */
&Z80::op_ed_nop, /* 0x0f */
&Z80::op_ed_nop, /* 0x10 */
&Z80::op_ed_nop, /* 0x11 */
&Z80::op_ed_nop, /* 0x12 */
&Z80::op_ed_nop, /* 0x13 */
&Z80::op_ed_nop, /* 0x14 */
&Z80::op_ed_nop, /* 0x15 */
&Z80::op_ed_nop, /* 0x16 */
&Z80::op_ed_nop, /* 0x17 */
&Z80::op_ed_nop, /* 0x18 */
&Z80::op_ed_nop, /* 0x19 */
&Z80::op_ed_nop, /* 0x1a */
&Z80::op_ed_nop, /* 0x1b */
&Z80::op_ed_nop, /* 0x1c */
&Z80::op_ed_nop, /* 0x1d */
&Z80::op_ed_nop, /* 0x1e */
&Z80::op_ed_nop, /* 0x1f */
&Z80::op_ed_nop, /* 0x20 */
&Z80::op_ed_nop, /* 0x21 */
&Z80::op_ed_nop, /* 0x22 */
&Z80::op_ed_nop, /* 0x23 */
&Z80::op_ed_nop, /* 0x24 */
&Z80::op_ed_nop, /* 0x25 */
&Z80::op_ed_nop, /* 0x26 */
&Z80::op_ed_nop, /* 0x27 */
&Z80::op_ed_nop, /* 0x28 */
&Z80::op_ed_nop, /* 0x29 */
&Z80::op_ed_nop, /* 0x2a */
&Z80::op_ed_nop, /* 0x2b */
&Z80::op_ed_nop, /* 0x2c */
&Z80::op_ed_nop, /* 0x2d */
&Z80::op_ed_nop, /* 0x2e */
&Z80::op_ed_nop, /* 0x2f */
&Z80::op_ed_nop, /* 0x30 */
&Z80::op_ed_nop, /* 0x31 */
&Z80::op_ed_nop, /* 0x32 */
&Z80::op_ed_nop, /* 0x33 */
&Z80::op_ed_nop, /* 0x34 */
&Z80::op_ed_nop, /* 0x35 */
&Z80::op_ed_nop, /* 0x36 */
&Z80::op_ed_nop, /* 0x37 */
&Z80::op_ed_nop, /* 0x38 */
&Z80::op_ed_nop, /* 0x39 */
&Z80::op_ed_nop, /* 0x3a */
&Z80::op_ed_nop, /* 0x3b */
&Z80::op_ed_nop, /* 0x3c */
&Z80::op_ed_nop, /* 0x3d */
&Z80::op_ed_nop, /* 0x3e */
&Z80::op_ed_nop, /* 0x3f */
&Z80::op_in_x_c, /* 0x40 -- */
&Z80::op_out_c_x, /* 0x41 -- */
&Z80::op_sbc_hl_xx, /* 0x42 -- */
&Z80::op_ld_inn_xx, /* 0x43 -- */
&Z80::op_neg, /* 0x44 -- */
&Z80::op_retn, /* 0x45 -- */
&Z80::op_im0, /* 0x46 -- */
&Z80::op_ld_i_a, /* 0x47 -- */
&Z80::op_in_x_c, /* 0x48 -- */
&Z80::op_out_c_x, /* 0x49 -- */
&Z80::op_adc_hl_xx, /* 0x4a -- */
&Z80::op_ld_xx_inn, /* 0x4b -- */
&Z80::op_neg, /* 0x4c undoc */
&Z80::op_reti, /* 0x4d -- */
&Z80::op_im0, /* 0x4e undoc */
&Z80::op_ld_r_a, /* 0x4f -- */
&Z80::op_in_x_c, /* 0x50 -- */
&Z80::op_out_c_x, /* 0x51 -- */
&Z80::op_sbc_hl_xx, /* 0x52 -- */
&Z80::op_ld_inn_xx, /* 0x53 -- */
&Z80::op_neg, /* 0x54 undoc */
&Z80::op_retn, /* 0x55 undoc */
&Z80::op_im1, /* 0x56 -- */
&Z80::op_ld_a_i, /* 0x57 -- */
&Z80::op_in_x_c, /* 0x58 -- */
&Z80::op_out_c_x, /* 0x59 -- */
&Z80::op_adc_hl_xx, /* 0x5a -- */
&Z80::op_ld_xx_inn, /* 0x5b -- */
&Z80::op_neg, /* 0x5c undoc */
&Z80::op_retn, /* 0x5d undoc */
&Z80::op_im2, /* 0x5e -- */
&Z80::op_ld_a_r, /* 0x5f -- */
&Z80::op_in_x_c, /* 0x60 -- */
&Z80::op_out_c_x, /* 0x61 -- */
&Z80::op_sbc_hl_xx, /* 0x62 -- */
&Z80::op_ld_inn_xx, /* 0x63 -- */
&Z80::op_neg, /* 0x64 undoc */
&Z80::op_retn, /* 0x65 undoc */
&Z80::op_im0, /* 0x66 undoc */
&Z80::op_rrd_ihl, /* 0x67 -- */
&Z80::op_in_x_c, /* 0x68 -- */
&Z80::op_out_c_x, /* 0x69 -- */
&Z80::op_adc_hl_xx, /* 0x6a -- */
&Z80::op_ld_xx_inn, /* 0x6b -- */
&Z80::op_neg, /* 0x6c undoc */
&Z80::op_retn, /* 0x6d undoc */
&Z80::op_im0, /* 0x6e undoc */
&Z80::op_rld_ihl, /* 0x6f -- */
&Z80::op_in_f_ic, /* 0x70 -- */
&Z80::op_out_c_0, /* 0x71 undoc */
&Z80::op_sbc_hl_xx, /* 0x72 -- */
&Z80::op_ld_inn_xx, /* 0x73 -- */
&Z80::op_neg, /* 0x74 undoc */
&Z80::op_retn, /* 0x75 undoc */
&Z80::op_im1, /* 0x76 undoc */
&Z80::op_ed_nop, /* 0x77 undoc */
&Z80::op_in_x_c, /* 0x78 -- */
&Z80::op_out_c_x, /* 0x79 -- */
&Z80::op_adc_hl_xx, /* 0x7a -- */
&Z80::op_ld_xx_inn, /* 0x7b -- */
&Z80::op_neg, /* 0x7c undoc */
&Z80::op_retn, /* 0x7d undoc */
&Z80::op_im2, /* 0x7e undoc */
&Z80::op_ed_nop, /* 0x7f undoc */
&Z80::op_ed_nop, /* 0x80 */
&Z80::op_ed_nop, /* 0x81 */
&Z80::op_ed_nop, /* 0x82 */
&Z80::op_ed_nop, /* 0x83 */
&Z80::op_ed_nop, /* 0x84 */
&Z80::op_ed_nop, /* 0x85 */
&Z80::op_ed_nop, /* 0x86 */
&Z80::op_ed_nop, /* 0x87 */
&Z80::op_ed_nop, /* 0x88 */
&Z80::op_ed_nop, /* 0x89 */
&Z80::op_ed_nop, /* 0x8a */
&Z80::op_ed_nop, /* 0x8b */
&Z80::op_ed_nop, /* 0x8c */
&Z80::op_ed_nop, /* 0x8d */
&Z80::op_ed_nop, /* 0x8e */
&Z80::op_ed_nop, /* 0x8f */
&Z80::op_ed_nop, /* 0x90 */
&Z80::op_ed_nop, /* 0x91 */
&Z80::op_ed_nop, /* 0x92 */
&Z80::op_ed_nop, /* 0x93 */
&Z80::op_ed_nop, /* 0x94 */
&Z80::op_ed_nop, /* 0x95 */
&Z80::op_ed_nop, /* 0x96 */
&Z80::op_ed_nop, /* 0x97 */
&Z80::op_ed_nop, /* 0x98 */
&Z80::op_ed_nop, /* 0x99 */
&Z80::op_ed_nop, /* 0x9a */
&Z80::op_ed_nop, /* 0x9b */
&Z80::op_ed_nop, /* 0x9c */
&Z80::op_ed_nop, /* 0x9d */
&Z80::op_ed_nop, /* 0x9e */
&Z80::op_ed_nop, /* 0x9f */
&Z80::op_ldi, /* 0xa0 -- */
&Z80::op_cpi, /* 0xa1 -- */
&Z80::op_ini, /* 0xa2 -- */
&Z80::op_outi, /* 0xa3 -- */
&Z80::op_ed_nop, /* 0xa4 */
&Z80::op_ed_nop, /* 0xa5 */
&Z80::op_ed_nop, /* 0xa6 */
&Z80::op_ed_nop, /* 0xa7 */
&Z80::op_ldd, /* 0xa8 -- */
&Z80::op_cpd, /* 0xa9 -- */
&Z80::op_ind, /* 0xaa -- */
&Z80::op_outd, /* 0xab -- */
&Z80::op_ed_nop, /* 0xac */
&Z80::op_ed_nop, /* 0xad */
&Z80::op_ed_nop, /* 0xae */
&Z80::op_ed_nop, /* 0xaf */
&Z80::op_ldir, /* 0xb0 -- */
&Z80::op_cpir, /* 0xb1 -- */
&Z80::op_inir, /* 0xb2 -- */
&Z80::op_otir, /* 0xb3 -- */
&Z80::op_ed_nop, /* 0xb4 */
&Z80::op_ed_nop, /* 0xb5 */
&Z80::op_ed_nop, /* 0xb6 */
&Z80::op_ed_nop, /* 0xb7 */
&Z80::op_lddr, /* 0xb8 -- */
&Z80::op_cpdr, /* 0xb9 -- */
&Z80::op_indr, /* 0xba -- */
&Z80::op_otdr, /* 0xbb -- */
&Z80::op_ed_nop, /* 0xbc */
&Z80::op_ed_nop, /* 0xbd */
&Z80::op_ed_nop, /* 0xbe */
&Z80::op_ed_nop, /* 0xbf */
&Z80::op_ed_nop, /* 0xc0 */
&Z80::op_ed_nop, /* 0xc1 */
&Z80::op_ed_nop, /* 0xc2 */
&Z80::op_ed_nop, /* 0xc3 */
&Z80::op_ed_nop, /* 0xc4 */
&Z80::op_ed_nop, /* 0xc5 */
&Z80::op_ed_nop, /* 0xc6 */
&Z80::op_ed_nop, /* 0xc7 */
&Z80::op_ed_nop, /* 0xc8 */
&Z80::op_ed_nop, /* 0xc9 */
&Z80::op_ed_nop, /* 0xca */
&Z80::op_ed_nop, /* 0xcb */
&Z80::op_ed_nop, /* 0xcc */
&Z80::op_ed_nop, /* 0xcd */
&Z80::op_ed_nop, /* 0xce */
&Z80::op_ed_nop, /* 0xcf */
&Z80::op_ed_nop, /* 0xd0 */
&Z80::op_ed_nop, /* 0xd1 */
&Z80::op_ed_nop, /* 0xd2 */
&Z80::op_ed_nop, /* 0xd3 */
&Z80::op_ed_nop, /* 0xd4 */
&Z80::op_ed_nop, /* 0xd5 */
&Z80::op_ed_nop, /* 0xd6 */
&Z80::op_ed_nop, /* 0xd7 */
&Z80::op_ed_nop, /* 0xd8 */
&Z80::op_ed_nop, /* 0xd9 */
&Z80::op_ed_nop, /* 0xda */
&Z80::op_ed_nop, /* 0xdb */
&Z80::op_ed_nop, /* 0xdc */
&Z80::op_ed_nop, /* 0xdd */
&Z80::op_ed_nop, /* 0xde */
&Z80::op_ed_nop, /* 0xdf */
&Z80::op_ed_nop, /* 0xe0 */
&Z80::op_ed_nop, /* 0xe1 */
&Z80::op_ed_nop, /* 0xe2 */
&Z80::op_ed_nop, /* 0xe3 */
&Z80::op_ed_nop, /* 0xe4 */
&Z80::op_ed_nop, /* 0xe5 */
&Z80::op_ed_nop, /* 0xe6 */
&Z80::op_ed_nop, /* 0xe7 */
&Z80::op_ed_nop, /* 0xe8 */
&Z80::op_ed_nop, /* 0xe9 */
&Z80::op_ed_nop, /* 0xea */
&Z80::op_ed_nop, /* 0xeb */
&Z80::op_ed_nop, /* 0xec */
&Z80::op_ed_nop, /* 0xed */
&Z80::op_ed_nop, /* 0xee */
&Z80::op_ed_nop, /* 0xef */
&Z80::op_ed_nop, /* 0xf0 */
&Z80::op_ed_nop, /* 0xf1 */
&Z80::op_ed_nop, /* 0xf2 */
&Z80::op_ed_nop, /* 0xf3 */
&Z80::op_ed_nop, /* 0xf4 */
&Z80::op_ed_nop, /* 0xf5 */
&Z80::op_ed_nop, /* 0xf6 */
&Z80::op_ed_nop, /* 0xf7 */
&Z80::op_ed_nop, /* 0xf8 */
&Z80::op_ed_nop, /* 0xf9 */
&Z80::op_ed_nop, /* 0xfa */
&Z80::op_ed_nop, /* 0xfb */
&Z80::op_ed_nop, /* 0xfc */
&Z80::op_ed_nop, /* 0xfd */
&Z80::op_ed_nop, /* 0xfe */
&Z80::op_ed_nop /* 0xff */
};
const Z80::opCodeMethod Z80::op_xxcb[32] =
{
&Z80::op_rlc_xx_d, /* 0x06 */
&Z80::op_rrc_xx_d, /* 0x0e */
&Z80::op_rl_xx_d, /* 0x16 */
&Z80::op_rr_xx_d, /* 0x1e */
&Z80::op_sla_xx_d, /* 0x26 */
&Z80::op_sra_xx_d, /* 0x2e */
&Z80::op_sll_xx_d, /* 0x36 */
&Z80::op_srl_xx_d, /* 0x3e */
&Z80::op_tb_n_xx_d, /* 0x46 */
&Z80::op_tb_n_xx_d, /* 0x4e */
&Z80::op_tb_n_xx_d, /* 0x56 */
&Z80::op_tb_n_xx_d, /* 0x5e */
&Z80::op_tb_n_xx_d, /* 0x66 */
&Z80::op_tb_n_xx_d, /* 0x6e */
&Z80::op_tb_n_xx_d, /* 0x76 */
&Z80::op_tb_n_xx_d, /* 0x7e */
&Z80::op_rb_n_xx_d, /* 0x86 */
&Z80::op_rb_n_xx_d, /* 0x8e */
&Z80::op_rb_n_xx_d, /* 0x96 */
&Z80::op_rb_n_xx_d, /* 0x9e */
&Z80::op_rb_n_xx_d, /* 0xa6 */
&Z80::op_rb_n_xx_d, /* 0xae */
&Z80::op_rb_n_xx_d, /* 0xb6 */
&Z80::op_rb_n_xx_d, /* 0xbe */
&Z80::op_sb_n_xx_d, /* 0xc6 */
&Z80::op_sb_n_xx_d, /* 0xce */
&Z80::op_sb_n_xx_d, /* 0xd6 */
&Z80::op_sb_n_xx_d, /* 0xde */
&Z80::op_sb_n_xx_d, /* 0xe6 */
&Z80::op_sb_n_xx_d, /* 0xee */
&Z80::op_sb_n_xx_d, /* 0xf6 */
&Z80::op_sb_n_xx_d /* 0xfe */
};
inline BYTE
Z80::readInst(void)
{
ticks -= 4;
BYTE val = ab_m->readByte(PC, processingIntr);
if (!processingIntr)
{
++PC;
}
R++; // increment refresh register
return val;
};
inline BYTE
Z80::readMEM(WORD addr)
{
ticks -= 3;
return (ab_m->readByte(addr));
};
inline void
Z80::writeMEM(WORD addr,
BYTE val)
{
ab_m->writeByte(addr, val);
ticks -= 3;
};
inline WORD
Z80::readWord(WORD addr)
{
return ((readMEM(addr + 1) << 8) | readMEM(addr));
}
inline void
Z80::writeWord(WORD addr,
WORD value)
{
writeMEM(addr++, value & 0xff);
writeMEM(addr, value >> 8);
}
inline BYTE
Z80::READn(void)
{
return (readMEM(PC++));
};
inline SBYTE
Z80::sREADn(void)
{
return ((SBYTE) readMEM(PC++));
};
inline WORD
Z80::READnn(void)
{
PC += 2;
return ((readMEM(PC - 1) << 8) | readMEM(PC - 2));
};
inline BYTE&
Z80::getReg8(BYTE val)
{
switch (val & 0x7)
{
case 0:
return (B);
case 1:
return (C);
case 2:
return (D);
case 3:
return (E);
case 4:
switch (prefix)
{
case ip_dd:
return (IXh);
case ip_fd:
return (IYh);
case ip_none:
default:
return (H);
}
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (W);
case 5:
switch (prefix)
{
case ip_dd:
return (IXl);
case ip_fd:
return (IYl);
case ip_none:
default:
return (L);
}
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (Z);
case 6:
// Should never be called in with this value.
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (Z);
case 7:
return (A);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (Z);
}
inline BYTE&
Z80::getCoreReg8(BYTE val)
{
switch (val & 0x7)
{
case 0:
return (B);
case 1:
return (C);
case 2:
return (D);
case 3:
return (E);
case 4:
return (H);
case 5:
return (L);
case 6:
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (Z);
case 7:
return (A);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x7)
assert(0);
return (Z);
}
inline BYTE
Z80::getReg8Val(BYTE val)
{
return (getReg8(val));
}
inline BYTE
Z80::getCoreReg8Val(BYTE val)
{
return (getCoreReg8(val));
}
// Register related
inline WORD&
Z80::getReg16(BYTE val)
{
switch (val & 0x3)
{
case 0:
return (BC);
case 1:
return (DE);
case 2:
switch (prefix)
{
case ip_dd:
return (IX);
case ip_fd:
return (IY);
case ip_none:
default:
return (HL);
}
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x3)
assert(0);
return (WZ);
case 3:
return (SP);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x3)
assert(0);
return (WZ);
}
inline WORD&
Z80::getCoreReg16(BYTE val)
{
switch (val & 0x3)
{
case 0:
return (BC);
case 1:
return (DE);
case 2:
return (HL);
case 3:
return (SP);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 0x3)
assert(0);
return (WZ);
}
inline WORD&
Z80::getHLReg16(void)
{
switch (prefix)
{
case ip_dd:
return (IX);
case ip_fd:
return (IY);
case ip_none:
default:
return (HL);
}
}
inline WORD
Z80::getXYReg16Val(void)
{
switch (prefix)
{
case ip_dd:
return (IX);
case ip_fd:
return (IY);
case ip_none:
break;
}
// should not have been called.
debugss(ssZ80, FATAL, "Invalid prefix mode")
assert(0);
return (WZ);
}
inline WORD
Z80::getIndirectAddr(void)
{
switch (prefix)
{
case ip_dd:
return (IX + sREADn());
case ip_fd:
return (IY + sREADn());
case ip_none:
default:
return (HL);
}
}
inline WORD
Z80::getHLReg16Val(void)
{
return (getHLReg16());
}
inline WORD
Z80::getReg16Val(BYTE val)
{
return (getReg16(val));
}
inline WORD
Z80::getCoreReg16Val(BYTE val)
{
return (getCoreReg16(val));
}
inline WORD&
Z80::getReg16qq(BYTE val)
{
switch (val & 0x3)
{
case 0:
return (BC);
case 1:
return (DE);
case 2:
switch (prefix)
{
case ip_dd:
return (IX);
case ip_fd:
return (IY);
case ip_none:
default:
return (HL);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 3)
assert(0);
return (WZ);
case 3:
return (AF);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 3)
assert(0);
return (WZ);
}
inline WORD&
Z80::getCoreReg16qq(BYTE val)
{
switch (val & 0x3)
{
case 0:
return (BC);
case 1:
return (DE);
case 2:
return (HL);
case 3:
return (AF);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown reg: %d", val & 3)
assert(0);
return (WZ);
}
inline WORD
Z80::getReg16qqVal(BYTE val)
{
return (getReg16qq(val));
}
inline WORD
Z80::getCoreReg16qqVal(BYTE val)
{
return (getCoreReg16qq(val));
}
inline BYTE
Z80::getBit(BYTE val)
{
return (1 << ((val >> 3) & 0x7));
}
inline bool
Z80::checkCondition(BYTE val)
{
switch ((val >> 3) & 0x7)
{
case 0: // NZ non-zero
return ((F & Z_FLAG) == 0);
case 1: // Z zero
return ((F & Z_FLAG) != 0);
case 2: // NC no carry
return ((F & C_FLAG) == 0);
case 3: // C carry
return ((F & C_FLAG) != 0);
case 4: // PO parity odd
return ((F & P_FLAG) == 0);
case 5: // PE parity even
return ((F & P_FLAG) != 0);
case 6: // P sign positive
return ((F & S_FLAG) == 0);
case 7: // M sign negative
return ((F & S_FLAG) != 0);
}
// All cases are handled above, can never get to this point, but to quiet the compiler
debugss(ssZ80, FATAL, "Unknown cond: %d", (val >> 3) & 7);
assert(0);
return (false);
}
// Routines related to the stack.
inline void
Z80::PUSH(WORD x)
{
writeMEM(--SP, x >> 8);
writeMEM(--SP, x & 0xff);
};
inline void
Z80::POP(WORD& x)
{
x = (readMEM(SP + 1) << 8) | readMEM(SP);
SP += 2;
};
// Routines related to FLAGS.
inline void
Z80::SET_FLAGS(BYTE flags)
{
F |= flags;
};
inline void
Z80::CLEAR_FLAGS(BYTE flags)
{
F &= ~flags;
};
inline void
Z80::UPDATE_FLAGS(BYTE setFlags,
BYTE clearFlags)
{
F = (F & ~clearFlags) | setFlags;
}
inline bool
Z80::CHECK_FLAGS(BYTE flags)
{
return ((F & flags) != 0);
};
inline void
Z80::COND_FLAGS(bool cond,
BYTE flags)
{
if (cond)
{
SET_FLAGS(flags);
}
else
{
CLEAR_FLAGS(flags);
}
};
///
/// \brief update the Z, S, and P flags
///
/// Implemented as a table look-up and bit-mask
///
/// @param val Byte value to base flags on
///
inline void
Z80::SET_ZSP_FLAGS(BYTE val)
{
// Mask off the bits.
CLEAR_FLAGS(Z_FLAG | S_FLAG | P_FLAG);
// Set bits from pre-generated table
F |= ZSP[val];
};
///
/// @param clockRate Speed of the Z80 in cycles per second.
/// @param ticksPerSecond Number of interrupts per second for the clock
///
Z80::Z80(Computer* computer,
int clockRate,
int ticksPerSecond): CPU(),
GppListener(z80_gppSpeedSelBit_c),
computer_m(computer),
A(af.hi),
sA(af.shi),
F(af.lo),
AF(af.val),
B(bc.hi),
C(bc.lo),
BC(bc.val),
D(de.hi),
E(de.lo),
DE(de.val),
H(hl.hi),
L(hl.lo),
HL(hl.val),
sHL(hl.sval),
W(wz.hi),
sW(wz.shi),
Z(wz.lo),
WZ(wz.val),
IXl(ix.lo),
IXh(ix.hi),
IX(ix.val),
IYl(iy.lo),
IYh(iy.hi),
IY(iy.val),
SP(sp.val),
processingIntr(false),
ticks(0),
lastInstTicks(0),
curInstByte(0),
mode(cm_reset),
prefix(ip_none),
speedUpFactor_m(40),
fast_m(false),
IM(0)
{
debugss(ssZ80, INFO, "Creating Z80 proc, clock (%d), ticks(%d)\n", clockRate, ticksPerSecond);
if ((clockRate) && (ticksPerSecond))
{
ticksPerClock_m = clockRate / ticksPerSecond;
ClockRate_m = clockRate;
ticksPerSecond_m = ticksPerSecond;
}
else
{
// Assume a 4MHz processor with a 10ms clock interrupt.
debugss(ssZ80, WARNING, "invalid parameters setting default\n");
ClockRate_m = 4000000;
ticksPerSecond_m = 100;
ticksPerClock_m = 40000;
}
WallClock::instance()->updateTicksPerSecond(ClockRate_m);
reset();
}
///
///
///
Z80::~Z80()
{
debugss(ssZ80, INFO, "\n");
}
///
/// Reset the state of the Z80 CPU.
///
/// \todo - Complete the reset implementation.
///
void
Z80::reset(void)
{
debugss(ssZ80, INFO, "\n");
PC = 0;
R = 0;
Rprime = 0;
I = 0;
IFF0 = IFF1 = IFF2 = false;
IM = 0;
// according to (modern) Z80 documentation, only the above registers
// are affected by RESET.
AF = SP = 0xffff;
prefix = ip_none;
curInstByte = 0;
lastInstTicks = 0;
int_type = 0;
mode = cm_running;
ticks = 0;
fast_m = false;
// TODO: reset speedup...
addClockTicks();
}
///
/// Provides the CPU with an addition amount of cpu cycles.
///
void
Z80::addClockTicks()
{
// if ticks is negative, add the new quota.
if (ticks < 0)
{
debugss(ssZ80, ALL, "ticks(%d) += ticksPerClock(%lu)\n", ticks, ticksPerClock_m);
ticks += ticksPerClock_m;
}
else
{
// else just set it, otherwise we run the risk of accumulating too many ticks if
// the CPU was idle waiting for input.
debugss(ssZ80, ALL, "ticks(%d) = ticksPerClock(%lu)\n", ticks, ticksPerClock_m);
ticks = (sig_atomic_t) ticksPerClock_m;
}
lastInstTicks = ticks;
}
void
Z80::setSpeedup(int factor) {
speedUpFactor_m = factor;
}
void
Z80::enableFast() {
GppListener::addListener(this);
}
void
Z80::gppNewValue(BYTE gpo) {
fast_m = ((gpo & z80_gppSpeedSelBit_c) != 0);
debugss(ssZ80, WARNING, "fast_m = %d\n", fast_m);
if (fast_m)
{
if (ticks > 0)
{
ticks *= speedUpFactor_m;
lastInstTicks = ticks;
}
ClockRate_m = 2048000 * speedUpFactor_m;
ticksPerClock_m = ClockRate_m / ticksPerSecond_m;
}
else
{
if (ticks > 0)
{
ticks /= speedUpFactor_m;
lastInstTicks = ticks;
}
ClockRate_m = 2048000;
ticksPerClock_m = ClockRate_m / ticksPerSecond_m;
}
WallClock::instance()->updateTicksPerSecond(ClockRate_m);
}
///
/// Raise the non-maskable interrupt.
///
void
Z80::raiseNMI(void)
{
debugss(ssZ80, VERBOSE, "\n");
int_type |= Intr_NMI;
}
///
/// Raise interrupt line
///
void
Z80::raiseINT()
{
debugss(ssZ80, VERBOSE, "\n");
if (!IFF1)
{
debugss(ssZ80, INFO, "interrupt raised, but currently disabled\n");
}
int_type |= Intr_INT;
}
///
/// Lower interrupt line
///
void
Z80::lowerINT()
{
debugss(ssZ80, VERBOSE, "\n");
int_type &= ~Intr_INT;
}
void
Z80::continueRunning(void)
{
mode = cm_running;
}
void
Z80::waitState(void)
{
WallClock::instance()->addTicks(1);
// TODO: anything else needs to make progress?
}
///
/// Links the address bus object to the virtual CPU.
///
/// @param ab pointer to the address bus object.
///
void
Z80::setAddressBus(AddressBus* ab)
{
debugss(ssZ80, INFO, "Entering\n");
ab_m = ab;
}
void
Z80::setIOBus(IOBus* io)
{
debugss(ssZ80, INFO, "Entering\n");
io_m = io;
}
void
Z80::traceInstructions(void)
{
if (chkdebuglevel(ssZ80, ERROR))
{
debugss(ssZ80, ERROR, "0x%04x(%03o.%03o) %04x %04x %04x %04x %04x : ",
PC, (PC >> 8) & 0xff, (PC & 0xff), AF, BC, DE, HL, SP);
if (mode == cm_halt)
{
debugss_nts(ssZ80, ERROR, "Halted\n");
}
else
{
disass(PC);
}
}
}
/// Single step the virtual CPU
///
/// \retval result of the executed instruction.
///
BYTE
Z80::step(void)
{
//
cpu_state = SINGLE_STEP_C;
return (execute(1));
}
// This is only used by the execute() thread.
void
Z80::systemMutexCycle()
{
computer_m->systemMutexRelease();
// If someone else is waiting, they should get the mutex now.
computer_m->systemMutexAcquire();
}
string
Z80::dumpDebug()
{
string ret = PropertyUtil::sprintf(
"A=%02x PSW=%s %s %s %s %s %s %s %s AF'=%04x\n"
"BC=%04x BC'=%04x\n"
"DE=%04x DE'=%04x\n"
"HL=%04x HL'=%04x\n"
"PC=%04x SP=%04x\n"
" executing: %02x %02x %02x %02x\n"
"IX=%04x IY=%04x mode=%s\n"
"R=%02x I=%02x IFF0=%d IFF1=%d IFF2=%d INT=%d NMI=%d\n",
A,
(F & S_FLAG) ? "S" : "s",
(F & Z_FLAG) ? "Z" : "z",
(F & N2_FLAG) ? "N2" : "n2",
(F & H_FLAG) ? "H" : "h",
(F & N1_FLAG) ? "N1" : "n1",
(F & P_FLAG) ? "P" : "p",
(F & N_FLAG) ? "N" : "n",
(F & C_FLAG) ? "C" : "c",
_af,
BC, _bc, DE, _de, HL, _hl,
PC, SP,
ab_m->readByte(PC + 0),
ab_m->readByte(PC + 1),
ab_m->readByte(PC + 2),
ab_m->readByte(PC + 3),
IX, IY,
(mode == cm_halt ? "halt" :
(mode == cm_running ? "run" :
(mode == cm_reset ? "reset" :
(mode == cm_singleStep ? "sstep" : "?")))),
R & 0xff, I, IFF0, IFF1, IFF2,
((int_type & Intr_INT) != 0),
((int_type & Intr_NMI) != 0));
return ret;
}
///
/// This function builds the Z80 central processing unit.
/// The opcode where PC points to is fetched from the memory
/// and PC incremented by one. The opcode is used as an
/// index to an array with function pointers, to execute a
/// function which emulates this Z80 opcode.
///
/// @param numInst Number of instructions to run. A value of zero implies
/// infinite number of instructions.
///
/// \retval number of cycles instruction took to execute.
///
BYTE
Z80::execute(WORD numInst)
{
bool limited = (numInst != 0);
cpu_state = RUN_C;
computer_m->systemMutexAcquire();
do
{
systemMutexCycle();
if (mode == cm_reset)
{
// any local variables need resetting?
mode = cm_running;
}
prefix = ip_none;
curInstByte = 0;
lastInstByte = 0;
#ifdef FRONTPANEL /* update frontpanel */
fp_led_address = PC;
fp_led_data = ram[PC];
fp_sampleData();
#endif
#ifdef HISIZE /* write history */
his[h_next].h_adr = PC;
his[h_next].h_af = REG_PAIR(A, F);
his[h_next].h_bc = REG_PAIR(B, C);
his[h_next].h_de = REG_PAIR(D, E);
his[h_next].h_hl = REG_PAIR(H, L);
his[h_next].h_ix = IX;
his[h_next].h_iy = IY;
his[h_next].h_sp = SP;
h_next++;
if (h_next == HISIZE)
{
h_flag = 1;
h_next = 0;
}
#endif
// CPU interrupt handling
//
if (int_type & Intr_NMI)
{
debugss(ssZ80, VERBOSE, "NMI Raised\n");
int_type &= ~Intr_NMI;
IFF0 = IFF1 = false;
PUSH(PC);
PC = 0x66;
mode = cm_running;
R++; // increment refresh register
ticks -= 11;
}
else if ((int_type & Intr_INT) && (IFF1))
{
// ISR required to enable interrupts (EI).
IFF2 = IFF1 = IFF0 = false;
mode = cm_running;
R++; // increment refresh register
switch (IM)
{
case 0:
debugss(ssZ80, VERBOSE, "Processing interrupt mode 0\n");
ticks -= 2;
processingIntr = true;
break;
case 1:
debugss(ssZ80, VERBOSE, "Processing interrupt mode 1\n");
int_type &= ~Intr_INT;
lastInstByte = 0xff;
op_rst();
ticks -= 2;
break;
case 2:
// mode 2 not currently supported.
debugss(ssZ80, FATAL, "Interrupt mode 2 not supported\n");
/// \todo assert
break;
default:
debugss(ssZ80, FATAL, "Invalid Interrupt Mode: %d\n", IM);
/// \todo assert
}
}
IFF1 = IFF0;
#if TEN_X_SLOWER
traceInstructions();
#endif
// check to see if the clock has any ticks left
if (ticks <= 0)
{
// No virtual time left in this timer tick, wait for the next one.
static struct timespec sp;
static struct timespec act;
// Can over-shoot the time to sleep, the timer interrupt will wake
// CPU at the correct time.
sp.tv_sec = 1;
sp.tv_nsec = 0;
computer_m->systemMutexRelease();
nanosleep(&sp, &act);
computer_m->systemMutexAcquire();
continue;
}
// If in halt, we just do a NOP, without any PC changes.
if (mode == cm_halt)
{
// use up 4 clocks
ticks -= 4;
// store current timestamp
lastInstTicks = ticks;
// inform any devices wanting clock info
WallClock::instance()->addTicks(4);
continue;
}
lastInstByte = curInst[0] = readInst();
(this->*op_code[curInst[0]])();
unsigned int val = lastInstTicks - ticks;
lastInstTicks = ticks;
WallClock::instance()->addTicks(val);
#ifdef WANT_GUI
check_gui_break();
#endif
if ((cpu_state == RUN_C) && (limited) && (--numInst == 0))
{
cpu_state = SINGLE_STEP_C;
}
processingIntr = false;
}
while (cpu_state == RUN_C);
computer_m->systemMutexRelease();
return (0);
}
///
/// \brief No Operation
///
/// \details No operation
///
/// Operation: -
///
/// Opcode: NOP
///
/// Binary | Hex
/// ----------|-------
/// 00000000 | 0x00
///
/// Description: The CPU performs no operation during this machine cycle.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: None
///
///
/// \retval none
///
void
Z80::op_nop(void)
{
}
///
/// \brief Halt
///
/// \details Halts the CPU
///
/// Operation: -
///
/// Opcode: HALT
///
/// Binary | Hex
/// ----------|-------
/// 01110110 | 0x76
///
/// Description: The HALT instruction suspends CPU operation until a subsequent interrupt
/// or reset is received. While in the HALT state, the processor executes NOPs
/// to maintain memory refresh logic.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|-----------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_halt(void)
{
debugss(ssZ80, VERBOSE, "iff1 %d iff2 %d\n", IFF1, IFF2);
mode = cm_halt;
}
///
/// \brief Set Carry Flag
///
/// \details
/// Operation: CY <- 1
///
/// Opcode: SCF
///
/// Binary | Hex
/// ----------|-------
/// 00110111 | 0x37
///
/// Description: The Carry flag in the F register is set.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is reset
/// * P/V is not affected
/// * N is reset
/// * C is set
///
/// \retval none
///
void
Z80::op_scf(void)
{
SET_FLAGS(C_FLAG);
CLEAR_FLAGS(N_FLAG | H_FLAG);
}
///
/// \brief Complement Carry Flag
///
/// Operation: CY <- !CY
///
/// Opcode: CCF
///
/// Binary | Hex
/// ----------|-------
/// 00110111 | 0x37
///
/// Description: The Carry flag in the F register is inverted.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H previous carry is copied
/// * P/V is not affected
/// * N is reset
/// * C is set if CY was 0 before operation; reset otherwise
///
/// \retval none
///
void
Z80::op_ccf(void)
{
if (CHECK_FLAGS(C_FLAG))
{
SET_FLAGS(H_FLAG);
CLEAR_FLAGS(C_FLAG);
}
else
{
CLEAR_FLAGS(H_FLAG);
SET_FLAGS(C_FLAG);
}
CLEAR_FLAGS(N_FLAG);
}
///
/// \brief Complement Accumulator
///
///
/// Operation: A <- !A
///
/// Opcode: CPL
///
/// Binary | Hex
/// ----------|-------
/// 00101111 | 0x2F
///
/// Description: The contents of the Accumulator (register A) are inverted (one's
/// complement).
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|-------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is set
/// * P/V is not affected
/// * N is set
/// * C is not affected
///
/// \retval none
///
void
Z80::op_cpl(void)
{
A = ~A;
SET_FLAGS(H_FLAG | N_FLAG);
}
///
/// \brief Decimal Adjust AL (DAA)
///
/// Operation:
///
/// Opcode: DAA
///
/// Binary | Hex
/// ----------|-------
/// 00100111 | 0x27
///
/// Description: This instruction conditionally adjusts the Accumulator for BCD addition and
/// subtraction operations. For addition (ADD, ADC, INC) or subtraction (SUB,
/// SBC, DEC, NEG), the following table indicates the operation performed:
///
/// \todo add table from manual here.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is set if most-significant bit of Accumulator is 1 after operation; reset
/// otherwise
/// * Z is set if Accumulator is zero after operation; reset otherwise
/// * H, see instruction
/// * P/V is set if Accumulator is even parity after operation; reset otherwise
/// * N is not affected
/// * C, see instruction
///
/// \note This took a LONG time to get all the results/flags accurate with a real Z80,
/// so any modifications should be done with extreme care and revalidated
/// with the instruction test program.
///
/// \retval none
///
void
Z80::op_daa(void)
{
WORD tmp_a = A;
BYTE low_nibble = A & 0x0f;
bool carry = CHECK_FLAGS(C_FLAG);
// determine what type of operation was last done.
if (CHECK_FLAGS(N_FLAG))
{
// Subtraction
int adjustment = (carry || (tmp_a > 0x99)) ? 0x160 : 0x00;
if (CHECK_FLAGS(H_FLAG) || (low_nibble > 9))
{
if (low_nibble > 5)
{
CLEAR_FLAGS(H_FLAG);
}
tmp_a = (tmp_a - 6) & 0xff;
}
tmp_a -= adjustment;
}
else
{
// Addition
if (CHECK_FLAGS(H_FLAG) || (low_nibble > 9))
{
COND_FLAGS((low_nibble > 9), H_FLAG);
tmp_a += 6;
}
if (carry || ((tmp_a & 0x1f0) > 0x90))
{
tmp_a += 0x60;
}
}
A = (tmp_a & 0xff);
COND_FLAGS((carry || (tmp_a & 0x100)), C_FLAG);
SET_ZSP_FLAGS(A);
}
///
/// \brief Enable Interrupts (EI)
///
/// Operation: IFF <- 1
///
/// Opcode: EI
///
/// Binary | Hex
/// ----------|-------
/// 11111011 | 0xFB
///
/// Description: The enable interrupt instruction sets both interrupt enable flip flops
/// (IFF1 and IFF2) to a logic 1, allowing recognition of any maskable
/// interrupt. Note that during the execution of this instruction and the
/// following instruction, maskable interrupts are disabled.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ei(void)
{
IFF2 = true;
// Keep IFF1 false, it will be set to true after the next instruction by IFF0
// this ensures that the next instruction executes before servicing another
// interrupt.
IFF0 = true;
}
///
/// \brief Disable Interrupts (DI)
///
/// Operation: IFF <- 0
///
/// Opcode: DI
///
/// Binary | Hex
/// ----------|-------
/// 11110011 | 0xF3
///
/// Description: DI disables the maskable interrupt by resetting the interrupt enable
/// flip-flops (IFF1 and IFF2). Note that this instruction disables the
/// maskable interrupt during its execution.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|-------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_di(void)
{
IFF0 = IFF1 = IFF2 = false;
}
///
/// \brief Read from Port (IN)
///
/// Operation: A <- (n)
///
/// Opcode: IN
/// Operands: A, (n)
///
/// Binary | Hex
/// ----------|-------
/// 11011011 | 0xDB
/// n | n
///
/// Description: The operand n is placed on the bottom half (A0 through A7) of the address
/// bus to select the I/O device at one of 256 possible ports. The contents of
/// the Accumulator also appear on the top half (A8 through A15) of the address
/// bus at this time. Then one byte from the selected port is placed on the data
/// bus and written to the Accumulator (register A) in the CPU.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|-------------
/// 3 | 11(4,3,4) | 2.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_in(void)
{
A = io_m->in(READn());
ticks -= 4;
}
///
/// \brief Write to Port (OUT)
///
/// Operation: (n) <- A
///
/// Opcode: OUT
/// Operands: (n), A
///
/// Binary | Hex
/// ----------|-------
/// 11010011 | 0xD3
/// n | n
///
/// Description: The operand n is placed on the bottom half (A0 through A7) of the address
/// bus to select the I/O device at one of 256 possible ports. The contents of
/// the Accumulator (register A) also appear on the top half (A8 through A15) of
/// the address bus at this time. Then the byte contained in the Accumulator is
/// placed on the data bus and written to the selected peripheral device.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|-------------
/// 3 | 11(4,3,4) | 2.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_out(void)
{
io_m->out(READn(), A);
ticks -= 4;
}
///
/// \brief Load Register (LD)
///
/// Operation: r <- (n)
///
/// Opcode: LD
/// Operands: r, n
///
/// Binary | Hex
/// ----------|-------
/// 00-r-110 |
/// n | n
///
/// Description: The 8-bit integer n is loaded to any register r, where r identifies
/// register A, B, C, D, E, H, or L, assembled as follows in the object code:
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_x_n(void)
{
getReg8(lastInstByte >> 3) = READn();
}
///
/// \brief LD A, (BC)
///
/// Operation: A <- (BC)
///
/// Opcode: LD
/// Operands: A, (BC)
///
/// Binary | Hex
/// ----------|-------
/// 00001010 | 0x0A
///
/// Description: The contents of the memory location specified by the contents of the BC
/// register pair are loaded to the Accumulator.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_a_ibc(void)
{
A = readMEM(BC);
}
///
/// \brief Load Accumulator
///
/// Operation: A <- (DE)
///
/// Opcode: LD
/// Operands: A, (DE)
///
/// Binary | Hex
/// ----------|-------
/// 00011010| 0x1A
///
/// Description: The contents of the memory location specified by the register pair DE are
/// loaded to the Accumulator.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_a_ide(void)
{
A = readMEM(DE);
}
///
/// \brief Load immediate Accumulator
///
/// Operation: A <- (nn)
///
/// Opcode: LD
/// Operands: A, (nn)
///
/// Binary | Hex
/// ----------|-------
/// 00111010| 0x3A
/// | n
/// | n
///
/// Description: The contents of the memory location specified by the operands nn are
/// loaded to the Accumulator. The first n operand after the Opcode is the
/// low order byte of a 2-byte memory address.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 4 |13(4,3,3,3)| 3.25
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_a_inn(void)
{
A = readMEM(READnn());
}
///
/// \brief Store Accumulator
///
/// Operation: (BC) <- A
///
/// Opcode: LD
/// Operands: (BC), A
///
/// Binary | Hex
/// ----------|-------
/// 00000010| 0x02
///
/// Description: The contents of the Accumulator are loaded to the memory location
/// specified by the contents of the register pair BC.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_ibc_a(void)
{
writeMEM(BC, A);
}
///
/// \brief Store Accumulator
///
/// Operation: (DE) <- A
///
/// Opcode: LD
/// Operands: (DE), A
///
/// Binary | Hex
/// ----------|-------
/// 00010010 | 0x12
///
/// Description: The contents of the Accumulator are loaded to the memory location
/// specified by the contents of the DE register pair.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_ide_a(void)
{
writeMEM(DE, A);
}
///
/// \brief Store immediate Accumulator
///
/// Operation: (nn) <- A
///
/// Opcode: LD
/// Operands: (nn), A
///
/// Binary | Hex
/// ----------|-------
/// 00110010 | 0x32
/// | n
/// | n
///
/// Description: The contents of the Accumulator are loaded to the memory address
/// specified by the operand nn. The first n operand after the Opcode is the
/// low order byte of nn.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 4 |13(4,3,3,3)| 3.25
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_inn_a(void)
{
writeMEM(READnn(), A);
}
///
/// \brief LD (HL), r
///
/// Operation: (HL) <- r
///
/// Opcode: LD
/// Operands: (HL), r
///
/// Binary | Hex
/// ----------|-------
/// 01110-r- |
///
/// Description: The contents of register r are loaded to the memory location specified by
/// the contents of the HL register pair. The symbol r identifies register A,
/// B, C, D, E, H, or L, assembled as follows in the object code:
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_ihl_x(void)
{
writeMEM(getIndirectAddr(), getCoreReg8Val(lastInstByte));
}
///
/// \brief Store immediate
///
/// Operation: (HL) <- n
///
/// Opcode: LD
/// Operands: (HL), n
///
/// Binary | Hex
/// ----------|-------
/// 00110110 | 0x36
/// | n
///
/// Description: Integer n is loaded to the memory address specified by the contents of the
/// HL register pair.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 3 | 10(4,3,3) | 3.25
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_ihl_n(void)
{
// Order is imperative here for DD/FD instructions:
// displacement is 3rd byte and value is 4th.
// Functions with side-effects can be dangerous.
WORD adr = getIndirectAddr();
BYTE n = READn();
writeMEM(adr, n);
}
///
/// \brief LD r, r'
///
/// Operation: r <- r'
///
/// Opcode: LD
/// Operands: r, r'
///
/// Binary | Hex
/// ----------|-------
/// 01-r--r' |
///
/// Description: The contents of any register r' are loaded to any other register r. r, r'
/// identifies any of the registers A, B, C, D, E, H, or L, assembled as follows
/// in the object code:
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_x_x(void)
{
getReg8(lastInstByte >> 3) = getReg8Val(lastInstByte);
}
///
/// \brief LD r,(HL)
///
/// Operation: r <- (HL)
///
/// Opcode: LD
/// Operands: r, (HL)
///
/// Binary | Hex
/// ----------|-------
/// 01-r-110 |
///
/// Description: The 8-bit contents of memory location (HL) are loaded to register r,
/// where r identifies register A, B, C, D, E, H, or L, assembled as follows in
/// the object code:
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 7(4,3) | 1.75
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_x_ihl(void)
{
getCoreReg8(lastInstByte >> 3) = readMEM(getIndirectAddr());
}
///
/// \brief LD dd, nn
///
/// Operation: dd <- nn
///
/// Opcode: LD
/// Operands: dd, nn
///
/// Binary | Hex
/// ----------|-------
/// 00dd0001 |
/// | n
/// | n
///
/// Description: The 2-byte integer nn is loaded to the dd register pair, where dd
/// defines the BC, DE, HL, or SP register pairs, assembled as follows
/// in the object code:
///
/// Register Pair | dd
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// SP | 11
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 2 | 10(4,3,3) | 2.50
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_xx_nn(void)
{
getReg16(lastInstByte >> 4) = READnn();
}
///
/// \brief LD SP, HL
///
/// Operation: SP <- HL
///
/// Opcode: LD
/// Operands: SP, HL
///
/// Binary | Hex
/// ----------|-------
/// 11111001 | 0xF9
///
/// Description: The contents of the register pair HL are loaded to the Stack Pointer (SP).
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 6 | 1.50
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_ld_sp_hl(void)
{
SP = HL;
ticks -= 2;
}
///
/// \brief LD HL, (nn)
///
/// <pre>
///
/// </pre>
///
/// \retval none
///
void
Z80::op_ld_hl_inn(void)
{
HL = readWord(READnn());
}
///
/// \brief LD (nn), HL
///
/// <pre>
///
/// </pre>
///
/// \retval none
///
void
Z80::op_ld_inn_hl(void)
{
writeWord(READnn(), HL);
}
///
/// \brief INC ss
///
/// Operation: ss <- ss + 1
///
/// Opcode: INC
/// Operands: ss
///
/// Binary | Hex
/// ----------|-------
/// 00ss0011 |
///
/// Register Pair | ss
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// SP | 11
///
/// Description: The contents of register pair ss (any of register pairs BC, DE, HL, or SP)
/// are incremented. Operand ss is specified as follows in the assembled
/// object code.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 6 | 1.50
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_inc_xx(void)
{
getReg16(lastInstByte >> 4)++;
ticks -= 2;
}
///
/// \brief Decrement ss
///
/// Operation: ss <- ss - 1
///
/// Opcode: DEC
/// Operands: ss
///
/// Binary | Hex
/// ----------|-------
/// 00ss1011 |
///
/// Register Pair | ss
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// SP | 11
///
/// Description: The contents of register pair ss (any of register pairs BC, DE, HL, or SP)
/// are incremented. Operand ss is specified as follows in the assembled
/// object code.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 1 | 6 | 1.50
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_dec_xx(void)
{
--getReg16(lastInstByte >> 4);
ticks -= 2;
}
///
/// \brief ADD HL, ss
///
/// Operation: HL <- HL + ss
///
/// Opcode: ADD
/// Operands: HL,ss
///
/// Binary | Hex
/// ----------|-------
/// 00ss1001 |
///
/// Register Pair | ss
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// SP | 11
///
/// Description: The contents of register pair ss (any of register pairs BC, DE, HL, or SP)
/// are added to the contents of register pair HL and the result is stored in HL.
/// Operand ss is specified as follows in the assembled object code.
///
/// M Cycles | T States | 4 MHz E.T.
/// ---------|-----------|------------
/// 3 | 11(4,4,3) | 2.75
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is set if carry out of bit 11; reset otherwise
/// * P/V is not affected
/// * N is reset
/// * C is set if carry from bit 15; reset otherwise
///
/// \retval none
///
inline void
Z80::op_add_reg16(WORD& res, WORD val)
{
unsigned int sum = res + val;
COND_FLAGS((res & 0x0fff) + (val & 0x0fff) > 0x0fff, H_FLAG);
COND_FLAGS(sum > 0xffff, C_FLAG);
CLEAR_FLAGS(N_FLAG);
res = (sum & 0xffff);
ticks -= 7;
}
///
/// \brief ADD HL, ss
///
/// \ref op_add_reg16
///
void
Z80::op_add_hl_xx(void)
{
op_add_reg16(getHLReg16(), getReg16Val(lastInstByte >> 4));
}
///
/// \brief Logical AND
///
/// Operation: A <- A ^ s
///
/// Opcode: AND
/// Operands: s
///
/// The s operand is any of r, n, (HL), (IX+d), or (lY+d), as defined for the
/// analogous ADD instructions. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
/// +-+-+-+-+-+-+-+-+
/// AND r |1|0|1|0|0| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// AND n |1|1|1|0|0|1|1|0| 0xE6
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// AND (HL) |1|0|1|0|0|1|1|0| 0xA6
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// AND (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|0|0|1|1|0| 0xA6
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// AND (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|0|0|1|1|0| 0xA6
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: A logical AND operation is performed between the byte specified by the s
/// operand and the byte contained in the Accumulator; the result is stored in
/// the Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|-------------|------------
/// AND r | 1 | 4 | 1.00
/// AND n | 2 | 7(4,3) | 1.75
/// AND (HL) | 2 | 7(4,3) | 1.75
/// AND (IX+d)| 5 |19(4,4,3,5,3)| 4.75
/// AND (IY+d)| 5 |19(4,4,3,5,3)| 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set
/// * P/V is reset if overflow; reset otherwise
/// * N is reset
/// * C is reset
///
/// \retval none
///
inline void
Z80::op_and(BYTE val)
{
A &= val;
SET_FLAGS(H_FLAG);
CLEAR_FLAGS((N_FLAG | C_FLAG));
SET_ZSP_FLAGS(A);
}
/// \brief AND <reg>
///
/// \ref op_and
///
/// \retval none
void
Z80::op_and_x(void)
{
op_and(getReg8Val(lastInstByte));
}
///
/// \brief AND (HL)
///
/// \ref op_and
///
/// \retval none
void
Z80::op_and_ihl(void)
{
op_and(readMEM(getIndirectAddr()));
}
///
/// \brief AND n
///
/// \ref op_and
///
/// \retval none
void
Z80::op_and_n(void)
{
op_and(READn());
}
///
/// \brief OR
///
/// Operation: A <- A v s
///
/// Opcode: OR
/// Operands: s
///
/// The s operand is any of r, n, (HL), (IX+d), or (lY+d), as defined for the
/// analogous ADD instructions. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// OR r |1|0|1|1|0| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// OR n |1|1|1|1|0|1|1|0| 0xF6
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// OR (HL) |1|0|1|1|0|1|1|0| 0xB6
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// OR (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|1|0|1|1|0| 0xB6
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// OR (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|1|0|1|1|0| 0xB6
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: A logical OR operation is performed between the byte specified by the s
/// operand and the byte contained in the Accumulator; the result is stored in
/// the Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|---------------|------------
/// OR r | 1 | 4 | 1.00
/// OR n | 2 | 7(4,3) | 1.75
/// OR (HL) | 2 | 7(4,3) | 1.75
/// OR (IX+d)| 5 | 19(4,4,3,5,3) | 4.75
/// OR (IY+d)| 5 | 19(4,4,3,5,3) | 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is reset
/// * P/V is set if overflow; reset otherwise
/// * N is reset
/// * C is reset
///
/// \retval none
///
inline void
Z80::op_or(BYTE val)
{
A |= val;
SET_ZSP_FLAGS(A);
CLEAR_FLAGS(H_FLAG | N_FLAG | C_FLAG);
}
///
/// \brief OR <reg>
///
/// \ref op_or
///
/// \retval none
///
void
Z80::op_or_x(void)
{
op_or(getReg8Val(lastInstByte));
}
///
/// \brief OR (HL)
///
/// \ref op_or
///
/// \retval none
///
void
Z80::op_or_ihl(void)
{
op_or(readMEM(getIndirectAddr()));
}
///
/// \brief OR n
///
/// \ref op_or
///
/// \retval none
///
void
Z80::op_or_n(void)
{
op_or(READn());
}
///
/// \brief XOR (Exclusive OR)
///
/// Operation: A <- A (+) s
///
/// Opcode: XOR
/// Operands: s
///
/// The s operand is any of r, n, (HL), (IX+d), or (lY+d), as defined for the
/// analogous ADD instructions. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// XOR r |1|0|1|0|1| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// XOR n |1|1|1|0|1|1|1|0| 0xEE
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// XOR (HL) |1|0|1|0|1|1|1|0| 0xAE
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// XOR (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|0|1|1|1|0| 0xAE
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// XOR (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|0|1|1|1|0| 0xAE
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The logical exclusive-OR operation is performed between the byte
/// specified by the s operand and the byte contained in the Accumulator; the
/// result is stored in the Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|-----------|-------------|------------
/// XOR r | 1 | 4 | 1.00
/// XOR n | 2 | 7(4,3) | 1.75
/// XOR (HL) | 2 | 7(4,3) | 1.75
/// XOR (IX+d)| 5 |19(4,4,3,5,3)| 4.75
/// XOR (IY+d)| 5 |19(4,4,3,5,3)| 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is reset
/// * P/V is set if parity even; reset otherwise
/// * N is reset
/// * C is reset
///
/// \retval none
///
inline void
Z80::op_xor(BYTE val)
{
A ^= val;
SET_ZSP_FLAGS(A);
CLEAR_FLAGS(H_FLAG | N_FLAG | C_FLAG);
}
///
/// \brief XOR <reg>
///
/// @ref op_xor
///
/// \retval none
///
void
Z80::op_xor_x(void)
{
op_xor(getReg8Val(lastInstByte));
}
///
/// \brief XOR (HL)
///
/// @ref op_xor
///
/// \retval none
///
void
Z80::op_xor_ihl(void)
{
op_xor(readMEM(getIndirectAddr()));
}
///
/// \brief XOR n
///
/// @ref op_xor
///
/// \retval none
///
void
Z80::op_xor_n(void)
{
op_xor(READn());
}
///
/// \brief ADD
///
/// Operation: A <- A + r
///
/// Opcode: ADD
/// Operands: A, r
///
/// Binary | Hex
/// ----------|-------
/// 10000-r- |
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The contents of register r are added to the contents of the Accumulator, and
/// the result is stored in the Accumulator. The symbol r identifies the
/// registers A, B, C, D, E, H, or L, assembled as follows in the object code:
///
/// M Cycles| T States | 4 MHz E.T.
/// --------+-----------+-------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if carry from bit 3; reset otherwise
/// * P/V is set if overflow; reset otherwise
/// * N is reset
/// * C is set if carry from bit 7; reset otherwise
///
/// \retval none
///
inline void
Z80::op_add(BYTE val)
{
SWORD i;
COND_FLAGS(((A & 0xf) + (val & 0xf) > 0xf), H_FLAG);
COND_FLAGS((A + val > 255), C_FLAG);
A = i = sA + (signed char) val;
COND_FLAGS((i < -128 || i > 127), P_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
COND_FLAGS((!A), Z_FLAG);
CLEAR_FLAGS(N_FLAG);
}
/// \brief ADD A,<reg>
///
/// \ref op_add
///
/// \retval none
///
void
Z80::op_add_x(void)
{
op_add(getReg8Val(lastInstByte));
}
/// \brief ADD A,(HL)
///
/// \ref op_add
///
/// \retval none
///
void
Z80::op_add_ihl(void)
{
op_add(readMEM(getIndirectAddr()));
}
/// \brief ADD A,n
///
/// \ref op_add
///
/// \retval none
///
void
Z80::op_add_n(void)
{
op_add(READn());
}
///
/// \brief ADC (Add w/ Carry)
///
/// Operation: A <- A + s + CY
///
/// Opcode: ADC
/// Operands: A, s
///
/// This s operand is any of r, n, (HL), (IX+d), or (lY+d) as defined for the
/// analogous ADD instruction. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// ADC A,r |1|0|0|0|1| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// ADC A,n |1|1|0|0|1|1|1|0| 0xCE
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// ADC A,(HL) |1|0|0|0|1|1|1|0| 0x8E
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// ADC A,(IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|0|1|1|1|0| 0x8E
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// ADC A,(IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|0|1|1|1|0| 0x8E
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The s operand, along with the Carry Flag (C in the F register) is added
/// to the contents of the Accumulator, and the result is stored in the
/// Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|---------------|------------
/// ADC A,r | 1 | 4 | 1.00
/// ADC A,n | 2 | 7(4,3) | 1.75
/// ADC A,(HL) | 2 | 7(4,3) | 1.75
/// ADC A,(IX+d)| 5 | 19(4,4,3,5,3) | 4.75
/// ADC A,(IY+d)| 5 | 19(4,4,3,5,3) | 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if carry from bit 3; reset otherwise
/// * P/V is set if overflow; reset otherwise
/// * N is reset
/// * C is set if carry from bit 7: reset otherwise
///
/// \retval none
///
inline void
Z80::op_adc(BYTE val)
{
SWORD i;
BYTE carry = CHECK_FLAGS(C_FLAG) ? 1 : 0;
COND_FLAGS(((A & 0xf) + (val & 0xf) + carry > 0xf), H_FLAG);
COND_FLAGS((A + val + carry > 255), C_FLAG);
A = i = sA + (signed char) val + carry;
COND_FLAGS((i < -128 || i > 127), P_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
COND_FLAGS((!A), Z_FLAG);
CLEAR_FLAGS(N_FLAG);
}
/// \brief ADC A,<reg>
///
/// \ref op_adc
///
/// \retval none
///
void
Z80::op_adc_x(void)
{
op_adc(getReg8Val(lastInstByte));
}
/// \brief ADC A,(HL)
///
/// \ref op_adc
///
/// \retval none
///
void
Z80::op_adc_ihl(void)
{
op_adc(readMEM(getIndirectAddr()));
}
/// \brief ADC A,(n)
///
/// \ref op_adc
///
/// \retval none
///
void
Z80::op_adc_n(void)
{
op_adc(READn());
}
///
/// \brief SUB (Subtract)
///
/// Operation: A <- A - s
///
/// Opcode: SUB
/// Operands: A, s
///
/// This s operand is any of r, n, (HL), (IX+d), or (lY+d) as defined for the
/// analogous ADD instruction. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// SUB A,r |1|0|0|1|0| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SUB A,n |1|1|0|1|0|1|1|0| 0xD6
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SUB A,(HL) |1|0|0|1|0|1|1|0| 0x96
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SUB A,(IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|1|0|1|1|0| 0x96
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SUB A,(IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|1|0|1|1|0| 0x96
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The s operand is subtracted from the contents of the Accumulator, and the
/// result is stored in the Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|---------------|------------
/// SUB A,r | 1 | 4 | 1.00
/// SUB A,n | 2 | 7(4,3) | 1.75
/// SUB A,(HL) | 2 | 7(4,3) | 1.75
/// SUB A,(IX+d)| 5 | 19(4,4,3,5,3) | 4.75
/// SUB A,(IY+d)| 5 | 19(4,4,3,5,3) | 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if borrow from bit 4; reset otherwise
/// * P/V is set if overflow; reset otherwise
/// * N is set
/// * C is set if borrow; reset otherwise
///
/// \retval none
///
inline void
Z80::op_sub(BYTE val)
{
SWORD i;
COND_FLAGS(((val & 0xf) > (A & 0xf)), H_FLAG);
COND_FLAGS((val > A), C_FLAG);
A = i = sA - (signed char) val;
COND_FLAGS(((i < -128) || (i > 127)), P_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
COND_FLAGS((!A), Z_FLAG);
SET_FLAGS(N_FLAG);
}
/// \brief SUB A,<reg>
///
/// \ref op_sub
///
/// \retval none
///
void
Z80::op_sub_x(void)
{
op_sub(getReg8Val(lastInstByte));
}
/// \brief SUB A,(HL)
///
/// \ref op_sub
///
/// \retval none
///
void
Z80::op_sub_ihl(void)
{
op_sub(readMEM(getIndirectAddr()));
}
/// \brief SUB A,n
///
/// \ref op_sub
///
/// \retval none
///
void
Z80::op_sub_n(void)
{
op_sub(READn());
}
///
/// \brief SBC (Subtract w/Carry)
///
/// Operation: A <- A - s - CY
///
/// Opcode: SBC
/// Operands: A, s
///
/// This s operand is any of r, n, (HL), (IX+d), or (lY+d) as defined for the
/// analogous ADD instruction. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// SBC A,r |1|0|0|1|1| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SBC A,n |1|1|0|1|1|1|1|0| 0xDE
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SBC A,(HL) |1|0|0|1|1|1|1|0| 0x9E
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SBC A,(IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|1|1|1|1|0| 0x9E
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// SBC A,(IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|0|1|1|1|1|0| 0x9E
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The s operand, along with the Carry flag (C in the F register) is subtracted
/// from the contents of the Accumulator, and the result is stored in the
/// Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ------------|----------|---------------|------------
/// SBC A,r | 1 | 4 | 1.00
/// SBC A,n | 2 | 7(4,3) | 1.75
/// SBC A,(HL) | 2 | 7(4,3) | 1.75
/// SBC A,(IX+d)| 5 | 19(4,4,3,5,3) | 4.75
/// SBC A,(IY+d)| 5 | 19(4,4,3,5,3) | 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if borrow from bit 4; reset otherwise
/// * P/V is reset if overflow; reset otherwise
/// * N is set
/// * C is set if borrow; reset otherwise
///
/// \retval none
///
inline void
Z80::op_sbc(BYTE val)
{
SWORD i;
BYTE carry = CHECK_FLAGS(C_FLAG) ? 1 : 0;
COND_FLAGS(((val & 0xf) + carry > (A & 0xf)), H_FLAG);
COND_FLAGS((val + carry > A), C_FLAG);
A = i = sA - (signed char) val - carry;
COND_FLAGS(((i < -128) || (i > 127)), P_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
COND_FLAGS((!A), Z_FLAG);
SET_FLAGS(N_FLAG);
}
/// \brief SBC A,<reg>
///
/// \ref op_sbc
///
/// \retval none
///
void
Z80::op_sbc_x(void)
{
op_sbc(getReg8Val(lastInstByte));
}
/// \brief SBC A,(HL)
///
/// \ref op_sbc
///
/// \retval none
///
void
Z80::op_sbc_ihl(void)
{
op_sbc(readMEM(getIndirectAddr()));
}
/// \brief SBC A,n
///
/// \ref op_sbc
///
/// \retval none
///
void
Z80::op_sbc_n(void)
{
op_sbc(READn());
}
///
/// \brief CP (compare)
///
/// Operation: A - s
///
/// Opcode: CP
/// Operands: s
///
/// This s operand is any of r, n, (HL), (IX+d), or (lY+d) as defined for the
/// analogous ADD instruction. These possible Opcode/operand
/// combinations are assembled as follows in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// CP r |1|0|1|1|1| r |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// CP n |1|1|1|1|1|1|1|0| 0xFE
/// +-+-+-+-+-+-+-+-+
/// | n |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// CP (HL) |1|0|1|1|1|1|1|0| 0xBE
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// CP (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|1|1|1|1|0| 0xBE
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// CP (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |1|0|1|1|1|1|1|0| 0xBE
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The s operand is subtracted from the contents of the Accumulator, and the
/// result is stored in the Accumulator.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|---------------|------------
/// CP r | 1 | 4 | 1.00
/// CP n | 2 | 7(4,3) | 1.75
/// CP (HL) | 2 | 7(4,3) | 1.75
/// CP (IX+d)| 5 | 19(4,4,3,5,3) | 4.75
/// CP (IY+d)| 5 | 19(4,4,3,5,3) | 4.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if borrow from bit 4; reset otherwise
/// * P/V is set if overflow; reset otherwise
/// * N is set
/// * C is set if borrow; reset otherwise
///
/// \retval none
///
inline void
Z80::op_cp(BYTE val)
{
SWORD i;
COND_FLAGS(((val & 0xf) > (A & 0xf)), H_FLAG);
COND_FLAGS((val > A), C_FLAG);
i = sA - (signed char) val;
COND_FLAGS(((i < -128) || (i > 127)), P_FLAG);
COND_FLAGS((i & 0x80), S_FLAG);
COND_FLAGS((!i), Z_FLAG);
SET_FLAGS(N_FLAG);
}
/// \brief CP <reg>
///
/// \ref op_cp
///
/// \retval none
///
void
Z80::op_cp_x(void)
{
op_cp(getReg8Val(lastInstByte));
}
/// \brief CP (HL)
///
/// \ref op_cp
///
/// \retval none
///
void
Z80::op_cp_ihl(void)
{
op_cp(readMEM(getIndirectAddr()));
}
/// \brief CP n
///
/// \ref op_cp
///
/// \retval none
///
void
Z80::op_cp_n(void)
{
op_cp(READn());
}
///
/// \brief INC (increment)
///
/// Operation: m <- m + 1
///
/// Opcode: INC
/// Operands: m
///
/// This m operand is any of r, (HL), (IX+d), or (lY+d). These
/// possible Opcode/operand combinations are assembled as follows
/// in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// INC r |0|0| r |1|0|0|
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// INC (HL) |0|0|1|1|0|1|0|0| 0x34
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// INC (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |0|0|1|1|0|1|0|0| 0x34
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// INC (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |0|0|1|1|0|1|0|0| 0x34
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The m operand is incremented by 1.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|-----------------|------------
/// INC r | 1 | 4 | 1.00
/// INC (HL) | 3 | 11(4,4,3) | 2.75
/// INC (IX+d)| 6 | 23(4,4,3,5,4,3) | 5.75
/// INC (IY+d)| 6 | 23(4,4,3,5,4,3) | 5.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if carry from bit 3; reset otherwise
/// * P/V is set if operand was 0x7f before operation; reset otherwise
/// * N is reset
/// * C is not affected
///
/// \retval none
///
inline void
Z80::op_inc(BYTE& val)
{
COND_FLAGS(((val & 0xf) == 0xf), H_FLAG);
val++;
COND_FLAGS((val == 0x80), P_FLAG);
COND_FLAGS((val & 0x80), S_FLAG);
COND_FLAGS((!val), Z_FLAG);
CLEAR_FLAGS(N_FLAG);
}
/// \brief INC <reg>
///
/// \ref op_inc
///
/// \retval none
///
void
Z80::op_inc_x(void)
{
op_inc(getReg8(lastInstByte >> 3));
}
/// \brief INC (HL)
///
/// \ref op_inc
///
/// \retval none
///
void
Z80::op_inc_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_inc(val);
writeMEM(addr, val);
ticks -= 1;
}
///
/// \brief DEC (decrement)
///
/// Operation: m <- m - 1
///
/// Opcode: DEC
/// Operands: m
///
/// This m operand is any of r, (HL), (IX+d), or (lY+d). These
/// possible Opcode/operand combinations are assembled as follows
/// in the object code:
///
/// +-+-+-+-+-+-+-+-+
/// DEC r |0|0| r |1|0|1|
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// DEC (HL) |0|0|1|1|0|1|0|1| 0x35
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// DEC (IX+d) |1|0|1|0|0|1|1|0| 0xDD
/// +-+-+-+-+-+-+-+-+
/// |0|0|1|1|0|1|0|1| 0x35
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
/// +-+-+-+-+-+-+-+-+
/// DEC (IY+d) |1|0|1|0|0|1|1|0| 0xFD
/// +-+-+-+-+-+-+-+-+
/// |0|0|1|1|0|1|0|1| 0x35
/// +-+-+-+-+-+-+-+-+
/// | d |
/// +-+-+-+-+-+-+-+-+
///
/// Register| r
/// --------|-------
/// A | 111
/// B | 000
/// C | 001
/// D | 010
/// E | 011
/// H | 100
/// L | 101
///
/// Description: The m operand decremented by 1.
///
/// Opcode | M Cycles | T States | 4 MHz E.T.
/// ----------|----------|-----------------|------------
/// DEC r | 1 | 4 | 1.00
/// DEC (HL) | 3 | 11(4,4,3) | 2.75
/// DEC (IX+d)| 6 | 23(4,4,3,5,4,3) | 5.75
/// DEC (IY+d)| 6 | 23(4,4,3,5,4,3) | 5.75
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is zero; reset otherwise
/// * H is set if borrow from bit 4; reset otherwise
/// * P/V is set if m was 0x80 before operation; reset otherwise
/// * N is set
/// * C is not affected
///
/// \retval none
///
inline void
Z80::op_dec(BYTE& val)
{
COND_FLAGS(((val & 0xf) == 0), H_FLAG);
COND_FLAGS((val == 0x80), P_FLAG);
val--;
COND_FLAGS((val & 0x80), S_FLAG);
COND_FLAGS((!val), Z_FLAG);
SET_FLAGS(N_FLAG);
}
/// \brief DEC <reg>
///
/// \ref op_dec
///
/// \retval none
///
void
Z80::op_dec_x(void)
{
op_dec(getReg8(lastInstByte >> 3));
}
/// \brief DEC (HL)
///
/// \ref op_dec
///
/// \retval none
///
void
Z80::op_dec_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_dec(val);
writeMEM(addr, val);
ticks -= 1;
}
///
/// \brief RLCA
///
/// Operation: +-------------+
/// [CY] <-+--[7 << 0]<--+
/// [- A - ]
///
/// Opcode: RLCA
/// Operands: -
///
/// Binary | Hex
/// ----------|-------
/// 00000111 | 0x07
///
/// Description: The contents of the Accumulator (register A) are rotated left
/// 1-bit position. The sign bit (bit 7) is copied to the Carry flag
/// and also to bit 0. Bit 0 is the least-significant bit.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is reset
/// * P/V is not affected
/// * N is reset
/// * C is data from bit 7 of Accumulator
///
/// \retval none
///
void
Z80::op_rlc_a(void)
{
BYTE i = (A & 0x80) ? 1 : 0;
COND_FLAGS((i), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
A <<= 1;
A |= i;
}
///
/// \brief RRCA
///
/// Operation: +<-------------+
/// +-->[7 >> 0]-->+--> [CY]
/// [- A - ]
///
/// Opcode: RRCA
/// Operands: -
///
/// Binary | Hex
/// ----------|-------
/// 00001111 | 0x0F
///
/// Description: The contents of the Accumulator (register A) are rotated right
/// 1-bit position. Bit 0 is copied to the Carry flag and also
/// to bit 7. Bit 0 is the least-significant bit.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is reset
/// * P/V is not affected
/// * N is reset
/// * C is data from bit 0 of Accumulator
///
/// \retval none
///
void
Z80::op_rrc_a(void)
{
BYTE i = (A & 1) ? 0x80 : 0x00;
COND_FLAGS((i), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
A >>= 1;
A |= i;
}
///
/// \brief RLA
///
/// Operation: +-----------------------+
/// +---[7 << 0]<---[CY]<---+
/// - A -
///
/// Opcode: RLA
/// Operands: -
///
/// Binary | Hex
/// ----------|-------
/// 00010111 | 0x17
///
/// Description: The contents of the Accumulator (register A) are rotated left
/// 1-bit position through the Carry flag. The previous content of
/// the Carry flag is copied to bit 0. Bit 0 is the least-significant
/// bit.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is reset
/// * P/V is not affected
/// * N is reset
/// * C is data from bit 7 of Accumulator
///
/// \retval none
///
void
Z80::op_rl_a(void)
{
BYTE i = (CHECK_FLAGS(C_FLAG) ? 0x01 : 0x00);
COND_FLAGS((A & 128), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
A <<= 1;
A |= i;
}
///
/// \brief RRA
///
/// Operation: +<----------------------+
/// +-->[7 >> 0]---->[CY]-->+
/// - A -
///
/// Opcode: RRA
/// Operands: -
///
/// Binary | Hex
/// ----------|-------
/// 00011111 | 0x1F
///
/// Description: The contents of the Accumulator (register A) are rotated right
/// 1-bit position through the Carry flag. The previous content of the
/// Carry flag is copied to bit 7. Bit 0 is the least-significant bit.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected:
/// * S is not affected
/// * Z is not affected
/// * H is reset
/// * P/V is not affected
/// * N is reset
/// * C is data from bit 0 of Accumulator
///
/// \retval none
///
void
Z80::op_rr_a(void)
{
BYTE i = (CHECK_FLAGS(C_FLAG) ? 0x80 : 0x00);
COND_FLAGS((A & 1), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
A >>= 1;
A |= i;
}
///
/// \brief EX DE, HL
///
/// Operation: DE <--> HL
///
/// Opcode: EX
/// Operands: DE, HL
///
/// Binary | Hex
/// ----------|-------
/// 11101011 | 0xEB
///
/// Description: The 2-byte contents of register pairs DE and HL are exchanged.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_ex_de_hl(void)
{
WORD tmp;
tmp = HL;
HL = DE;
DE = tmp;
}
///
/// \brief EX AF, AF'
///
/// Operation: AF <--> AF'
///
/// Opcode: EX
/// Operands: AF, AF'
///
/// Binary | Hex
/// ----------|-------
/// 00001000 | 0x08
///
/// Description: The 2-byte contents of register pairs AF and AF' are exchanged.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_ex_af_af(void)
{
WORD tmp;
tmp = AF;
AF = _af;
_af = tmp;
}
///
/// \brief EXX
///
/// Operation: BC <--> BC', DE <--> DE', HL <--> HL'
///
/// Opcode: EXX
/// Operands: --
///
/// Binary | Hex
/// ----------|-------
/// 11011001 | 0xD9
///
/// Description: Each 2-byte value in register pairs BC, DE, and HL is exchanged with the
/// 2-byte value in BC', DE', and HL', respectively.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|-----------|------------
/// 1 | 4 | 1.00
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_exx(void)
{
WORD tmp;
tmp = BC;
BC = _bc;
_bc = tmp;
tmp = DE;
DE = _de;
_de = tmp;
tmp = HL;
HL = _hl;
_hl = tmp;
}
///
/// \brief EX (SP), HL
///
/// Operation: H <--> (SP+1), L <--> (SP)
///
/// Opcode: EX
/// Operands: (SP), HL
///
/// Binary | Hex
/// ----------|-------
/// 11100011 | 0xE3
///
/// Description: The low order byte contained in register pair HL is exchanged with the
/// contents of the memory address specified by the contents of register pair
/// SP (Stack Pointer), and the high order byte of HL is exchanged with the
/// next highest memory address (SP+1).
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 5 | 19(4,3,4,3,5) | 4.75
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_ex_isp_hl(void)
{
WORD i = readWord(SP);
writeWord(SP, HL);
HL = i;
ticks -= 3;
}
///
/// \brief PUSH qq
///
/// Operation: (SP-2) <-- qqL, (SP-1) <-- qqH
///
/// Opcode: PUSH
/// Operands: qq
///
/// Binary | Hex
/// ----------|-------
/// 11qq0101 |
///
/// Register Pair | qq
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// AF | 11
///
/// Description: The contents of the register pair qq are pushed to the external memory
/// LIFO (last-in, first-out) Stack. The Stack Pointer (SP) register pair
/// holds the 16-bit address of the current top of the Stack. This instruction
/// first decrements SP and loads the high order byte of the register pair qq
/// to the memory address specified by the SP. The SP is decremented again and
/// loads the low order byte of qq to the memory location corresponding to this
/// new address in the SP. The operand qq identifies register pair BC, DE, HL,
/// or AF, assembled as follows in the object code:
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 3 | 11(5,3,3) | 2.75
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_push_xx(void)
{
PUSH(getReg16qq(lastInstByte >> 4));
ticks -= 1;
}
///
/// \brief POP qq
///
/// Operation: qqH <-- (SP+1), qqL <-- (SP)
///
/// Opcode: POP
/// Operands: qq
///
/// Binary | Hex
/// ----------|-------
/// 11qq0101 |
///
/// Register Pair | qq
/// ---------------|-------
/// BC | 00
/// DE | 01
/// HL | 10
/// AF | 11
///
/// Description: The top two bytes of the external memory LIFO (last-in, first-out) Stack
/// are popped to the register pair qq. The Stack Pointer (SP) register pair
/// holds the 16-bit address of the current top of the Stack. This instruction
/// first loads to the low order portion of qq, the byte at memory location
/// corresponding to the contents of SP; then SP is incremented and the
/// contents of the corresponding adjacent memory location are loaded to the
/// high order portion of qq and the SP is incremented again. The operand qq
/// identifies register pair BC, DE, HL, or AF, assembled as follows in the
/// object code:
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 3 | 10(4,3,3) | 2.50
///
/// Condition Bits Affected: None
///
/// \retval none
///
void
Z80::op_pop_xx(void)
{
POP(getReg16qq(lastInstByte >> 4));
}
/// \brief Jump
///
/// \todo - document JP.
///
/// \retval none
///
void
Z80::op_jp(void) // JP
{
PC = READnn();
}
/// \brief JP HL
///
/// \retval none
///
void
Z80::op_jp_hl(void) // JP HL - manual states JP (HL), but this is wrong.
{
PC = getHLReg16Val();;
}
/// \retval none
///
void
Z80::op_jr(void) // JR
{
SBYTE rjmp = sREADn();
// Note: do NOT try to optimize this into a single PC += sREADn(); does not work.
PC += rjmp;
ticks -= 5;
}
/// \retval none
///
void
Z80::op_djnz(void) // DJNZ
{
if (--B)
{
ticks -= 3;
op_jr();
}
else
{
PC++;
ticks -= 4;
}
}
/// \brief CALL
///
/// \retval none
///
void
Z80::op_call(void)
{
WORD i = READnn();
PUSH(PC);
PC = i;
ticks -= 5;
}
/// \brief RET
///
/// \retval none
///
void
Z80::op_ret(void)
{
POP(PC);
}
/// \retval none
///
void
Z80::op_jp_cc(void)
{
if (checkCondition(curInst[0]))
{
PC = READnn();
}
else
{
PC += 2;
}
}
/// \todo - document CALL
///
/// \retval none
///
void
Z80::op_call_cc(void)
{
if (checkCondition(curInst[0]))
{
WORD i = READnn();
PUSH(PC);
PC = i;
ticks -= 5;
}
else
{
PC += 2;
ticks -= 6;
}
}
/// \todo - document RET
///
/// \retval none
///
void
Z80::op_ret_cc(void)
{
ticks -= 1;
if (checkCondition(curInst[0]))
{
POP(PC);
}
}
/// \todo - document JR
///
/// \retval none
///
void
Z80::op_jr_z(void) // JR Z,n
{
if (CHECK_FLAGS(Z_FLAG))
{
op_jr();
}
else
{
PC++;
ticks -= 3;
}
}
/// \todo - FIXME ???
///
/// \retval none
///
void
Z80::op_jr_nz(void) // JR NZ,n
{
if (!CHECK_FLAGS(Z_FLAG))
{
op_jr();
}
else
{
PC++;
ticks -= 3;
}
}
/// \retval none
///
void
Z80::op_jr_c(void) // JR C,n
{
if (CHECK_FLAGS(C_FLAG))
{
op_jr();
}
else
{
PC++;
ticks -= 3;
}
}
/// \retval none
///
void
Z80::op_jr_nc(void) // JR NC,n
{
if (!CHECK_FLAGS(C_FLAG))
{
op_jr();
}
else
{
PC++;
ticks -= 3;
}
}
///
/// \brief RST
///
/// <pre>
/// Operation: (SP-1) <- PCH, (SP-2) <- PCL, PCH <- 0, PCL <- P
///
/// Opcode: RST
/// Operands: p
///
/// Binary | Hex
/// ----------|-------
/// 11-t-111 |
///
/// p | t
/// ------|------
/// 0x00 | 000
/// 0x08 | 001
/// 0x10 | 010
/// 0x18 | 011
/// 0x20 | 100
/// 0x28 | 101
/// 0x30 | 110
/// 0x38 | 111
///
/// Description: The current Program Counter (PC) contents are pushed onto the external
/// memory stack, and the page zero memory location given by operand p is
/// loaded to the PC. Program execution then begins with the Opcode in the
/// address now pointed to by PC. The push is performed by first decrementing
/// the contents of the Stack Pointer (SP), loading the high-order byte of PC to
/// the memory address now pointed to by SP, decrementing SP again, and
/// loading the low order byte of PC to the address now pointed to by SP. The
/// Restart instruction allows for a jump to one of eight addresses indicated in
/// the table below. The operand p is assembled to the object code using the
/// corresponding T state.
///
/// Because all addresses are in page zero of memory, the high order byte of
/// PC is loaded with 00H. The number selected from the p column of the table
/// is loaded to the low order byte of PC.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 3 | 11(5,3,3) | 2.75
///
/// Condition Bits Affected: None
/// </pre>
///
/// \retval none
///
void
Z80::op_rst(void)
{
PUSH(PC);
PC = (lastInstByte & 0x38);
ticks -= 1;
}
///
/// CB Prefix instructions
///
/// \retval none
///
void
Z80::op_cb_handle(void)
{
switch (prefix)
{
case ip_dd:
case ip_fd:
lastInstByte = curInst[2] = readInst();
sW = (signed char) curInst[2];
xxcb_effectiveAddress = getXYReg16Val() + sW;
lastInstByte = curInst[3] = readInst();
(this->*op_xxcb[curInst[3] >> 3])();
break;
case ip_none:
default:
lastInstByte = curInst[1] = readInst();
(this->*op_cb[curInst[1]])();
break;
}
}
/// \brief SRL - Shift Right Logical
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_srl(BYTE& m)
{
COND_FLAGS((m & 1), C_FLAG);
m >>= 1;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief SRL <reg>
///
/// \ref op_srl
///
/// \retval none
///
void
Z80::op_srl_x(void)
{
op_srl(getReg8(lastInstByte));
}
///
/// \brief SRL (HL)
///
/// \ref op_srl
///
/// \retval none
///
void
Z80::op_srl_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_srl(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief SLA - Shift Left Arithmetic
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_sla(BYTE& m)
{
COND_FLAGS((m & 0x80), C_FLAG);
m <<= 1;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief SLA <reg>
///
/// \ref op_sla
///
/// \retval none
///
void
Z80::op_sla_x(void)
{
op_sla(getReg8(lastInstByte));
}
///
/// \brief SLA (HL)
///
/// \ref op_sla
///
/// \retval none
///
void
Z80::op_sla_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_sla(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief undocumented SLL - Shift Left Logical
///
/// \todo - documented
/// same as SLA but bit 0 is set.
/// coded based on "The Undocumented Z80 Documented", vers. 0.91
///
/// \retval none
///
inline void
Z80::op_undoc_sll(BYTE& m)
{
COND_FLAGS((m & 0x80), C_FLAG);
m <<= 1;
m |= 1;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief SLL <reg>
///
/// \ref op_undoc_sll
///
/// \retval none
///
void
Z80::op_sll_x(void)
{
op_undoc_sll(getReg8(lastInstByte));
}
///
/// \brief SLL (HL)
///
/// \ref op_undoc_sll
///
/// \retval none
///
void
Z80::op_sll_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_undoc_sll(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief RL - Rotate Left
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_rl(BYTE& m)
{
BYTE carry = CHECK_FLAGS(C_FLAG) ? 0x01 : 0x00;
COND_FLAGS((m & 128), C_FLAG);
m <<= 1;
m |= carry;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief RL <reg>
///
/// \ref op_rl
///
/// \retval none
///
void
Z80::op_rl_x(void)
{
op_rl(getReg8(lastInstByte));
}
///
/// \brief RL (HL)
///
/// \ref op_rl
///
/// \retval none
///
void
Z80::op_rl_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_rl(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief RR - Rotate Right
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_rr(BYTE& m)
{
BYTE carry = CHECK_FLAGS(C_FLAG) ? 0x80 : 0x00;
COND_FLAGS((m & 1), C_FLAG);
m >>= 1;
m |= carry;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief RR <reg>
///
/// \ref op_rr
///
/// \retval none
///
void
Z80::op_rr_x(void)
{
op_rr(getReg8(lastInstByte));
}
///
/// \brief RR (HL)
///
/// \ref op_rr
///
/// \retval none
///
void
Z80::op_rr_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_rr(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief RRC - Rotate Right Circular
///
/// \todo document
///
/// \retval none
///
inline void
Z80::op_rrc(BYTE& m)
{
BYTE carry = (m & 0x01) ? 0x80 : 0x00;
COND_FLAGS((carry), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
m >>= 1;
m |= carry;
SET_ZSP_FLAGS(m);
}
///
/// \brief RRC <reg>
///
/// \ref op_rrc
///
/// \retval none
///
void
Z80::op_rrc_x(void)
{
op_rrc(getReg8(lastInstByte));
}
///
/// \brief RRC (HL)
///
/// \ref op_rrc
///
/// \retval none
///
void
Z80::op_rrc_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_rrc(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief RLC - Rotate Left Circular
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_rlc(BYTE& m)
{
BYTE carry = (m & 0x80) ? 0x01 : 0x00;
COND_FLAGS((carry), C_FLAG);
CLEAR_FLAGS(H_FLAG | N_FLAG);
m <<= 1;
m |= carry;
SET_ZSP_FLAGS(m);
}
///
/// \brief RLC <reg>
///
/// \ref op_rlc
///
/// \retval none
///
void
Z80::op_rlc_x(void)
{
op_rlc(getReg8(lastInstByte));
}
///
/// \brief RLC (HL)
///
/// \ref op_rlc
///
/// \retval none
///
void
Z80::op_rlc_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_rlc(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief SRA - Shift Right Arithmetic
///
/// \todo - document
///
/// \retval none
///
void
Z80::op_sra(BYTE& m)
{
BYTE i = m & 0x80;
COND_FLAGS((m & 1), C_FLAG);
m >>= 1;
m |= i;
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(m);
}
///
/// \brief SRA <reg>
///
/// \ref op_sra
///
/// \retval none
///
void
Z80::op_sra_x(void)
{
op_sra(getReg8(lastInstByte));
}
///
/// \brief SRA (HL)
///
/// \ref op_sra
///
/// \retval none
///
void
Z80::op_sra_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_sra(val);
writeMEM(addr, val);
ticks -= 1;
}
/// \brief SET - set bit
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_sb_n(BYTE& val)
{
val |= getBit(lastInstByte);
}
///
/// \brief SET <reg>
///
/// \ref op_sb_n
///
/// \retval none
///
void
Z80::op_sb_n_x(void)
{
op_sb_n(getReg8(lastInstByte));
}
///
/// \brief SET (HL)
///
/// \ref op_sb_n
///
/// \retval none
///
void
Z80::op_sb_n_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_sb_n(val);
writeMEM(addr, val);
ticks -= 1;
}
///
/// \brief RES - reset bit
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_rb_n(BYTE& val)
{
val &= ~getBit(lastInstByte);
}
///
/// \brief RES <reg>
///
/// \ref op_rb_n
///
/// \retval none
///
void
Z80::op_rb_n_x(void)
{
op_rb_n(getReg8(lastInstByte));
}
///
/// \brief RES (HL)
///
/// \ref op_rb_n
///
/// \retval none
///
void
Z80::op_rb_n_ihl(void)
{
WORD addr = getIndirectAddr();
BYTE val;
val = readMEM(addr);
op_rb_n(val);
writeMEM(addr, val);
ticks -= 1;
}
///
/// \brief BIT - test bit
///
/// \todo - document
///
/// \retval none
///
inline void
Z80::op_tb_n(BYTE m,
BYTE bit)
{
CLEAR_FLAGS(N_FLAG);
SET_FLAGS(H_FLAG);
m &= bit;
COND_FLAGS((!(m)), (Z_FLAG | P_FLAG));
COND_FLAGS((m & 0x80), S_FLAG);
}
///
/// \brief BIT <reg>
///
/// \ref op_tb_n
///
/// \retval none
///
void
Z80::op_tb_n_x(void)
{
op_tb_n(getReg8(lastInstByte), getBit(lastInstByte));
}
///
/// \brief BIT (HL)
///
/// \ref op_tb_n
///
/// \retval none
///
void
Z80::op_tb_n_ihl(void)
{
op_tb_n(readMEM(getIndirectAddr()), getBit(lastInstByte));
ticks -= 1; // read handles 3 of the ticks, just have to have 1 here.
}
///
/// \brief Handle DD Prefix instructions
///
///
/// \retval none
///
void
Z80::op_dd_handle(void)
{
prefix = ip_dd;
lastInstByte = curInst[1] = readInst();
(this->*op_code[curInst[1]])();
}
///
/// \brief Handle ED Prefix instructions.
///
/// \retval none
///
void
Z80::op_ed_handle(void)
{
lastInstByte = curInst[1] = readInst();
(this->*op_ed[curInst[1]])();
}
///
/// \brief ED prefixed NOP
///
/// Many 2 byte instructions with an ED prefix do not
/// perform any operation, but just act as 2 NOP instructions
///
/// \retval none
///
void
Z80::op_ed_nop(void)
{
// NOP - do nothing.
// It's like 2 NOP instructions..
}
///
/// \brief Interrupt Mode 0
///
/// Operation: -
///
/// Opcode: IM
/// Operands: 0
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01000110 | 0x46
///
/// Description: The IM 0 instruction sets interrupt mode 0. In this mode, the interrupting
/// device can insert any instruction on the data bus for execution by the
/// CPU. The first byte of a multi-byte instruction is read during the interrupt
/// acknowledge cycle. Subsequent bytes are read in by a normal memory
/// read sequence.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 2 | 8(4,4) | 2.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_im0(void)
{
IM = 0;
}
///
/// \brief Interrupt Mode 1
///
/// Operation: -
///
/// Opcode: IM
/// Operands: 1
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01010110 | 0x56
///
/// Description: The IM 1 instruction sets interrupt mode 1. In this mode, the processor
/// responds to an interrupt by executing a restart to location 0038H.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 2 | 8(4,4) | 2.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_im1(void)
{
IM = 1;
}
///
/// \brief Interrupt Mode 2
///
/// Operation: -
///
/// Opcode: IM
/// Operands: 2
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01011110 | 0x5E
///
/// Description: The IM 2 instruction sets the vectored interrupt mode 2. This mode allows
/// an indirect call to any memory location by an 8-bit vector supplied from the
/// peripheral device. This vector then becomes the least-significant eight bits
/// of the indirect pointer, while the I register in the CPU provides the most-
/// significant eight bits. This address points to an address in a vector table
/// that is the starting address for the interrupt service routine.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 2 | 8(4,4) | 2.00
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_im2(void)
{
IM = 2;
}
///
/// \brief Return from Interrupt
///
/// Operation: Return from Interrupt
///
/// Opcode: RETI
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01001101 | 0x4D
///
/// Description: This instruction is used at the end of a maskable interrupt service routine
/// to:
/// * Restore the contents of the Program Counter (PC) (analogous to the
/// RET instruction)
/// * Signal an I/O device that the interrupt routine is completed. The RETI
/// instruction also facilitates the nesting of interrupts, allowing higher
/// priority devices to temporarily suspend service of lower priority
/// service routines. However, this instruction does not enable interrupts
/// that were disabled when the interrupt routine was entered. Before
/// doing the RETI instruction, the enable interrupt instruction (EI)
/// should be executed to allow recognition of interrupts after completion
/// of the current service routine.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 4 | 14(4,4,3,3) | 3.50
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_reti(void)
{
POP(PC);
}
///
/// \brief Return from non-maskable interrupt
///
/// Operation: Return from non maskable interrupt
///
/// Opcode: RETN
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01000101 | 0x45
///
/// Description: This instruction is used at the end of a non-maskable interrupts service
/// routine to restore the contents of the Program Counter (PC) (analogous to
/// the RET instruction). The state of IFF2 is copied back to IFF1 so that
/// maskable interrupts are enabled immediately following the RETN if they
/// were enabled before the non-maskable interrupt.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 4 | 14(4,4,3,3) | 3.50
///
/// Condition Bits Affected: none
///
/// \retval none
///
void
Z80::op_retn(void)
{
POP(PC);
IFF0 = IFF1 = IFF2;
}
///
/// \brief Negate
///
/// Operation: A <- 0 - A
///
/// Opcode: NEG
///
/// Binary | Hex
/// ----------|-------
/// 11101101 | 0xED
/// 01000100 | 0x44
///
///
/// Description: The contents of the Accumulator are negated (two's complement). This is
/// the same as subtracting the contents of the Accumulator from zero. Note
/// that 80H is left unchanged.
///
/// M Cycles| T States | 4 MHz E.T.
/// --------|---------------|------------
/// 2 | 8(4,4) | 2.00
///
/// Condition Bits Affected:
/// * S is set if result is negative; reset otherwise
/// * Z is set if result is 0; reset otherwise
/// * H is set if borrow from bit 4; reset otherwise
/// * P/V is set if Accumulator was 80H before operation; reset otherwise
/// * N is set
/// * C is set if Accumulator was not 00H before operation; reset otherwise
///
/// \retval none
///
void
Z80::op_neg(void)
{
COND_FLAGS((A), C_FLAG);
COND_FLAGS((A == 0x80), P_FLAG);
COND_FLAGS((A & 0xf), H_FLAG);
A = 0 - A;
SET_FLAGS(N_FLAG);
COND_FLAGS((!A), Z_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
}
///
/// \brief IN val, (C)
///
/// \retval none
///
inline void
Z80::op_in_ic(BYTE& reg)
{
reg = io_m->in(C);
CLEAR_FLAGS(N_FLAG | H_FLAG);
SET_ZSP_FLAGS(reg);
ticks -= 4;
}
///
/// \brief IN x,(C)
///
/// \retval none
///
void
Z80::op_in_x_c(void)
{
op_in_ic(getReg8(lastInstByte >> 3));
}
///
/// \brief IN F, (C)
///
/// This instruction only sets the flags, it doesn't store the value
///
/// \retval none
///
void
Z80::op_in_f_ic(void)
{
BYTE tmp;
op_in_ic(tmp);
}
///
/// \brief OUT (C),x
///
/// \retval none
///
void
Z80::op_out_c_x(void)
{
io_m->out(C, getReg8Val(lastInstByte >> 3));
ticks -= 4;
}
///
/// \brief OUT (C),0
///
/// \retval none
///
void
Z80::op_out_c_0(void)
{
io_m->out(C, 0);
ticks -= 4;
}
///
/// \brief INI
///
/// \retval none
///
void
Z80::op_ini(void)
{
writeMEM(HL, io_m->in(C));
HL++;
B--;
SET_FLAGS(N_FLAG);
COND_FLAGS((!B), Z_FLAG);
ticks -= 5;
}
///
/// \brief INIR
///
/// \retval none
///
void
Z80::op_inir(void)
{
op_ini();
if (B)
{
PC -= 2;
ticks -= 5;
}
}
///
/// \brief IND
///
/// \retval none
///
void
Z80::op_ind(void)
{
writeMEM(HL, io_m->in(C));
HL--;
B--;
SET_FLAGS(N_FLAG);
COND_FLAGS((!B), Z_FLAG);
ticks -= 5;
}
///
/// \brief INDR
///
/// \retval none
///
void
Z80::op_indr(void)
{
op_ind();
if (B)
{
PC -= 2;
ticks -= 5;
}
}
///
/// \brief OUTI
///
/// \retval none
///
void
Z80::op_outi(void)
{
io_m->out(C, readMEM(HL));
HL++;
B--;
SET_FLAGS(N_FLAG);
COND_FLAGS((!B), Z_FLAG);
ticks -= 5;
}
///
/// \brief OTIR
///
/// \retval none
///
void
Z80::op_otir(void)
{
op_outi();
if (B)
{
PC -= 2;
ticks -= 5;
}
}
///
/// \brief OUTD
///
/// \retval none
///
void
Z80::op_outd(void)
{
io_m->out(C, readMEM(HL));
HL--;
B--;
SET_FLAGS(N_FLAG);
COND_FLAGS((!B), Z_FLAG);
ticks -= 5;
}
///
/// \brief OTDR
///
/// \retval none
///
void
Z80::op_otdr(void)
{
op_outd();
if (B)
{
PC -= 2;
ticks -= 5;
}
}
///
/// \brief LD A,I
///
/// \retval none
///
void
Z80::op_ld_a_i(void)
{
A = I;
CLEAR_FLAGS(N_FLAG | H_FLAG);
COND_FLAGS((IFF2), P_FLAG);
COND_FLAGS((!A), Z_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
ticks -= 1;
}
///
/// \brief LD A,R
///
/// \retval none
///
void
Z80::op_ld_a_r(void)
{
A = (Rprime & 0x80) | (R & 0x7f);
CLEAR_FLAGS(N_FLAG | H_FLAG);
COND_FLAGS((IFF2), P_FLAG);
COND_FLAGS((!A), Z_FLAG);
COND_FLAGS((A & 0x80), S_FLAG);
ticks -= 1;
}
///
/// \brief LD I,A
///
/// \retval none
///
void
Z80::op_ld_i_a(void)
{
I = A;
ticks -= 1;
}
///
/// \brief LD R,A
///
/// \retval none
///
void
Z80::op_ld_r_a(void)
{
Rprime = A;
R = A;
ticks -= 1;
}
///
/// \brief LD xx,(nn)
///
/// \retval none
///
void
Z80::op_ld_xx_inn(void)
{
getReg16(lastInstByte >> 4) = readWord(READnn());
}
///
/// \brief LD (nn),xx
///
/// \retval none
///
void
Z80::op_ld_inn_xx(void)
{
writeWord(READnn(), getReg16Val(lastInstByte >> 4));
}
/// \brief ADC HL,xx
///
///
/// \retval none
///
inline void
Z80::op_adc16(WORD op)
{
WORD carry = (CHECK_FLAGS(C_FLAG)) ? 1 : 0;
SWORD sOp = op;
int i;
COND_FLAGS(((HL & 0x0fff) + (op & 0x0fff) + carry) > 0x0fff, H_FLAG);
i = sHL + sOp + carry;
COND_FLAGS((i > 32767) || (i < -32768), P_FLAG);
COND_FLAGS((HL + op + carry) & 0x10000, C_FLAG);
i &= 0xffff;
COND_FLAGS(!i, Z_FLAG);
COND_FLAGS(i & 0x8000, S_FLAG);
CLEAR_FLAGS(N_FLAG);
HL = i;
ticks -= 7;
}
///
/// \brief ADC HL,xx
///
/// \retval none
///
void
Z80::op_adc_hl_xx(void)
{
op_adc16(getCoreReg16Val(lastInstByte >> 4));
}
///
/// \brief sbc16
/// \details 16-bit subtract with carry
///
/// \retval none
///
inline void
Z80::op_sbc16(WORD op)
{
WORD carry = (CHECK_FLAGS(C_FLAG)) ? 1 : 0;
SWORD sOp = op;
int i;
COND_FLAGS(((op & 0x0fff) + carry) > (HL & 0x0fff), H_FLAG);
i = sHL - sOp - carry;
COND_FLAGS((i > 32767) || (i < -32768), P_FLAG);
COND_FLAGS((op + carry) > HL, C_FLAG);
i &= 0xffff;
COND_FLAGS(!i, Z_FLAG);
COND_FLAGS(i & 0x8000, S_FLAG);
SET_FLAGS(N_FLAG);
HL = i;
ticks -= 7;
}
///
/// \brief SBC HL,xx
///
/// \retval none
///
void
Z80::op_sbc_hl_xx(void)
{
op_sbc16(getCoreReg16Val(lastInstByte >> 4));
}
///
/// \brief LDI
///
/// \retval none
///
void
Z80::op_ldi(void)
{
writeMEM(DE++, readMEM(HL++));
COND_FLAGS((--BC), P_FLAG);
CLEAR_FLAGS(N_FLAG | H_FLAG);
ticks -= 2;
}
///
/// \brief LDIR
///
/// \retval none
///
void
Z80::op_ldir(void)
{
op_ldi();
if (BC)
{
// BC not zero, repeat instruction.
PC -= 2;
ticks -= 5;
}
}
///
/// \brief LDD
///
/// \retval none
///
void
Z80::op_ldd(void)
{
writeMEM(DE--, readMEM(HL--));
COND_FLAGS((--BC), P_FLAG);
CLEAR_FLAGS(N_FLAG | H_FLAG);
ticks -= 2;
}
///
/// \brief LDDR
///
/// \retval none
///
void
Z80::op_lddr(void)
{
op_ldd();
if (BC)
{
// BC not zero, repeat instruction.
PC -= 2;
ticks -= 5;
}
}
///
/// \brief CPI
///
/// \retval none
///
void
Z80::op_cpi(void)
{
BYTE i;
i = readMEM(HL++);
COND_FLAGS((i & 0xf) > (A & 0xf), H_FLAG);
i = A - i;
SET_FLAGS(N_FLAG);
COND_FLAGS((--BC), P_FLAG);
COND_FLAGS((!i), Z_FLAG);
COND_FLAGS((i & 0x80), S_FLAG);
ticks -= 5;
}
///
/// \brief CPIR
///
/// \retval none
///
void
Z80::op_cpir(void)
{
op_cpi();
if ((BC) && (!CHECK_FLAGS(Z_FLAG)))
{
// not a match and BC not zero, retry instruction.
PC -= 2;
ticks -= 5;
}
}
///
/// \brief CPD
///
/// From The Undocumented Z80 Documented
/// SF, ZF, HF flags - Set by the hypothetical CP (HL).
/// PF flag Set if BC is not 0.
/// NF flag Always set.
/// CF flag Unchanged.
///
/// \retval none
///
void
Z80::op_cpd(void)
{
BYTE i;
i = readMEM(HL--);
COND_FLAGS((i & 0xf) > (A & 0xf), H_FLAG);
i = A - i;
SET_FLAGS(N_FLAG);
COND_FLAGS((--BC), P_FLAG);
COND_FLAGS((!i), Z_FLAG);
COND_FLAGS((i & 0x80), S_FLAG);
ticks -= 5;
}
///
/// \brief CPDR
///
/// \retval none
///
void
Z80::op_cpdr(void)
{
op_cpd();
if ((BC) && (!CHECK_FLAGS(Z_FLAG)))
{
// not a match and BC not zero, retry instruction.
PC -= 2;
ticks -= 5;
}
}
///
/// \brief RLD (HL)
///
/// \todo - document RLD
/// \retval none
///
void
Z80::op_rld_ihl(void)
{
BYTE i, j;
WORD addr = getIndirectAddr();
i = readMEM(addr);
j = A & 0x0f;
A = (A & 0xf0) | (i >> 4);
i = (i << 4) | j;
writeMEM(addr, i);
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(A);
ticks -= 4;
}
///
/// \brief RRD (HL)
///
/// \todo - document RRD
/// \retval none
///
void
Z80::op_rrd_ihl(void)
{
BYTE i, j;
WORD addr = getIndirectAddr();
i = readMEM(addr);
j = A & 0x0f;
A = (A & 0xf0) | (i & 0x0f);
i = (i >> 4) | (j << 4);
writeMEM(addr, i);
CLEAR_FLAGS(H_FLAG | N_FLAG);
SET_ZSP_FLAGS(A);
ticks -= 4;
}
//
// FD Prefix Instructions
//
///
/// \brief Handle FD Prefix Instructions
///
///
/// \retval none
///
void
Z80::op_fd_handle(void)
{
prefix = ip_fd;
lastInstByte = curInst[1] = readInst();
(this->*op_code[curInst[1]])();
}
//
// Prefix DD CB or FD CB
// Actual Operands are either IX or IY
///
/// \brief BIT n,(XY+d)
///
/// \retval none
///
void
Z80::op_tb_n_xx_d(void)
{
op_tb_n(readMEM(xxcb_effectiveAddress), getBit(curInst[3]));
ticks -= 1;
}
///
/// \brief RES n,(XY+d)
///
/// \retval none
///
void
Z80::op_rb_n_xx_d(void)
{
BYTE val;
val = readMEM(xxcb_effectiveAddress);
val &= ~getBit(curInst[3]);
writeMEM(xxcb_effectiveAddress, val);
// The undocumented function of also storing it to one of the register.
if ((curInst[3] & 0x7) != 0x06)
{
getCoreReg8(curInst[3]) = val;
}
ticks -= 1;
}
///
/// \brief SET n,(XY+d)
///
/// \retval none
///
void
Z80::op_sb_n_xx_d(void)
{
BYTE val;
val = readMEM(xxcb_effectiveAddress);
val |= getBit(curInst[3]);
writeMEM(xxcb_effectiveAddress, val);
// The undocumented function of also storing it to one of the register.
if ((curInst[3] & 0x7) != 0x06)
{
getCoreReg8(curInst[3]) = val;
}
ticks -= 1;
}
/// Generic helper routine for both the DDCB and FDCB instructions.
///
inline void
Z80::op_xxx_xx_d(xd_cbMethod operation)
{
BYTE val;
val = readMEM(xxcb_effectiveAddress);
(this->*(operation))(val);
writeMEM(xxcb_effectiveAddress, val);
// The undocumented function of also storing it to one of the register.
if ((curInst[3] & 0x7) != 0x06)
{
getCoreReg8(curInst[3]) = val;
}
ticks -= 1;
}
///
/// \brief RLC (XY+d)
///
/// \retval none
///
void
Z80::op_rlc_xx_d(void)
{
op_xxx_xx_d(&Z80::op_rlc);
}
///
/// \brief RRC (XY+d)
///
/// \retval none
///
void
Z80::op_rrc_xx_d(void)
{
op_xxx_xx_d(&Z80::op_rrc);
}
///
/// \brief RL (XY+d)
///
/// \retval none
///
void
Z80::op_rl_xx_d(void)
{
op_xxx_xx_d(&Z80::op_rl);
}
///
/// \brief RR (XY+d)
///
/// \retval none
///
void
Z80::op_rr_xx_d(void)
{
op_xxx_xx_d(&Z80::op_rr);
}
///
/// \brief SLA (XY+d)
///
/// \retval none
///
void
Z80::op_sla_xx_d(void)
{
op_xxx_xx_d(&Z80::op_sla);
}
///
/// \brief SRA (XY+d)
///
/// \retval none
///
void
Z80::op_sra_xx_d(void)
{
op_xxx_xx_d(&Z80::op_sra);
}
///
/// \brief SRL (XY+d)
///
/// \retval none
///
void
Z80::op_srl_xx_d(void)
{
op_xxx_xx_d(&Z80::op_srl);
}
///
/// \brief SLL (XY+d)
///
/// \retval none
///
void
Z80::op_sll_xx_d(void)
{
op_xxx_xx_d(&Z80::op_undoc_sll);
}
<file_sep>/VirtualH89/Src/h-17-1.h
/// \file h-17-1.h
///
/// \date May 2, 2009
/// \author <NAME>
///
#ifndef H_17_1_H_
#define H_17_1_H_
#include "DiskDrive.h"
///
/// \brief Virtual Single-Sided, 48 tpi Floppy Disk drive.
///
/// Implements a virtual disk drive. Single-Sided, 48 tpi.
/// When connected to the H17 (H-88-1) hard-sector controller, it supports
/// 102 k (40 tracks * 10 sectors/track * 256 bytes/sector)
/// When connected the the H37 (Z-89-37) soft-sector controller it supports
/// both single and double-density disks.
///
class H_17_1: public DiskDrive
{
public:
H_17_1();
virtual ~H_17_1() override;
void getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect) override;
void step(bool direction) override;
void selectSide(BYTE side) override;
BYTE readData(unsigned long pos) override;
void writeData(unsigned long pos,
BYTE data) override;
virtual BYTE readSectorData(BYTE sector,
unsigned long pos) override;
private:
static const unsigned int maxTracks_c = 40;
static const unsigned char head_c = 0;
};
#endif // H_17_1_H_
<file_sep>/VirtualH89/Src/NetworkServer.h
/// \file NetworkServer.h
///
/// Interface for network servers used with CPNetDevice.
/// First implementation was HostFileBdos.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#ifndef NETWORKSERVER_H_
#define NETWORKSERVER_H_
/// \cond
#include <stdint.h>
/// \endcond
class NetworkServer
{
public:
NetworkServer();
virtual ~NetworkServer();
virtual int checkRecvMsg(uint8_t clientId, uint8_t* msgbuf, int len) = 0;
virtual int sendMsg(uint8_t* msgbuf, int len) = 0;
// This is the standard CP/Net message header.
struct ndos
{
uint8_t mcode; // cmd=00, response=01, for CP/Net
uint8_t mdid;
uint8_t msid;
uint8_t mfunc;
uint8_t msize; // size is msize+1 (1-256 bytes)
};
private:
};
#endif // NETWORKSERVER_H_
<file_sep>/VirtualH89/Src/ParallelLink.h
///
/// \name ParallelLink.h
///
///
/// \date Aug 12, 2013
/// \author <NAME>
///
#ifndef PARALLELLINK_H_
#define PARALLELLINK_H_
#include "h89Types.h"
class ParallelPortConnection;
/// Parallel Interface between the H/Z-47 Disk Drive System to the H8 or H89 computer
///
/// I/O Transaction Sequence
///
/// All I/O transactions between the computer and the disk system operates as follows:
///
/// a. The first byte transferred to the subsystem while it is in a system ready
/// state (that is busy false and DTR true) is interpreted as a command. The disk
/// system will set busy true and DTR false upon receipt of a command (including
/// invalid commands).
///
/// b. The disk system will determine the direction of data transfer using the DDOut
/// line. DDOut true indicates data flow to the computer; DDOut false indicates data
/// flow from the computer.
///
/// c. All data transfers are requested by the disk system by setting DTR true.
///
/// d. All data transfers must be acknowledged by the computer with a DTAK in response
/// to a DTR from the disk system. NOTE: Data input or output, to or from the computer,
/// precede a DTAK. Data output from the H8 must remain valid until DTR goes low.
///
/// e. The error flag is valid for the preceding operation (that is, when the disk system
/// completes an operation and sets BUSY false and DTR true).
///
/// f. MRST (Master ReSeT) will unconditionally abort any command and set the disk system
/// to the system ready state. The error flag will not be valid.
///
/// g. When a command has completed, the disk system will return to the system ready state.
///
/// Depending on the command presented by the computer, the disk system will request
/// additional parameters (unit number, track number, sector number, etc.) in the sequence
/// outlined in steps c and d above.
///
class ParallelLink
{
public:
ParallelLink();
virtual ~ParallelLink();
virtual void sendHostData(BYTE val);
virtual void sendDriveData(BYTE val);
virtual void readDataBusByHost(BYTE& val);
virtual void readDataBusByDrive(BYTE& val);
virtual void setBusy(bool val);
virtual bool readBusy();
virtual void setDTR(bool val);
virtual bool readDTR();
virtual void masterReset();
virtual void setDDOut(bool val);
virtual bool readDDOut();
virtual void setDTAK(bool val);
virtual bool readDTAK();
virtual void setError(bool val);
virtual bool readError();
virtual void registerDevice(ParallelPortConnection* device);
virtual void registerHost(ParallelPortConnection* host);
protected:
BYTE data_m;
bool dataFromHost_m;
bool dataFromDrive_m;
/// Busy output. A true indicates that the disk system has received a command and is
/// in the process of executing that command (including illegal commands). A low
/// indicates that the disk sytem is idle and will accept a command.
bool busy_m;
/// Data Transfer Request output. A true indicates that the the disk system requires
/// data on the data bas for an input (DDOUT false) or has placed data on the bus for an
/// output (DDOUT true). DTR will become false after the data bus is invalid.
bool DTR_m;
/// Master ReSeT input. A true will cause the system to stop any operation in process,
/// clear error conditions, raise all master and slave heads, and reset the disk system
/// to an idle state.
bool MRST_m;
/// Data Direction OUT to H8. The data direction signal line is controlled by the disk
/// system to indicate the direction that data is being transmitted on the bidirectional
/// data bus D0 through D7. A false signal indicates a data transfer into the disk system.
/// A true indicates a data transfer to the H8.
bool DDOut_m;
/// Data Transfer AcKnowledge. A true from the H8 acknowledges that data has been place
/// on or taken from the data bus, depending on the level of DDOut in response to DTR.
bool DTAK_m;
/// ERROR output. A true indicates that one of the following error conditions has
/// occurred:
/// (1) Record not found
/// (2) CRC error
/// (3) Lost data
/// (4) Illegal command
/// (5) Excess bad tracks
/// (6) Drive not ready when accessed
/// (7) Attempting to write on a write protected diskette
/// (8) Sector with deleted data mark encountered.
/// The specific error condition(s) can be found by a read status command.
bool error_m;
// pointer to the host computer
ParallelPortConnection* host_m;
// pointer to the drive subsystem
ParallelPortConnection* device_m;
};
#endif // PARALLELLINK_H_
<file_sep>/VirtualH89/Src/h-17-4.cpp
///
/// \file h-17-4.cpp
///
/// \date Jul 21, 2012
/// \author <NAME>
///
#include "h-17-4.h"
#include "logger.h"
#include "FloppyDisk.h"
H_17_4::H_17_4(): DiskDrive(maxTracks_c),
side_m(0),
track_m(0)
{
}
H_17_4::~H_17_4()
{
}
void
H_17_4::getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect)
{
debugss(ssH17_4, INFO, "pos: %ld\n", pos);
trackZero = (track_m == 0);
if (disk_m)
{
disk_m->getControlInfo(pos, hole, writeProtect);
}
else
{
debugss(ssH17_4, INFO, "no disk_m\n");
hole = true;
writeProtect = false;
}
}
void
H_17_4::step(bool direction)
{
if (direction)
{
if (track_m < 79)
{
++track_m;
}
debugss(ssH17_4, WARNING, "in(up) (%d)\n", track_m);
}
else
{
if (track_m)
{
--track_m;
}
debugss(ssH17_4, WARNING, "out(down) (%d)\n", track_m);
}
}
void
H_17_4::selectSide(BYTE side)
{
if (side == side_m)
{
return;
}
debugss(ssH17_4, WARNING, "%d\n", side);
if ((side == 0) || (side == 1))
{
side_m = side;
}
else
{
debugss(ssH17_4, ERROR, "Invalid Side: %d\n", side);
}
}
BYTE
H_17_4::readData(unsigned long pos)
{
BYTE data = 0;
if ((disk_m) && (disk_m->readData(side_m, track_m, pos, data)))
{
debugss(ssH17_4, INFO, "read passed - pos(%lu) data(%d)\n", pos, data);
}
else
{
debugss(ssH17_4, WARNING, "read failed - pos(%lu)\n", pos);
}
return data;
}
void
H_17_4::writeData(unsigned long pos,
BYTE data)
{
debugss(ssH17_4, INFO, "pos(%lu) data(%d)\n", pos, data);
if ((disk_m) && (!disk_m->writeData(side_m, track_m, pos, data)))
{
debugss(ssH17_4, WARNING, "pos(%lu)\n", pos);
}
}
BYTE
H_17_4::readSectorData(BYTE sector,
unsigned long pos)
{
BYTE data = 0;
if ((disk_m) && (disk_m->readSectorData(side_m, track_m, sector, pos, data)))
{
debugss(ssH17_4, INFO, "read passed - pos(%lu) data(%d)\n", pos, data);
}
else
{
debugss(ssH17_4, WARNING, "read failed - pos(%lu)\n", pos);
}
return data;
}
<file_sep>/VirtualH89/Src/CPNetDevice.h
/// \file CPNetDevice.h
///
/// Virtual access to host filesystem via CP/Net-style I/O device.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#ifndef CPNETDEVICE_H_
#define CPNETDEVICE_H_
#include "IODevice.h"
#include "NetworkServer.h"
#include "propertyutil.h"
/// \cond
#include <dirent.h>
#include <string>
/// \endcond
class CPNetDevice: public IODevice
{
public:
CPNetDevice(int base, int clientId);
virtual ~CPNetDevice();
static CPNetDevice* install_CPNetDevice(PropertyUtil::PropertyMapT& props);
virtual BYTE in(BYTE adr);
virtual void out(BYTE adr, BYTE val);
virtual void reset();
private:
std::map<BYTE, NetworkServer*> servers;
void addServer(BYTE serverId, NetworkServer* server);
void swapIds(struct NetworkServer::ndos* header);
int sendMsg(BYTE* msgbuf, int len);
int checkRecvMsg(BYTE clientId, BYTE* msgbuf, int len);
static const int ndosLen = sizeof(struct NetworkServer::ndos);
BYTE clientId;
const char* dir;
BYTE buffer[256 + ndosLen];
struct NetworkServer::ndos* header;
int bufIx;
int msgLen;
int respLen;
bool initDev;
static const BYTE serverId = 0;
static const int BUFFER_OVERRUN = 512; // any value larger than buffer[]
static const int dataPortOffset = 0;
static const int statusPortOffset = 1;
static const BYTE sts_DataReady = 0x01;
static const BYTE sts_CmdOverrun = 0x02;
static const BYTE sts_RespUnderrun = 0x04;
static const BYTE sts_Error = 0x08;
};
#endif // CPNETDEVICE_H_
<file_sep>/VirtualH89/Src/Track.cpp
///
/// \name Track.cpp
///
///
/// \date Jun 21, 2013
/// \author <NAME>
///
#include "Track.h"
#include "Sector.h"
#include "logger.h"
using namespace std;
Track::Track(BYTE sideNum,
BYTE trackNum): sideNum_m(sideNum),
trackNum_m(trackNum),
density_m(density_Unknown),
dataRate_m(dr_Unknown),
formattingMode_m(fs_none)
{
}
Track::~Track()
{
}
void
Track::startFormat()
{
sectors_m.clear();
formattingMode_m = fs_waitingForIndex;
}
BYTE
Track::getTrackNumber()
{
return trackNum_m;
}
BYTE
Track::getSideNumber()
{
return sideNum_m;
}
bool
Track::addSector(shared_ptr<Sector> sector)
{
sectors_m.push_back(sector);
return false;
}
void
Track::dump()
{
debugss(ssFloppyDisk, INFO, "Dumping track - head: %d track: %d\n", sideNum_m,
trackNum_m);
for (shared_ptr<Sector> sector : sectors_m)
{
debugss(ssFloppyDisk, INFO, " Sector: %d\n", sector->getSectorNum());
sector->dump();
}
}
void
Track::setDensity(Density density)
{
density_m = density;
}
void
Track::setDataRate(DataRate datarate)
{
dataRate_m = datarate;
}
shared_ptr<Sector>
Track::findSector(BYTE sectorNum)
{
for (shared_ptr<Sector> sector : sectors_m)
{
if (sector->getSectorNum() == sectorNum)
{
debugss(ssFloppyDisk, INFO, "found\n");
return sector;
}
}
return nullptr;
}
<file_sep>/VirtualH89/Src/H19TextFrame.cpp
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: H19TextFrame.cpp
// Purpose:
// Author:
// Modified by:
// Created: Sun 23 Apr 2017 06:59:01 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include "H19TextFrame.h"
////@begin XPM images
////@end XPM images
/*
* H19TextFrame type definition
*/
IMPLEMENT_DYNAMIC_CLASS( H19TextFrame, wxScrolledWindow )
/*
* H19TextFrame event table definition
*/
BEGIN_EVENT_TABLE( H19TextFrame, wxScrolledWindow )
////@begin H19TextFrame event table entries
EVT_PAINT( H19TextFrame::OnPaint )
EVT_CHAR( H19TextFrame::OnChar )
////@end H19TextFrame event table entries
END_EVENT_TABLE()
#include "VirtualH89Frame.h"
#include "h19.h"
#include "GUIwxWidgets.h"
extern GUIwxWidgets *TheGUIwxWidgets;
/*
* H19TextFrame constructors
*/
H19TextFrame::H19TextFrame()
{
Init();
}
H19TextFrame::H19TextFrame(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
Init();
Create(parent, id, pos, size, style);
}
/*
* H19TextFrame creator
*/
bool H19TextFrame::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
////@begin H19TextFrame creation
wxScrolledWindow::Create(parent, id, pos, size, style);
CreateControls();
////@end H19TextFrame creation
return true;
}
/*
* H19TextFrame destructor
*/
H19TextFrame::~H19TextFrame()
{
////@begin H19TextFrame destruction
////@end H19TextFrame destruction
}
/*
* Member initialisation
*/
void H19TextFrame::Init()
{
////@begin H19TextFrame member initialisation
////@end H19TextFrame member initialisation
}
/*
* Control creation for H19TextFrame
*/
void H19TextFrame::CreateControls()
{
////@begin H19TextFrame content construction
H19TextFrame* itemScrolledWindow1 = this;
this->SetForegroundColour(wxColour(255, 255, 255));
this->SetBackgroundColour(wxColour(0, 0, 0));
this->SetScrollbars(1, 1, 0, 0);
////@end H19TextFrame content construction
}
/*
* wxEVT_PAINT event handler for ID_SCROLLEDWINDOW_H19Text
*/
void H19TextFrame::OnPaint( wxPaintEvent& event )
{
////@begin wxEVT_PAINT event handler for ID_SCROLLEDWINDOW_H19Text in H19TextFrame.
// Before editing this code, remove the block markers.
wxPaintDC dc(this);
////@end wxEVT_PAINT event handler for ID_SCROLLEDWINDOW_H19Text in H19TextFrame.
// Initial paint will not have the emulator running. Check for that.
if (H19::GetH19())
{
// Draw the character using the font bitmaps.
for (auto y = 0u; y < H19Screen::rows_c; ++y)
{
for (auto x = 0u; x < H19Screen::cols_c; ++x)
{
unsigned int Char = H19::GetH19()->screen_m[x][y] & 0xFFu;
// Chars above 0x80 are inverse video of the ASCII char.
// Get ASCII char.
unsigned int ASCIIChar = Char & 0x7Fu;
if ((ASCIIChar >= ' ') && (ASCIIChar < 0x7Fu))
{
// Draw the character at the correct location using the bitmap
// for that character. The bitmaps were created in VirtualH89Frame::CreateControl().
dc.DrawBitmap(FontBitmaps[Char], x * 8u, y * 20u);
}
}
}
}
return;
}
/*
* Should we show tooltips?
*/
bool H19TextFrame::ShowToolTips()
{
return true;
}
/*
* Get bitmap resources
*/
wxBitmap H19TextFrame::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin H19TextFrame bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end H19TextFrame bitmap retrieval
}
/*
* Get icon resources
*/
wxIcon H19TextFrame::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin H19TextFrame icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end H19TextFrame icon retrieval
}
/*
* wxEVT_CHAR event handler for ID_SCROLLEDWINDOW_H19Text
*/
void H19TextFrame::OnChar( wxKeyEvent& event )
{
////@begin wxEVT_CHAR event handler for ID_SCROLLEDWINDOW_H19Text in H19TextFrame.
// Before editing this code, remove the block markers.
event.Skip();
////@end wxEVT_CHAR event handler for ID_SCROLLEDWINDOW_H19Text in H19TextFrame.
if (TheGUIwxWidgets->GUIKeyboardFunc)
{
int Key = event.GetKeyCode();
switch (Key)
{
case WXK_F1:
TheGUIwxWidgets->GUIKeyboardFunc('S' | 0x80);
break;
case WXK_F2:
TheGUIwxWidgets->GUIKeyboardFunc('T' | 0x80);
break;
case WXK_F3:
TheGUIwxWidgets->GUIKeyboardFunc('U' | 0x80);
break;
case WXK_F4:
TheGUIwxWidgets->GUIKeyboardFunc('V' | 0x80);
break;
case WXK_F5:
TheGUIwxWidgets->GUIKeyboardFunc('W' | 0x80);
break;
case WXK_F6:
TheGUIwxWidgets->GUIKeyboardFunc('P' | 0x80);
break;
case WXK_F7:
TheGUIwxWidgets->GUIKeyboardFunc('Q' | 0x80);
break;
case WXK_F8:
TheGUIwxWidgets->GUIKeyboardFunc('R' | 0x80);
break;
case WXK_HOME:
TheGUIwxWidgets->GUIKeyboardFunc('H' | 0x80);
break;
case WXK_UP:
TheGUIwxWidgets->GUIKeyboardFunc('A' | 0x80);
break;
case WXK_DOWN:
TheGUIwxWidgets->GUIKeyboardFunc('B' | 0x80);
break;
case WXK_LEFT:
TheGUIwxWidgets->GUIKeyboardFunc('D' | 0x80);
break;
case WXK_RIGHT:
TheGUIwxWidgets->GUIKeyboardFunc('C' | 0x80);
break;
default:
TheGUIwxWidgets->GUIKeyboardFunc(Key);
break;
}
}
return;
}
#endif
<file_sep>/VirtualH89/Src/SoftSectoredDisk.h
///
/// \name SoftSectoredDisk.h
///
///
/// \date Oct 2, 2012
/// \author <NAME>
///
#ifndef SOFTSECTOREDDISK_H_
#define SOFTSECTOREDDISK_H_
// #include "FloppyDisk.h"
#include "GenericFloppyDisk.h"
/// \cond
#include <vector>
/// \endcond
class DiskSide;
class Track;
class Sector;
class SoftSectoredDisk: public GenericFloppyDisk
{
public:
SoftSectoredDisk();
virtual ~SoftSectoredDisk() override;
virtual bool readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data) override;
virtual bool writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result) override;
bool findSector(BYTE sideNum,
BYTE trackNum,
BYTE sectorNum) override;
virtual bool isReady() override;
virtual void eject(const std::string name) override;
virtual void dump(void) override;
/* enum DiskImageFormat
{
dif_Unknown,
dif_RAW,
dif_IMD,
dif_TD0,
dif_8RAW
};
SoftSectoredDisk(const char* name,
DiskImageFormat format);
SoftSectoredDisk();
virtual ~SoftSectoredDisk();
virtual bool readData(BYTE side,
BYTE track,
unsigned long pos,
BYTE& data);
virtual bool writeData(BYTE side,
BYTE track,
unsigned long pos,
BYTE data);
virtual void getControlInfo(unsigned long pos,
bool& hole,
bool& writeProtect);
virtual bool readSectorData(BYTE side,
BYTE track,
BYTE sector,
WORD pos,
BYTE& data);
virtual void eject(const char* name);
*/
protected:
std::vector<std::shared_ptr<DiskSide> > sideData_m;
BYTE numSides_m;
std::shared_ptr<Sector> curSector_m;
unsigned sectorPos_m;
unsigned sectorLength_m;
BYTE secLenCode_m;
bool ready_m;
virtual void addTrack(std::shared_ptr<Track> track);
/* static const unsigned int bytesPerTrack_c = 6400;
static const unsigned int tracksPerSide_c = 80;
static const unsigned int maxHeads_c = 2;
BYTE rawImage_m[maxHeads_c][tracksPerSide_c][bytesPerTrack_c];
std::vector <Track*> tracks_m[maxHeads_c];
BYTE maxTrack_m;
bool initialized_m = false;
BYTE numTracks_m = 80;
BYTE numHeads_m = 2;
BYTE numSectors_m = 10;
// move these to track, that is how it is encoded in IMD files.
// DataRate dataRate_m;
bool defaultHoleStatus(unsigned long pos);
void determineDiskFormat(const char* name,
DiskImageFormat& format);
bool readTD0(const char* name);
bool readIMD(const char* name);
bool readRaw(const char* name);
bool readRaw8(const char* name);
protected:
void dump();
*/
};
#endif // SOFTSECTOREDDISK_H_
<file_sep>/VirtualH89/Src/h19.cpp
/// \file h19.cpp
///
/// \date Apr 12, 2009
/// \author <NAME>
///
#include "h19.h"
// #include "h19-font.h"
#include "logger.h"
#include "ascii.h"
/// \cond
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
/// \endcond
// \TODO make this run-time config.
#define CONSOLE_LOG 1
static pthread_mutex_t h19_mutex;
H19* H19::h19;
unsigned int H19::screenRefresh_m = screenRefresh_c;
H19::H19(std::string sw401, std::string sw402): Console(0, nullptr),
countdownToSend_m(0),
characterDelay_m(2133),
updated_m(true),
offline_m(false)
// TODO: Remove
// ,
// curCursor_m(false)
{
h19 = this;
pthread_mutex_init(&h19_mutex, nullptr);
setSW401((BYTE) strtol(sw401.c_str(), nullptr, 2));
setSW402((BYTE) strtol(sw402.c_str(), nullptr, 2));
reset();
}
H19::~H19()
{
pthread_mutex_destroy(&h19_mutex);
}
void
H19::setSW401(BYTE sw401)
{
// Manual suggested setting for Zenith/Heath Computer
// 10001100 (0x8c)
//
// ------------------------
// | Bit | Meaning |
// +======+===============+
// | 7 | Duplex |
// | 6 | Sitck Parity |
// | 5 | Even Parity |
// | 4 | Parity |
// | 3 | Baud Rate |
// | 2 | Baud Rate |
// | 1 | Baud Rate |
// | 0 | Baud Rate |
// +======+===============+
//
sw401_m = sw401;
// \todo implement serial settings.
}
void
H19::setSW402(BYTE sw402)
{
//
// ------------------------
// | Bit | Meaning |
// +======+===============+
// | 7 | Refresh Freq |
// | 6 | Keypad mode |
// | 5 | Zenith/ANSI |
// | 4 | Auto CR |
// | 3 | Auto LF |
// | 2 | Wrap at EOL |
// | 1 | Key Click |
// | 0 | Cursor type |
// +======+===============+
//
sw402_m = sw402;
// should anything be done with refresh frequency
keypadShifted_m = ((sw402 & KeypadMode_c) == KeypadMode_c);
// don't support ANSI yet, so can't do anything here.. - 5 - Zenith/ANSI
autoCR_m = ((sw402 & AutoCR_c) == AutoCR_c);
autoLF_m = ((sw402 & AutoLF_c) == AutoLF_c);
wrapEOL_m = ((sw402 & WrapEOL_c) == WrapEOL_c);
keyClick_m = ((sw402 & KeyClick_c) == KeyClick_c);
cursorBlock_m = ((sw402 & BlockCursor) == BlockCursor);
}
bool
H19::checkUpdated()
{
pthread_mutex_lock(&h19_mutex);
static unsigned int count = 0;
if (!cursorOff_m)
{
if ((++count % 20) == 0)
{
curCursor_m = !curCursor_m;
updated_m = true;
}
}
bool tmp = updated_m;
updated_m = false;
pthread_mutex_unlock(&h19_mutex);
return tmp;
}
void
H19::init()
{
}
void
H19::display()
{
pthread_mutex_lock(&h19_mutex);
TheGUI->GUIDisplay();
pthread_mutex_unlock(&h19_mutex);
}
void
H19::receiveData(BYTE ch)
{
pthread_mutex_lock(&h19_mutex);
processCharacter(ch);
pthread_mutex_unlock(&h19_mutex);
}
void
H19::keypress(char ch)
{
pthread_mutex_lock(&h19_mutex);
/// \todo fix this
if (offline_m)
{
processCharacter(ch);
}
else
{
if ((ch & 0x80) != 0)
{
// TODO: modify keycode based on current terminal mode,
// e.g. convert to ZDS or ANSI codes.
// Note difference from H19 keyboard: a modern keyboard
// has separate cursor keys that are always active,
// so it is as if the user pressed SHIFT to get the code.
sendData(ascii::ESC);
sendData(ch & 0x7f);
}
else
{
sendData(ch);
}
}
pthread_mutex_unlock(&h19_mutex);
}
void
H19::reset()
{
/// \todo - make sure these modes are the defaults.
/// \todo - some of these are affected by dipswitches - implement.
mode_m = Normal;
reverseVideo_m = false;
graphicMode_m = false;
insertMode_m = false;
line25_m = false;
holdScreen_m = false;
cursorOff_m = false;
altKeypadMode_m = false;
keyboardEnabled_m = true;
setSW401(sw401_m);
setSW402(sw402_m);
posX_m = 0;
posY_m = 0;
saveX_m = 0;
saveY_m = 0;
for (unsigned int y = 0; y < rows_c; ++y)
{
eraseLine(y);
}
// specify the special symbol to end the line.
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][rows_c] = 0x100;
}
}
void
H19::consoleLog(std::string message)
{
#if CONSOLE_LOG
fprintf(console_out, "%s", message.c_str());
#endif
}
void
H19::processCharacter(char ch)
{
// mask off the high bit just in case, the real H19 would not have it set.
ch &= 0x7f;
if (mode_m == Normal)
{
switch (ch)
{
case ascii::NUL:
case ascii::SOH:
case ascii::STX:
case ascii::ETX:
case ascii::EOT:
case ascii::ENQ:
case ascii::ACK:
case ascii::VT:
case ascii::FF:
case ascii::SO:
case ascii::SI:
case ascii::DLE:
case ascii::DC1:
case ascii::DC2:
case ascii::DC3:
case ascii::DC4:
case ascii::NAK:
case ascii::SYN:
case ascii::ETB:
case ascii::EM:
case ascii::SUB:
case ascii::FS:
case ascii::GS:
case ascii::RS:
case ascii::US:
case ascii::DEL:
// From manual, these characters are not processed by the terminal
break;
case ascii::BEL: // Rings the bell.
/// \todo - implement ringing bell.
consoleLog("<BEL>");
break;
case ascii::BS: // Backspace
consoleLog("<BS>");
processBS();
break;
case ascii::HT: // Horizontal Tab
consoleLog("<TAB>");
processTAB();
break;
case ascii::LF: // Line Feed
processLF();
if (autoCR_m)
{
processCR();
}
consoleLog("\n");
break;
case ascii::CR: // Carriage Return
processCR();
if (autoLF_m)
{
processLF();
}
break;
case ascii::CAN: // Cancel.
break;
case ascii::ESC: // Escape
mode_m = Escape;
consoleLog("<ESC>");
break;
default:
// if Printable character display it.
#if CONSOLE_LOG
fprintf(console_out, "%c", ch);
#endif
displayCharacter(ch);
break;
}
}
else if (mode_m == Escape)
{
// Assume we go back to Normal, so only the few that don't need to set the mode.
mode_m = Normal;
switch (ch)
{
case ascii::CAN: // CAN - Cancel
// return to Normal mode, already set.
break;
case ascii::ESC: // Escape
// From the ROM listing, stay in this mode.
mode_m = Escape;
break;
// Cursor Functions
case 'H': // Cursor Home
posX_m = posY_m = 0;
updated_m = true;
break;
case 'C': // Cursor Forward
cursorForward();
break;
case 'D': // Cursor Backward
processBS(); // same processing as cursor backward
break;
case 'B': // Cursor Down
cursorDown();
break;
case 'A': // Cursor Up
cursorUp();
break;
case 'I': // Reverse Index
reverseIndex();
break;
case 'n': // Cursor Position Report
cursorPositionReport();
break;
case 'j': // Save cursor position
saveCursorPosition();
break;
case 'k': // Restore cursor position
restoreCursorPosition();
break;
case 'Y': // Direct Cursor Addressing
mode_m = DCA_1;
break;
// Erase and Editing
case 'E': // Clear Display
clearDisplay();
break;
case 'b': // Erase Beginning of Display
eraseBOD();
break;
case 'J': // Erase to End of Page
eraseEOP();
break;
case 'l': // Erase entire Line
eraseEL();
break;
case 'o': // Erase Beginning Of Line
eraseBOL();
break;
case 'K': // Erase To End Of Line
eraseEOL();
break;
case 'L': // Insert Line
insertLine();
break;
case 'M': // Delete Line
deleteLine();
break;
case 'N': // Delete Character
deleteChar();
break;
case '@': // Enter Insert Character Mode
insertMode_m = true;
break;
case 'O': // Exit Insert Character Mode
insertMode_m = false;
break;
// Configuration
case 'z': // Reset To Power-Up Configuration
reset();
break;
case 'r': // Modify the Baud Rate
/// \todo - determine if we should support this.
debugss(ssH19, ERROR, "Error Unimplemented Modify Baud\n");
break;
case 'x': // Set Mode
mode_m = SetMode;
break;
case 'y': // Reset Mode
mode_m = ResetMode;
break;
case '<': // Enter ANSI Mode
/// \todo - implement ANSI mode.
// ROM - just sets the mode
debugss(ssH19, ERROR, "Error Entering ANSI mode - unsupported\n");
break;
// Modes of operation
case '[': // Enter Hold Screen Mode
holdScreen_m = true;
break;
case '\\': // Exit Hold Screen Mode
holdScreen_m = false;
break;
case 'p': // Enter Reverse Video Mode
reverseVideo_m = true;
break;
case 'q': // Exit Reverse Video Mode
reverseVideo_m = false;
break;
case 'F': // Enter Graphics Mode
graphicMode_m = true;
break;
case 'G': // Exit Graphics Mode
graphicMode_m = false;
break;
case 't': // Enter Keypad Shifted Mode
keypadShifted_m = true;
break;
case 'u': // Exit Keypad Shifted Mode
// ROM - just sets the mode
keypadShifted_m = false;
break;
case '=': // Enter Alternate Keypad Mode
// ROM - just sets the mode
keypadShifted_m = true;
break;
case '>': // Exit Alternate Keypad Mode
// ROM - just sets the mode
keypadShifted_m = false;
break;
// Additional Functions
case '}': // Keyboard Disable
/// \todo - determine whether to do this.
keyboardEnabled_m = false;
break;
case '{': // Keyboard Enable
keyboardEnabled_m = true;
break;
case 'v': // Wrap Around at End Of Line
wrapEOL_m = true;
break;
case 'w': // Discard At End Of Line
wrapEOL_m = false;
break;
case 'Z': // Identify as VT52 (Data: ESC / K)
debugss(ssH19, ERROR, "Identify request\n");
sendData(ascii::ESC);
sendData('/');
sendData('K');
break;
case ']': // Transmit 25th Line
transmitLine25();
break;
case '#': // Transmit Page
transmitPage();
break;
default:
debugss(ssH19, WARNING, "Unhandled ESC: %d\n", ch);
/// \todo - verify this is how the H19 ROM does it.
break;
}
}
else if (mode_m == SetMode)
{
mode_m = Normal;
switch (ch)
{
case '1': // Enable 25th line
// From the ROM, it erases line 25 on the enable, but here we erase on the disable.
line25_m = true;
break;
case '2': // No key click
keyClick_m = true;
break;
case '3': // Hold screen mode
holdScreen_m = true;
break;
case '4': // Block Cursor
cursorBlock_m = true;
updated_m = true;
break;
case '5': // Cursor Off
cursorOff_m = true;
updated_m = true;
break;
case '6': // Keypad Shifted
keypadShifted_m = true;
break;
case '7': // Alternate Keypad mode
altKeypadMode_m = true;
break;
case '8': // Auto LF
autoLF_m = true;
break;
case '9': // Auto CR
autoCR_m = true;
break;
default:
/// \todo Need to process ch as if none of this happened...
debugss(ssH19, WARNING, "Invalid set Mode: %c\n", ch);
break;
}
}
else if (mode_m == ResetMode)
{
mode_m = Normal;
switch (ch)
{
case '1': // Disable 25th line
eraseLine(rowsMain_c);
line25_m = false;
updated_m = true;
break;
case '2': // key click
keyClick_m = false;
break;
case '3': // Hold screen mode
holdScreen_m = false;
break;
case '4': // Block Cursor
cursorBlock_m = false;
updated_m = true;
break;
case '5': // Cursor On
cursorOff_m = false;
updated_m = true;
break;
case '6': // Keypad Unshifted
keypadShifted_m = false;
break;
case '7': // Exit Alternate Keypad mode
altKeypadMode_m = false;
break;
case '8': // No Auto LF
autoLF_m = false;
break;
case '9': // No Auto CR
autoCR_m = false;
break;
default:
/// \todo Need to process ch as if none of this happened...
debugss(ssH19, WARNING, "Invalid reset Mode: %c\n", ch);
break;
}
}
else if (mode_m == DCA_1)
{
// From actual H19, once the line is specified, the cursor
// immediately moves to that line, so no need to save the
// position and wait for the entire command.
/// \todo verify that this is the same on newer H19s.
if (ch == ascii::CAN)
{
// cancel
mode_m = Normal;
}
else
{
// \todo handle error conditions
int pos = ch - 31;
// verify valid Position
if (((pos > 0) && (pos < (signed) rows_c)) || ((pos == (signed) rows_c) && (line25_m)))
{
posY_m = pos - 1;
}
else
{
/// \todo check to see how a real h19 handles this.
debugss(ssH19, INFO, "DCA invalid Y: %d\n", pos);
}
mode_m = DCA_2;
}
}
else if (mode_m == DCA_2)
{
if (ch == ascii::CAN)
{
// cancel
mode_m = Normal;
}
else
{
int pos = ch - 31;
if ((pos > 0) && (pos < 81))
{
posX_m = pos - 1;
}
else
{
posX_m = (cols_c - 1);
}
updated_m = true;
mode_m = Normal;
}
}
}
/// \brief Display character
///
void
H19::displayCharacter(unsigned int ch)
{
// when in graphic mode, use this lookup table to determine character to display,
// note: although entries 0 to 31 are defined, they are not used, since the control
// characters are specifically checked in the switch statement.
static char graphicLookup[0x80] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 127, 31,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32
};
unsigned int symbol;
if (graphicMode_m)
{
// Look up symbol
symbol = graphicLookup[ch];
}
else
{
symbol = ch;
}
if (reverseVideo_m)
{
// set the high-bit for reverse video.
symbol |= 0x80;
}
if (!((posX_m <= cols_c) && (posY_m < rows_c)))
{
debugss(ssH19, ERROR, "Invalid posX_m, posY_m: %d, %d\n", posX_m, posY_m);
posX_m = 0;
posY_m = 0;
}
if (insertMode_m)
{
for (unsigned int x = (cols_c - 1); x > posX_m; --x)
{
screen_m[x][posY_m] = screen_m[x - 1][posY_m];
}
}
if (posX_m >= cols_c)
{
if (wrapEOL_m)
{
posX_m = 0;
if (posY_m < (rowsMain_c - 1))
{
posY_m++;
}
else if (posY_m == (rowsMain_c - 1))
{
scroll();
}
else
{
// On a real H19, it just wraps back to column 0, and stays
// on line 25 (24)
assert(posY_m == rowsMain_c);
}
}
else
{
posX_m = (cols_c - 1);
}
}
screen_m[posX_m][posY_m] = symbol;
posX_m++;
updated_m = true;
}
/// \brief Process Carriage Return
///
void
H19::processCR()
{
// check to possibly save the update.
if (posX_m)
{
posX_m = 0;
updated_m = true;
}
}
/// \brief Process Line Feed
///
/// \todo - verify line 25 handling. make sure it doesn't clear line 25.
void
H19::processLF()
{
if (onLine25())
{
// On line 25, don't do anything
return;
}
// Determine if we can just move down a row, or if we have to scroll.
if (posY_m < (rowsMain_c - 1))
{
++posY_m;
}
else
{
// must be line 24 - have to scroll.
scroll();
}
updated_m = true;
}
/// \brief Process Backspace
///
void
H19::processBS()
{
if (posX_m)
{
--posX_m;
updated_m = true;
}
}
/// \brief Process TAB
///
void
H19::processTAB()
{
if (posX_m < 72)
{
posX_m += 8;
// mask off the lower 3 bits to get the correct column.
posX_m &= 0xf8;
updated_m = true;
}
else if (posX_m < (cols_c - 1))
{
posX_m++;
updated_m = true;
}
}
/// \brief Process Cursor Home
/// \todo - Determine how these function in relation to line 25..
void
H19::cursorHome()
{
if (posX_m || posY_m)
{
posX_m = 0;
posY_m = 0;
updated_m = true;
}
}
/// \brief Process Cursor Forward
///
void
H19::cursorForward()
{
// ROM comment says that it will wrap around when at pos 80, but the code does not do that,
// and verifying on a real H89, even with wrap-around enabled, the cursor will not wrap.
if (posX_m < (cols_c - 1))
{
++posX_m;
updated_m = true;
}
}
/// \brief Process cursor down
///
void
H19::cursorDown()
{
// ROM - Moves the cursor down one line on the display but does not cause a scroll past
// the last line
if (posY_m < (rowsMain_c - 1))
{
++posY_m;
updated_m = true;
}
}
/// \brief Process cursor up
/// \todo determine if this is correct with line 25.
void
H19::cursorUp()
{
if (posY_m)
{
--posY_m;
updated_m = true;
}
}
///
/// \brief Process reverse index
///
void
H19::reverseIndex()
{
// Check for being on line 25
if (onLine25())
{
/// \todo - is this right? or should we clear the 25th line?
return;
}
// Make sure not first line
if (posY_m)
{
// simply move up a row
--posY_m;
}
else
{
// must be line 0 - have to scroll down.
for (int y = (rowsMain_c - 1); y > 0; --y)
{
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][y] = screen_m[x][y - 1];
}
}
eraseLine(0);
}
updated_m = true;
}
/// \brief Process cursor position report
///
/// Send ESC Y <posY_m+0x20> <posX_m+0x20>
void
H19::cursorPositionReport()
{
// Send ESC Y <posY_m+0x20> <posX_m+0x20>
sendData(ascii::ESC);
sendData('Y');
sendData(posY_m + 0x20);
sendData(posX_m + 0x20);
}
/// \brief Process save cursor position
///
void
H19::saveCursorPosition()
{
saveX_m = posX_m;
saveY_m = posY_m;
}
/// \brief process restore cursor position
///
void
H19::restoreCursorPosition()
{
posX_m = saveX_m;
posY_m = saveY_m;
updated_m = true;
}
// Erasing and Editing
/// \brief Clear Display
void
H19::clearDisplay()
{
// if on line 25, then only erase line 25
if (onLine25())
{
eraseEL();
/// \todo determine if 'posX_m = 0' is needed.
}
else
{
for (unsigned int y = 0; y < rowsMain_c; ++y)
{
eraseLine(y);
}
posX_m = 0;
posY_m = 0;
}
updated_m = true;
}
/// \brief Erase to Beginning of display
///
void
H19::eraseBOD()
{
eraseBOL();
// if on line 25 just erase to beginning of line
if (!onLine25())
{
int y = posY_m - 1;
while (y >= 0)
{
eraseLine(y);
--y;
}
}
updated_m = true;
}
/// \brief Erase to End of Page
///
void
H19::eraseEOP()
{
eraseEOL();
unsigned int y = posY_m + 1;
/// \todo what about line 25?
while (y < rowsMain_c)
{
eraseLine(y);
++y;
}
updated_m = true;
}
/// \brief Erase to End of Line
///
void
H19::eraseEL()
{
eraseLine(posY_m);
updated_m = true;
}
/// \brief Erase to beginning of line
///
void
H19::eraseBOL()
{
int x = posX_m;
do
{
screen_m[x--][posY_m] = ascii::SP;
}
while (x >= 0);
updated_m = true;
}
/// \brief erase to end of line
///
void
H19::eraseEOL()
{
unsigned int x = posX_m;
do
{
screen_m[x++][posY_m] = ascii::SP;
}
while (x < cols_c);
updated_m = true;
}
/// \brief insert line
///
void
H19::insertLine()
{
/// \todo - Determine how the REAL H89 does this on Line 25, the ROM listing is not clear.
/// - a real H19 messes up with either an insert or delete line on line 25.
/// - note tested with early H19, newer H19 roms should have this fixed.
for (unsigned int y = (rowsMain_c - 1); y > posY_m; --y)
{
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][y] = screen_m[x][y - 1];
}
}
eraseLine(posY_m);
posX_m = 0;
updated_m = true;
}
/// \brief delete line
///
/// \todo - Determine how the REAL H89 does this on Line 25, the ROM listing is not clear.
/// - a real H19 messes up with either an insert or delete line on line 25.
/// - note tested with early H19, newer H19 roms should have this fixed.
void
H19::deleteLine()
{
// Go to the beginning of line
posX_m = 0;
// move all the lines up.
for (unsigned int y = posY_m; y < (rowsMain_c - 1); ++y)
{
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][y] = screen_m[x][y + 1];
}
}
// clear line 24.
eraseLine((rowsMain_c - 1));
updated_m = true;
}
/// \brief delete character
///
void
H19::deleteChar()
{
// move all character in.
for (unsigned int x = posX_m; x < (cols_c - 1); x++)
{
screen_m[x][posY_m] = screen_m[x + 1][posY_m];
}
// clear the last column
screen_m[cols_c - 1][posY_m] = ascii::SP;
updated_m = true;
}
void
H19::eraseLine(unsigned int line)
{
assert(line < rows_c);
for (unsigned int x = 0; x < cols_c; ++x)
{
screen_m[x][line] = ascii::SP;
}
};
/// \brief Process enable line 25.
///
void
H19::processEnableLine25()
{
// From the ROM, it erases line 25 on the enable, but here we erase on the disable.
//
}
void
H19::transmitLines(int start,
int end)
{
/// \todo verify this table.
static char characterLookup[0x80] =
{
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '_',
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, '^'
};
bool reverse = false;
bool graphics = false;
unsigned char ch;
for (int line = start; line <= end; line++)
{
for (unsigned int col = 0; col < cols_c; col++)
{
bool newReverse = ((screen_m[col][line] & 0x80) == 0x80);
/// \todo determine if we should only change for lower case and graphics characters.
///
bool newGraphics = (((screen_m[col][line] & 0x7f) < 0x20) ||
((screen_m[col][line] & 0x7f) == 0x7f));
/// \todo - determine which mode a real H19 sends first.
if (newReverse != reverse)
{
if (newReverse)
{
/// \todo - if in ANSI mode, must send the ANSI codes
// send turn on reverse
sendData(ascii::ESC);
sendData('p');
}
else
{
// send turn off reverse
sendData(ascii::ESC);
sendData('q');
}
reverse = newReverse;
}
if (newGraphics != graphics)
{
if (newGraphics)
{
// send turn on graphics
sendData(ascii::ESC);
sendData('F');
}
else
{
// send turn off graphics
sendData(ascii::ESC);
sendData('G');
}
graphics = newGraphics;
}
// mask off the inverse video.
ch = screen_m[col][line] & 0x7f;
if (graphics)
{
// look up the character
ch = characterLookup[ch];
}
// finally send the character.
sendData(ch);
}
}
/// \todo - determine if we need to turn off inverse and graphics if they are on.
}
/// \brief Process transmit line 25
///
void
H19::transmitLine25()
{
// if line 25 is not enabled, only send CR and ring bell.
if (line25_m)
{
// Transmit line 25.
transmitLines(rowsMain_c, rowsMain_c);
}
sendData(ascii::CR);
bell();
}
/// \brief Process transmit page
///
void
H19::transmitPage()
{
transmitLines(0, rowsMain_c - 1);
sendData(ascii::CR);
bell();
}
/// \brief Ring the H19 bell.
///
/// \todo implement bell
void
H19::bell(void)
{
}
unsigned int
H19::getBaudRate()
{
/// \todo get this from the dip switch.
return (9600);
}
void
H19::timer(void)
{
static int count = 0;
if ((++count % 60) == 0)
{
fflush(console_out);
}
return;
}
void
H19::keyboard(unsigned char key)
{
h19->keypress(key);
}
void
H19::GUIDisplay()
{
h19->display();
}
void
H19::run()
{
TheGUI->InitGUI();
TheGUI->SetKeyboardFunc(keyboard);
TheGUI->SetDisplayFunc(GUIDisplay);
TheGUI->SetTimerFunc(screenRefresh_m, timer);
TheGUI->StartGUI();
return;
}
bool
H19::sendData(BYTE data)
{
if (countdownToSend_m == 0)
{
Console::sendData(data);
countdownToSend_m = characterDelay_m;
}
else
{
charToSend.push(data);
}
return true;
}
void
H19::notification(unsigned int cycleCount)
{
if (countdownToSend_m < cycleCount)
{
if (charToSend.empty())
{
countdownToSend_m = 0;
}
else
{
Console::sendData(charToSend.front());
charToSend.pop();
countdownToSend_m = characterDelay_m;
}
}
else
{
countdownToSend_m -= cycleCount;
return;
}
}
<file_sep>/VirtualH89/Src/TD0FloppyDisk.h
///
/// \file TD0FloppyDisk.h
///
/// \author <NAME>
/// \date May 2, 2016
///
#ifndef TD0FLOPPYDISK_H_
#define TD0FLOPPYDISK_H_
#include "GenericFloppyDisk.h"
#include "SoftSectoredDisk.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class DiskSide;
class Track;
class Sector;
class TD0FloppyDisk: public SoftSectoredDisk
{
public:
TD0FloppyDisk(std::vector<std::string> argv);
virtual ~TD0FloppyDisk() override;
static std::shared_ptr<GenericFloppyDisk> getDiskette(std::vector<std::string> argv);
private:
// int gapLen_m;
// int indexGapLen_m;
// unsigned long writePos_m;
// bool trackWrite_m;
protected:
bool readTD0(const char* name);
// LZSS parameters
static const int SB_SIZE = 4096; // Size of Ring buffer
static const int LA_SIZE = 60; // Size of Look-ahead buffer
static const int THRESHOLD = 2; // Minimum match for compress
// Huffman coding parameters
static const int N_CHAR = (256 - THRESHOLD + LA_SIZE); // Character code (= 0..N_CHAR-1)
static const int T_SIZE = (N_CHAR * 2 - 1); // Size of table
static const int ROOT = (T_SIZE - 1); // Root position
static const int MAX_FREQ = 0x8000; // Update when cumulative frequency
// reaches this value
unsigned long int pos_m = 0;
BYTE* buf;
size_t size_m;
unsigned int parent[T_SIZE + N_CHAR]; // parent nodes (0..T-1) and leaf positions (rest)
unsigned int son[T_SIZE]; // pointers to child nodes (son[], son[]+1)
unsigned int freq[T_SIZE + 1]; // frequency table
unsigned int bits_m, bitBuff_m; // buffered bit count and left-aligned bit buffer
unsigned int GBr; // Ring buffer position
unsigned int GBi; // Decoder index
unsigned int GBj; // Decoder index
unsigned int GBk; // Decoder index
unsigned char ring_buff[SB_SIZE + LA_SIZE - 1]; // text buffer for match strings
bool gbState_m; // Decoder state
bool eof_m; // End-of-file indicator
bool advanceCompression_m;
static unsigned char d_code[256];
static unsigned char d_len[];
void initDecompress();
void update(int c);
unsigned GetChar();
unsigned GetBit();
unsigned GetByte();
unsigned DecodeChar();
unsigned DecodePosition();
unsigned getbyte();
unsigned getword();
};
#endif // TD0FLOPPYDISK_H_
<file_sep>/VirtualH89/Src/Memory8K.h
///
/// \file Memory8K.h
///
/// An 8K page of RAM.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef MEMORY8K_H_
#define MEMORY8K_H_
#include "h89Types.h"
/// \cond
#include <memory>
/// \endcond
class Memory8K
{
public:
Memory8K(WORD base);
virtual ~Memory8K();
WORD getBase();
inline BYTE readByte(WORD adr)
{
return mem[adr & MemoryAddressMask_c];
}
virtual void writeByte(WORD adr, BYTE val) = 0;
protected:
WORD base_m;
BYTE mem[8 * 1024];
static const WORD MemoryAddressMask_c = 0x1fff;
};
typedef std::shared_ptr<Memory8K> Memory8K_ptr;
#endif // MEMORY8K_H_
<file_sep>/VirtualH89/Src/main.h
/// \file main.h
///
/// \date Mar 9, 2009
/// \author <NAME>
///
#ifndef MAIN_H_
#define MAIN_H_
#endif // MAIN_H_
<file_sep>/VirtualH89/Src/ROM.cpp
/// \file ROM.cpp
///
/// \brief Implementation of virtual ROM.
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#include "ROM.h"
#include "logger.h"
/// \cond
#include <cassert>
#include <fstream>
/// \endcond
ROM::ROM(int size):
data_m(0),
base_m(0),
size_m(size)
{
debugss(ssROM, INFO, "Creating ROM: %d\n", size_m);
data_m = new BYTE[size_m];
}
ROM::~ROM()
{
debugss(ssROM, INFO, "Destroying ROM\n");
delete[] data_m;
data_m = 0;
size_m = 0;
}
ROM*
ROM::getROM(const char* filename,
WORD addr)
{
std::ifstream file;
unsigned long int fileSize;
BYTE* buf;
ROM* rom = nullptr;
file.open(filename, std::ios::binary);
if (!file.is_open())
{
debugss(ssROM, ERROR, "ROM image \"%s\" cannot be opened\n", filename);
return nullptr;
}
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
if (fileSize != 2048 && fileSize != 4096)
{
debugss(ssROM, ERROR, "ROM image \"%s\" has invalid size %d\n", filename, fileSize);
return nullptr;
}
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
rom = new ROM((int) fileSize);
rom->setBaseAddress(addr);
rom->initialize(buf, fileSize);
return rom;
}
void
ROM::setBaseAddress(WORD adr) {
base_m = adr;
}
void
ROM::initialize(BYTE* block,
WORD size)
{
debugss(ssROM, INFO, "size(%d)\n", size);
if (size > size_m)
{
// error attempting to store too much
debugss(ssROM, ERROR, "size to big size(%d) size_m(%d)\n", size, size_m);
size = size_m;
}
for (int i = 0; i < size; i++)
{
debugss(ssROM, VERBOSE, "block[%d] = %d\n", i, block[i]);
data_m[i] = block[i];
}
}
void
ROM::writeByte(WORD addr,
BYTE val)
{
// can't write to ROM.
/// \todo update to set the RAM.
debugss(ssROM, INFO, "Attempting to write to ROM [%d] = %d\n", addr, val);
return;
}
BYTE
ROM::readByte(WORD addr)
{
BYTE val = 0;
WORD offset = addr - base_m;
if ((addr < base_m) || (offset >= size_m))
{
debugss(ssROM, ERROR, "Invalid address: %d (base: %d/size: %d)\n", addr, base_m, size_m);
assert((addr >= base_m) && (offset < size_m));
}
else
{
val = data_m[offset];
}
debugss(ssROM, ALL, "addr[%d] = %d\n", addr, val);
return (val);
}
WORD
ROM::getBase() {
return base_m;
}
WORD
ROM::getSize() {
return size_m;
}
BYTE*
ROM::getImage() {
return data_m;
}
<file_sep>/VirtualH89/Src/INS8250.cpp
/// \file INS8250.cpp
///
/// \date Apr 4, 2009
/// \author <NAME>
///
#include "INS8250.h"
#include "computer.h"
#include "WallClock.h"
#include "logger.h"
#include "SerialPortDevice.h"
INS8250::INS8250(Computer* computer,
BYTE base,
int intLevel): IODevice(base, 8),
computer_m(computer),
DLAB_m(false),
ERBFI_m(false),
receiveInterruptPending(false),
OE_m(false),
PE_m(false),
FE_m(false),
device_m(0),
rxByteAvail(false),
txByteAvail(false),
lsBaudDiv(0),
msBaudDiv(0),
baud_m(0),
lastTransmit(0),
saveIER(0),
saveIIR(0),
saveLCR(0),
saveMCR(0),
saveLSR(0),
saveMSR(MSB_ClearToSend | MSB_DataSetReady)
{
intLevel_m = intLevel;
/// \todo Use H89 manual to verify/set all the conditions on reset of chip.
}
INS8250::~INS8250()
{
}
void
INS8250::reset()
{
DLAB_m = false;
ERBFI_m = false;
receiveInterruptPending = false;
OE_m = false;
PE_m = false;
FE_m = false;
rxByteAvail = false;
txByteAvail = false;
lsBaudDiv = 0;
msBaudDiv = 0;
baud_m = 0;
lastTransmit = 0;
saveIER = 0;
saveIIR = 0;
saveLCR = 0;
saveMCR = 0;
saveLSR = 0;
saveMSR = MSB_ClearToSend | MSB_DataSetReady;
}
BYTE
INS8250::in(BYTE addr)
{
BYTE val = 0x00;
if (verifyPort(addr))
{
BYTE offset = addr - baseAddress_m;
switch (offset)
{
case RBR: // Receiver Buffer Register
if (DLAB_m)
{
// set baud rate
// LS Byte
val = lsBaudDiv;
}
else
{
if (rxByteAvail)
{
rxByteAvail = false;
receiveInterruptPending = false;
lowerInterrupt();
val = RecvBuf;
}
}
break;
case IER: // Interrupt Enable Register
if (DLAB_m)
{
// set baud rate
// LS Byte
val = msBaudDiv;
}
else
{
val = saveIER;
}
break;
case IIR: // Interrupt Identification Register
if (receiveInterruptPending)
{
val = IIR_DataAvailable;
}
else
{
val = IIR_NoInterruptPending;
}
break;
case LCR: // Line Control Register
val = saveLCR;
break;
case MCR: // Modem Control Register
val = saveMCR;
break;
case LSR: // Line Status Register
if (rxByteAvail)
{
val |= LSB_DataReady;
}
if ((WallClock::instance()->getClock() - lastTransmit) > 2133)
{
val |= LSB_THRE;
}
if (1) /// \todo - what to do here?
{
val |= LSB_TSRE;
}
if (OE_m)
{
val |= LSB_Overrun;
OE_m = false;
}
if (FE_m)
{
val |= LSB_FramingError;
FE_m = false;
}
if (PE_m)
{
val |= LSB_ParityError;
PE_m = false;
}
break;
case MSR: // Modem Status Register
val = saveMSR;
break;
default:
/// \todo determine what value is set here.
return (0);
}
debugss(ss8250, INFO, "%d(%d) <- %d\n", addr, offset, val);
}
else
{
debugss(ss8250, ERROR, "Verify Port failed: %d\n", addr);
return (0);
}
return (val);
}
void
INS8250::out(BYTE addr,
BYTE val)
{
if (verifyPort(addr))
{
BYTE offset = addr - baseAddress_m;
switch (offset)
{
case THR:
if (!DLAB_m)
{
if (device_m)
{
device_m->receiveData(val);
lastTransmit = WallClock::instance()->getClock();
}
else
{
debugss(ss8250, ERROR, "THR - No device_m.");
}
}
else
{
unsigned int div;
lsBaudDiv = val;
div = (msBaudDiv << 8) | (lsBaudDiv);
if (div)
{
baud_m = 115200 / div;
}
debugss(ss8250, INFO, "baud_m = %d\n", baud_m);
}
break;
case IER:
if (!DLAB_m)
{
saveIER = val;
if (val & IER_ReceiveData)
{
ERBFI_m = true;
}
else
{
ERBFI_m = false;
}
}
else
{
unsigned int div;
// set baud.
msBaudDiv = val;
div = (msBaudDiv << 8) | (lsBaudDiv);
if (div)
{
baud_m = 115200 / div;
}
debugss(ss8250, INFO, "baud_m = %d\n", baud_m);
}
break;
case IIR:
saveIIR = val;
break;
case LCR:
saveLCR = val;
bits_m = (val & 0x3) + 5;
stopBits_m = (val & 0x4);
parityEnable_m = (val & 0x8);
evenParity_m = (val & 0x10);
stickParity_m = (val & 0x20);
break_m = (val & 0x40);
DLAB_m = (val & 0x80);
break;
case MCR:
saveMCR = val;
break;
case LSR:
saveLSR = val;
break;
case MSR:
saveMSR = val;
break;
default:
// nothing to save.
break;
}
}
}
bool
INS8250::attachDevice(SerialPortDevice* dev)
{
if (!device_m)
{
device_m = dev;
device_m->attachPort(this);
return true;
}
return false;
}
bool
INS8250::receiveReady()
{
return !rxByteAvail;
}
void
INS8250::receiveData(BYTE data)
{
debugss(ss8250, ALL, "%d\n", data);
unsigned int baud = device_m->getBaudRate();
if (baud == SerialPortDevice::DISABLE_BAUD_CHECK)
{
baud = baud_m;
}
if (baud == baud_m)
{
debugss(ss8250, ALL, "Baud matches\n");
PE_m = false;
FE_m = false;
}
else if (baud > baud_m)
{
// computer is at lower baud than the remote device.
debugss(ss8250, ALL, "device baud exceeds our baud.\n");
PE_m = true;
FE_m = false;
// a full character will not be received, so we must exit and not set rxByteAvail
return;
}
else
{
// computer is at a faster baud than the remote device.
debugss(ss8250, ALL, "device baud lower\n");
PE_m = false;
FE_m = true;
}
RecvBuf = data;
rxByteAvail = true;
if (ERBFI_m)
{
receiveInterruptPending = true;
raiseInterrupt();
}
}
/// \todo many more areas in this file that can raise and lower the interrupt.
void
INS8250::raiseInterrupt()
{
if (intLevel_m >= 0)
{
computer_m->raiseINT(intLevel_m);
}
}
void
INS8250::lowerInterrupt()
{
if (intLevel_m >= 0)
{
computer_m->lowerINT(intLevel_m);
}
}
<file_sep>/VirtualH89/Src/computer.cpp
///
/// \name computer.cpp
///
/// \date Jul 16, 2012
/// \author <NAME>
///
#include "computer.h"
Computer::Computer(void)
{
}
Computer::~Computer(void)
{
}
<file_sep>/VirtualH89/Src/GUIwxWidgets.h
#if defined(__GUIwx__)
///
/// \name GUIwxWidgets.h
///
/// A GUI implementation based on wxWidgets.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#ifndef GUIWXWIDGETS_H_
#define GUIWXWIDGETS_H_
#include <wx/panel.h>
#include <wx/thread.h>
#include "GUI.h"
#include "h19.h"
/// \cond
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
/// \cond
class wxGUIThread : public wxThread
{
public:
wxGUIThread(tDisplayFunc _GUITimerFunc, unsigned int _Period)
: wxThread(wxTHREAD_DETACHED), GUITimerFunc(_GUITimerFunc), Period(_Period)
{ return; }
~wxGUIThread(void) { return;}
protected:
ExitCode Entry(void);
tDisplayFunc GUITimerFunc;
unsigned int Period;
};
class GUIwxWidgets: public GUI
{
public:
GUIwxWidgets();
virtual ~GUIwxWidgets() override;
// Interface functions.
virtual void GUIDisplay(void) override;
virtual void InitGUI(void) override;
virtual void StartGUI(void) override;
// Callback functions.
virtual void SetKeyboardFunc(tKeyboardFunc KeyboardFunc) override;
virtual void SetDisplayFunc(tDisplayFunc DisplayFunc) override;
virtual void SetTimerFunc(unsigned int ms, tTimerFunc TimerFunc) override;
static tKeyboardFunc GUIKeyboardFunc;
static tDisplayFunc GUITimerFunc;
private:
static unsigned int m_ms;
static void GUIwxWidgetsDisplayFunc(void);
static tDisplayFunc GUIDisplayFunc;
unsigned int fontOffset_m;
unsigned char* fontTable;
wxGUIThread *Thread;
};
#endif
#endif
<file_sep>/VirtualH89/Src/TD0FloppyDisk.cpp
///
/// \file TD0FloppyDisk.cpp
///
/// \author <NAME>
/// \date May 2, 2016
///
#include <cstring>
#include "TD0FloppyDisk.h"
#include "DiskSide.h"
#include "Track.h"
#include "Sector.h"
#include "GenericFloppyFormat.h"
#include "logger.h"
/// \cond
#include <fstream>
/// \endcond
using namespace std;
//
// TD0 file handling
//
unsigned char TD0FloppyDisk::d_code[256] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B,
0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F,
0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13,
0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x17,
0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, 0x1C, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F,
0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27,
0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
};
unsigned char TD0FloppyDisk::d_len[] =
{
2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7
};
//
// Initialize the decompressor trees and state variables
//
void
TD0FloppyDisk::initDecompress()
{
unsigned i, j;
for (i = j = 0; i < N_CHAR; ++i)
{
// Walk up
freq[i] = 1;
son[i] = i + T_SIZE;
parent[i + T_SIZE] = i;
}
while (i <= ROOT)
{
// Back down
freq[i] = freq[j] + freq[j + 1];
son[i] = j;
parent[j] = parent[j + 1] = i++;
j += 2;
}
memset(ring_buff, ' ', sizeof ring_buff);
freq[T_SIZE] = 0xFFFF;
parent[ROOT] = bitBuff_m = bits_m = 0;
GBr = SB_SIZE - LA_SIZE;
}
//
// Increment frequency tree entry for a given code
//
void
TD0FloppyDisk::update(int c)
{
unsigned i, j, k, f, l;
if (freq[ROOT] == MAX_FREQ)
{
// Tree is full - rebuild
// Halve cumulative freq for leaf nodes
for (i = j = 0; i < T_SIZE; ++i)
{
if (son[i] >= T_SIZE)
{
freq[j] = (freq[i] + 1) / 2;
son[j] = son[i];
++j;
}
}
// make a tree - first connect children nodes
for (i = 0, j = N_CHAR; j < T_SIZE; i += 2, ++j)
{
k = i + 1;
f = freq[j] = freq[i] + freq[k];
for (k = j - 1; f < freq[k]; --k)
{
;
}
++k;
l = (j - k) * sizeof(freq[0]);
memmove(&freq[k + 1], &freq[k], l);
freq[k] = f;
memmove(&son[k + 1], &son[k], l);
son[k] = i;
}
// Connect parent nodes
for (i = 0; i < T_SIZE; ++i)
{
if ((k = son[i]) >= T_SIZE)
{
parent[k] = i;
}
else
{
parent[k] = parent[k + 1] = i;
}
}
}
c = parent[c + T_SIZE];
do
{
k = ++freq[c];
// Swap nodes if necessary to maintain frequency ordering
if (k > freq[l = c + 1])
{
while (k > freq[++l])
{
;
}
freq[c] = freq[--l];
freq[l] = k;
parent[i = son[c]] = l;
if (i < T_SIZE)
{
parent[i + 1] = l;
}
parent[j = son[l]] = c;
son[l] = i;
if (j < T_SIZE)
{
parent[j + 1] = c;
}
son[c] = j;
c = l;
}
}
while ((c = parent[c]) != 0); // Repeat up to root
}
//
// Get a byte from the input file and flag Eof at end
// NOTE: MUST be byte aligned.
//
unsigned
TD0FloppyDisk::GetChar()
{
if (pos_m < size_m)
{
return buf[pos_m++];
}
// nothing left.
eof_m = true;
return 0;
}
//
// Get a single bit from the input stream
//
unsigned
TD0FloppyDisk::GetBit()
{
unsigned t;
if (!bits_m--)
{
bitBuff_m |= GetChar() << 8;
bits_m = 7;
}
t = (bitBuff_m >> 15) & 0x01;
bitBuff_m <<= 1;
return t;
}
//
// Get a byte from the input stream - NOT bit-aligned
//
unsigned
TD0FloppyDisk::GetByte()
{
unsigned t;
if (bits_m < 8)
{
bitBuff_m |= GetChar() << (8 - bits_m);
}
else
{
bits_m -= 8;
}
t = bitBuff_m >> 8;
bitBuff_m <<= 8;
return (t & 0xff);
}
//
// Decode a character value from table
//
unsigned
TD0FloppyDisk::DecodeChar()
{
// search the tree from the root to leaves.
unsigned c = ROOT;
// choose node #(son[]) if input bit == 0
// choose node #(son[]+1) if input bit == 1
while ((c = son[c]) < T_SIZE)
{
c += GetBit();
}
update(c -= T_SIZE);
return c;
}
//
// Decode a compressed string index from the table
//
unsigned
TD0FloppyDisk::DecodePosition()
{
unsigned i, j, c;
// Decode upper 6 bits from given table
i = GetByte();
c = d_code[i] << 6;
// input lower 6 bits directly
j = d_len[i >> 4];
while (--j)
{
i = (i << 1) | GetBit();
}
return (i & 0x3F) | c;
}
//
// Get a byte from the input file - decompress if required
//
// This implements a state machine to perform the LZSS decompression
// allowing us to decompress the file "on the fly", without having to
// have it all in memory.
//
unsigned
TD0FloppyDisk::getbyte()
{
unsigned c;
if (!advanceCompression_m)
{
// No compression
return GetChar();
}
// returns are in the loop
while (true)
{
// Decompressor state machine
if (eof_m)
{
// End of file has been flagged
return -1;
}
if (!gbState_m)
{
// Not in the middle of a string
c = DecodeChar();
if (c < 256)
{
// Direct data extraction
ring_buff[GBr++] = c;
GBr &= (SB_SIZE - 1);
return c;
}
gbState_m = true; // Begin extracting a compressed string
GBi = (GBr - DecodePosition() - 1) & (SB_SIZE - 1);
GBj = c - 255 + THRESHOLD;
GBk = 0;
}
if (GBk < GBj)
{
// Extract a compressed string
ring_buff[GBr++] = c = ring_buff[(GBk++ + GBi) & (SB_SIZE - 1)];
GBr &= (SB_SIZE - 1);
return c;
}
gbState_m = false; // Reset to non-string state
}
}
//
// Get a word from the input file via getbyte (for compression)
//
unsigned
TD0FloppyDisk::getword()
{
unsigned w = getbyte();
return w | (getbyte() << 8);
}
shared_ptr<GenericFloppyDisk>
TD0FloppyDisk::getDiskette(vector<string> argv)
{
shared_ptr<GenericFloppyDisk> gd = make_shared<TD0FloppyDisk>(argv);
if (gd->isReady())
{
return gd;
}
return nullptr;
}
TD0FloppyDisk::TD0FloppyDisk(vector<string> argv): SoftSectoredDisk()
{
if (argv.size() < 1)
{
debugss(ssFloppyDisk, WARNING, "no file specified\n");
return;
}
imageName_m = argv[0];
string name(argv[0].c_str());
debugss(ssFloppyDisk, INFO, "reading: %s\n", name.c_str());
for (int x = 1; x < argv.size(); ++x)
{
if (argv[x].compare("rw") == 0)
{
writeProtect_m = false;
}
}
if (!readTD0(name.c_str()))
{
ready_m = false;
debugss(ssFloppyDisk, ERROR, "Read of file %s failed\n", name.c_str());
}
}
TD0FloppyDisk::~TD0FloppyDisk()
{
}
bool
TD0FloppyDisk::readTD0(const char* name)
{
ifstream file;
Track::Density density;
Track::DataRate dataRate;
debugss(ssFloppyDisk, INFO, "file: %s\n", name);
file.open(name, ios::binary);
file.seekg(0, ios::end);
size_m = file.tellg();
file.seekg(0, ios::beg);
buf = new BYTE[size_m];
file.read((char*) buf, size_m);
file.close();
if ((buf[0] == 'T') && (buf[1] == 'D'))
{
debugss(ssFloppyDisk, INFO, "TD0 file with Normal Compression\n");
advanceCompression_m = false;
}
else if ((buf[0] == 't') && (buf[1] == 'd'))
{
debugss(ssFloppyDisk, INFO, "TD0 file with Advanced Compression\n");
advanceCompression_m = true;
initDecompress();
}
else
{
debugss(ssFloppyDisk, ERROR, "Not a TD0 file: 0x%02x 0x%02x\n", buf[0], buf[1]);
delete [] buf;
return false;
}
debugss(ssFloppyDisk, INFO, "Sequence: %d\n", buf[2]);
debugss(ssFloppyDisk, INFO, "Check Sequence: %d\n", buf[3]);
debugss(ssFloppyDisk, INFO, "Teledisk Version %d.%d\n", buf[4] & 0xf0 >> 4,
buf[4] & 0x0f);
debugss(ssFloppyDisk, INFO, "Data Rate: %d\n", buf[5]);
switch (buf[5] & 0x3)
{
case 0:
dataRate = Track::dr_250kbps;
break;
case 1:
dataRate = Track::dr_300kbps;
break;
case 2:
dataRate = Track::dr_500kbps;
break;
default:
debugss(ssFloppyDisk, ERROR, " Unknown(%d)", buf[5]);
dataRate = Track::dr_Unknown;
break;
}
if (buf[5] & 0x80)
{
density = Track::singleDensity;
doubleDensity_m = false;
}
else
{
density = Track::doubleDensity;
doubleDensity_m = true;
}
debugss(ssFloppyDisk, INFO, "Density: %d\n", density);
debugss(ssFloppyDisk, INFO, "Drive Type: %d\n", buf[6]);
debugss(ssFloppyDisk, INFO, "DOS Allocation flag: %s\n", ((buf[8] != 0) ? "True" : "False"));
numSides_m = (buf[9] == 1) ? 1 : 2;
debugss(ssFloppyDisk, INFO, "Sides: %d\n", numSides_m);
debugss(ssFloppyDisk, INFO, "CRC Check: 0x%02x%02x\n", buf[10], buf[11]);
for (BYTE side = 0; side < numSides_m; side++)
{
sideData_m.push_back(make_shared<DiskSide>(side));
}
pos_m = 12;
if (buf[7] & 0x80)
{
unsigned char a, b, c;
debugss(ssFloppyDisk, INFO, "Comment: \n");
a = getbyte();
b = getbyte();
debugss(ssFloppyDisk, INFO, "CRC Check: 0x%02x%02x\n", a, b);
unsigned commentLen = getword();
debugss(ssFloppyDisk, INFO, "Data Length: %d\n", commentLen);
a = getbyte();
b = getbyte();
c = getbyte();
debugss(ssFloppyDisk, INFO, "Year: %d/%d/%d\n", 1900 + a, b, c);
a = getbyte();
b = getbyte();
c = getbyte();
debugss(ssFloppyDisk, INFO, "Time: %d:%02d:%02d\n", a, b, c);
// debugss(ssFloppyDisk, INFO, " Comment: ");
for (int i = 0; i < commentLen; i++)
{
// \TODO ignore comment for now, but need to store it, so that when
// image is written back to disk, it can be written too.
// a = getbyte();
getbyte();
}
}
bool done = false;
// read track
do
{
unsigned sectors = getbyte();
unsigned cylinder = getbyte();
unsigned side = getbyte();
density = (side & 0x80) ? Track::singleDensity : Track::doubleDensity;
side &= 0x01;
if (cylinder >= numTracks_m)
{
numTracks_m = cylinder + 1;
}
unsigned crc = getbyte();
debugss(ssFloppyDisk, INFO, "Track %d head: %d density: %d CRC: %d\n", cylinder,
side, density, crc);
if (sectors == 255)
{
done = true;
}
else
{
shared_ptr<Track> trk = make_shared<Track>(side, cylinder);
trk->setDensity(density);
trk->setDataRate(dataRate);
for (unsigned sectorNum = 0; sectorNum < sectors; sectorNum++)
{
unsigned secCyl = getbyte();
unsigned secHead = getbyte();
unsigned secNum = getbyte();
unsigned secSize = 0;
unsigned tmp = getbyte();
if (tmp < 7)
{
secSize = 128 << tmp;
}
else
{
debugss(ssFloppyDisk, ERROR, "Unknown sector size: %d\n", tmp);
}
unsigned secFlags = getbyte();
unsigned secCRC = getbyte();
debugss(ssFloppyDisk, INFO, "Sector %d data:\n", sectorNum);
debugss(ssFloppyDisk, INFO, "Cyl: %d\n", secCyl);
debugss(ssFloppyDisk, INFO, "Head: %d\n", secHead);
debugss(ssFloppyDisk, INFO, "Num: %d\n", secNum);
debugss(ssFloppyDisk, INFO, "Size: %d\n", secSize);
debugss(ssFloppyDisk, INFO, "Flags: 0x%02x\n", secFlags);
debugss(ssFloppyDisk, INFO, "CRC: 0x%02x\n", secCRC);
// make sure there is data
if ((secFlags & 0x30) == 0)
{
unsigned blockSize = getword();
// apparently blockSize includes the encoding byte, take it off
blockSize--;
unsigned encoding = getbyte();
unsigned char block[8096];
unsigned blockPos = 0;
switch (encoding)
{
case 0: // Raw Data
for (; blockPos < blockSize; blockPos++)
{
block[blockPos] = getbyte();
}
break;
case 1: // Repeat 2 bytes
do
{
unsigned runlength = getword();
block[blockPos++] = getbyte();
block[blockPos++] = getbyte();
while (--runlength)
{
block[blockPos] = block[blockPos - 2];
blockPos++;
block[blockPos] = block[blockPos - 2];
blockPos++;
}
}
while (blockPos < secSize);
break;
case 2: // Run Length Encoding
do
{
unsigned code = getbyte();
unsigned length;
if (code == 0)
{
// run of raw bytes.
length = getbyte();
while (length--)
{
block[blockPos++] = getbyte();
}
}
else
{
// run-length encoded.
// length of data that is repeating
unsigned blockLength = length = code * 2;
// the number of time to repeat it
unsigned repeat = getbyte();
// instead of copying data to a temp block and copy
// from there, read it into the actual block and
// read the repeated blocks from the previously
// written data.
// read in the data
while (length--)
{
block[blockPos++] = getbyte();
}
// Now just copy the data from the previous read.
while (--repeat)
{
length = blockLength;
while (length--)
{
// look back at the last read
block[blockPos] = block[blockPos - blockLength];
blockPos++;
}
}
}
}
while (blockPos < secSize);
break;
default:
debugss(ssFloppyDisk, ERROR, "Unknown sector encoding %d\n", encoding);
break;
}
// create sector
shared_ptr<Sector> sect = make_shared<Sector>(secHead, secCyl, secNum, secSize,
block);
// set flags
sect->setReadError((secFlags & 0x02) == 0x02);
sect->setDeletedDataAddressMark((secFlags & 0x04) == 0x04);
// add sector to track
trk->addSector(sect);
}
}
// add track to disk
sideData_m[side]->addTrack(trk);
}
}
while (!done);
delete [] buf;
debugss(ssFloppyDisk, INFO, "Read successful.\n");
return true;
}
<file_sep>/VirtualH89/Src/DiskDrive.h
///
/// \file DiskDrive.h
///
/// \brief Base virtual Disk Drive
///
/// \date Jul 21, 2012
/// \author <NAME>
///
#ifndef DISKDRIVE_H_
#define DISKDRIVE_H_
#include "h89Types.h"
/// \cond
#include <string>
#include <memory>
/// \endcond
class FloppyDisk;
class DiskDrive
{
public:
static std::shared_ptr<DiskDrive> getInstance(std::string type);
DiskDrive(BYTE tracks = 40);
virtual ~DiskDrive();
virtual void insertDisk(std::shared_ptr<FloppyDisk> disk);
virtual void ejectDisk(const char* name);
virtual void getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect) = 0;
virtual void selectSide(BYTE side) = 0;
virtual void step(bool direction) = 0;
virtual BYTE readData(unsigned long pos) = 0;
virtual void writeData(unsigned long pos,
BYTE data) = 0;
virtual BYTE readSectorData(BYTE sector,
unsigned long pos) = 0;
virtual void loadHead();
virtual void unLoadHead();
virtual bool getHeadLoadStatus();
protected:
std::shared_ptr<FloppyDisk> disk_m;
bool headLoaded_m;
BYTE numTracks_m;
BYTE track_m = 0;
};
#endif // DISKDRIVE_H_
<file_sep>/VirtualH89/Src/StdioProxyConsole.h
/// \file StdioProxyConsole.h
///
/// A console replacement that supports an external process as the H19.
/// Also supports a out-of-band channel for command/control messages.
/// Typically, this is selected by commandline options for main(),
/// with the parent process as the H19 emulation.
///
/// \date Feb 6, 2016
/// \author <NAME>
///
#ifndef STDIOPROXYCONSOLE_H_
#define STDIOPROXYCONSOLE_H_
#include "Console.h"
/// \cond
#include <assert.h>
/// \endcond
class H89Operator;
/// \brief StdioProxyConsole
///
///
class StdioProxyConsole: public Console
{
public:
StdioProxyConsole(int argc,
char** argv);
virtual ~StdioProxyConsole() override;
virtual void init() override;
virtual void reset() override;
virtual void display() override;
virtual void processCharacter(char ch) override;
virtual void keypress(char ch) override;
virtual void receiveData(BYTE) override;
virtual bool checkUpdated() override;
virtual unsigned int getBaudRate() override;
virtual void run() override;
private:
H89Operator* op_m;
bool logConsole;
};
#endif // STDIOPROXYCONSOLE_H_
<file_sep>/VirtualH89/Src/Sector.h
///
/// \name Sector.h
///
///
/// \date Jun 22, 2013
/// \author <NAME>
///
#ifndef SECTOR_H_
#define SECTOR_H_
#include "h89Types.h"
class Sector
{
private:
BYTE headNum_m;
BYTE trackNum_m;
BYTE sectorNum_m;
bool deletedDataAddressMark_m;
bool readError_m;
bool valid_m;
BYTE* data_m;
WORD sectorLength_m;
Sector();
public:
//
Sector(BYTE headNum,
BYTE trackNum,
BYTE sectorNum,
WORD sectorLength,
BYTE* data);
Sector(BYTE headNum,
BYTE trackNum,
BYTE sectorNum,
WORD sectorLength,
BYTE data = 0xe5);
virtual ~Sector();
void setDeletedDataAddressMark(bool val);
void setReadError(bool val);
bool getDeletedDataAddressMark();
bool getReadError();
BYTE getSectorNum();
WORD getSectorLength();
BYTE getHeadNum();
BYTE getTrackNum();
bool readData(WORD pos,
BYTE& data);
bool writeData(WORD pos,
BYTE data);
void dump();
};
#endif // SECTOR_H_
<file_sep>/VirtualH89/Src/GenericFloppyFormat.h
/// \file GenericFloppyFormat.h
///
/// Some constants and conventions used to represent floppy diskette formats.
///
/// \date Feb 1, 2016
/// \author <NAME>
///
#ifndef GENERICFLOPPYFORMAT_H_
#define GENERICFLOPPYFORMAT_H_
#include "h89Types.h"
///
/// \brief Virtual Generic Floppy Drive
///
/// Implements a virtual floppy disk drive. Supports 48/96 tpi 5.25",
/// 48 tpi 8", either can be SS or DS. Note, the media determines density.
///
class GenericFloppyFormat
{
public:
enum AMbytes
{
INDEX_AM_BYTE = 0xfc,
ID_AM_BYTE = 0xfe,
DATA_AM_BYTE = 0xfb,
CRC_BYTE = 0xf7,
INDEX_AM = -INDEX_AM_BYTE,
ID_AM = -ID_AM_BYTE,
DATA_AM = -DATA_AM_BYTE,
CRC = -CRC_BYTE,
ERROR = -1,
NO_DATA = -2,
};
private:
};
#endif // GENERICFLOPPYFORMAT_H_
<file_sep>/VirtualH89/Src/h89-io.cpp
/// \file h89-io.cpp
///
/// \date Mar 7, 2009
/// \author <NAME>
///
/// \brief Implements framework to handle all the I/O devices on the H89.
///
#include "h89-io.h"
#include "DiskController.h"
#include "logger.h"
using namespace std;
H89_IO::H89_IO(): IOBus()
{
debugss(ssIO, INFO, "%\n");
}
H89_IO::~H89_IO()
{
debugss(ssIO, INFO, "\n");
}
vector<DiskController*>&
H89_IO::getDiskDevices()
{
return dsk_devs;
}
bool
H89_IO::addDiskDevice(DiskController* device)
{
dsk_devs.push_back(device);
return addDevice(device);
}
<file_sep>/VirtualH89/Src/SystemMemory8K.cpp
///
/// \file SystemMemory8K.cpp
///
///
/// \author <NAME>
/// \date May 8, 2016
#include "SystemMemory8K.h"
#include "ROM.h"
#include <cstring>
using namespace std;
SystemMemory8K::SystemMemory8K(): RAMemory8K(0x0000),
maskRO(0),
maskInstalled(0),
RAM(nullptr)
{
}
void
SystemMemory8K::overlayRAM(shared_ptr<Memory8K> ram)
{
RAM = ram;
}
void
SystemMemory8K::enableRAM(WORD base, WORD len)
{
WORD adr = base & MemoryAddressMask_c;
if (adr + len > sizeof(mem))
{
// error? or just trim?
len = sizeof(mem) - adr;
}
int a = (adr >> 10) & 0x07;
int n = a + (((len + 0x03ff) >> 10) & 0x07);
// TODO: find more-elegant way
for (; a < n; ++a)
{
maskInstalled |= (1 << a);
}
}
void
SystemMemory8K::writeProtect(WORD adr, WORD len)
{
int a = (adr >> 10) & 0x07;
int n = a + (((len + 0x03ff) >> 10) & 0x07);
// TODO: find more-elegant way
for (; a < n && a < 8; ++a)
{
maskRO |= (1 << a);
}
}
void
SystemMemory8K::writeEnable(WORD adr, WORD len)
{
int a = (adr >> 10) & 0x07;
int n = a + (((len + 0x03ff) >> 10) & 0x07);
// TODO: find more-elegant way
for (; a < n && a < 8; ++a)
{
maskRO &= ~(1 << a);
}
}
void
SystemMemory8K::installROM(ROM* rom)
{
WORD adr = rom->getBase() & MemoryAddressMask_c;
int len = rom->getSize();
if (adr + len > sizeof(mem))
{
// error? or just trim?
len = sizeof(mem) - adr;
}
memcpy(&mem[adr], rom->getImage(), len);
int a = (adr >> 10) & 0x07;
int n = a + (((len + 0x03ff) >> 10) & 0x07);
// TODO: find more-elegant way
for (; a < n; ++a)
{
maskRO |= (1 << a);
maskInstalled |= (1 << a);
}
}
<file_sep>/VirtualH89/Src/main.cpp
/// \file main.cpp
///
/// \date Mar 7, 2009
/// \author <NAME>
///
///
///
///
///
#include "main.h"
#include "H89.h"
#include "Console.h"
#include "h19.h"
#include "StdioConsole.h"
#include "StdioProxyConsole.h"
#include "logger.h"
#include "propertyutil.h"
#if !defined(__GUIwx__)
#include "GUIglut.h"
#endif
/// \cond
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
/// \endcond
using namespace std;
const char* Z80_COPYRIGHT_c = "Portions derived from Z80Pack Release 1.17"
"- Copyright (C) 1987-2008 by Udo Munk";
const char* RELEASE_VERSION_c = "1.93";
const char* H89_COPYRIGHT_c = "Copyright (C) 2009-2016 by <NAME>";
const char* usage_str = " -q -g";
/// \todo - make H89 into a singleton.
H89 h89;
Console* console = nullptr;
FILE* log_out = 0;
FILE* console_out = 0;
void
displayLogo()
{
cout << "Virtual H89" << endl << endl;
cout << " # # ### #### ##### # # # # # # ### ### " << endl;
cout << " # # # # # # # # # # # # # # # # #" << endl;
cout << " # # # # # # # # # # # # # # # # #" << endl;
cout << " # # # #### # # # ##### # ##### ### ####" << endl;
cout << " # # # # # # # # # # # # # # # #" << endl;
cout << " # # # # # # # # # # # # # # # # #" << endl;
cout << " # ### # # # ### # # ##### # # ### ### " << endl;
cout << endl << Z80_COPYRIGHT_c << endl;
cout << "Virtual H89 - " << H89_COPYRIGHT_c << endl << endl;
cout << "Release " << RELEASE_VERSION_c << endl;
}
void
usage(char* pn)
{
cerr << "usage: " << pn << usage_str << endl;
// cerr << "\ts = save core and cpu" << endl;
// cerr << "\tl = load core and cpu" << endl;
cerr << "\tg = specify gui to use, default is built-in H19 emulation" << endl;
cerr << "\tq = quiet - don't display opening banner" << endl;
exit(1);
}
static void*
cpuThreadFunc(void* v)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
pthread_sigmask(SIG_UNBLOCK, &set, 0);
H89* h89 = (H89*) v;
#if FIXME
if (l_flag)
{
if (load_core())
{
return (1);
}
}
#endif
BYTE cpu_error;
cpu_error = h89->run();
#if FIXME
if (s_flag)
{
save_core();
}
#endif
return (0);
}
// This is the getopt string for ALL consumers of argc/argv.
// Right now, it must be manually kept up to date.
//
// option owner
// -g <gui> main.cpp
// -l StdioProxyConsole.cpp
// -q main.cpp
//
const char* getopts = "g:lq";
#if defined(__GUIwx__)
int
VirtualH89main(int argc,
char* argv[])
#else
int
main(int argc,
char* argv[])
#endif
{
int c;
extern char* optarg;
string gui("H19");
int quiet = 0;
setDebugLevel();
#if !defined(__GUIwx__)
// Start a GUI engine.
TheGUI = new GUIglut();
#endif
while ((c = getopt(argc, argv, getopts)) != EOF)
{
switch (c)
{
case 'q':
quiet = 1;
break;
case 'g':
gui = optarg;
break;
}
}
if ((log_out = fopen("op.out", "w")) == 0 && !quiet)
{
cerr << endl << "Unable to open op.out" << endl;
}
if ((console_out = fopen("console.out", "w")) == 0 && !quiet)
{
cerr << endl << "Unable to open console.out" << endl;
}
else if (!quiet)
{
cout << "Successfully opened console.out" << endl;
}
if (!quiet)
{
displayLogo();
cout << "CPU speed is 2.048 MHz" << endl << endl;
}
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGALRM);
pthread_sigmask(SIG_BLOCK, &set, 0);
// TODO: allow specification of config file via cmdline args.
string cfg;
char* env = getenv("V89_CONFIG");
PropertyUtil::PropertyMapT props;
string sw401;
string sw402;
// \todo - if file not found, default to something sane (h17 + 64k)
if (env)
{
// If file-not-found, we still might create it later...
cfg = env;
try
{
PropertyUtil::read(cfg.c_str(), props);
}
catch (exception& e)
{
}
}
else
{
cfg = getenv("HOME");
cfg += "/.v89rc";
try
{
PropertyUtil::read(cfg.c_str(), props);
}
catch (exception& e)
{
}
}
sw401 = props["sw401"];
sw402 = props["sw402"];
if (gui.compare("stdio") == 0)
{
console = new StdioConsole(argc, argv);
}
else if (gui.compare("proxy") == 0)
{
console = new StdioProxyConsole(argc, argv);
}
else
{
console = new H19(sw401.c_str(), sw402.c_str());
}
h89.buildSystem(console, props);
pthread_t cpuThread;
pthread_create(&cpuThread, nullptr, cpuThreadFunc, &h89);
h89.init();
console->run();
// TODO: call destructors...
// Leave open so destructors can log messages.
// exit() always closes files anyway.
// fclose(log_out);
// fclose(console_out);
return (0);
}
<file_sep>/VirtualH89/Src/ParallelLink.cpp
///
/// \name ParallelLink.cpp
///
///
/// \date Aug 12, 2013
/// \author <NAME>
///
#include "ParallelLink.h"
#include "ParallelPortConnection.h"
#include "logger.h"
ParallelLink::ParallelLink(): data_m(0xff),
dataFromHost_m(false),
dataFromDrive_m(false),
busy_m(false),
DTR_m(false),
MRST_m(false),
DDOut_m(false),
DTAK_m(false),
error_m(false),
host_m(0),
device_m(0)
{
}
ParallelLink::~ParallelLink()
{
}
void
ParallelLink::sendHostData(BYTE data)
{
debugss(ssParallel, INFO, "Entering: %d\n", data);
if (host_m)
{
if ((dataFromDrive_m) || (dataFromHost_m))
{
debugss(ssParallel, ERROR, "Data already on bus: fromDrive: %d fromHost: %d.\n",
dataFromDrive_m, dataFromHost_m);
}
data_m = data;
dataFromDrive_m = true;
setDTR(true);
}
else
{
debugss(ssParallel, ERROR, "Host not connected.\n");
}
}
void
ParallelLink::sendDriveData(BYTE data)
{
debugss(ssParallel, INFO, "Entering: %d\n", data);
if (device_m)
{
if ((dataFromDrive_m) || (dataFromHost_m))
{
debugss(ssParallel, ERROR, "Data already on bus: fromDrive: %d fromHost: %d.\n",
dataFromDrive_m, dataFromHost_m);
}
data_m = data;
dataFromHost_m = true;
setDTAK(true);
}
else
{
debugss(ssParallel, FATAL, "Drive not connected.\n");
}
}
void
ParallelLink::readDataBusByHost(BYTE& data)
{
debugss(ssParallel, INFO, "Entering, returning: 0x%02x\n", data_m);
if (dataFromDrive_m)
{
data = data_m;
dataFromDrive_m = false;
}
else
{
debugss(ssParallel, FATAL, "Drive did not provide data: %d\n", dataFromHost_m);
}
}
void
ParallelLink::readDataBusByDrive(BYTE& data)
{
debugss(ssParallel, INFO, "Entering, returning: 0x%02x\n", data_m);
if (dataFromHost_m)
{
data = data_m;
dataFromHost_m = false;
}
else
{
debugss(ssParallel, FATAL, "Drive did not provide data: %d\n", dataFromDrive_m);
}
}
void
ParallelLink::setBusy(bool val)
{
debugss(ssParallel, INFO, "Entering\n");
if (host_m)
{
if (val)
{
host_m->raiseSignal(ParallelPortConnection::st_Busy);
}
else
{
host_m->lowerSignal(ParallelPortConnection::st_Busy);
}
}
busy_m = val;
}
bool
ParallelLink::readBusy()
{
debugss(ssParallel, INFO, "Entering\n");
return busy_m;
}
void
ParallelLink::setDTR(bool val)
{
debugss(ssParallel, INFO, "Entering\n");
if (host_m)
{
if (val)
{
host_m->raiseSignal(ParallelPortConnection::st_DTR);
}
else
{
host_m->lowerSignal(ParallelPortConnection::st_DTR);
}
}
else
{
debugss(ssParallel, ERROR, "host_m is NULL\n");
}
DTR_m = val;
}
bool
ParallelLink::readDTR()
{
debugss(ssParallel, INFO, "Entering\n");
return DTR_m;
}
void
ParallelLink::masterReset()
{
debugss(ssParallel, INFO, "Entering\n");
if (device_m)
{
device_m->raiseSignal(ParallelPortConnection::st_MasterReset);
}
}
void
ParallelLink::setDDOut(bool val)
{
debugss(ssParallel, INFO, "Entering\n");
if (host_m)
{
if (val)
{
host_m->raiseSignal(ParallelPortConnection::st_DDOUT);
}
else
{
host_m->lowerSignal(ParallelPortConnection::st_DDOUT);
}
// host_m->notify(ParallelPortConnection::nt_DDOUT);
}
DDOut_m = val;
}
bool
ParallelLink::readDDOut()
{
debugss(ssParallel, INFO, "Entering\n");
return DDOut_m;
}
void
ParallelLink::setDTAK(bool val)
{
debugss(ssParallel, INFO, "Entering\n");
if (device_m)
{
if (val)
{
device_m->raiseSignal(ParallelPortConnection::st_DTAK);
}
else
{
device_m->lowerSignal(ParallelPortConnection::st_DTAK);
}
}
DTAK_m = val;
}
bool
ParallelLink::readDTAK()
{
debugss(ssParallel, INFO, "Entering\n");
return DTAK_m;
}
void
ParallelLink::setError(bool val)
{
debugss(ssParallel, INFO, "Entering\n");
if (host_m)
{
if (val)
{
host_m->raiseSignal(ParallelPortConnection::st_Error);
}
else
{
host_m->lowerSignal(ParallelPortConnection::st_Error);
}
}
error_m = val;
}
bool
ParallelLink::readError()
{
debugss(ssParallel, INFO, "Entering\n");
return error_m;
}
void
ParallelLink::registerDevice(ParallelPortConnection* device)
{
debugss(ssParallel, INFO, "Entering\n");
if (device_m)
{
debugss(ssParallel, ERROR, "device already defined\n");
}
device_m = device;
}
void
ParallelLink::registerHost(ParallelPortConnection* host)
{
debugss(ssParallel, INFO, "Entering\n");
if (host_m)
{
debugss(ssParallel, ERROR, "device already defined\n");
}
host_m = host;
}
<file_sep>/VirtualH89/Src/ClockUser.h
///
/// \name ClockUser.h
///
/// \date Aug 11, 2012
/// \author <NAME>
///
#ifndef CLOCKUSER_H_
#define CLOCKUSER_H_
class ClockUser
{
public:
ClockUser();
virtual ~ClockUser();
virtual void notification(unsigned int cycleCount) = 0;
private:
};
#endif // CLOCKUSER_H_
<file_sep>/README.md
# VirtualH89
Heathkit H89 Emulator in C++
## Description
The Heathkit H89, was an 8-bit Z80-based system sold in kit-form during 1979-1985 by Heath Company. An identical system was sold assembled, by Zenith Data System, as the Z-89 and Z-90. It supported upto 64k of RAM, and offered several different options for storage, including cassette, hard-sectored 5.25" floppy disks, soft-sectored 5.25" floppy disks, 8" floppy disks, and a 10M Winchester HardDrive. Currently, the emulator supports hard-sectored 5.25" floppy drives/disks, the MMS 77316 Soft-sectored Controller, and the MMS 77320 SASI controller. .
It is targeted to Unix-based systems, including Mac OS X and Linux.
Currently using GLUT for the UI, but plan to change to a more modern cross-platfrom library.
Additional details are available on my site: [Heathkit H89 Emulator](http://heathkit.garlanger.com/emulator/)
## Getting Started
An xcode project is provided for the Mac OS X platform.
## Configuration file
By default, the emulator will look for a configuration file specified in the env variable V89_CONFIG.
Without a config file, the emulator will default to a basic H89 with 64k (ORG-0 support), and H17 controller
and 3 H-17-1 hard-sectored disk drives.
## Example config file
```
sw401 = 10001100 # switch sw401 as defined on the Terminal Board
sw402 = 00000101 # switch sw402 as defined on the Terminal Board
sw501 = 00100000 # switch sw501 as defined on the Terminal Board
monitor_rom = /Users/mgarlanger/h89Data/ROMs/Heath/2732_444-142_MTR90A.bin # location of ROM image
ORG0 = True # Whether or not ORG-0 support provide - set to False if ORG-0 is not supported, defaults to True
slot_p503 = MMS77318 # type of memory add-on card - Options MMS77318 - MMS's 128k board
# WH-88-16 - Heath's 16k board, Empty
CPU_Memory = 48K # Amount of memory on CPU board, Options: 16K, 32K, 48K (64K - although there is not enough
# sockets for 64k, some systems have memory chips piggy-back on the top row.
# Heath's H37 soft-sector controller
slot_p504 = H37 # type of card in the 3rd slot from the right, typically soft-sectored controller cards
# Options: H37, MMS77316 - MMS's soft-sectored controller.
h37_drive1 = FDD_5_25_DS_DT
h37_drive2 = FDD_5_25_DS_DT
h37_drive3 = FDD_5_25_DS_DT
h37_drive4 = FDD_5_25_DS_DT
h37_disk1 = /Users/mgarlanger/h89Data/Disks/h37/MMS_CPM_Plus_Disk1.IMD rw
h37_disk2 = /Users/mgarlanger/h89Data/Disks/h37/MMS_CPM_Plus_Disk2.IMD rw
h37_disk3 = /Users/mgarlanger/h89Data/Disks/h37/MMS_CPM_Plus_Disk3.IMD rw
h37_disk4 = /Users/mgarlanger/h89Data/Disks/h37/MMS_CPM_Plus_Disk4.IMD rw
# another option MMS77316 soft-sectored controller
#slot_p504 = MMS77316
#mms77316_drive1 = FDD_8_DS
#mms77316_drive2 = FDD_8_DS
#mms77316_drive3 = FDD_8_DS
#mms77316_drive4 = FDD_8_DS
#mms77316_drive5 = FDD_5_25_DS_DT
#mms77316_drive6 = FDD_5_25_DS_DT
#mms77316_drive7 = FDD_5_25_DS_DT
#mms77316_drive8 = FDD_5_25_DS_DT
#mms77316_disk1 = /Users/mgarlanger/h89Data/Disks/mmscpm3ds8.logdisk rw
#mms77316_disk2 = /Users/mgarlanger/h89Data/Disks/mmscpm3ds8.logdisk rw
#mms77316_disk3 = /Users/mgarlanger/h89Data/Disks/mmscpm3ds8.logdisk rw
#mms77316_disk4 = /Users/mgarlanger/h89Data/Disks/mmscpm3ds8.logdisk rw
#mms77316_disk5 = /Users/mgarlanger/h89Data/Disks/mms-cpm-distro2.mmsdisk rw
#mms77316_disk6 = /Users/mgarlanger/h89Data/Disks/mms-cpm-distro3.mmsdisk rw
#mms77316_disk7 = /Users/mgarlanger/h89Data/Disks/invaders.mmsdisk rw
#mms77316_disk8 = /Users/mgarlanger/h89Data/Disks/blank5ddds.mmsdisk rw
# 3 port serial
slot_p505 = H_88_3
# hard-sectored controller
slot_p506 = H17
h17_drive1 = H17_1
h17_drive2 = H17_1
h17_drive3 = H17_1
h17_disk1 = /Users/mgarlanger/h89Data/Disks/h37/HDOS_2-0_Hos_5_Update.h17raw
h17_disk2 = /Users/mgarlanger/h89Data/Disks/diskB.tmpdisk
h17_disk3 = /Users/mgarlanger/h89Data/Disks/diskC.tmpdisk
```
<file_sep>/VirtualH89/Src/ROM.h
/// \file ROM.h
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#ifndef ROM_H_
#define ROM_H_
#include "h89Types.h"
/// \brief Virtual %ROM
///
/// Implementation of Read Only Memory (ROM).
///
class ROM
{
private:
/// \brief Actual storage for the rom.
///
BYTE* data_m;
WORD base_m;
WORD size_m;
public:
ROM(int size);
virtual ~ROM();
static ROM* getROM(const char* file,
WORD addr);
virtual void setBaseAddress(WORD adr);
virtual void initialize(BYTE* block,
WORD size);
virtual void writeByte(WORD addr,
BYTE val);
virtual BYTE readByte(WORD addr);
virtual WORD getBase();
virtual WORD getSize();
virtual BYTE* getImage();
};
#endif // ROM_H_
<file_sep>/VirtualH89/Src/FloppyDisk.cpp
/// \file FloppyDisk.cpp
///
/// \date May 19, 2009
/// \author <NAME>
///
#include "FloppyDisk.h"
FloppyDisk::FloppyDisk(): writeProtect_m(false),
maxTrack_m(0),
maxPos_m(0)
{
}
FloppyDisk::FloppyDisk(const char* name): writeProtect_m(false),
maxTrack_m(0),
maxPos_m(0)
{
}
FloppyDisk::~FloppyDisk()
{
}
void
FloppyDisk::setWriteProtect(bool value)
{
writeProtect_m = value;
}
bool
FloppyDisk::checkWriteProtect(void)
{
return (writeProtect_m);
}
void
FloppyDisk::setMaxTrack(BYTE maxTrack)
{
maxTrack_m = maxTrack;
}
void
FloppyDisk::setMaxPosition(unsigned int maxPosition)
{
maxPos_m = maxPosition;
}
<file_sep>/VirtualH89/Src/disasm.cpp
/// \file disasm.cpp
///
/// \date Mar 10, 2009
/// \author <NAME>
///
///
/// Z80 disassembler for Z80-CPU simulator
///
/// Copyright (C) 1989-2008 by <NAME>
/// Parts Copyright (C) 2008 by <NAME>
///
/// History:
/// 28-SEP-87 Development on TARGON/35 with AT&T Unix System V.3
/// 11-JAN-89 Release 1.1
/// 08-FEB-89 Release 1.2
/// 13-MAR-89 Release 1.3
/// 09-FEB-90 Release 1.4 Ported to TARGON/31 M10/30
/// 20-DEC-90 Release 1.5 Ported to COHERENT 3.0
/// 10-JUN-92 Release 1.6 long casting problem solved with COHERENT 3.2
/// and some optimization
/// 25-JUN-92 Release 1.7 comments in english and ported to COHERENT 4.0
/// 02-OCT-06 Release 1.8 modified to compile on modern POSIX OS's
/// 18-NOV-06 Release 1.9 modified to work with CP/M sources
/// 08-DEC-06 Release 1.10 modified MMU for working with CP/NET
/// 17-DEC-06 Release 1.11 TCP/IP sockets for CP/NET
/// 25-DEC-06 Release 1.12 CPU speed option
/// 19-FEB-07 Release 1.13 various improvements
/// 06-OCT-07 Release 1.14 bug fixes and improvements
/// 06-AUG-08 Release 1.15 many improvements and Windows support via Cygwin
/// 25-AUG-08 Release 1.16 console status I/O loop detection and line discipline
/// 20-OCT-08 Release 1.17 frontpanel integrated and Altair/IMSAI emulations
///
/// \todo update all number output for a #define option of using OCTAL. -or
/// parent/child class to
/// \todo update to include all undocumented opcodes
#define OCTAL 1
#include "disasm.h"
#include "H89.h"
#include "logger.h"
#include "AddressBus.h"
/// \cond
#include <stdio.h>
#include <string.h>
/// \endcond
//
// Forward declarations
//
static int opout(const char*, WORD);
static int nout(const char*, WORD);
static int iout(const char*, WORD);
static int rout(const char*, WORD);
static int nnout(const char*, WORD);
static int inout(const char*, WORD);
static int cbop(const char*, WORD);
static int edop(const char*, WORD);
static int ddfd(const char*, WORD);
BYTE
readMemory(const WORD addr)
{
return (h89.getAddressBus().readByte(addr));
}
///
/// Opcode tables
///
struct opt
{
int (* fun)(const char*, WORD);
const char* text;
};
static struct opt optab[256] =
{
{opout, "NOP" }, // 0x00
{nnout, "LD\tBC," }, // 0x01
{opout, "LD\t(BC),A" }, // 0x02
{opout, "INC\tBC" }, // 0x03
{opout, "INC\tB" }, // 0x04
{opout, "DEC\tB" }, // 0x05
{nout, "LD\tB," }, // 0x06
{opout, "RLCA" }, // 0x07
{opout, "EX\tAF,AF'" }, // 0x08
{opout, "ADD\tHL,BC" }, // 0x09
{opout, "LD\tA,(BC)" }, // 0x0a
{opout, "DEC\tBC" }, // 0x0b
{opout, "INC\tC" }, // 0x0c
{opout, "DEC\tC" }, // 0x0d
{nout, "LD\tC," }, // 0x0e
{opout, "RRCA" }, // 0x0f
{rout, "DJNZ\t" }, // 0x10
{nnout, "LD\tDE," }, // 0x11
{opout, "LD\t(DE),A" }, // 0x12
{opout, "INC\tDE" }, // 0x13
{opout, "INC\tD" }, // 0x14
{opout, "DEC\tD" }, // 0x15
{nout, "LD\tD," }, // 0x16
{opout, "RLA" }, // 0x17
{rout, "JR\t" }, // 0x18
{opout, "ADD\tHL,DE" }, // 0x19
{opout, "LD\tA,(DE)" }, // 0x1a
{opout, "DEC\tDE" }, // 0x1b
{opout, "INC\tE" }, // 0x1c
{opout, "DEC\tE" }, // 0x1d
{nout, "LD\tE," }, // 0x1e
{opout, "RRA" }, // 0x1f
{rout, "JR\tNZ," }, // 0x20
{nnout, "LD\tHL," }, // 0x21
{inout, "LD\t(%04X),HL"}, // 0x22
{opout, "INC\tHL" }, // 0x23
{opout, "INC\tH" }, // 0x24
{opout, "DEC\tH" }, // 0x25
{nout, "LD\tH," }, // 0x26
{opout, "DAA" }, // 0x27
{rout, "JR\tZ," }, // 0x28
{opout, "ADD\tHL,HL" }, // 0x29
{inout, "LD\tHL,(%04X)"}, // 0x2a
{opout, "DEC\tHL" }, // 0x2b
{opout, "INC\tL" }, // 0x2c
{opout, "DEC\tL" }, // 0x2d
{nout, "LD\tL," }, // 0x2e
{opout, "CPL" }, // 0x2f
{rout, "JR\tNC," }, // 0x30
{nnout, "LD\tSP," }, // 0x31
{inout, "LD\t(%04X),A" }, // 0x32
{opout, "INC\tSP" }, // 0x33
{opout, "INC\t(HL)" }, // 0x34
{opout, "DEC\t(HL)" }, // 0x35
{nout, "LD\t(HL)," }, // 0x36
{opout, "SCF" }, // 0x37
{rout, "JR\tC," }, // 0x38
{opout, "ADD\tHL,SP" }, // 0x39
{inout, "LD\tA,(%04X)" }, // 0x3a
{opout, "DEC\tSP" }, // 0x3b
{opout, "INC\tA" }, // 0x3c
{opout, "DEC\tA" }, // 0x3d
{nout, "LD\tA," }, // 0x3e
{opout, "CCF" }, // 0x3f
{opout, "LD\tB,B" }, // 0x40
{opout, "LD\tB,C" }, // 0x41
{opout, "LD\tB,D" }, // 0x42
{opout, "LD\tB,E" }, // 0x43
{opout, "LD\tB,H" }, // 0x44
{opout, "LD\tB,L" }, // 0x45
{opout, "LD\tB,(HL)" }, // 0x46
{opout, "LD\tB,A" }, // 0x47
{opout, "LD\tC,B" }, // 0x48
{opout, "LD\tC,C" }, // 0x49
{opout, "LD\tC,D" }, // 0x4a
{opout, "LD\tC,E" }, // 0x4b
{opout, "LD\tC,H" }, // 0x4c
{opout, "LD\tC,L" }, // 0x4d
{opout, "LD\tC,(HL)" }, // 0x4e
{opout, "LD\tC,A" }, // 0x4f
{opout, "LD\tD,B" }, // 0x50
{opout, "LD\tD,C" }, // 0x51
{opout, "LD\tD,D" }, // 0x52
{opout, "LD\tD,E" }, // 0x53
{opout, "LD\tD,H" }, // 0x54
{opout, "LD\tD,L" }, // 0x55
{opout, "LD\tD,(HL)" }, // 0x56
{opout, "LD\tD,A" }, // 0x57
{opout, "LD\tE,B" }, // 0x58
{opout, "LD\tE,C" }, // 0x59
{opout, "LD\tE,D" }, // 0x5a
{opout, "LD\tE,E" }, // 0x5b
{opout, "LD\tE,H" }, // 0x5c
{opout, "LD\tE,L" }, // 0x5d
{opout, "LD\tE,(HL)" }, // 0x5e
{opout, "LD\tE,A" }, // 0x5f
{opout, "LD\tH,B" }, // 0x60
{opout, "LD\tH,C" }, // 0x61
{opout, "LD\tH,D" }, // 0x62
{opout, "LD\tH,E" }, // 0x63
{opout, "LD\tH,H" }, // 0x64
{opout, "LD\tH,L" }, // 0x65
{opout, "LD\tH,(HL)" }, // 0x66
{opout, "LD\tH,A" }, // 0x67
{opout, "LD\tL,B" }, // 0x68
{opout, "LD\tL,C" }, // 0x69
{opout, "LD\tL,D" }, // 0x6a
{opout, "LD\tL,E" }, // 0x6b
{opout, "LD\tL,H" }, // 0x6c
{opout, "LD\tL,L" }, // 0x6d
{opout, "LD\tL,(HL)" }, // 0x6e
{opout, "LD\tL,A" }, // 0x6f
{opout, "LD\t(HL),B" }, // 0x70
{opout, "LD\t(HL),C" }, // 0x71
{opout, "LD\t(HL),D" }, // 0x72
{opout, "LD\t(HL),E" }, // 0x73
{opout, "LD\t(HL),H" }, // 0x74
{opout, "LD\t(HL),L" }, // 0x75
{opout, "HALT" }, // 0x76
{opout, "LD\t(HL),A" }, // 0x77
{opout, "LD\tA,B" }, // 0x78
{opout, "LD\tA,C" }, // 0x79
{opout, "LD\tA,D" }, // 0x7a
{opout, "LD\tA,E" }, // 0x7b
{opout, "LD\tA,H" }, // 0x7c
{opout, "LD\tA,L" }, // 0x7d
{opout, "LD\tA,(HL)" }, // 0x7e
{opout, "LD\tA,A" }, // 0x7f
{opout, "ADD\tA,B" }, // 0x80
{opout, "ADD\tA,C" }, // 0x81
{opout, "ADD\tA,D" }, // 0x82
{opout, "ADD\tA,E" }, // 0x83
{opout, "ADD\tA,H" }, // 0x84
{opout, "ADD\tA,L" }, // 0x85
{opout, "ADD\tA,(HL)" }, // 0x86
{opout, "ADD\tA,A" }, // 0x87
{opout, "ADC\tA,B" }, // 0x88
{opout, "ADC\tA,C" }, // 0x89
{opout, "ADC\tA,D" }, // 0x8a
{opout, "ADC\tA,E" }, // 0x8b
{opout, "ADC\tA,H" }, // 0x8c
{opout, "ADC\tA,L" }, // 0x8d
{opout, "ADC\tA,(HL)" }, // 0x8e
{opout, "ADC\tA,A" }, // 0x8f
{opout, "SUB\tB" }, // 0x90
{opout, "SUB\tC" }, // 0x91
{opout, "SUB\tD" }, // 0x92
{opout, "SUB\tE" }, // 0x93
{opout, "SUB\tH" }, // 0x94
{opout, "SUB\tL" }, // 0x95
{opout, "SUB\t(HL)" }, // 0x96
{opout, "SUB\tA" }, // 0x97
{opout, "SBC\tA,B" }, // 0x98
{opout, "SBC\tA,C" }, // 0x99
{opout, "SBC\tA,D" }, // 0x9a
{opout, "SBC\tA,E" }, // 0x9b
{opout, "SBC\tA,H" }, // 0x9c
{opout, "SBC\tA,L" }, // 0x9d
{opout, "SBC\tA,(HL)" }, // 0x9e
{opout, "SBC\tA,A" }, // 0x9f
{opout, "AND\tB" }, // 0xa0
{opout, "AND\tC" }, // 0xa1
{opout, "AND\tD" }, // 0xa2
{opout, "AND\tE" }, // 0xa3
{opout, "AND\tH" }, // 0xa4
{opout, "AND\tL" }, // 0xa5
{opout, "AND\t(HL)" }, // 0xa6
{opout, "AND\tA" }, // 0xa7
{opout, "XOR\tB" }, // 0xa8
{opout, "XOR\tC" }, // 0xa9
{opout, "XOR\tD" }, // 0xaa
{opout, "XOR\tE" }, // 0xab
{opout, "XOR\tH" }, // 0xac
{opout, "XOR\tL" }, // 0xad
{opout, "XOR\t(HL)" }, // 0xae
{opout, "XOR\tA" }, // 0xaf
{opout, "OR\tB" }, // 0xb0
{opout, "OR\tC" }, // 0xb1
{opout, "OR\tD" }, // 0xb2
{opout, "OR\tE" }, // 0xb3
{opout, "OR\tH" }, // 0xb4
{opout, "OR\tL" }, // 0xb5
{opout, "OR\t(HL)" }, // 0xb6
{opout, "OR\tA" }, // 0xb7
{opout, "CP\tB" }, // 0xb8
{opout, "CP\tC" }, // 0xb9
{opout, "CP\tD" }, // 0xba
{opout, "CP\tE" }, // 0xbb
{opout, "CP\tH" }, // 0xbc
{opout, "CP\tL" }, // 0xbd
{opout, "CP\t(HL)" }, // 0xbe
{opout, "CP\tA" }, // 0xbf
{opout, "RET\tNZ" }, // 0xc0
{opout, "POP\tBC" }, // 0xc1
{nnout, "JP\tNZ," }, // 0xc2
{nnout, "JP\t" }, // 0xc3
{nnout, "CALL\tNZ," }, // 0xc4
{opout, "PUSH\tBC" }, // 0xc5
{nout, "ADD\tA," }, // 0xc6
{opout, "RST\t0" }, // 0xc7
{opout, "RET\tZ" }, // 0xc8
{opout, "RET" }, // 0xc9
{nnout, "JP\tZ," }, // 0xca
{cbop, "" }, // 0xcb
{nnout, "CALL\tZ," }, // 0xcc
{nnout, "CALL\t" }, // 0xcd
{nout, "ADC\tA," }, // 0xce
{opout, "RST\t8" }, // 0xcf
{opout, "RET\tNC" }, // 0xd0
{opout, "POP\tDE" }, // 0xd1
{nnout, "JP\tNC," }, // 0xd2
{iout, "OUT\t(%02X),A"}, // 0xd3
{nnout, "CALL\tNC," }, // 0xd4
{opout, "PUSH\tDE" }, // 0xd5
{nout, "SUB\t" }, // 0xd6
{opout, "RST\t10" }, // 0xd7
{opout, "RET\tC" }, // 0xd8
{opout, "EXX" }, // 0xd9
{nnout, "JP\tC," }, // 0xda
{iout, "IN\tA,(%02X)" }, // 0xdb
{nnout, "CALL\tC," }, // 0xdc
{ddfd, "" }, // 0xdd
{nout, "SBC\tA," }, // 0xde
{opout, "RST\t18" }, // 0xdf
{opout, "RET\tPO" }, // 0xe0
{opout, "POP\tHL" }, // 0xe1
{nnout, "JP\tPO," }, // 0xe2
{opout, "EX\t(SP),HL" }, // 0xe3
{nnout, "CALL\tPO," }, // 0xe4
{opout, "PUSH\tHL" }, // 0xe5
{nout, "AND\t" }, // 0xe6
{opout, "RST\t20" }, // 0xe7
{opout, "RET\tPE" }, // 0xe8
{opout, "JP\t(HL)" }, // 0xe9
{nnout, "JP\tPE," }, // 0xea
{opout, "EX\tDE,HL" }, // 0xeb
{nnout, "CALL\tPE," }, // 0xec
{edop, "" }, // 0xed
{nout, "XOR\t" }, // 0xee
{opout, "RST\t28" }, // 0xef
{opout, "RET\tP" }, // 0xf0
{opout, "POP\tAF" }, // 0xf1
{nnout, "JP\tP," }, // 0xf2
{opout, "DI" }, // 0xf3
{nnout, "CALL\tP," }, // 0xf4
{opout, "PUSH\tAF" }, // 0xf5
{nout, "OR\t" }, // 0xf6
{opout, "RST\t30" }, // 0xf7
{opout, "RET\tM" }, // 0xf8
{opout, "LD\tSP,HL" }, // 0xf9
{nnout, "JP\tM," }, // 0xfa
{opout, "EI" }, // 0xfb
{nnout, "CALL\tM," }, // 0xfc
{ddfd, "" }, // 0xfd
{nout, "CP\t" }, // 0xfe
{opout, "RST\t38" } // 0xff
};
static const char* unkown = "???";
static const char* reg[] = {"B", "C", "D", "E", "H", "L", "(HL)", "A"};
static const char* regix = "IX";
static const char* regiy = "IY";
/* globals for passing disassembled code to anyone else who's interested */
char Disass_Str[64];
char Opcode_Str[64];
/* Set up machine code hex in Opcode_Str for GUI disassembly */
void
get_opcodes(WORD addr,
int len)
{
#if OCTAL
switch (len)
{
case 1:
sprintf(Opcode_Str, "%03o ", readMemory(addr));
break;
case 2:
sprintf(Opcode_Str, "%03o %03o ", readMemory(addr), readMemory(addr + 1));
break;
case 3:
sprintf(Opcode_Str, "%03o %03o %03o ", readMemory(addr), readMemory(addr + 1),
readMemory(addr + 2));
break;
case 4:
sprintf(Opcode_Str, "%03o %03o %03o %02X3o", readMemory(addr),
readMemory(addr + 1),
readMemory(addr + 2),
readMemory(addr + 3));
break;
default:
sprintf(Opcode_Str, "xxx xxx xxx xxx");
break;
}
#else
switch (len)
{
case 1:
sprintf(Opcode_Str, "%02x ", readMemory(addr));
break;
case 2:
sprintf(Opcode_Str, "%02x %02x ", readMemory(addr), readMemory(addr + 1));
break;
case 3:
sprintf(Opcode_Str, "%02x %02x %02x ", readMemory(addr), readMemory(addr + 1),
readMemory(addr + 2));
break;
case 4:
sprintf(Opcode_Str, "%02x %02x %02x %02x", readMemory(addr),
readMemory(addr + 1),
readMemory(addr + 2),
readMemory(addr + 3));
break;
default:
sprintf(Opcode_Str, "xx xx xx xx");
break;
}
#endif
}
///
/// The function disass() is the only global function of
/// this module. The addr argument is the PC to disassemble.
/// unsigned char pointer, which points to the op-code
/// to disassemble. The output of the disassembly goes
/// to stdout, terminated by a newline. After the
/// disassembly the pointer to the op-code will be
/// increased by the size of the op-code, so that
/// disass() can be called again.
/// The second argument is the (Z80) address of the
/// op-code to disassemble. It is used to calculate the
/// destination address of relative jumps.
///
BYTE
disass(WORD addr)
{
int len;
BYTE val = readMemory(addr);
len = (*optab[val].fun)(optab[val].text, addr);
get_opcodes(addr, len);
fprintf(log_out, " %s: %s\n", Opcode_Str, Disass_Str);
return (len);
}
///
/// disassemble 1 byte op-codes
///
static int
opout(const char* s,
WORD)
{
sprintf(Disass_Str, "%s", s);
return (1);
}
///
/// disassemble 2 byte op-codes of type "Op n"
///
static int
nout(const char* s,
WORD addr)
{
#if OCTAL
sprintf(Disass_Str, "%s%03o", s, readMemory(addr + 1));
#else
sprintf(Disass_Str, "%s%02X", s, readMemory(addr + 1));
#endif
return (2);
}
///
/// disassemble 2 byte op-codes with indirect addressing
///
static int
iout(const char* s,
WORD addr)
{
sprintf(Disass_Str, s, readMemory(addr + 1));
return (2);
}
///
/// disassemble 2 byte op-codes with relative addressing
///
static int
rout(const char* s,
WORD addr)
{
sprintf(Disass_Str, "%s%04X", s, addr + ((signed char) readMemory(addr + 1)) + 2);
return (2);
}
///
/// disassemble 3 byte op-codes of type "Op nn"
///
static int
nnout(const char* s,
WORD addr)
{
int i;
i = readMemory(addr + 1) + (readMemory(addr + 2) << 8);
sprintf(Disass_Str, "%s%04X", s, i);
return (3);
}
///
/// disassemble 3 byte op-codes with indirect addressing
///
static int
inout(const char* s,
WORD addr)
{
int i;
i = readMemory(addr + 1) + (readMemory(addr + 2) << 8);
sprintf(Disass_Str, s, i);
return (3);
}
///
/// disassemble multi byte op-codes with prefix 0xcb
///
static int
cbop(const char* s,
WORD addr)
{
int b2;
b2 = readMemory(addr + 1);
switch (b2 & 0xc0)
{
case 0x00:
switch (b2 & 0x38)
{
case 0x00:
sprintf(Disass_Str, "RLC\t%s", reg[b2 & 7]);
break;
case 0x08:
sprintf(Disass_Str, "RRC\t%s", reg[b2 & 7]);
break;
case 0x10:
sprintf(Disass_Str, "RL\t%s", reg[b2 & 7]);
break;
case 0x18:
sprintf(Disass_Str, "RR\t%s", reg[b2 & 7]);
break;
case 0x20:
sprintf(Disass_Str, "SLA\t%s", reg[b2 & 7]);
break;
case 0x28:
sprintf(Disass_Str, "SRA\t%s", reg[b2 & 7]);
break;
case 0x30:
sprintf(Disass_Str, "SLL\t%s", reg[b2 & 7]);
break;
case 0x38:
sprintf(Disass_Str, "SRL\t%s", reg[b2 & 7]);
break;
}
break;
case 0x40:
sprintf(Disass_Str, "BIT\t%c,%s", ((b2 >> 3) & 7) + '0', reg[b2 & 7]);
break;
case 0x80:
sprintf(Disass_Str, "RES\t%c,%s", ((b2 >> 3) & 7) + '0', reg[b2 & 7]);
break;
case 0xC0:
sprintf(Disass_Str, "SET\t%c,%s", ((b2 >> 3) & 7) + '0', reg[b2 & 7]);
break;
}
return (2);
}
///
/// disassemble multi byte op-codes with prefix 0xed
///
static int
edop(const char* s,
WORD addr)
{
int b2, i;
int len = 2;
Disass_Str[0] = 0;
b2 = readMemory(addr + 1);
switch (b2)
{
case 0x40:
strcat(Disass_Str, "IN\tB,(C)");
break;
case 0x41:
strcat(Disass_Str, "OUT\t(C),B");
break;
case 0x42:
strcat(Disass_Str, "SBC\tHL,BC");
break;
case 0x43:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t(%04X),BC", i);
len = 4;
break;
case 0x44:
strcat(Disass_Str, "NEG");
break;
case 0x45:
strcat(Disass_Str, "RETN");
break;
case 0x46:
strcat(Disass_Str, "IM\t0");
break;
case 0x47:
strcat(Disass_Str, "LD\tI,A");
break;
case 0x48:
strcat(Disass_Str, "IN\tC,(C)");
break;
case 0x49:
strcat(Disass_Str, "OUT\t(C),C");
break;
case 0x4a:
strcat(Disass_Str, "ADC\tHL,BC");
break;
case 0x4b:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\tBC,(%04X)", i);
len = 4;
break;
case 0x4d:
strcat(Disass_Str, "RETI");
break;
case 0x4f:
strcat(Disass_Str, "LD\tR,A");
break;
case 0x50:
strcat(Disass_Str, "IN\tD,(C)");
break;
case 0x51:
strcat(Disass_Str, "OUT\t(C),D");
break;
case 0x52:
strcat(Disass_Str, "SBC\tHL,DE");
break;
case 0x53:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t(%04X),DE", i);
len = 4;
break;
case 0x56:
strcat(Disass_Str, "IM\t1");
break;
case 0x57:
strcat(Disass_Str, "LD\tA,I");
break;
case 0x58:
strcat(Disass_Str, "IN\tE,(C)");
break;
case 0x59:
strcat(Disass_Str, "OUT\t(C),E");
break;
case 0x5a:
strcat(Disass_Str, "ADC\tHL,DE");
break;
case 0x5b:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\tDE,(%04X)", i);
len = 4;
break;
case 0x5e:
strcat(Disass_Str, "IM\t2");
break;
case 0x5f:
strcat(Disass_Str, "LD\tA,R");
break;
case 0x60:
strcat(Disass_Str, "IN\tH,(C)");
break;
case 0x61:
strcat(Disass_Str, "OUT\t(C),H");
break;
case 0x62:
strcat(Disass_Str, "SBC\tHL,HL");
break;
case 0x67:
strcat(Disass_Str, "RRD");
break;
case 0x68:
strcat(Disass_Str, "IN\tL,(C)");
break;
case 0x69:
strcat(Disass_Str, "OUT\t(C),L");
break;
case 0x6a:
strcat(Disass_Str, "ADC\tHL,HL");
break;
case 0x6f:
strcat(Disass_Str, "RLD");
break;
case 0x72:
strcat(Disass_Str, "SBC\tHL,SP");
break;
case 0x73:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t(%04X),SP", i);
len = 4;
break;
case 0x78:
strcat(Disass_Str, "IN\tA,(C)");
break;
case 0x79:
strcat(Disass_Str, "OUT\t(C),A");
break;
case 0x7a:
strcat(Disass_Str, "ADC\tHL,SP");
break;
case 0x7b:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\tSP,(%04X)", i);
len = 4;
break;
case 0xa0:
strcat(Disass_Str, "LDI");
break;
case 0xa1:
strcat(Disass_Str, "CPI");
break;
case 0xa2:
strcat(Disass_Str, "INI");
break;
case 0xa3:
strcat(Disass_Str, "OUTI");
break;
case 0xa8:
strcat(Disass_Str, "LDD");
break;
case 0xa9:
strcat(Disass_Str, "CPD");
break;
case 0xaa:
strcat(Disass_Str, "IND");
break;
case 0xab:
strcat(Disass_Str, "OUTD");
break;
case 0xb0:
strcat(Disass_Str, "LDIR");
break;
case 0xb1:
strcat(Disass_Str, "CPIR");
break;
case 0xb2:
strcat(Disass_Str, "INIR");
break;
case 0xb3:
strcat(Disass_Str, "OTIR");
break;
case 0xb8:
strcat(Disass_Str, "LDDR");
break;
case 0xb9:
strcat(Disass_Str, "CPDR");
break;
case 0xba:
strcat(Disass_Str, "INDR");
break;
case 0xbb:
strcat(Disass_Str, "OTDR");
break;
default:
strcat(Disass_Str, unkown);
break;
}
return (len);
}
///
/// disassemble multi byte op-codes with prefix 0xdd and 0xfd
///
/// \todo fix the offset + x to show current number +-
static int
ddfd(const char* s,
WORD addr)
{
int b2;
const char* ireg;
int len = 3; // assume 3, some will be either 2 or 4, set those
WORD i;
if (readMemory(addr) == 0xdd)
{
ireg = regix;
}
else
{
ireg = regiy;
}
b2 = readMemory(addr + 1);
if (b2 >= 0x70 && b2 <= 0x77)
{
sprintf(Disass_Str, "LD\t(%s+%02X),%s", ireg, readMemory(addr + 2),
reg[b2 & 7]);
return (3);
}
switch (b2)
{
case 0x09:
sprintf(Disass_Str, "ADD\t%s,BC", ireg);
len = 2;
break;
case 0x19:
sprintf(Disass_Str, "ADD\t%s,DE", ireg);
len = 2;
break;
case 0x21:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t%s,%04X", ireg, i);
len = 4;
break;
case 0x22:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t(%04X),%s", i, ireg);
len = 4;
break;
case 0x23:
sprintf(Disass_Str, "INC\t%s", ireg);
len = 2;
break;
case 0x29:
sprintf(Disass_Str, "ADD\t%s,%s", ireg, ireg);
len = 2;
break;
case 0x2a:
i = readMemory(addr + 2) + (readMemory(addr + 3) << 8);
sprintf(Disass_Str, "LD\t%s,(%04X)", ireg, i);
len = 4;
break;
case 0x2b:
sprintf(Disass_Str, "DEC\t%s", ireg);
len = 2;
break;
case 0x34:
sprintf(Disass_Str, "INC\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x35:
sprintf(Disass_Str, "DEC\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x36:
sprintf(Disass_Str, "LD\t(%s+%02X),%02X", ireg, readMemory(addr + 2),
readMemory(addr + 3));
len = 4;
break;
case 0x39:
sprintf(Disass_Str, "ADD\t%s,SP", ireg);
len = 2;
break;
case 0x46:
sprintf(Disass_Str, "LD\tB,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x4e:
sprintf(Disass_Str, "LD\tC,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x56:
sprintf(Disass_Str, "LD\tD,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x5e:
sprintf(Disass_Str, "LD\tE,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x66:
sprintf(Disass_Str, "LD\tH,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x6e:
sprintf(Disass_Str, "LD\tL,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x7e:
sprintf(Disass_Str, "LD\tA,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x86:
sprintf(Disass_Str, "ADD\tA,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x8e:
sprintf(Disass_Str, "ADC\tA,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x96:
sprintf(Disass_Str, "SUB\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x9e:
sprintf(Disass_Str, "SBC\tA,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xa6:
sprintf(Disass_Str, "AND\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xae:
sprintf(Disass_Str, "XOR\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xb6:
sprintf(Disass_Str, "OR\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xbe:
sprintf(Disass_Str, "CP\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xcb:
switch (readMemory(addr + 3))
{
case 0x06:
sprintf(Disass_Str, "RLC\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x0e:
sprintf(Disass_Str, "RRC\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x16:
sprintf(Disass_Str, "RL\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x1e:
sprintf(Disass_Str, "RR\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x26:
sprintf(Disass_Str, "SLA\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x2e:
sprintf(Disass_Str, "SRA\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x36: // Undocumented SLL
sprintf(Disass_Str, "SLL\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x3e:
sprintf(Disass_Str, "SRL\t(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x46:
sprintf(Disass_Str, "BIT\t0,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x4e:
sprintf(Disass_Str, "BIT\t1,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x56:
sprintf(Disass_Str, "BIT\t2,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x5e:
sprintf(Disass_Str, "BIT\t3,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x66:
sprintf(Disass_Str, "BIT\t4,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x6e:
sprintf(Disass_Str, "BIT\t5,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x76:
sprintf(Disass_Str, "BIT\t6,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x7e:
sprintf(Disass_Str, "BIT\t7,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x86:
sprintf(Disass_Str, "RES\t0,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x8e:
sprintf(Disass_Str, "RES\t1,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x96:
sprintf(Disass_Str, "RES\t2,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0x9e:
sprintf(Disass_Str, "RES\t3,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xa6:
sprintf(Disass_Str, "RES\t4,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xae:
sprintf(Disass_Str, "RES\t5,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xb6:
sprintf(Disass_Str, "RES\t6,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xbe:
sprintf(Disass_Str, "RES\t7,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xc6:
sprintf(Disass_Str, "SET\t0,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xce:
sprintf(Disass_Str, "SET\t1,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xd6:
sprintf(Disass_Str, "SET\t2,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xde:
sprintf(Disass_Str, "SET\t3,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xe6:
sprintf(Disass_Str, "SET\t4,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xee:
sprintf(Disass_Str, "SET\t5,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xf6:
sprintf(Disass_Str, "SET\t6,(%s+%02X)", ireg, readMemory(addr + 2));
break;
case 0xfe:
sprintf(Disass_Str, "SET\t7,(%s+%02X)", ireg, readMemory(addr + 2));
break;
default:
strcat(Disass_Str, unkown);
break;
}
len = 4;
break;
case 0xe1:
sprintf(Disass_Str, "POP\t%s", ireg);
len = 2;
break;
case 0xe3:
sprintf(Disass_Str, "EX\t(SP),%s", ireg);
len = 2;
break;
case 0xe5:
sprintf(Disass_Str, "PUSH\t%s", ireg);
len = 2;
break;
case 0xe9:
sprintf(Disass_Str, "JP\t(%s)", ireg);
len = 2;
break;
case 0xf9:
sprintf(Disass_Str, "LD\tSP,%s", ireg);
len = 2;
break;
default:
strcat(Disass_Str, unkown);
break;
}
return (len);
}
<file_sep>/VirtualH89/Src/crc-ccitt.h
///
/// \name crc-ccitt.h
///
///
/// \date Oct 5, 2012
/// \author <NAME>
///
#ifndef CRC_CCITT_H_
#define CRC_CCITT_H_
#include "h89Types.h"
class CRC_CCITT
{
public:
CRC_CCITT();
~CRC_CCITT();
void initCRC();
void updateCRC(BYTE val);
WORD getCRC();
private:
WORD crc_m;
static const WORD initValue_c = 0xffff;
static const WORD crctable[256];
};
#endif // CRC_CCITT_H_
<file_sep>/VirtualH89/Src/GppListener.cpp
///
/// \file GppListener.cpp
///
/// Register parties interested in GPIO bits, and notify them whenever bits change.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#include "GppListener.h"
using namespace std;
std::vector<GppListener*> GppListener::notifications;
GppListener::GppListener(BYTE bits): interestedBits_m(bits)
{
}
void
GppListener::addListener(GppListener* listener)
{
// If we have more than one, need vector<>, array, or ...
notifications.push_back(listener);
}
void
GppListener::notifyListeners(BYTE gpo,
BYTE diffs)
{
for (GppListener* listener : notifications)
{
if ((listener->interestedBits_m & diffs) != 0)
{
listener->gppNewValue(gpo);
}
}
}
<file_sep>/VirtualH89/Src/H37InterruptController.cpp
///
/// \file H37InterruptController.cpp
///
/// \author <NAME>
/// \date Mar. 17, 2016
///
#include "H37InterruptController.h"
#include "cpu.h"
#include "logger.h"
H37InterruptController::H37InterruptController(CPU* cpu): InterruptController(cpu),
intrqRaised_m(false),
drqRaised_m(false),
interruptsBlocked_m(false)
{
debugss(ssH37InterruptController, INFO, "Entering\n");
}
H37InterruptController::~H37InterruptController()
{
debugss(ssH37InterruptController, INFO, "Entering\n");
}
void
H37InterruptController::setINTLine()
{
// debugss(ssH37InterruptController, INFO, "intLevel: %d intrqRaised_m: %d drqRaised: %d\n",
// intLevel_m, intrqRaised_m, drqRaised_m);
if ((!interruptsBlocked_m && intLevel_m != 0) || intrqRaised_m || drqRaised_m)
{
cpu_m->raiseINT();
cpu_m->continueRunning();
}
else
{
cpu_m->lowerINT();
}
}
/// reading instructions for interrupts
/// this models the real hardware, in which the circuit generated the right
/// bits to be the desired instruction
BYTE
H37InterruptController::readDataBus()
{
BYTE opCode = 0;
// debugss(ssH37InterruptController, INFO, "intLevel: %d intrqRaised_m: %d drqRaised: %d\n",
// intLevel_m, intrqRaised_m, drqRaised_m);
if (intrqRaised_m)
{
debugss(ssH37InterruptController, INFO, "intrq set\n");
// RST 20H (Interrupt 4)
opCode = 0xe7;
}
else if (drqRaised_m)
{
// EI
debugss(ssH37InterruptController, ALL, "drq set\n");
opCode = 0xfb;
}
else if (!interruptsBlocked_m)
{
opCode = InterruptController::readDataBus();
}
else
{
debugss(ssH37InterruptController, ERROR, "interruptsBlocked_m, requesting instruction\n");
opCode = InterruptController::readDataBus();
}
debugss(ssH37InterruptController, ALL, "opCode: %d\n", opCode);
return opCode;
}
void
H37InterruptController::setIntrq(bool raise)
{
debugss(ssH37InterruptController, VERBOSE, "Entering: %d\n", raise);
intrqRaised_m = raise;
setINTLine();
}
void
H37InterruptController::setDrq(bool raise)
{
debugss(ssH37InterruptController, VERBOSE, "Entering: %d\n", raise);
drqRaised_m = raise;
setINTLine();
}
void
H37InterruptController::blockInterrupts(bool block)
{
debugss(ssH37InterruptController, INFO, "Entering: %d\n", block);
interruptsBlocked_m = block;
setINTLine();
}
<file_sep>/VirtualH89/Doxygen/generateDoxy
#! /bin/sh
/Applications/Doxygen.app/Contents/Resources/doxygen ./doxygen.conf
<file_sep>/VirtualH89/Src/DiskDrive.cpp
///
/// \file DiskDrive.cpp
///
/// \date Jul 21, 2012
/// \author <NAME>
///
#include "DiskDrive.h"
#include "FloppyDisk.h"
#include "logger.h"
#include "h-17-1.h"
#include "h-17-4.h"
/// \cond
#include <memory>
/// \endcond
using namespace std;
DiskDrive::DiskDrive(BYTE tracks): disk_m(0),
headLoaded_m(false),
numTracks_m(tracks)
{
}
DiskDrive::~DiskDrive()
{
}
shared_ptr<DiskDrive>
DiskDrive::getInstance(string type)
{
shared_ptr<DiskDrive> drive = nullptr;
if ((type.compare("FDD_5_25_SS_ST") == 0) || (type.compare("H17_1") == 0))
{
debugss(ssDiskDrive, INFO, "allocating h17-1 drive\n");
drive = make_shared<H_17_1>();
}
// \todo support ss_dt & ds_st
// else if (type.compare("FDD_5_25_SS_DT") == 0)
// {
// etype = FDD_5_25_SS_DT;
// }
// else if (type.compare("FDD_5_25_DS_ST") == 0)
// {
// etype = FDD_5_25_DS_ST;
// }
else if ((type.compare("FDD_5_25_DS_DT") == 0) || (type.compare("H17_4") == 0))
{
debugss(ssDiskDrive, INFO, "allocating h17-4 drive\n");
drive = make_shared<H_17_4>();
}
else
{
debugss(ssDiskDrive, ERROR, "unable to allocate drive\n");
}
return drive;
}
void
DiskDrive::insertDisk(shared_ptr<FloppyDisk> disk)
{
disk_m = disk;
// check for a Null disk insertion.
if (disk_m)
{
disk_m->setMaxTrack(numTracks_m);
}
}
void
DiskDrive::ejectDisk(const char* name)
{
if (disk_m)
{
disk_m->eject(name);
}
disk_m = nullptr;
}
void
DiskDrive::loadHead()
{
headLoaded_m = true;
}
void
DiskDrive::unLoadHead()
{
headLoaded_m = false;
}
bool
DiskDrive::getHeadLoadStatus()
{
return headLoaded_m;
}
<file_sep>/VirtualH89/Src/h-17-4.h
///
/// \file h-17-4.h
///
/// \date Jul 21, 2012
/// \author <NAME>
///
#ifndef H_17_4_H_
#define H_17_4_H_
#include "DiskDrive.h"
class FloppyDisk;
/// \brief Virtual double-sided 96 tpi floppy disk drive.
///
/// Implements a virtual floppy disk drive. The H-17-4 is a double-sided, 80 track drive.
/// On a H-17 controller, this yields 160 total track and 1600 total sectors. Each sector
/// is 256 bytes, this provides support for about 400k per drive.
/// Upcoming support for the Z-89-37 controller will allow this drive to store up to 720K.
///
class H_17_4: public DiskDrive
{
public:
H_17_4();
virtual ~H_17_4() override;
void getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect) override;
void selectSide(BYTE side) override;
void step(bool direction) override;
BYTE readData(unsigned long pos) override;
void writeData(unsigned long pos,
BYTE data) override;
virtual BYTE readSectorData(BYTE sector,
unsigned long pos) override;
private:
BYTE side_m;
BYTE track_m;
static const unsigned int maxTracks_c = 80;
};
#endif // H_17_4_H_
<file_sep>/VirtualH89/Src/propertyutil.h
// Java-Style Properties in C++
//
// (c) <NAME>
// Senzee 5
// http://senzee.blogspot.com
#ifndef _PROPERTYUTIL_H
#define _PROPERTYUTIL_H
/// \cond
#include <map>
#include <string>
#include <iostream>
#include <vector>
/// \endcond
class PropertyUtil
{
// enum { DEBUG = 0 };
public:
typedef std::map<std::string, std::string> PropertyMapT;
typedef PropertyMapT::value_type value_type;
typedef PropertyMapT::iterator iterator;
static void read(const char* filename,
PropertyMapT& map);
static void read(std::istream& is,
PropertyMapT& map);
static void write(const char* filename,
PropertyMapT& map,
const char* header = nullptr);
static void write(std::ostream& os,
PropertyMapT& map,
const char* header = nullptr);
static void print(std::ostream& os,
PropertyMapT& map);
static std::vector<std::string> splitArgs(std::string prop);
static std::string combineArgs(std::vector<std::string> args,
int start = 0);
static std::vector<std::string> shiftArgs(std::vector<std::string> args,
int start);
static std::string sprintf(const char* fmt ...);
private:
static inline char m_hex(int nibble)
{
static const char* digits = "0123456789ABCDEF";
return digits[nibble & 0xf];
}
};
#endif // _PROPERTYUTIL_H
<file_sep>/VirtualH89/Src/GeneralPurposePort.h
/// \file GeneralPurposePort.h
///
/// The H89 has this 'General Purpose Port', that allows the CPU to read the configured
/// dip switches on the CPU port. It is also used to control some behavior when written.
///
/// \date Apr 20, 2009
/// \author <NAME>
///
#ifndef GENERALPURPOSEPORT_H_
#define GENERALPURPOSEPORT_H_
#include "IODevice.h"
/// \cond
#include <string>
/// \endcond
class Computer;
///
/// \brief General Purpose Port
///
/// Reads from the General Purpose Port, returns the values of a dip switch on the CPU board.
/// Writes to the General Purpose Port, control some behavior such as timer interrupts,
/// mapping of ROM, and single-step.
///
class GeneralPurposePort: public virtual IODevice
{
public:
GeneralPurposePort(Computer* computer);
GeneralPurposePort(Computer* computer, std::string settings);
virtual ~GeneralPurposePort() override;
BYTE in(BYTE addr) override;
void out(BYTE addr,
BYTE val) override;
virtual std::string dumpDebug();
void reset() override;
private:
Computer* computer_m;
BYTE dipsw_m;
BYTE portBits_m;
/// Address for General Purpose Port
/// Octal 362
static const BYTE GPP_BaseAddress_c = 0xf2;
static const BYTE GPP_NumPorts_c = 1;
/// Configuration Values
/// MTR-88
/// Memory Test at power up
static const BYTE Mtr88_MemoryTest_Mask_c = 0x20;
/// Memory Test at power up on
static const BYTE Mtr88_MemoryTest_On_c = 0x00;
/// Memory Test at power up off
static const BYTE Mtr88_MemoryTest_Off_c = 0x20;
/// Baud rate Mask
static const BYTE Mtr88_Baud_Mask_c = 0xc0;
/// Baud rate 9600
static const BYTE Mtr88_Baud_9600_c = 0x00;
/// Baud rate 19200
static const BYTE Mtr88_Baud_19200_c = 0x40;
/// Baud rate 38400
static const BYTE Mtr88_Baud_38400_c = 0x80;
/// Baud rate 57600
static const BYTE Mtr88_Baud_57600_c = 0xc0;
/// MTR-89
static const BYTE Mtr89_Port174_Mask_c = 0x03; // Mask for determining controller
// at right slot
static const BYTE Mtr89_Port174_H_88_1_c = 0x00; // H-88-1 hard-sectored controller
static const BYTE Mtr89_Port174_Z_89_47_c = 0x01; // Z-89-47 8" floppy disk controller
static const BYTE Mtr89_Port174_Undef1_c = 0x02; // Undefined
static const BYTE Mtr89_Port174_Undef2_c = 0x03; // Undefined
static const BYTE Mtr89_Port170_Mask_c = 0x0c; // Mask for determining controller
// at left slot
static const BYTE Mtr89_Port170_Unused_c = 0x00; // Undefined
static const BYTE Mtr89_Port170_Z_89_47_c = 0x04; // Z-89-47 8" floppy disk controller
static const BYTE Mtr89_Port170_Undef1_c = 0x08; // Undefined
static const BYTE Mtr89_Port170_Undef2_c = 0x0c; // Undefined
static const BYTE Mtr89_PrimaryPort_c = 0x10; // Determine primary controller
static const BYTE Mtr89_PrimaryPort_174_c = 0x00; // Primary boot device is at port 174
static const BYTE Mtr89_PrimaryPort_170_c = 0x10; // Primary boot device is at port 170
static const BYTE Mtr89_MemoryTest_Mask_c = Mtr88_MemoryTest_Mask_c;
static const BYTE Mtr89_MemoryTest_On_c = Mtr88_MemoryTest_On_c;
static const BYTE Mtr89_MemoryTest_Off_c = Mtr88_MemoryTest_Off_c;
static const BYTE Mtr89_Baud_Mask_c = 0x40; // Baud mask
static const BYTE Mtr89_Baud_9600_c = Mtr88_Baud_9600_c;
static const BYTE Mtr89_Baud_19200_c = Mtr88_Baud_19200_c;
static const BYTE Mtr89_AutoBoot_c = 0x80; // Autoboot on power-up
/// MTR-90
static const BYTE Mtr90_Port174_Mask_c = Mtr89_Port174_Mask_c;
static const BYTE Mtr90_Port174_H_88_1_c = Mtr89_Port174_H_88_1_c;
static const BYTE Mtr90_Port174_Z_89_47_c = Mtr89_Port174_Z_89_47_c;
static const BYTE Mtr90_Port174_Z_89_67_c = 0x02; // Z-89-67 Winchester and 8" floppy
static const BYTE Mtr90_Port174_Undef_c = Mtr89_Port174_Undef2_c;
static const BYTE Mtr90_Port170_Mask_c = Mtr89_Port170_Mask_c;
static const BYTE Mtr90_Port170_Z_89_37_c = 0x00; // Z-89-37 soft-sectored controller
static const BYTE Mtr90_Port170_Z_89_47_c = 0x04; // Z-89-47 8" floppy disk controller
static const BYTE Mtr90_Port170_Z_89_67_c = 0x08; // Z-89-67 Winchester and 8" floppy
static const BYTE Mtr90_Port170_Undef_c = Mtr89_Port170_Undef2_c; // Undefined
static const BYTE Mtr90_PrimaryPort_174_c = Mtr89_PrimaryPort_174_c;
static const BYTE Mtr90_PrimaryPort_170_c = Mtr89_PrimaryPort_170_c;
static const BYTE Mtr90_MemoryTest_Mask_c = Mtr89_MemoryTest_Mask_c;
static const BYTE Mtr90_MemoryTest_On_c = Mtr89_MemoryTest_On_c;
static const BYTE Mtr90_MemoryTest_Off_c = Mtr89_MemoryTest_Off_c;
static const BYTE Mtr90_Baud_Mask_c = Mtr89_Baud_Mask_c;
static const BYTE Mtr90_Baud_9600_c = Mtr89_Baud_9600_c;
static const BYTE Mtr90_Baud_19200_c = Mtr89_Baud_19200_c;
static const BYTE Mtr90_AutoBoot_c = Mtr89_AutoBoot_c;
/// Out constants
/// Enable Single Step Interrupt - not sure about this.
static const BYTE gpp_SingleStepInterrupt_c = 0x01;
};
#endif // GENERALPURPOSEPORT_H_
<file_sep>/VirtualH89/Src/mms77316.cpp
/// \file mms77316.cpp
///
/// Implementation of the MMS 77316 floppy disk controller.
///
/// \date Jan 30, 2016
/// \author <NAME>, cloned from h37.cpp by <NAME>
///
#include "mms77316.h"
#include "logger.h"
#include "GenericFloppyDrive.h"
#include "RawFloppyImage.h"
#include "SectorFloppyImage.h"
#include "InterruptController.h"
#include "wd1797.h"
/// \cond
#include <string.h>
/// \endcond
const char* MMS77316::MMS77316_Name_c = "MMS77316";
GenericFloppyDrive*
MMS77316::getCurrentDrive()
{
// This could be NULL
return drives_m[controlReg_m & ctrl_DriveSel_c];
}
int
MMS77316::getClockPeriod()
{
return ((controlReg_m & ctrl_525DriveSel_c) != 0 ? 1000 : 500);
}
MMS77316::MMS77316(int baseAddr,
InterruptController* ic): DiskController(baseAddr,
MMS77316_NumPorts_c),
intrqRaised_m(false),
drqRaised_m(false),
ic_m(ic),
controlReg_m(0),
intLevel_m(MMS77316_Intr_c),
drqCount_m(0)
{
wd1797_m = new WD1797(this);
for (int x = 0; x < numDisks_c; ++x)
{
drives_m[x] = nullptr;
}
}
std::vector<GenericDiskDrive*>
MMS77316::getDiskDrives()
{
std::vector<GenericDiskDrive*> drives;
for (int x = 0; x < numDisks_c; ++x)
{
drives.push_back(drives_m[x]); // might be null, but must preserve number.
}
return drives;
}
std::string
MMS77316::getDriveName(int index)
{
if (index < 0 || index >= numDisks_c)
{
return nullptr;
}
char buf[32];
sprintf(buf, "%s-%d", MMS77316_Name_c, index + 1);
std::string str(buf);
return str;
}
GenericDiskDrive*
MMS77316::findDrive(std::string ident)
{
if (ident.find(MMS77316_Name_c) != 0 || ident[strlen(MMS77316_Name_c)] != '-')
{
return nullptr;
}
char* e;
unsigned long x = strtoul(ident.c_str() + strlen(MMS77316_Name_c) + 1, &e, 10);
if (*e != '\0' || x == 0 || x > numDisks_c)
{
return nullptr;
}
return drives_m[x - 1];
}
MMS77316*
MMS77316::install_MMS77316(InterruptController* ic,
PropertyUtil::PropertyMapT& props,
std::string slot)
{
std::map<int, GenericFloppyDrive*> mmsdrives;
std::string s;
MMS77316* m316 = new MMS77316(BasePort_c, ic);
// First identify what drives are installed.
for (int x = 0; x < numDisks_c; ++x)
{
std::string prop = "mms77316_drive";
prop += ('0' + x + 1);
s = props[prop];
if (!s.empty())
{
mmsdrives[x] = GenericFloppyDrive::getInstance(s);
}
}
// Now connect drives to controller.
if (mmsdrives.size() > 0)
{
for (int x = 0; x < numDisks_c; ++x)
{
if (mmsdrives[x] != nullptr)
{
m316->connectDrive(x, mmsdrives[x]);
}
}
}
// Next identify what diskettes are pre-inserted.
// TODO: GUI should allow manipulation of diskettes.
for (int x = 0; x < numDisks_c; ++x)
{
std::string prop = "mms77316_disk";
prop += ('0' + x + 1);
s = props[prop];
if (!s.empty())
{
GenericFloppyDrive* drv = m316->getDrive(x);
if (drv != nullptr)
{
drv->insertDisk(SectorFloppyImage::getDiskette(drv, PropertyUtil::splitArgs(s)));
}
}
}
return m316;
}
MMS77316::~MMS77316()
{
for (int x = 0; x < numDisks_c; ++x)
{
if (drives_m[x] != nullptr)
{
drives_m[x]->insertDisk(nullptr);
}
}
}
void
MMS77316::reset(void)
{
controlReg_m = 0;
intrqRaised_m = false;
drqRaised_m = false;
ic_m->setIntrq(intrqRaised_m);
ic_m->setDrq(drqRaised_m);
wd1797_m->reset();
}
BYTE
MMS77316::in(BYTE addr)
{
BYTE offset = getPortOffset(addr);
BYTE val = 0;
// case ControlPort_Offset_c: NOT READABLE
if (offset >= Wd1797_Offset_c)
{
offset -= Wd1797_Offset_c;
if (offset == WD1797::DataPort_Offset_c)
{
// might need to simulate WAIT states...
// Must NOT wait too long - this blocks all other progress.
// TODO: redesign this to return to execute() loop and
// stall there... requires in() to return a status or
// some other way inform the CPU to stall. The MMS77316
// has a built-in timeout on the WAIT hardware anyway,
// so, insure we don't stay here forever. The hardware
// timed out after 16 busclk (2MHz, i.e. CPU clock) cycles,
// really should count those but this is probably close enough.
int timeout = 0;
while (burstMode() && !drqRaised_m && !intrqRaised_m && ++timeout < 16)
{
// TODO: this stalls
wd1797_m->waitForData();
}
}
val = wd1797_m->in(offset);
}
else
{
debugss(ssMMS77316, ERROR, "(Unknown addr - 0x%02x)\n", addr);
}
debugss(ssMMS77316, VERBOSE, "(addr: %d) - %d\n", addr, val);
return (val);
}
void
MMS77316::out(BYTE addr,
BYTE val)
{
BYTE offset = getPortOffset(addr);
debugss(ssMMS77316, VERBOSE, "(addr: %d, %d (0x%x))\n", addr, val, val);
if (offset >= Wd1797_Offset_c)
{
offset -= Wd1797_Offset_c;
if (offset == WD1797::DataPort_Offset_c)
{
// See notes for MMS77316::in()...
int timeout = 0;
while (burstMode() && !drqRaised_m && !intrqRaised_m && ++timeout < 16)
{
wd1797_m->waitForData();
}
}
wd1797_m->out(offset, val);
}
else if (offset == ControlPort_Offset_c)
{
debugss(ssMMS77316, VERBOSE, "(ControlPort) %02x\n", val);
controlReg_m = val;
drqCount_m = 0;
GenericFloppyDrive* drive = getCurrentDrive();
if ((controlReg_m & ctrl_525DriveSel_c) != 0)
{
if (drive)
{
drive->motor(true);
}
}
wd1797_m->setCurrentDrive(drive);
wd1797_m->setDoubleDensity((controlReg_m & ctrl_SetMFMRecordingN_c) == 0);
if ((controlReg_m & ctrl_EnableIntReq_c) != 0 && (intrqRaised_m || drqRaised_m))
{
// Interrupt still pending, but now un-masked. Raise it.
ic_m->setIntrq(intrqRaised_m);
ic_m->setDrq(drqRaised_m);
}
}
else
{
debugss(ssMMS77316, ERROR, "(Unknown addr- 0x%02x): %d\n", addr, val);
}
}
GenericFloppyDrive*
MMS77316::getDrive(BYTE unitNum)
{
if (unitNum < numDisks_c)
{
return drives_m[unitNum];
}
return nullptr;
}
bool
MMS77316::readReady()
{
GenericFloppyDrive* drive = getCurrentDrive();
if (drive)
{
return drive->isReady();
}
return false;
}
bool
MMS77316::connectDrive(BYTE unitNum,
GenericFloppyDrive* drive)
{
bool retVal = false;
debugss(ssMMS77316, INFO, "unit (%d), drive (%p)\n", unitNum, drive);
if (unitNum < numDisks_c)
{
if (drives_m[unitNum] == nullptr)
{
drives_m[unitNum] = drive;
retVal = true;
}
else
{
debugss(ssMMS77316, ERROR, "drive already connect\n");
}
}
else
{
debugss(ssMMS77316, ERROR, "Invalid unit number (%d)\n", unitNum);
}
return (retVal);
}
bool
MMS77316::removeDrive(BYTE unitNum)
{
return (false);
}
void
MMS77316::raiseIntrq()
{
debugss(ssMMS77316, VERBOSE, "\n");
drqCount_m = 0;
intrqRaised_m = true;
if (intrqAllowed())
{
ic_m->setIntrq(intrqRaised_m);
}
}
void
MMS77316::raiseDrq()
{
debugss(ssMMS77316, INFO, "\n");
drqRaised_m = true;
if (drqAllowed())
{
++drqCount_m;
ic_m->setDrq(drqRaised_m);
}
}
void
MMS77316::lowerIntrq()
{
debugss(ssMMS77316, INFO, "\n");
intrqRaised_m = false;
ic_m->setIntrq(intrqRaised_m);
}
void
MMS77316::lowerDrq()
{
debugss(ssMMS77316, INFO, "\n");
drqRaised_m = false;
ic_m->setDrq(drqRaised_m);
}
void
MMS77316::loadHead(bool load)
{
debugss(ssMMS77316, INFO, "\n");
// wd1797_m->loadHead(load);
if (!load)
{
// TODO: fix this... need timeout...
// debugss(ssMMS77316, ERROR, "Clearing controlReg_m\n");
// controlReg_m = 0;
// TODO: start timer for motor-off (if was on...)
}
}
std::string
MMS77316::dumpDebug()
{
std::string ret = PropertyUtil::sprintf(
"CTRL=%02x\n"
// "FDC-STS=%02x FDC-CMD=%02x\n"
// "FDC-TRK=%d FDC-SEC=%d FDC-DAT=%02x\n"
"DRQ=%d INTRQ=%d\n",
controlReg_m,
// statusReg_m, cmdReg_m,
// trackReg_m, sectorReg_m, dataReg_m,
drqRaised_m, intrqRaised_m);
return ret;
}
<file_sep>/VirtualH89/Src/H89Operator.cpp
/// \file H89Operator.cpp
///
/// The VirtualH89-side implementation of the H89 Operator's interface, for
/// standard functions such as RESET and diskette muont/unmount, but also
/// providing virtual features like debugging.
///
/// \date Feb 9, 2016
/// \author <NAME>
///
#include "H89Operator.h"
#include "cpu.h"
#include "H89.h"
#include "h89-io.h"
#include "logger.h"
#include "DiskController.h"
#include "GenericDiskDrive.h"
#include "RawFloppyImage.h"
#include "SectorFloppyImage.h"
#include "propertyutil.h"
/// \cond
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <sstream>
/// \endcond
/// \brief H89Operator
///
///
H89Operator::H89Operator()
{
}
H89Operator::~H89Operator() {
}
GenericDiskDrive*
H89Operator::findDrive(std::string name)
{
std::vector<DiskController*> devs = h89.getIO().getDiskDevices();
for (int x = 0; x < devs.size(); ++x)
{
DiskController* dev = devs[x];
GenericDiskDrive* drv = nullptr;
if (dev != nullptr && (drv = dev->findDrive(name)) != nullptr)
{
return drv;
}
}
return nullptr;
}
DiskController*
H89Operator::findDiskCtrlr(std::string name)
{
std::vector<DiskController*> devs = h89.getIO().getDiskDevices();
for (int x = 0; x < devs.size(); ++x)
{
DiskController* dev = devs[x];
if (dev != nullptr && name.compare(dev->getDeviceName()) == 0)
{
return dev;
}
}
return nullptr;
}
std::string
H89Operator::cleanse(std::string resp)
{
size_t pos = 0;
while ((pos = resp.find('\n', pos)) != std::string::npos)
{
resp.replace(pos, 1, ";");
pos += 1;
}
return resp;
}
std::string
H89Operator::executeCommand(std::string cmd)
{
std::string resp;
std::vector<std::string> args = PropertyUtil::splitArgs(cmd);
debugss(ssStdioConsole, INFO, "Servicing cmd = %s\n", cmd.c_str());
if (args.size() < 1)
{
return "ok";
}
if (args[0].compare("quit") == 0)
{
h89.systemMutexRelease();
exit(0);
}
if (args[0].compare("echo") == 0)
{
return "ok " + PropertyUtil::combineArgs(args, 1);
}
if (args[0].compare("reset") == 0)
{
h89.reset();
return "ok";
}
if (args[0].compare("mount") == 0)
{
if (args.size() < 3)
{
return "error syntax: " + cmd;
}
GenericDiskDrive* drv = findDrive(args[1]);
if (drv == nullptr)
{
return "error nodrive: " + args[1];
}
drv->insertDisk(SectorFloppyImage::getDiskette(drv, PropertyUtil::shiftArgs(args, 2)));
return "ok";
}
if (args[0].compare("getdisks") == 0)
{
int count = 0;
std::vector<DiskController*> devs = h89.getIO().getDiskDevices();
std::ostringstream resp;
resp << "ok ";
for (int x = 0; x < devs.size(); ++x)
{
DiskController* dev = devs[x];
if (dev != nullptr)
{
std::vector<GenericDiskDrive*> drives = dev->getDiskDrives();
for (int y = 0; y < drives.size(); ++y)
{
GenericDiskDrive* drv = drives[y];
if (drv != nullptr)
{
if (count++ > 0)
{
resp << ';';
}
std::string media = drv->getMediaName();
// media = media.replaceAll(" ", "%20");
resp << dev->getDriveName(y) << "=" << media;
}
}
}
}
return resp.str();
}
if (args[0].compare("dump") == 0 && args.size() > 1)
{
if (args[1].compare("cpu") == 0)
{
std::string dump = "ok " + h89.getCPU().dumpDebug();
return cleanse(dump);
}
if (args[1].compare("mach") == 0)
{
std::string dump = "ok " + h89.dumpDebug();
return cleanse(dump);
}
if (args[1].compare("disk") == 0 && args.size() > 2)
{
DiskController* dev = findDiskCtrlr(args[2]);
if (dev == nullptr)
{
return "error no device " + args[2];
}
std::string dump = "ok " + dev->dumpDebug();
return cleanse(dump);
}
}
return "error badcmd: " + cmd;
}
std::string
H89Operator::handleCommand(std::string cmd)
{
h89.systemMutexAcquire();
std::string resp = executeCommand(cmd);
h89.systemMutexRelease();
return resp;
}
<file_sep>/VirtualH89/Src/WD179xUserIf.cpp
//
// WD179xUserIf.cpp
// VirtualH89
//
// Created by <NAME> on 4/9/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#include "WD179xUserIf.h"
WD179xUserIf::WD179xUserIf()
{
}
WD179xUserIf::~WD179xUserIf()
{
}
void
WD179xUserIf::loadHead(bool load)
{
}
<file_sep>/VirtualH89/Src/ParallelPortConnection.h
///
/// \name ParallelPortConnection.h
///
///
/// \date Aug 17, 2013
/// \author <NAME>
///
#ifndef PARALLELPORTCONNECTION_H_
#define PARALLELPORTCONNECTION_H_
#include "h89Types.h"
class ParallelLink;
class ParallelPortConnection
{
public:
ParallelPortConnection();
virtual ~ParallelPortConnection();
//
virtual void connectLink(ParallelLink* link);
enum SignalType
{
/// Master Reset (Host to Disk System)
st_MasterReset,
/// Data Acknowledge (Host to Disk System)
st_DTAK,
/// Data Ready (Disk System to Host)
st_DTR,
/// Disk Drive Out (Disk System to Host)
st_DDOUT,
/// Busy (Disk System to Host)
st_Busy,
/// Error (Disk System to Host)
st_Error
};
virtual void raiseSignal(SignalType sigType) = 0;
virtual void lowerSignal(SignalType sigType) = 0;
virtual void pulseSignal(SignalType sigType) = 0;
// virtual void receiveData(BYTE val) = 0;
protected:
ParallelLink* link_m;
};
#endif // PARALLELPORTCONNECTION_H_
<file_sep>/VirtualH89/Src/IOBus.cpp
//
// IOBus.cpp
// VirtualH89
//
// Created by <NAME> on 4/16/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#include "IOBus.h"
#include "logger.h"
#include "IODevice.h"
IOBus::IOBus()
{
debugss(ssIO, INFO, "%\n");
for (int port = 0; port < 256; ++port)
{
iodevices[port] = 0;
}
}
IOBus::~IOBus()
{
debugss(ssIO, INFO, "\n");
}
bool
IOBus::addDevice(IODevice* device)
{
debugss(ssIO, INFO, "\n");
if (device == nullptr)
{
// NULL device passed in
debugss(ssIO, ERROR, "Null Device\n");
return (false);
}
BYTE base = device->getBaseAddress();
BYTE num = device->getNumPorts();
BYTE last = base + num;
debugss(ssIO, INFO, "ports (%03o - %03o)\n", base, last);
if (!num)
{
// no ports.
debugss(ssIO, ERROR, "no ports\n");
return (false);
}
// First make sure there is no conflict
for (BYTE port = base; port < last; ++port)
{
if (iodevices[port])
{
// Address already in use
debugss(ssIO, ERROR, "duplicate devices on port (%03o)\n", port);
return (false);
}
}
// Now set the new value
for (BYTE port = base; port < last; ++port)
{
iodevices[port] = device;
}
return (true);
}
bool
IOBus::removeDevice(IODevice* device)
{
bool retVal = true;
if (device)
{
BYTE base = device->getBaseAddress();
BYTE num = device->getNumPorts();
BYTE last = base + num;
debugss(ssIO, INFO, "ports (%03o - %03o)\n", base, last);
if (num)
{
for (BYTE port = base; port < last; ++port)
{
if (iodevices[port] == device)
{
// TODO: call destructor? (i.e. "delete iodevices[port];"?)
iodevices[port] = 0;
}
else
{
// Doesn't match what is attempting to be removed.
debugss(ssIO, ERROR, "non-matching device on port (%03o)\n", port);
retVal = false;
}
}
}
else
{
// no ports.
debugss(ssIO, ERROR, "no ports\n");
retVal = false;
}
}
else
{
// NULL device passed in
debugss(ssIO, ERROR, "Null Device\n");
retVal = false;
}
return (retVal);
}
void
IOBus::reset()
{
for (int port = 0; port < 256; ++port)
{
if (iodevices[port] != nullptr)
{
iodevices[port]->reset();
}
}
}
BYTE
IOBus::in(BYTE addr)
{
BYTE val = 0xff;
debugss(ssIO, ALL, "(%03o)\n", addr);
if (iodevices[addr])
{
val = iodevices[addr]->in(addr);
}
else
{
// undefined in
debugss(ssIO, WARNING, "undefined port (%03o)\n", addr);
}
debugss(ssIO, ALL, "(%03o): %d\n", addr, val);
return (val);
}
void
IOBus::out(BYTE addr,
BYTE val)
{
debugss(ssIO, ALL, "(%03o) = 0x%02x\n", addr, val);
if (iodevices[addr])
{
iodevices[addr]->out(addr, val);
}
else
{
debugss(ssIO, WARNING, "undefined port (%03o) = 0x%02x\n", addr, val);
}
}
<file_sep>/VirtualH89/Src/InterruptController.cpp
///
/// \name InterruptController.cpp
///
///
/// \date Feb 7, 2016
/// \author <NAME>
///
#include "InterruptController.h"
#include "logger.h"
#include "cpu.h"
InterruptController::InterruptController(CPU* cpu): intLevel_m(0),
cpu_m(cpu)
{
debugss(ssInterruptController, INFO, "Entering\n");
}
InterruptController::~InterruptController()
{
debugss(ssInterruptController, INFO, "Entering\n");
}
void
InterruptController::setINTLine()
{
debugss(ssInterruptController, ALL, "\n");
if (intLevel_m != 0)
{
cpu_m->raiseINT();
}
else
{
cpu_m->lowerINT();
}
}
void
InterruptController::raiseInterrupt(BYTE level)
{
debugss(ssInterruptController, ALL, "level(%d)\n", level);
// verify level - only 0-7 are valid
if ((level < 0) || (level > 7))
{
debugss(ssInterruptController, ERROR, "invalid level(%d)\n", level);
return;
}
intLevel_m |= (1 << level);
// raise interrupt line to cpu
setINTLine();
}
void
InterruptController::lowerInterrupt(BYTE level)
{
debugss(ssInterruptController, ALL, "level(%d)\n", level);
// verify level - only 0-7 are valid
if ((level < 0) || (level > 7))
{
// INT level out-of-range.
debugss(ssInterruptController, ERROR, "invalid level(%d)\n", level);
return;
}
intLevel_m &= ~(1 << level);
// update interrupt line to cpu
setINTLine();
}
// reading instructions for interrupts
BYTE
InterruptController::readDataBus()
{
BYTE opCode = 0;
if (intLevel_m & 0x80)
{
opCode = 0xff;
}
else if (intLevel_m & 0x40)
{
opCode = 0xf7;
}
else if (intLevel_m & 0x20)
{
opCode = 0xef;
}
else if (intLevel_m & 0x10)
{
opCode = 0xe7;
}
else if (intLevel_m & 0x08)
{
opCode = 0xdf;
}
else if (intLevel_m & 0x04)
{
opCode = 0xd7;
}
else if (intLevel_m & 0x02)
{
opCode = 0xcf;
}
else if (intLevel_m & 0x01)
{
opCode = 0xc7;
}
else
{
// invalid interrupt level.
debugss(ssInterruptController, ERROR, "Invalid interrupt level: %d\n", intLevel_m);
}
debugss(ssInterruptController, ALL, "Interrupt Instruction %d\n", opCode);
return opCode;
}
void
InterruptController::setDrq(bool raise)
{
// shouldn't be called
debugss(ssInterruptController, ERROR, "base called(%d)\n", raise);
}
void
InterruptController::setIntrq(bool raise)
{
debugss(ssInterruptController, ERROR, "base called(%d)\n", raise);
}
void
InterruptController::blockInterrupts(bool block)
{
debugss(ssInterruptController, ERROR, "base called(%d)\n", block);
}
<file_sep>/VirtualH89/Src/ascii.h
/// \file ascii.h
///
/// Defines for ASCII characters
///
/// \date Nov 22, 2010
/// \author <NAME>
///
#ifndef ASCII_H_
#define ASCII_H_
#include "h89Types.h"
///
/// \namespace ascii
///
/// ASCII Constants.
///
namespace ascii
{
/// Null - not processed by the H19.
const BYTE NUL = 0x00;
/// Start Of Heading - not processed by the H19.
const BYTE SOH = 0x01;
/// Start Of Text - not processed by the H19.
const BYTE STX = 0x02;
/// End Of Text - not processed by the H19.
const BYTE ETX = 0x03;
/// End Of Transmission - not processed by the H19.
const BYTE EOT = 0x04;
/// Enquiry - not processed by the H19.
const BYTE ENQ = 0x05;
/// Acknowledge - not processed by the H19.
const BYTE ACK = 0x06;
/// Bell - Rings the bell
const BYTE BEL = 0x07;
/// Back Space
const BYTE BS = 0x08;
/// Horizontal Tab
const BYTE HT = 0x09;
/// Line Feed
const BYTE LF = 0x0a;
/// Vertical Tab - not processed by the H19.
const BYTE VT = 0x0b;
/// Form Feed - not processed by the H19.
const BYTE FF = 0x0c;
/// Carriage Return
const BYTE CR = 0x0d;
/// Shift Out - not processed by the H19.
const BYTE SO = 0x0e;
/// Shift In - not processed by the H19.
const BYTE SI = 0x0f;
/// Data Line Escape - not processed by the H19.
const BYTE DLE = 0x10;
/// Device Control 1: Turns transmitter on (XON) - not processed by the H19.
const BYTE DC1 = 0x11;
const BYTE XON = DC1;
/// Device Control 2 - not processed by the H19.
const BYTE DC2 = 0x12;
/// Device Control 3: Turns transmitter off (XOFF) - not processed by the H19.
const BYTE DC3 = 0x13;
const BYTE XOFF = DC3;
/// Device Control 4 - not processed by the H19.
const BYTE DC4 = 0x14;
/// Negative Acknowledge: Also ERR (error) - not processed by the H19.
const BYTE NAK = 0x15;
/// Synchronous Idle - not processed by the H19.
const BYTE SYN = 0x16;
/// End of Transmission Block - not processed by the H19.
const BYTE ETB = 0x17;
/// Cancel. Cancels current Escape Sequence
const BYTE CAN = 0x18;
/// End of Medium - not processed by the H19.
const BYTE EM = 0x19;
/// Substitute - not processed by the H19.
const BYTE SUB = 0x1a;
/// Escape
const BYTE ESC = 0x1b;
/// File Separator - not processed by the H19.
const BYTE FS = 0x1c;
/// Group Separator - not processed by the H19.
const BYTE GS = 0x1d;
/// Record Separator - not processed by the H19.
const BYTE RS = 0x1e;
/// Unit Separator - not processed by the H19.
const BYTE US = 0x1f;
/// Space
const BYTE SP = 0x20;
/// Delete (rubout) - not processed by the H19.
const BYTE DEL = 0x7f;
}
#endif // ASCII_H_
<file_sep>/VirtualH89/Src/IMDFloppyDisk.cpp
///
/// \file IMDFloppyDisk.cpp
///
/// \author <NAME>
/// \date April 17, 2016
///
#include "IMDFloppyDisk.h"
#include "Track.h"
#include "Sector.h"
#include "GenericFloppyFormat.h"
#include "logger.h"
/// \cond
#include <fstream>
#include <memory>
/// \endcond
using namespace std;
shared_ptr<GenericFloppyDisk>
IMDFloppyDisk::getDiskette(vector<string> argv)
{
shared_ptr<GenericFloppyDisk> gd = make_shared<IMDFloppyDisk>(argv);
if (gd->isReady())
{
return gd;
}
return nullptr;
}
IMDFloppyDisk::IMDFloppyDisk(vector<string> argv): GenericFloppyDisk(),
// imageName_m(nullptr),
curSector_m(nullptr),
dataPos_m(0),
sectorLength_m(0),
secLenCode_m(0),
ready_m(true)
{
if (argv.size() < 1)
{
debugss(ssFloppyDisk, WARNING, "no file specified\n");
return;
}
string name(argv[0]);
debugss(ssFloppyDisk, INFO, "reading: %s\n", name.c_str());
for (int x = 1; x < argv.size(); ++x)
{
if (argv[x].compare("rw") == 0)
{
writeProtect_m = false;
}
}
if (!readIMD(name.c_str()))
{
ready_m = false;
debugss(ssFloppyDisk, ERROR, "Read of file %s failed\n", name.c_str());
}
}
IMDFloppyDisk::~IMDFloppyDisk()
{
}
bool
IMDFloppyDisk::findSector(BYTE side,
BYTE track,
BYTE sector)
{
if (hypoTrack_m)
{
if ((track & 1) != 0)
{
// return false;
}
track /= 2;
}
else if (hyperTrack_m)
{
track *= 2;
}
if (!tracks_m[side][track])
{
return false;
}
curSector_m = tracks_m[side][track]->findSector(sector);
if (!curSector_m)
{
return false;
}
if (curSector_m->getHeadNum() != side || curSector_m->getTrackNum() != track)
{
curSector_m = nullptr;
return false;
}
sectorLength_m = curSector_m->getSectorLength();
// TODO handle if the L options is set to '0'.
switch (sectorLength_m)
{
case 128:
secLenCode_m = 0;
break;
case 256:
secLenCode_m = 1;
break;
case 512:
secLenCode_m = 2;
break;
case 1024:
secLenCode_m = 3;
break;
default:
debugss(ssFloppyDisk, ERROR, "bad sector size: %s\n", sectorLength_m);
curSector_m = nullptr;
return false;
}
return true;
}
bool
IMDFloppyDisk::readIMD(const char* name)
{
ifstream file;
unsigned long int fileSize;
unsigned long int pos = 0;
BYTE* buf;
debugss(ssFloppyDisk, INFO, "file: %s\n", name);
file.open(name, ios::binary);
if (!file.is_open())
{
debugss(ssFloppyDisk, ERROR, "file not found: %s\n", name);
return false;
}
file.seekg(0, ios::end);
fileSize = file.tellg();
file.seekg(0, ios::beg);
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
// get past the EOF character.
while (buf[pos++] != 0x1a)
{
if (pos == fileSize)
{
delete [] buf;
return (false);
}
}
BYTE sectorOrder[256];
BYTE sectorCylMapping[256];
BYTE sectorHeadMapping[256];
BYTE mode, cyl, head, numSec, sectorSizeKey;
WORD sectorSize;
bool sectorCylMap, sectorHeadMap;
Track::Density density;
Track::DataRate dataRate;
// After the text comment at the beginning, the rest of the file is individual tracks.
do
{
// mode
mode = buf[pos++];
switch (mode)
{
case 0:
density = Track::singleDensity;
dataRate = Track::dr_500kbps;
debugss(ssFloppyDisk, INFO, "FM/500 kbps\n");
break;
case 1:
density = Track::singleDensity;
dataRate = Track::dr_300kbps;
debugss(ssFloppyDisk, INFO, "FM/300 kbps\n");
break;
case 2:
density = Track::singleDensity;
dataRate = Track::dr_250kbps;
debugss(ssFloppyDisk, INFO, "FM/250 kbps\n");
break;
case 3:
density = Track::doubleDensity;
dataRate = Track::dr_500kbps;
debugss(ssFloppyDisk, INFO, "MFM/500 kbps\n");
break;
case 4:
density = Track::doubleDensity;
dataRate = Track::dr_300kbps;
debugss(ssFloppyDisk, INFO, "MFM/300 kbps\n");
break;
case 5:
density = Track::doubleDensity;
dataRate = Track::dr_250kbps;
debugss(ssFloppyDisk, INFO, "MFM/250 kbps\n");
break;
default:
density = Track::density_Unknown;
dataRate = Track::dr_Unknown;
debugss(ssFloppyDisk, WARNING, "Unknown density/data rate: %d\n", mode);
break;
}
doubleDensity_m = (density == Track::doubleDensity);
cyl = buf[pos++];
debugss(ssFloppyDisk, ALL, "Cylinder: %d\n", cyl);
head = buf[pos++];
// Check flags.
sectorCylMap = ((head & 0x80) != 0);
sectorHeadMap = ((head & 0x40) != 0);
// mask off any flags
head &= 1;
debugss(ssFloppyDisk, ALL, "Head: %d\n", head);
if (numTracks_m <= cyl)
{
numTracks_m = cyl + 1;
}
shared_ptr<Track> trk = make_shared<Track>(head, cyl);
trk->setDataRate(dataRate);
trk->setDensity(density);
numSec = buf[pos++];
debugss(ssFloppyDisk, ALL, "Num Sectors: %d\n", numSec);
sectorSizeKey = buf[pos++];
if (sectorSizeKey < 7)
{
sectorSize = 1 << (sectorSizeKey + 7);
}
else
{
debugss(ssFloppyDisk, ERROR, "Sector Size unknown: %d\n", sectorSizeKey);
delete [] buf;
return (false);
}
debugss(ssFloppyDisk, ALL, "Sector Size: %d (%d)\n", sectorSize, sectorSizeKey);
for (int i = 0; i < numSec; i++)
{
sectorOrder[i] = buf[pos++];
}
if (sectorCylMap)
{
debugss(ssFloppyDisk, INFO, "Sector Cylinder Map Present\n");
for (int i = 0; i < numSec; i++)
{
sectorCylMapping[i] = buf[pos++];
}
}
if (sectorHeadMap)
{
debugss(ssFloppyDisk, INFO, "Sector Head Map Present\n");
for (int i = 0; i < numSec; i++)
{
sectorHeadMapping[i] = buf[pos++];
}
}
for (int i = 0; i < numSec; i++)
{
unsigned char sectorType = buf[pos++];
debugss(ssFloppyDisk, INFO, "Sector: %d(%d) Type: %d\n", sectorOrder[i], i, sectorType);
if (sectorType == 0x00)
{
// Sector Data Unavailable
debugss(ssFloppyDisk, INFO, "Sector Size unknown: %d\n", sectorSizeKey);
}
else if (sectorType > 0x08)
{
// Out of Range.
debugss(ssFloppyDisk, ERROR, "Out of Range: %d\n", sectorType);
delete [] buf;
return false;
}
else
{
// by subtracting 1, can get the value to act like a bit mask.
BYTE type = sectorType - 1;
bool compressed = ((type & 0x01) != 0);
bool deleteData = ((type & 0x02) != 0);
bool dataError = ((type & 0x04) != 0);
BYTE sectorData[sectorSize];
if (compressed)
{
BYTE val = buf[pos++];
for (int i = 0; i < sectorSize; i++)
{
sectorData[i] = val;
}
}
else
{
for (int i = 0; i < sectorSize; i++)
{
sectorData[i] = buf[pos++];
}
}
// create sector
shared_ptr<Sector> sect = make_shared<Sector>(head,
cyl,
sectorOrder[i],
sectorSize,
§orData[0]);
// set flags
sect->setReadError(dataError);
sect->setDeletedDataAddressMark(deleteData);
// add sector to track
trk->addSector(sect);
}
}
// add track to disk
tracks_m[head].push_back(trk);
}
while (pos < fileSize);
delete [] buf;
debugss(ssFloppyDisk, INFO, "Read successful.\n");
return true;
}
bool
IMDFloppyDisk::readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data)
{
if (inSector < 0)
{
if (sector == 0xfd)
{
data = GenericFloppyFormat::ID_AM;
return true;
}
else if (sector == 0xff)
{
data = GenericFloppyFormat::INDEX_AM;
return true;
}
else if (findSector(side, track, sector))
{
dataPos_m = 0;
data = GenericFloppyFormat::DATA_AM;
return true;
}
data = GenericFloppyFormat::NO_DATA;
return true;
}
if (sector == 0xfd)
{
switch (inSector)
{
case 0:
if (hypoTrack_m)
{
data = track / 2;
}
else if (hyperTrack_m)
{
data = track * 2;
}
else
{
data = track;
}
break;
break;
case 1:
data = side;
break;
case 2:
data = 1; // anything will do? 'sector' is 0xfd...
break;
case 3:
data = secLenCode_m;
break;
// TODO calculated and provide the actual CRC here.
case 4:
data = 0; // CRC 1
break;
case 5:
data = 0; // CRC 2
break;
default:
data = GenericFloppyFormat::CRC;
break;
}
return true;
}
else if (sector == 0xff)
{
if (inSector < sectorLength_m)
{
// TODO: implement this
data = 0;
}
else
{
data = GenericFloppyFormat::CRC;
}
return true;
}
if (dataPos_m < sectorLength_m)
{
if (curSector_m)
{
BYTE sectorData;
curSector_m->readData(dataPos_m++, sectorData);
data = sectorData;
}
else
{
debugss(ssFloppyDisk, ERROR, "curSector_m not set\n");
}
}
else
{
debugss(ssFloppyDisk, INFO, "data done %d %d %d\n", track, side, sector);
data = GenericFloppyFormat::CRC;
}
return true;
}
bool
IMDFloppyDisk::writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result)
{
if (checkWriteProtect())
{
debugss(ssSectorFloppyImage, ERROR, "write protect\n");
return false;
}
if (inSector < 0)
{
if (sector == 0xff || sector == 0xfe)
{
result = GenericFloppyFormat::ERROR;
return true;
}
else if (findSector(side, track, sector))
{
dataPos_m = 0;
result = GenericFloppyFormat::DATA_AM;
return true;
}
result = GenericFloppyFormat::NO_DATA;
return true;
}
debugss(ssSectorFloppyImage, INFO, "pos=%d data=%02x\n", inSector, data);
if (dataPos_m < sectorLength_m)
{
if (!dataReady)
{
debugss(ssSectorFloppyImage, ERROR, "data not read pos=%d\n", inSector);
result = GenericFloppyFormat::NO_DATA;
}
else
{
if (curSector_m)
{
curSector_m->writeData(dataPos_m++, data);
result = data;
}
else
{
debugss(ssFloppyDisk, ERROR, "curSector_m not set\n");
}
}
}
else
{
debugss(ssSectorFloppyImage, INFO, "CRC pos=%d data=%02x\n", inSector, data);
result = GenericFloppyFormat::CRC;
}
return true;
}
bool
IMDFloppyDisk::isReady()
{
return ready_m;
}
void
IMDFloppyDisk::eject(const string name)
{
}
void
IMDFloppyDisk::dump(void)
{
}
<file_sep>/VirtualH89/Src/mms77316.h
/// \file mms77316.h
///
/// Implementation of the MMS 77316 floppy disk controller.
///
/// \date Jan 30, 2016
/// \author <NAME>, cloned from h37.h by <NAME>
///
#ifndef MMS77316_H_
#define MMS77316_H_
#include "WD179xUserIf.h"
#include "DiskController.h"
#include "propertyutil.h"
class GenericFloppyDrive;
class GenericDiskDrive;
class InterruptController;
class WD1797;
///
/// \brief Virtual soft-sectored disk controller
///
/// A virtual Magnolia Microsystems soft-sectored disk controller (MMS77316).
///
/// The MMS77316 uses the 1797-02 controller.
///
class MMS77316: public DiskController, public WD179xUserIf
{
public:
static const int numDisks_c = 8;
MMS77316(int baseAddr, InterruptController* ic);
virtual ~MMS77316() override;
static MMS77316* install_MMS77316(InterruptController* ic,
PropertyUtil::PropertyMapT& props,
std::string slot);
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual bool connectDrive(BYTE unitNum,
GenericFloppyDrive* drive);
virtual bool removeDrive(BYTE unitNum);
virtual GenericFloppyDrive* getDrive(BYTE unitNum);
virtual void reset(void) override;
static const BYTE MMS77316_Intr_c = 5; // INT 5
// TODO: implement this
std::vector<GenericDiskDrive*> getDiskDrives() override;
std::string getDriveName(int index) override;
std::string getDeviceName() override
{
return MMS77316_Name_c;
}
GenericDiskDrive* findDrive(std::string ident) override;
std::string dumpDebug() override;
protected:
static const char* MMS77316_Name_c;
private:
bool intrqRaised_m;
bool drqRaised_m;
void raiseIntrq() override;
void raiseDrq() override;
void lowerIntrq() override;
void lowerDrq() override;
static const BYTE MMS77316_NumPorts_c = 8;
static const BYTE BasePort_c = 0x38;
static const BYTE ControlPort_Offset_c = 0;
static const BYTE Wd1797_Offset_c = 4;
BYTE controlReg_m;
int getClockPeriod() override;
InterruptController* ic_m;
GenericFloppyDrive* drives_m[numDisks_c];
unsigned char intLevel_m;
int drqCount_m;
/// Bits set in cmd_ControlPort_c
static const BYTE ctrl_EnableIntReq_c = 0x08;
static const BYTE ctrl_EnableBurstN_c = 0x20;
static const BYTE ctrl_SetMFMRecordingN_c = 0x40;
static const BYTE ctrl_DriveSel_c = 0x07;
static const BYTE ctrl_525DriveSel_c = 0x04;
bool burstMode()
{
return (controlReg_m & ctrl_EnableBurstN_c) == 0;
}
bool intrqAllowed()
{
return (controlReg_m & ctrl_EnableIntReq_c) != 0;
}
bool drqAllowed()
{
return (controlReg_m & ctrl_EnableIntReq_c) != 0 &&
((controlReg_m & ctrl_EnableBurstN_c) != 0 || drqCount_m < 1);
}
void loadHead(bool load) override;
virtual GenericFloppyDrive* getCurrentDrive();
virtual bool readReady() override;
WD1797* wd1797_m;
};
#endif // MMS77316_H_
<file_sep>/VirtualH89/Src/RAMemory8K.h
///
/// \file RAMemory8K.h
///
/// An 8K page of RAM (R/W).
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef RAMEMORY8K_H_
#define RAMEMORY8K_H_
#include "Memory8K.h"
class RAMemory8K: public Memory8K
{
public:
RAMemory8K(WORD baseAddr): Memory8K(baseAddr)
{
}
virtual ~RAMemory8K()
{
};
virtual void writeByte(WORD addr, BYTE val) override
{
mem[addr & MemoryAddressMask_c] = val;
}
protected:
};
#endif // RAMEMORY8K_H_
<file_sep>/VirtualH89/Src/WallClock.cpp
///
/// \file WallClock.cpp
///
/// \date Apr 29, 2009
///
/// \author <NAME>
///
#include "WallClock.h"
#include "ClockUser.h"
#include "logger.h"
/// \cond
#include <cstddef>
/// \endcond
WallClock* WallClock::_inst = nullptr;
WallClock::WallClock(): clock_m(0),
ticks_m(0)
{
}
WallClock::~WallClock()
{
}
WallClock*
WallClock::instance(void)
{
if (!_inst)
{
_inst = new WallClock();
}
return (_inst);
}
void
WallClock::addTimerEvent()
{
/// \todo Properly handle other CPU Speeds.
if (ticks_m > 4096)
{
clock_m += ticks_m;
}
else
{
/// \todo determine if we need to notify all users here too for (4096 - ticks_m)
/// number of ticks.
clock_m += 4096;
}
ticks_m = 0;
}
void
WallClock::addTicks(unsigned ticks)
{
ticks_m += ticks;
for (ClockUser* clockUser : users_m)
{
clockUser->notification(ticks);;
}
}
long long unsigned int
WallClock::getClock()
{
return (clock_m + ticks_m);
}
long long unsigned int
WallClock::getElapsedTime(long long unsigned int origTime)
{
return (clock_m + ticks_m - origTime);
}
void
WallClock::printTime(FILE* file)
{
// determine seconds, millisec, microseconds..
/// \todo Properly handle other CPU Speeds.
unsigned long long time = clock_m + ticks_m;
unsigned long long millisec = time >> 11;
unsigned long long seconds = millisec / 1000;
millisec %= 1000;
fprintf(file, "%05lld.%03lld:%04lld - ", seconds, millisec, time & 0x7ff);
}
bool
WallClock::registerUser(ClockUser* user)
{
users_m.push_back(user);
return true;
}
bool
WallClock::unregisterUser(ClockUser* user)
{
users_m.remove(user);
return true;
}
void
WallClock::updateTicksPerSecond(unsigned long ticks)
{
ticksPerSecond = ticks;
}
<file_sep>/VirtualH89/Src/Z47Interface.cpp
///
/// \name Z47Interface.cpp
///
/// Interface card on the H89 to support the Z47 external dual 8" floppy disks.
///
/// \date Jul 14, 2013
/// \author <NAME>
///
#include "Z47Interface.h"
#include "logger.h"
#include "ParallelLink.h"
Z47Interface::Z47Interface(int baseAddr): DiskController(baseAddr, H47_NumPorts_c),
interruptsEnabled_m(false),
DTR_m(false),
DDOut_m(false),
Busy_m(true),
Error_m(false),
Done_m(false),
linkToDrive_m(0)
{
debugss(ssH47, ALL, "(%d)\n", baseAddr);
}
Z47Interface::~Z47Interface()
{
}
BYTE
Z47Interface::in(BYTE addr)
{
debugss(ssH47, ALL, "(%d)\n", addr);
BYTE offset = getPortOffset(addr);
BYTE data = 0;
switch (offset)
{
case StatusPort_Offset_c:
readStatus(data);
debugss(ssH47, ALL, "StatusPort - 0x%02x\n", data);
break;
case DataPort_Offset_c:
readData(data);
debugss(ssH47, ALL, "DataPort - 0x%02x\n", data);
break;
default:
debugss(ssH47, ERROR, "Unknown Port offset - %d\n", offset);
break;
}
return data;
}
void
Z47Interface::out(BYTE addr,
BYTE val)
{
BYTE offset = getPortOffset(addr);
debugss(ssH47, ALL, "(%d) = 0x%02x\n", addr, val);
switch (offset)
{
case StatusPort_Offset_c:
debugss(ssH47, ALL, "StatusPort\n");
writeStatus(val);
break;
case DataPort_Offset_c:
debugss(ssH47, ALL, " DataPort\n");
writeData(val);
break;
default:
debugss(ssH47, ERROR, "Unknown Port offset - %d\n", offset);
break;
}
}
void
Z47Interface::reset(void)
{
debugss(ssH47, ALL, "\n");
/// \todo Determine what to do for a reset.
if (linkToDrive_m)
{
linkToDrive_m->masterReset();
}
}
void
Z47Interface::notification(unsigned int cycleCount)
{
debugss(ssH47, ALL, "\n");
}
void
Z47Interface::writeStatus(BYTE cmd)
{
debugss(ssH47, ALL, "cmd = 0x%02x\n", cmd);
if ((cmd & cmd_MasterReset_c) == cmd_MasterReset_c)
{
debugss(ssH47, INFO, "Master Reset\n");
reset();
}
if ((cmd & cmd_U137BSet_c) == cmd_U137BSet_c)
{
debugss(ssH47, INFO, "FlipFlop U137B\n");
}
if ((cmd & cmd_InterruptsEnabled_c) == cmd_InterruptsEnabled_c)
{
debugss(ssH47, INFO, "Interrupts Enabled\n");
interruptsEnabled_m = true;
}
else
{
interruptsEnabled_m = false;
}
if ((cmd & cmd_Undefined_c) != 0)
{
debugss(ssH47, WARNING, "Unexpected command bits: 0x%02x\n", cmd);
}
}
void
Z47Interface::writeData(BYTE data)
{
debugss(ssH47, ALL, "data = 0x%02x\n", data);
if (linkToDrive_m)
{
linkToDrive_m->sendDriveData(data);
}
else
{
debugss(ssH47, ERROR, "link to Drive not configured\n");
}
}
void
Z47Interface::readStatus(BYTE& data)
{
BYTE val = 0;
if (interruptsEnabled_m)
{
val |= stat_InterruptEnabled_c;
}
if (DTR_m)
{
val |= stat_DataTransferRequest_c;
}
if (Done_m)
{
val |= stat_Done_c;
}
data = val;
debugss(ssH47, ALL, "Status 0x%02x\n", data);
}
void
Z47Interface::readData(BYTE& data)
{
if (linkToDrive_m)
{
linkToDrive_m->readDataBusByHost(data);
linkToDrive_m->setDTAK(true);
}
debugss(ssH47, ALL, "Data 0x%02x\n", data);
}
void
Z47Interface::connectDriveLink(ParallelLink* link)
{
debugss(ssH47, ALL, "\n");
linkToDrive_m = link;
if (linkToDrive_m)
{
linkToDrive_m->registerHost(this);
}
else
{
debugss(ssH47, ERROR, "link to Drive not configured\n");
}
}
void
Z47Interface::raiseSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
switch (sigType)
{
// Master Reset (Host to Disk System)
case st_MasterReset:
// Handle a reset
debugss(ssH47, ERROR, "Invalid Master Reset received.\n");
break;
// Data Acknowledge (Host to Disk System)
case st_DTAK:
// Handle data acknowledge.
debugss(ssH47, ERROR, "Invalid DTAK received.\n");
break;
// Data Ready (Disk System to Host)
case st_DTR:
debugss(ssH47, INFO, "DTR raised.\n");
DTR_m = true;
break;
// Disk Drive Out (Disk System to Host)
case st_DDOUT:
debugss(ssH47, INFO, "DDOUT raised.\n");
DDOut_m = true;
break;
// Busy (Disk System to Host)
case st_Busy:
debugss(ssH47, INFO, "Busy raised.\n");
Busy_m = true;
Done_m = false;
break;
// Error (Disk System to Host)
case st_Error:
debugss(ssH47, INFO, "Error raised.\n");
Error_m = true;
break;
default:
debugss(ssH47, ERROR, "Invalid sigType received.\n");
break;
}
}
void
Z47Interface::lowerSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
switch (sigType)
{
// Master Reset (Host to Disk System)
case st_MasterReset:
// Handle a reset
debugss(ssH47, ERROR, "Invalid Master Reset received.\n");
break;
// Data Acknowledge (Host to Disk System)
case st_DTAK:
debugss(ssH47, ERROR, "Invalid DTAK received.\n");
break;
// Data Ready (Disk System to Host)
case st_DTR:
debugss(ssH47, INFO, "DTR lowered.\n");
DTR_m = false;
linkToDrive_m->setDTAK(false);
break;
// Disk Drive Out (Disk System to Host)
case st_DDOUT:
debugss(ssH47, INFO, "DDOUT lowered.\n");
DDOut_m = false;
break;
// Busy (Disk System to Host)
case st_Busy:
debugss(ssH47, INFO, "Busy lowered.\n");
Busy_m = false;
Done_m = true;
break;
// Error (Disk System to Host)
case st_Error:
debugss(ssH47, INFO, "Error lowered.\n");
Error_m = false;
break;
default:
debugss(ssH47, ERROR, "Invalid sigType received.\n");
break;
}
}
void
Z47Interface::pulseSignal(SignalType sigType)
{
debugss(ssH47, ALL, "\n");
}
<file_sep>/VirtualH89/Src/h37.h
/// \file h37.h
///
/// \date May 13, 2009
/// \author <NAME>
///
#ifndef Z_89_37_H_
#define Z_89_37_H_
#include "DiskController.h"
#include "WD179xUserIf.h"
#include "propertyutil.h"
class GenericFloppyDrive;
class WD1797;
class InterruptController;
class Computer;
///
/// \brief Virtual soft-sectored disk controller
///
/// A virtual Heathkit soft-sectored disk controller (Z-89-37).
///
/// The Z-89-37 uses the 1797-02 controller.
///
class Z_89_37: public DiskController, public WD179xUserIf
{
public:
Z_89_37(Computer* computer, int baseAddr, InterruptController* ic);
virtual ~Z_89_37() override;
static Z_89_37* install_H37(Computer* computer,
BYTE baseAddr,
InterruptController* ic,
PropertyUtil::PropertyMapT& props,
std::string slot);
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual bool connectDrive(BYTE unitNum,
GenericFloppyDrive* drive);
virtual GenericFloppyDrive* getCurrentDrive();
virtual bool removeDrive(BYTE unitNum);
virtual void reset(void) override;
// TODO: implement this
std::vector<GenericDiskDrive*> getDiskDrives() override
{
return *(new std::vector<GenericDiskDrive*>());
}
std::string getDeviceName() override
{
return "H37";
}
GenericDiskDrive* findDrive(std::string ident) override
{
return nullptr;
}
std::string getDriveName(int index) override
{
return "";
}
std::string dumpDebug() override
{
return "";
}
virtual void raiseIntrq() override;
virtual void raiseDrq() override;
virtual void lowerIntrq() override;
virtual void lowerDrq() override;
virtual bool readReady() override;
virtual int getClockPeriod() override;
private:
void motorOn(bool motor);
Computer* computer_m;
WD1797* wd1797_m;
InterruptController* ic_m;
static const BYTE H37_NumPorts_c = 4;
///
/// DK.PORT - Octal - 0170 (0x78) base port.
///
// DK.PORT
static const BYTE BasePort_c = 0x78;
// DK.CON
static const BYTE ControlPort_Offset_c = 0;
// DK.INT
static const BYTE InterfaceControl_Offset_c = 1;
// FD.STAT
static const BYTE StatusPort_Offset_c = 2;
// FD.CMD
static const BYTE CommandPort_Offset_c = 2;
// FD.DAT
static const BYTE DataPort_Offset_c = 3;
// FD.SEC
static const BYTE SectorPort_Offset_c = 2;
// FD.TRK
static const BYTE TrackPort_Offset_c = 3;
BYTE interfaceReg_m;
BYTE controlReg_m;
bool motorOn_m;
bool dataReady_m;
bool lostDataStatus_m;
enum Disks
{
ds0 = 0,
ds1 = 1,
ds2 = 2,
ds3 = 3,
numDisks_c = 4
};
bool sectorTrackAccess_m;
GenericFloppyDrive* genericDrives_m[numDisks_c];
Disks curDiskDrive_m;
bool intrqAllowed_m;
bool drqAllowed_m;
unsigned long long cycleCount_m;
/// Bits set in cmd_ControlPort_c - DK.CON
enum ControlBits : BYTE
{
ctrl_EnableIntReq_c = 0x01,
ctrl_EnableDrqInt_c = 0x02,
ctrl_SetMFMRecording_c = 0x04,
ctrl_MotorsOn_c = 0x08,
ctrl_Drive_0_c = 0x10,
ctrl_Drive_1_c = 0x20,
ctrl_Drive_2_c = 0x40,
ctrl_Drive_3_c = 0x80
};
/// Bits to set alternate registers on InterfaceControl_c - DK.INT
enum InterfaceControlBits : BYTE
{
if_SelectCommandData_c = 0x00,
if_SelectSectorTrack_c = 0x01
};
/// Floppy disk related items
// static const int bytesPerTrack_c = 6400;
// static const int clocksPerByte_c = 64;
};
#endif // Z_89_37_H_
<file_sep>/VirtualH89/Src/GppListener.h
///
/// \file GppListener.h
///
/// Object to facilitate interested parties of GPIO bit changes to get
/// notified when bits change.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef GPPLISTENER_H_
#define GPPLISTENER_H_
#include "h89Types.h"
/// \cond
#include <vector>
#include <memory>
/// \endcond
class GppListener: public std::enable_shared_from_this<GppListener>
{
public:
GppListener(BYTE bits = 0xff);
static void addListener(GppListener* lstr);
static void notifyListeners(BYTE gpo, BYTE diffs);
protected:
virtual void gppNewValue(BYTE gpo) = 0;
BYTE interestedBits_m;
private:
static std::vector<GppListener*> notifications;
};
#endif // GPPLISTENER_H_
<file_sep>/VirtualH89/Src/AddressBus.h
/// \file AddressBus.h
///
/// Abstracts the CPU's Address Bus to allow special handling of
/// memory addresses.
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#ifndef ADDRESSBUS_H_
#define ADDRESSBUS_H_
#include "h89Types.h"
/// \cond
#include <memory>
/// \endcond
/// \todo make AddressBus a base class and this functionality in an H89AddressBus
/// class
class MemoryDecoder;
class InterruptController;
/// \class AddressBus
///
/// \brief %Memory address bus
///
/// The AddressBus connects the CPU to the computer's memory.
///
class AddressBus
{
private:
std::shared_ptr<MemoryDecoder> mem_m;
InterruptController* ic_m;
public:
AddressBus(InterruptController* ic);
virtual ~AddressBus();
// setup memory
void installMemory(std::shared_ptr<MemoryDecoder> mem);
BYTE readByte(WORD addr,
bool interruptAck = false);
void writeByte(WORD addr,
BYTE val);
void reset();
};
#endif // ADDRESSBUS_H_
<file_sep>/VirtualH89/Src/Memory8K.cpp
///
/// \file Memory8K.cpp
///
/// \author <NAME>
/// \date May 8, 2016
///
#include "Memory8K.h"
/// \cond
#include <string.h>
/// \endcond
Memory8K::Memory8K(WORD base): base_m(base)
{
memset(mem, 0, sizeof(mem));
}
Memory8K::~Memory8K()
{
}
WORD
Memory8K::getBase()
{
return base_m;
}
<file_sep>/VirtualH89/Src/GenericDiskDrive.cpp
/// \file GenericDiskDrive.cpp
///
/// Interface for a floppy disk drive, supporting methods for handling
/// mounted media.
///
/// \date Feb 8, 2016
/// \author <NAME>
///
#include "GenericDiskDrive.h"
GenericDiskDrive::GenericDiskDrive()
{
}
GenericDiskDrive::~GenericDiskDrive()
{
}
<file_sep>/VirtualH89/Src/logger.cpp
/// \file logger.cpp
///
/// \date May 6, 2009
/// \author <NAME>
///
#include <cstdarg>
#include "logger.h"
#include "WallClock.h"
#define ANSI 0
#define PRINT_CLOCK 1
unsigned debugLevel[ssMax];
extern FILE* log_out;
logger::logger(): printToFile(false),
printToScreen(false),
logFile(nullptr)
{
}
logger::~logger()
{
}
void
setDebugLevel()
{
logLevel defaultLevel = ERROR;
debugLevel[ssH89] = defaultLevel; // The overall H89
debugLevel[ssMEM] = defaultLevel; // Memory class
debugLevel[ssRAM] = defaultLevel; // RAM accesses
debugLevel[ssROM] = defaultLevel; // ROM accesses
debugLevel[ssZ80] = defaultLevel; // Z80 CPU
debugLevel[ssH37InterruptController] = defaultLevel; // Interrupt Controller
debugLevel[ssInterruptController] = defaultLevel; // Interrupt Controller
debugLevel[ssAddressBus] = defaultLevel; // Address Bus
debugLevel[ssIO] = defaultLevel; // I/O ports
debugLevel[ssH17] = defaultLevel; // H17 controller
debugLevel[ssH37] = defaultLevel; // H37 controller
debugLevel[ssH47] = defaultLevel; // H47 controller
debugLevel[ssH67] = defaultLevel; // H67 controller
debugLevel[ssDiskDrive] = defaultLevel; // Floppy disks
debugLevel[ssH17_1] = defaultLevel;
debugLevel[ssH17_4] = defaultLevel;
debugLevel[ssH47Drive] = defaultLevel;
debugLevel[ssConsole] = defaultLevel; // Console
debugLevel[ssH19] = defaultLevel; // H19 Terminal
debugLevel[ss8250] = defaultLevel; // 8250 Serial Port
debugLevel[ssTimer] = defaultLevel; // 2 mSec Timer
debugLevel[ssWallClock] = defaultLevel; // Wall Clock.
debugLevel[ssFloppyDisk] = defaultLevel; // Floppy Disk
debugLevel[ssGpp] = defaultLevel; // General Purpose Port
debugLevel[ssParallel] = defaultLevel; // Parallel Port Interface (Z47)
debugLevel[ssStdioConsole] = defaultLevel;
debugLevel[ssMMS77316] = defaultLevel;
debugLevel[ssWD1797] = defaultLevel;
debugLevel[ssGenericFloppyDrive] = defaultLevel;
debugLevel[ssRawFloppyImage] = defaultLevel;
debugLevel[ssMMS77320] = defaultLevel;
debugLevel[ssGenericSASIDrive] = defaultLevel;
debugLevel[ssHostFileBdos] = defaultLevel;
debugLevel[ssCPNetDevice] = defaultLevel;
debugLevel[ssSectorFloppyImage] = defaultLevel;
}
void
setDebug(subSystems ss,
logLevel level)
{
debugLevel[ss] = level;
}
void
__debugss(enum logLevel level, const char* functionName, const char* fmt, ...)
{
va_list vl;
#if ANSI
int __val = 0;
if (level < ERROR)
{
__val = 31; /* FATAL = Red */
}
else if (level < WARNING)
{
__val = 33; /* ERROR = Yellow */
}
else if (level < INFO)
{
__val = 35; /* WARNING = Magenta */
}
else if (level < VERBOSE)
{
__val = 34; /* INFO = Blue */
}
else
{
__val = 32; /* default = Green */
}
fprintf(log_out, "\x1b[37m");
#endif
#if PRINT_CLOCK
WallClock::instance()->printTime(log_out);
#endif
#if ANSI
fprintf(log_out, "\x1b[36m%s: \x1b[%dm", functionName, __val);
#else
fprintf(log_out, "%s: ", functionName);
#endif
va_start(vl, fmt);
vfprintf(log_out, fmt, vl);
va_end(vl);
#if ANSI
fprintf(log_out, "\x1b[0m");
#endif
fflush(log_out);
}
void
__debugss_nts(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
vfprintf(log_out, fmt, vl);
va_end(vl);
fflush(log_out);
}
<file_sep>/VirtualH89/Src/GUI.cpp
///
/// \name GUI.h
///
/// GUI base class. It defines the interface between the H19 terminal class and an abstract GUI.
/// It also houses the character generator ROM, which is needed by any GUI implementation.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#include <cassert>
#include "GUI.h"
#include "h19-font.h"
// All GUI access is through this pointer to the base GUI class.
GUI* TheGUI = nullptr;
GUI::GUI()
{
// There can only be one GUI engine in the system.
assert(TheGUI == nullptr);
// This is not the one and only GUI enging.
TheGUI = this;
return;
}
GUI::~GUI()
{
// We no longer have a GUI engine.
TheGUI = nullptr;
return;
}
<file_sep>/VirtualH89/Src/GenericSASIDrive.h
/// \file GenericSASIDrive.h
///
/// Implementation of a generic SASI disk drive and controller. Media is separate.
/// Currently based on a XEBEC controller (only documentation available).
///
/// \date Feb 1, 2016
/// \author <NAME>
///
#ifndef GENERICSASIDRIVE_H_
#define GENERICSASIDRIVE_H_
#include "GenericDiskDrive.h"
#include "h89Types.h"
/// \cond
#include <memory>
/// \endcond
class GenericFloppyDisk;
///
/// \brief Virtual Generic SASI Drive
///
/// Implements a virtual floppy disk drive. Supports 48/96 tpi 5.25",
/// 48 tpi 8", either can be SS or DS. Note, the media determines density.
///
class GenericSASIDrive: public GenericDiskDrive
{
public:
enum DriveType
{
INVALID = 0,
// TODO: fix this: controllers vs. drives...
XEBEC_ST506, // 5.3MB (XEBEC ctrlr + Seagate ST506 drive)
XEBEC_ST412, // 10.6MB
XEBEC_CM5206, // 4.4MB
XEBEC_CM5410, // 8.9MB
XEBEC_CM5616, // 13.3MB
XEBEC_RO201, // 5.5MB
XEBEC_RO202, // 11.1MB
XEBEC_RO203, // 16.7MB
XEBEC_RO204, // 22.3MB
other_other, // not supported
NUM_DRV_TYPE
};
GenericSASIDrive(DriveType type,
std::string media,
int cnum,
int sectorSize);
virtual ~GenericSASIDrive() override;
static GenericSASIDrive* getInstance(std::string type,
std::string path,
int unitNum);
// not used:
int getRawBytesPerTrack() override
{
return 0;
}
int getNumTracks() override
{
return 0;
}
bool isReady() override
{
return true;
}
bool isWriteProtect() override
{
return false;
}
void insertDisk(std::shared_ptr<GenericFloppyDisk> disk) override
{
}
std::string getMediaName() override;
// These are called by the host to indicate change events on ctl bits.
void resetSASI(BYTE& data,
BYTE& dataOut,
BYTE& ctl);
void select(BYTE& data,
BYTE& dataOut,
BYTE& ctl);
void run(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctl); // this is actually the absense of any bits.
void ack(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctl);
void reset(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctl);
void deselect(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl);
int getCtlBits();
void setCtlBits(int bits);
void clearCtlBits(int bits);
static const BYTE ctl_Busy_o_c = 0x01;
static const BYTE ctl_Ack_i_c = 0x02;
static const BYTE ctl_Reset_i_c = 0x04;
static const BYTE ctl_Msg_o_c = 0x08;
static const BYTE ctl_Sel_i_c = 0x10;
static const BYTE ctl_Cmd_o_c = 0x20;
static const BYTE ctl_Req_o_c = 0x40;
static const BYTE ctl_Out_o_c = 0x80;
// SASI Command codes, class/opcode.
static const BYTE cmd_TestDriveReady_c = 0x00;
static const BYTE cmd_Recal_c = 0x01;
static const BYTE cmd_ReqSense_c = 0x03;
static const BYTE cmd_FormatDrive_c = 0x04;
static const BYTE cmd_CheckTrackFmt_c = 0x05;
static const BYTE cmd_FormatTrack_c = 0x06;
static const BYTE cmd_FormatBadTrack_c = 0x07;
static const BYTE cmd_Read_c = 0x08;
static const BYTE cmd_Write_c = 0x0a;
static const BYTE cmd_Seek_c = 0x0b;
static const BYTE cmd_InitDriveChar_c = 0x0c;
static const BYTE cmd_ReadECCLen_c = 0x0d;
static const BYTE cmd_FormatAltTrack_c = 0x0e;
static const BYTE cmd_WriteSecBuf_c = 0x0f;
static const BYTE cmd_ReadSecBuf_c = 0x10;
static const BYTE cmd_RAMDiag_c = 0xe0;
static const BYTE cmd_DriveDiag_c = 0xe3; // was 0xe4 - conflict!
static const BYTE cmd_CtrlIntDiag_c = 0xe4; // conflict!
static const BYTE cmd_ReadLong_c = 0xe5;
static const BYTE cmd_WriteLong_c = 0xe6;
private:
bool checkHeader(BYTE* b, int n);
void startStatus(BYTE& ctrl);
void startSense(BYTE& ctrl);
void startDataIn(BYTE& ctrl);
void startDataOut(BYTE& ctrl);
void startError(BYTE& ctrl,
BYTE err);
void startDCB(BYTE& ctrl);
void processCmd(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl);
void processData(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl);
void processDCB(BYTE& dataIn,
BYTE& dataOut,
BYTE& ctrl);
enum State
{
IDLE,
COMMAND,
DATA_IN,
DATA_OUT,
SENSE,
DRIVECB,
STATUS,
};
enum State curState;
int driveFd;
int driveSecLen;
int sectorsPerTrack;
unsigned long capacity;
off_t dataOffset;
BYTE driveCode;
int driveCnum;
const char* driveMedia;
enum DriveType driveType;
long mediaSpt;
long mediaSsz;
long mediaCyl;
long mediaHead;
long mediaLat;
int blockCount;
// mode COMMAND
BYTE cmdBuf[6];
static const int cmdLength = 6;
int cmdIx;
// mode SENSE
BYTE senseBuf[4];
static const int senseLength = 4;
int senseIx;
// mode DRIVECB
BYTE dcbBuf[8];
static const int dcbLength = 8;
int dcbIx;
// mode STATUS
BYTE stsBuf[2];
static const int stsLength = 2;
static const int lastStsIx = 1;
int stsIx;
// mode DATA_IN/DATA_OUT
BYTE* dataBuf;
int dataLength;
int dataIx;
static int params[NUM_DRV_TYPE][4];
};
#endif // GENERICSASIDRIVE_H_
<file_sep>/VirtualH89/Src/Z47Interface.h
///
/// \name Z47Interface.h
///
/// Interface card on the H89 to support the Z47 external dual 8" floppy disks.
///
/// \date Jul 14, 2013
/// \author <NAME>
///
#ifndef Z47INTERFACE_H_
#define Z47INTERFACE_H_
#include "DiskController.h"
#include "ClockUser.h"
#include "ParallelPortConnection.h"
class Z47Interface: public virtual DiskController,
public virtual ClockUser,
public virtual ParallelPortConnection
{
public:
Z47Interface(int baseAddr);
virtual ~Z47Interface() override;
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual void reset(void) override;
virtual void notification(unsigned int cycleCount) override;
void connectDriveLink(ParallelLink* link);
virtual void raiseSignal(SignalType sigType) override;
virtual void lowerSignal(SignalType sigType) override;
virtual void pulseSignal(SignalType sigType) override;
// TODO: implement this
std::vector<GenericDiskDrive*> getDiskDrives() override
{
return *(new std::vector<GenericDiskDrive*>());
}
std::string getDeviceName() override
{
return "Z47";
}
GenericDiskDrive* findDrive(std::string ident) override
{
return nullptr;
}
std::string getDriveName(int index) override
{
return "";
}
std::string dumpDebug() override
{
return "";
}
private:
static const BYTE H47_NumPorts_c = 2;
///
/// 0170 (0x78) base port. (or could be 0174) if in the right-hand slot
/// ? move to public?
static const BYTE BasePort1_c = 0x78;
static const BYTE BasePort2_c = 0x7c;
static const BYTE StatusPort_Offset_c = 0;
static const BYTE DataPort_Offset_c = 1;
static const BYTE stat_Error_c = 0x01;
static const BYTE stat_sw101_a_c = 0x02;
static const BYTE stat_sw101_b_c = 0x04;
static const BYTE stat_sw101_c_c = 0x08;
static const BYTE stat_sw101_d_c = 0x10;
static const BYTE stat_Done_c = 0x20;
static const BYTE stat_InterruptEnabled_c = 0x40;
static const BYTE stat_DataTransferRequest_c = 0x80;
//
// Commands
//
static const BYTE cmd_U137BSet_c = 0x01;
static const BYTE cmd_MasterReset_c = 0x02;
static const BYTE cmd_InterruptsEnabled_c = 0x40;
static const BYTE cmd_Undefined_c = ~(cmd_U137BSet_c |
cmd_MasterReset_c |
cmd_InterruptsEnabled_c);
bool interruptsEnabled_m;
bool DTR_m;
bool DDOut_m;
bool Busy_m;
bool Error_m;
bool Done_m;
void writeStatus(BYTE cmd);
void writeData(BYTE data);
void readStatus(BYTE& status);
void readData(BYTE& data);
ParallelLink* linkToDrive_m;
};
#endif // Z47INTERFACE_H_
<file_sep>/VirtualH89/Src/config.h
/// \file config.h
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#ifndef CONFIG_H_
#define CONFIG_H_
/// \TODO this file should be removed and make all configuration run-time in the configuration file.
/// \todo Determine what needs to be a configuration variable, and what can be removed.
// #define BUS_8080
// Need if dumping all the Z80 logs. Otherwise system is too slow to process
// all the output - actually 20x
#define TEN_X_SLOWER 0
#endif // CONFIG_H_
<file_sep>/VirtualH89/Src/wd1797.cpp
/// \file wd1797.cpp
///
/// Implementation of the WD1797 FDC (floppy disk controller) chip.
///
/// \date Feb 1, 2016
/// \author <NAME>, cloned from h37.cpp by <NAME>
///
#include "wd1797.h"
#include "H89.h"
#include "logger.h"
#include "GenericFloppyDrive.h"
#include "GenericFloppyFormat.h"
#include "WD179xUserIf.h"
#include "WallClock.h"
// 8" (2MHz) step rates, 5.25" (1MHz) are 2x.
const BYTE WD1797::speeds[maxStepSpeeds_c] = {3, 6, 10, 15};
const int WD1797::sectorLengths[2][4] =
{
{256, 512, 1024, 128}, // [0]
{128, 256, 512, 1024} // [1]
};
WD1797::WD1797(int baseAddr): ClockUser(),
basePort_m(baseAddr),
trackReg_m(0),
sectorReg_m(0),
dataReg_m(0),
cmdReg_m(0),
statusReg_m(0),
dataReady_m(false),
intrqRaised_m(false),
drqRaised_m(false),
headLoaded_m(false),
sectorLength_m(0),
lastIndexStatus_m(false),
indexCount_m(0),
stepUpdate_m(false),
stepSettle_m(0),
missCount_m(0),
seekSpeed_m(0),
verifyTrack_m(false),
multiple_m(false),
delay_m(false),
side_m(0),
deleteDAM_m(false),
curCommand_m(noneCmd),
stepDirection_m(dir_out),
curPos_m(0),
sectorPos_m(InitialSectorPos_c),
cmdIV_readyToNotReady(false),
cmdIV_notReadyToReady(false),
cmdIV_indexPulse(false),
userIf_m(nullptr),
curNotification(&WD1797::noneNotification),
currentDrive_m(nullptr),
cycleCount_m(0),
formattingState_m(fs_none),
doubleDensity_m(false),
immediateInterruptSet_m(false)
{
}
WD1797::WD1797(WD179xUserIf* userIf): WD1797(0)
{
userIf_m = userIf;
}
WD1797::~WD1797()
{
}
void
WD1797::reset(void)
{
trackReg_m = 0;
sectorReg_m = 0;
dataReg_m = 0;
cmdReg_m = 0;
statusReg_m = 0;
dataReady_m = false;
intrqRaised_m = false;
drqRaised_m = false;
headLoaded_m = false;
sectorLength_m = 0;
lastIndexStatus_m = false;
indexCount_m = 0;
stepUpdate_m = false;
stepSettle_m = 0;
missCount_m = 0;
seekSpeed_m = 0;
verifyTrack_m = false;
multiple_m = false;
delay_m = false;
side_m = 0;
deleteDAM_m = false;
curCommand_m = noneCmd;
cmdIV_readyToNotReady = false;
cmdIV_notReadyToReady = false;
cmdIV_indexPulse = false;
immediateInterruptSet_m = false;
curNotification = &WD1797::noneNotification;
stepDirection_m = dir_out;
// leave curPos_m alone, diskette is still spinning...
sectorPos_m = InitialSectorPos_c;
}
BYTE
WD1797::in(BYTE addr)
{
BYTE offset = addr - basePort_m;
BYTE val = 0;
debugss(ssWD1797, INFO, "(%d)\n", addr);
switch (offset)
{
case StatusPort_Offset_c:
debugss(ssWD1797, INFO, "(StatusPort) (0x%02x) trk=%d sec=%d dat=0x%02x\n",
statusReg_m, trackReg_m, sectorReg_m, dataReg_m);
val = statusReg_m;
if (!immediateInterruptSet_m)
{
lowerIntrq();
}
break;
case TrackPort_Offset_c:
debugss(ssWD1797, VERBOSE, "(TrackPort) - %d\n", trackReg_m);
val = trackReg_m;
break;
case SectorPort_Offset_c:
debugss(ssWD1797, VERBOSE, "(SectorPort) - %d\n", sectorReg_m);
val = sectorReg_m;
break;
case DataPort_Offset_c:
// TODO - should this check dataReady_m first?
debugss(ssWD1797, VERBOSE, "(DataPort) - %d\n", dataReg_m);
val = dataReg_m;
dataReady_m = false;
statusReg_m &= ~stat_DataRequest_c;
lowerDrq();
break;
default:
debugss(ssWD1797, ERROR, "(Unknown - 0x%02x)\n", addr);
break;
}
return (val);
}
void
WD1797::out(BYTE addr,
BYTE val)
{
BYTE offset = addr - basePort_m;
debugss(ssWD1797, INFO, "(%d, %d (0x%x))\n", addr, val, val);
switch (offset)
{
case CommandPort_Offset_c:
debugss(ssWD1797, VERBOSE, "(CommandPort): %02x trk=%02x sec=%02x dat=%02x\n",
val, trackReg_m, sectorReg_m, dataReg_m);
// MUST tolerate changing of selected disk *after* setting command...
// timing is tricky...
indexCount_m = 0;
cmdReg_m = val;
processCmd(val);
break;
case TrackPort_Offset_c:
debugss(ssWD1797, INFO, "(TrackPort): %d\n", val);
trackReg_m = val;
break;
case SectorPort_Offset_c:
debugss(ssWD1797, VERBOSE, "(SectorPort): %d\n", val);
sectorReg_m = val;
break;
case DataPort_Offset_c:
debugss(ssWD1797, INFO, "(DataPort): %02x\n", val);
// unpredictable results if !dataReady_m... (data changed while being written).
// other mechanisms detect lostData, which is different.
dataReg_m = val;
dataReady_m = true;
lowerDrq();
break;
default:
debugss(ssWD1797, ERROR, "(Unknown - 0x%02x): %d\n", addr, val);
break;
}
}
void
WD1797::waitForData()
{
h89.waitCPU();
}
void
WD1797::processCmd(BYTE cmd)
{
debugss(ssWD1797, INFO, "cmd: 0x%02x\n", cmd);
// First check for the Force Interrupt command
if ((cmd & cmd_Mask_c) == cmd_ForceInterrupt_c)
{
processCmdTypeIV(cmd);
return;
}
// Make sure controller is not already busy. Documentation
// did not specify what would happen, it mentions 'This register should not
// be loaded when the device is busy unless the new command is a force interrupt.'
// for now, start the new command.
if ((statusReg_m & stat_Busy_c) == stat_Busy_c)
{
debugss(ssWD1797, ERROR, "New command while still busy: %d\n", cmd);
// TODO determine the proper behavior.
// return;
}
// set Busy flag
statusReg_m = stat_Busy_c;
debugss(ssWD1797, INFO, "Setting busy flag\n")
if ((cmd & 0x80) == 0x00)
{
// Type I commands
processCmdTypeI(cmd);
}
else if ((cmd & 0x40) == 0x00)
{
// Type II commands
processCmdTypeII(cmd);
}
else
{
// must be Type III command
processCmdTypeIII(cmd);
}
}
void
WD1797::processCmdTypeI(BYTE cmd)
{
debugss(ssWD1797, INFO, "cmd: 0x%02x\n", cmd);
verifyTrack_m = ((cmd & cmdop_VerifyTrack_c) != 0);
seekSpeed_m = speeds[cmd & cmdop_StepMask_c];
dataReady_m = false;
if (userIf_m->getClockPeriod() > 500)
{
seekSpeed_m *= 2;
}
loadHead((cmd & cmdop_HeadLoad_c) != 0);
stepUpdate_m = true;
// reset CRC Error, Seek Error, DRQ, INTRQ
statusReg_m &= ~(stat_CRCError_c | stat_SeekError_c);
lowerDrq();
if (!immediateInterruptSet_m)
{
lowerIntrq();
}
if ((cmd & 0xf0) == 0x00)
{
debugss(ssWD1797, WARNING, "Restore: %dms, v=%d\n", seekSpeed_m, verifyTrack_m);
curCommand_m = restoreCmd;
trackReg_m = 255;
}
else if ((cmd & 0xe0) == 0x00)
{
// Some of the documentation shows two different bit patterns for seek,
// but none for plain 'step', this is an apparent typo, the version of
// the document in the Z-89-37 seems to be the correct one and the
// pattern "0 0 1 T h V r1 r2" is the step command not the seek command.
debugss(ssWD1797, WARNING, "Seek: %d, %dms, v=%d\n", dataReg_m, seekSpeed_m, verifyTrack_m);
curCommand_m = seekCmd;
}
else
{
// One of the Step commands
stepUpdate_m = (cmd & cmdop_TrackUpdate_c) != 0;
debugss(ssWD1797, WARNING, "Step: %dms, v=%d ut: %d\n", seekSpeed_m, verifyTrack_m,
stepUpdate_m);
curCommand_m = stepCmd;
stepUpdate_m = (cmd & cmdop_TrackUpdate_c) != 0;
// check for step in or step out.
if ((cmd & 0x40) == 0x40)
{
if ((cmd & 0x20) == 0x20)
{
// Step Out
debugss(ssWD1797, WARNING, "Step Out\n");
stepDirection_m = dir_out;
}
else
{
// Step In
debugss(ssWD1797, WARNING, "Step In\n");
stepDirection_m = dir_in;
}
}
}
// Drive selection might change, need to delay start of command...
stepSettle_m = HeadSettleTimeInTicks_c;
curNotification = &WD1797::cmdTypeI_Notification;
}
void
WD1797::processCmdTypeII(BYTE cmd)
{
multiple_m = ((cmd & cmdop_MultipleRecord_c) != 0);
delay_m = ((cmd & cmdop_Delay_15ms_c) != 0);
sectorLength_m = ((cmd & cmdop_SectorLength_c) != 0 ? 1 : 0);
side_m = ((cmd & cmdop_UpdateSSO_c) >> cmdop_UpdateSSO_Shift_c);
loadHead(true);
debugss(ssWD1797, INFO, "cmd: 0x%02x\n", cmd);
lowerDrq();
dataReady_m = false;
sectorPos_m = InitialSectorPos_c;
if ((cmd & 0x20) == 0x20)
{
// Write Sector
deleteDAM_m = ((cmd & cmdop_DataAddressMark_c) != 0);
if (deleteDAM_m)
{
debugss(ssWD1797, ERROR, "Deleted Data Addr Mark not supported - ignored\n");
}
debugss(ssWD1797, INFO, "Write Sector - \n");
curCommand_m = writeSectorCmd;
}
else
{
// Read Sector
debugss(ssWD1797, INFO,
"Read Sector: %d - multi: %d delay: %d sectorLength_m: %d side: %d\n",
sectorReg_m, multiple_m, delay_m, sectorLength_m, side_m);
curCommand_m = readSectorCmd;
}
stepSettle_m = HeadSettleTimeInTicks_c; // give host time to get ready...
curNotification = &WD1797::cmdTypeII_Notification;
}
void
WD1797::processCmdTypeIII(BYTE cmd)
{
delay_m = ((cmd & cmdop_Delay_15ms_c) != 0);
side_m = ((cmd & cmdop_UpdateSSO_c) >> cmdop_UpdateSSO_Shift_c);
loadHead(true);
lowerDrq();
dataReady_m = false;
sectorPos_m = InitialSectorPos_c;
debugss(ssWD1797, INFO, "cmd: 0x%02x\n", cmd);
if ((cmd & 0xf0) == 0xc0)
{
// Read Address
debugss(ssWD1797, INFO, "Read Address\n");
curCommand_m = readAddressCmd;
}
else if ((cmd & 0xf0) == 0xf0)
{
// write Track
debugss(ssWD1797, ERROR, "Write Track: %d\n", trackReg_m);
currentDrive_m->startTrackFormat(trackReg_m);
curCommand_m = writeTrackCmd;
formattingState_m = fs_waitingForIndex;
raiseDrq();
}
else if ((cmd & 0xf0) == 0xe0)
{
// read Track
debugss(ssWD1797, ERROR, "Read Track: %d\n", trackReg_m);
curCommand_m = readTrackCmd;
}
else
{
debugss(ssWD1797, ERROR, "Invalid type-III cmd: %x\n", cmd);
statusReg_m &= ~stat_Busy_c;
return;
}
stepSettle_m = HeadSettleTimeInTicks_c; // give host time to get ready...
curNotification = &WD1797::cmdTypeIII_Notification;
}
// 'drive' might be NULL.
void
WD1797::processCmdTypeIV(BYTE cmd)
{
debugss(ssWD1797, INFO, "cmd-IV: 0x%02x\n", cmd);
loadHead(false);
// we assume drive won't change for Type IV commands...
curCommand_m = forceInterruptCmd;
// check to see if previous command is still running
if (statusReg_m & stat_Busy_c)
{
debugss(ssWD1797, INFO, "Aborting Command\n");
// still running, abort command and reset busy
abortCmd();
}
else if (currentDrive_m)
{
// no Command running, update status.
// try more-surgical repair of status register.
statusReg_m &= ~stat_SeekError_c;
statusReg_m &= ~stat_CRCError_c;
// if previous command was Type II or III, need to clear
// stat_LostData_c and stat_DataRequest_c ? But not if Type I.
debugss(ssWD1797, INFO, "updating statusReg: %d\n", statusReg_m);
}
else
{
debugss(ssWD1797, WARNING, "Type IV with no drive\n");
statusReg_m = stat_NotReady_c;
}
if ((cmd & 0x0f) != 0x00)
{
// at least one bit is set.
cmdIV_notReadyToReady = ((cmd & cmdop_NotReadyToReady_c) == cmdop_NotReadyToReady_c);
debugss(ssWD1797, INFO, "Not Ready to Ready - %d\n", cmdIV_notReadyToReady);
cmdIV_readyToNotReady = ((cmd & cmdop_ReadyToNotReady_c) == cmdop_ReadyToNotReady_c);
debugss(ssWD1797, INFO, "Ready to Not Ready - %d\n", cmdIV_readyToNotReady);
cmdIV_indexPulse = ((cmd & cmdop_IndexPulse_c) == cmdop_IndexPulse_c);
debugss(ssWD1797, INFO, "Index Pulse - %d\n", cmdIV_indexPulse);
if ((cmd & cmdop_ImmediateInterrupt_c) == cmdop_ImmediateInterrupt_c)
{
debugss(ssWD1797, INFO, "Immediate Interrupt\n");
statusReg_m &= ~stat_Busy_c;
immediateInterruptSet_m = true;
raiseIntrq();
}
curNotification = &WD1797::cmdTypeIV_Notification;
}
else
{
debugss(ssWD1797, INFO, "No Interrupt/ Clear Busy\n");
statusReg_m &= ~stat_Busy_c;
curCommand_m = noneCmd;
curNotification = &WD1797::noneNotification;
immediateInterruptSet_m = false;
lowerIntrq();
updateStatusTypeI(currentDrive_m);
}
}
void
WD1797::verifyTrack(GenericFloppyDrive* drive)
{
int track, sector, side;
if (drive)
{
// TODO: confirm this works...
if (!drive->readAddress(track, sector, side))
{
statusReg_m |= stat_CRCError_c;
}
else if (track != trackReg_m)
{
statusReg_m |= stat_SeekError_c;
}
}
else
{
debugss(ssWD1797, INFO, "seekCmd no drive: %d\n", trackReg_m);
statusReg_m |= stat_SeekError_c;
}
}
void
WD1797::completeCmd()
{
debugss(ssWD1797, INFO, "\n");
curCommand_m = noneCmd;
statusReg_m &= ~stat_Busy_c;
formattingState_m = fs_none;
raiseIntrq();
curNotification = &WD1797::noneNotification;
}
void
WD1797::abortCmd()
{
debugss(ssWD1797, INFO, "\n");
curCommand_m = noneCmd;
statusReg_m &= ~stat_Busy_c;
formattingState_m = fs_none;
curNotification = &WD1797::noneNotification;
}
void
WD1797::raiseIntrq()
{
debugss(ssWD1797, INFO, "\n");
intrqRaised_m = true;
userIf_m->raiseIntrq();
}
void
WD1797::raiseDrq()
{
debugss(ssWD1797, INFO, "\n");
drqRaised_m = true;
userIf_m->raiseDrq();
}
void
WD1797::lowerIntrq()
{
debugss(ssWD1797, INFO, "\n");
intrqRaised_m = false;
userIf_m->lowerIntrq();
}
void
WD1797::lowerDrq()
{
debugss(ssWD1797, INFO, "\n");
drqRaised_m = false;
userIf_m->lowerDrq();
}
void
WD1797::loadHead(bool load)
{
debugss(ssWD1797, INFO, "%sload\n", load ? "" : "un");
headLoaded_m = load;
if (currentDrive_m)
{
currentDrive_m->headLoad(load);
}
}
/// data transfered from the drive to the controller chip.
void
WD1797::transferData(int data)
{
if (dataReady_m)
{
statusReg_m |= stat_LostData_c;
}
dataReady_m = true;
dataReg_m = data;
statusReg_m |= stat_DataRequest_c;
raiseDrq();
}
void
WD1797::notification(unsigned int cycleCount)
{
cycleCount_m += cycleCount;
(this->*curNotification)(cycleCount);
}
// new notification function
void
WD1797::noneNotification(unsigned int cycleCount)
{
if (userIf_m->readReady())
{
// Clear notReady
statusReg_m &= ~stat_NotReady_c;
}
else
{
// Set notReady
statusReg_m |= stat_NotReady_c;
}
if (currentDrive_m)
{
if (currentDrive_m->isWriteProtect())
{
statusReg_m |= stat_WriteProtect_c;
}
else
{
statusReg_m &= ~stat_WriteProtect_c;
}
if (currentDrive_m->getIndexPulse())
{
statusReg_m |= stat_IndexPulse_c;
}
else
{
statusReg_m &= ~stat_IndexPulse_c;
}
}
}
void
WD1797::cmdTypeI_Notification(unsigned int cycleCount)
{
if (userIf_m->readReady())
{
statusReg_m &= ~stat_NotReady_c;
}
else
{
statusReg_m |= stat_NotReady_c;
}
if (currentDrive_m && currentDrive_m->getIndexPulse())
{
statusReg_m |= stat_IndexPulse_c;
if (!lastIndexStatus_m)
{
++indexCount_m;
}
lastIndexStatus_m = true;
}
else
{
statusReg_m &= ~stat_IndexPulse_c;
lastIndexStatus_m = false;
}
if (stepSettle_m > 0)
{
if (stepSettle_m > cycleCount)
{
stepSettle_m -= cycleCount;
return;
}
else
{
stepSettle_m = 0;
missCount_m = 0;
}
}
switch (curCommand_m)
{
case restoreCmd:
if (currentDrive_m && currentDrive_m->getTrackZero())
{
trackReg_m = 0;
statusReg_m |= stat_TrackZero_c;
if (verifyTrack_m)
{
verifyTrack(currentDrive_m);
}
completeCmd();
}
else
{
if (trackReg_m)
{
--trackReg_m;
if (currentDrive_m)
{
currentDrive_m->step(false);
}
stepSettle_m = HeadSettleTimeInTicks_c;
}
else
{
// went 255 steps, still not seeing track 0.
if (verifyTrack_m)
{
statusReg_m |= stat_SeekError_c;
}
completeCmd();
}
}
break;
case seekCmd:
if (dataReg_m != trackReg_m)
{
bool dir = (dataReg_m > trackReg_m);
if (currentDrive_m)
{
currentDrive_m->step(dir);
}
trackReg_m += (dir ? 1 : -1);
stepSettle_m = HeadSettleTimeInTicks_c;
}
else
{
if (verifyTrack_m)
{
verifyTrack(currentDrive_m);
}
if (currentDrive_m && currentDrive_m->getTrackZero())
{
statusReg_m |= stat_TrackZero_c;
}
else
{
statusReg_m &= ~stat_TrackZero_c;
}
completeCmd();
}
break;
case stepCmd:
if (stepDirection_m == dir_out)
{
debugss(ssWD1797, INFO, "step out\n");
if (currentDrive_m && currentDrive_m->getTrackZero())
{
statusReg_m |= stat_TrackZero_c;
}
else
{
if (currentDrive_m)
{
currentDrive_m->step(false);
}
stepSettle_m = HeadSettleTimeInTicks_c;
if (stepUpdate_m)
{
trackReg_m--;
}
}
}
else if (stepDirection_m == dir_in)
{
debugss(ssWD1797, INFO, "step in\n");
if (currentDrive_m)
{
currentDrive_m->step(true);
}
statusReg_m &= ~stat_TrackZero_c;
stepSettle_m = HeadSettleTimeInTicks_c;
if (stepUpdate_m)
{
trackReg_m++;
}
}
curCommand_m = stepDoneCmd;
break;
case stepDoneCmd:
if (currentDrive_m && currentDrive_m->getTrackZero())
{
statusReg_m |= stat_TrackZero_c;
}
else
{
statusReg_m &= ~stat_TrackZero_c;
}
completeCmd();
break;
default:
debugss(ssWD1797, ERROR, "unexpect command: %d\n", curCommand_m);
break;
}
}
void
WD1797::cmdTypeII_Notification(unsigned int cycleCount)
{
if (userIf_m->readReady())
{
// Clear notReady
statusReg_m &= ~stat_NotReady_c;
}
else
{
// Set notReady
statusReg_m |= stat_NotReady_c;
abortCmd();
raiseIntrq();
return;
}
if (currentDrive_m)
{
if (currentDrive_m->getIndexPulse())
{
if (!lastIndexStatus_m)
{
++indexCount_m;
}
lastIndexStatus_m = true;
}
else
{
lastIndexStatus_m = false;
}
}
if (stepSettle_m > 0)
{
if (stepSettle_m > cycleCount)
{
stepSettle_m -= cycleCount;
return;
}
stepSettle_m = 0;
missCount_m = 0;
}
if (!currentDrive_m)
{
debugss(ssWD1797, WARNING, "No drive\n");
// TODO determine right way to handle this... on MMS controller, ready would
// not be set, so it would abort above, abort for now on the H37
abortCmd();
raiseIntrq();
return;
}
unsigned long charPos = currentDrive_m->getCharPos(doubleDensity_m);
if (charPos == curPos_m)
{
// Position hasn't changed just return
return;
}
debugss(ssWD1797, ALL, "New character Pos - old: %ld, new: %ld\n", curPos_m, charPos);
curPos_m = charPos;
int data;
int result;
switch (curCommand_m)
{
case readSectorCmd:
debugss(ssWD1797, INFO, "readSectorCmd - dataReady_m: %d\n", dataReady_m);
// user may choose to ignore data... must not hang here!
if (dataReady_m)
{
debugss(ssWD1797, WARNING, "readSectorCmd\n");
if ((statusReg_m & stat_LostData_c) == 0 && ++missCount_m < 4)
{
debugss(ssWD1797, WARNING, "missCount_m - %d\n", missCount_m);
// wait a little for host to catch up
break;
}
debugss(ssWD1797, ERROR, "Lost Data\n");
statusReg_m |= stat_LostData_c;
}
missCount_m = 0;
currentDrive_m->selectSide(side_m);
debugss(ssWD1797, WARNING, "track: %d, sector: %d, sectorPos_m- %d\n", trackReg_m,
sectorReg_m, sectorPos_m);
// only check for correct sector at the start of the sector.
if (sectorPos_m == InitialSectorPos_c &&
!currentDrive_m->verifyTrackSector(trackReg_m, sectorReg_m))
{
debugss(ssWD1797, WARNING, "sector not found track: %d, sector: %d\n", trackReg_m,
sectorReg_m);
statusReg_m |= stat_RecordNotFound_c;
completeCmd();
return;
}
data = currentDrive_m->readData(doubleDensity_m, trackReg_m,
side_m, sectorReg_m, sectorPos_m);
debugss(ssWD1797, WARNING, "data- %d\n", data);
if (data == GenericFloppyFormat::NO_DATA)
{
debugss(ssWD1797, WARNING, "no data\n");
// just wait for sector to come around..
}
else if (data == GenericFloppyFormat::DATA_AM)
{
debugss(ssWD1797, WARNING, "DATA_AM\n");
sectorPos_m = 0;
}
else if (data == GenericFloppyFormat::CRC)
{
if (multiple_m)
{
sectorReg_m++;
sectorPos_m = InitialSectorPos_c;
}
else
{
sectorPos_m = ErrorSectorPos_c;
completeCmd();
}
}
else if (data < 0)
{
debugss(ssWD1797, WARNING, "less than zero\n");
// probably ERROR
sectorPos_m = ErrorSectorPos_c;
statusReg_m |= stat_CRCError_c;
completeCmd();
}
else
{
transferData(data);
++sectorPos_m;
}
break;
case writeSectorCmd:
currentDrive_m->selectSide(side_m);
// only check for correct sector at the start of the sector.
if (sectorPos_m == InitialSectorPos_c &&
!currentDrive_m->verifyTrackSector(trackReg_m, sectorReg_m))
{
statusReg_m |= stat_RecordNotFound_c;
completeCmd();
return;
}
// TODO - dataReady shouldn't be sent to the drive, according to the
// WD docs, after the start of writing, if a DRQ is not responded to, it
// should write '0' and set the status flag - LOST DATA.
result = currentDrive_m->writeData(doubleDensity_m, trackReg_m, side_m, sectorReg_m,
sectorPos_m, dataReg_m, dataReady_m);
if (result == GenericFloppyFormat::NO_DATA)
{
// out of paranoia, but must be careful
if (sectorPos_m >= 0 && !drqRaised_m)
{
raiseDrq();
}
// just wait for sector to come around..
}
else if (result == GenericFloppyFormat::DATA_AM)
{
sectorPos_m = 0;
}
else if (result == GenericFloppyFormat::CRC)
{
if (multiple_m)
{
sectorReg_m++;
sectorPos_m = InitialSectorPos_c;
}
else
{
sectorPos_m = ErrorSectorPos_c;
completeCmd();
}
}
else if (result < 0)
{
// other errors
sectorPos_m = ErrorSectorPos_c;
statusReg_m |= stat_WriteFault_c;
completeCmd();
}
else
{
dataReady_m = false;
++sectorPos_m;
raiseDrq();
}
break;
default:
debugss(ssWD1797, ERROR, "Unexpected cmd: %d\n", curCommand_m);
break;
}
}
void
WD1797::cmdTypeIII_Notification(unsigned int cycleCount)
{
if (userIf_m->readReady())
{
// Clear notReady
statusReg_m &= ~stat_NotReady_c;
}
else
{
// Set notReady
statusReg_m |= stat_NotReady_c;
abortCmd();
raiseIntrq();
return;
}
if (currentDrive_m)
{
if (currentDrive_m->getIndexPulse())
{
if (!lastIndexStatus_m)
{
lastIndexStatus_m = true;
++indexCount_m;
if (formattingState_m == fs_waitingForIndex)
{
formattingState_m = fs_writing;
}
}
}
else
{
lastIndexStatus_m = false;
}
}
if (stepSettle_m > 0)
{
if (stepSettle_m > cycleCount)
{
stepSettle_m -= cycleCount;
return;
}
stepSettle_m = 0;
missCount_m = 0;
}
if (!currentDrive_m)
{
debugss(ssWD1797, WARNING, "No drive\n");
// TODO figure out the right thing to do
abortCmd();
raiseIntrq();
return;
}
unsigned long charPos = currentDrive_m->getCharPos(doubleDensity_m);
if (charPos == curPos_m)
{
// Position hasn't changed just return
return;
}
debugss(ssWD1797, ALL, "New character Pos - old: %ld, new: %ld\n", curPos_m, charPos);
curPos_m = charPos;
int data;
int result;
switch (curCommand_m)
{
case readAddressCmd:
// user may choose to ignore data... must not hang here!
if (dataReady_m)
{
if ((statusReg_m & stat_LostData_c) == 0 && ++missCount_m < 4)
{
// wait a little for host to catch up
break;
}
statusReg_m |= stat_LostData_c;
}
missCount_m = 0;
currentDrive_m->selectSide(side_m);
// sector '0xfd' indicates a read address
data = currentDrive_m->readData(doubleDensity_m, trackReg_m, side_m,
0xfd, sectorPos_m);
if (data == GenericFloppyFormat::NO_DATA)
{
// just wait for sector to come around..
// should never happen, as long as track was formatted.
}
else if (data == GenericFloppyFormat::ID_AM)
{
sectorPos_m = 0;
}
else if (data == GenericFloppyFormat::CRC)
{
debugss(ssWD1797, INFO, "read address %d - done\n", sectorPos_m);
sectorPos_m = ErrorSectorPos_c;
completeCmd();
}
else if (data < 0)
{
// probably ERROR
sectorPos_m = ErrorSectorPos_c;
statusReg_m |= stat_CRCError_c;
completeCmd();
}
else
{
if (sectorPos_m == 0)
{
sectorReg_m = data;
}
debugss(ssWD1797, INFO, "read address %d - %02x\n", sectorPos_m, data);
transferData(data);
++sectorPos_m;
}
break;
case readTrackCmd:
// user may choose to ignore data... must not hang here!
if (dataReady_m)
{
if ((statusReg_m & stat_LostData_c) == 0 && ++missCount_m < 4)
{
// wait a little for host to catch up
break;
}
statusReg_m |= stat_LostData_c;
}
missCount_m = 0;
currentDrive_m->selectSide(side_m);
data = currentDrive_m->readData(doubleDensity_m, trackReg_m, side_m,
0xff, sectorPos_m);
if (data == GenericFloppyFormat::NO_DATA)
{
// just wait for index to come around..
}
else if (data == GenericFloppyFormat::INDEX_AM)
{
sectorPos_m = 0;
}
else if (data == GenericFloppyFormat::CRC)
{
sectorPos_m = ErrorSectorPos_c;
completeCmd();
}
else if (data < 0)
{
// probably ERROR
sectorPos_m = ErrorSectorPos_c;
statusReg_m |= stat_CRCError_c;
completeCmd();
}
else
{
transferData(data);
++sectorPos_m;
}
break;
case writeTrackCmd:
currentDrive_m->selectSide(side_m);
// \todo
result = currentDrive_m->writeData(doubleDensity_m, trackReg_m, side_m, 0xff,
sectorPos_m, dataReg_m, dataReady_m);
if (result == GenericFloppyFormat::NO_DATA)
{
// out of paranoia, but must be careful
if (sectorPos_m >= 0 && !drqRaised_m)
{
raiseDrq();
}
// just wait for sector to come around..
}
else if (result == GenericFloppyFormat::INDEX_AM)
{
sectorPos_m = 0;
}
else if (result == GenericFloppyFormat::CRC)
{
sectorPos_m = ErrorSectorPos_c;
completeCmd();
}
else if (result < 0)
{
// other errors
debugss(ssWD1797, WARNING, "Error in write track\n");
sectorPos_m = ErrorSectorPos_c;
statusReg_m |= stat_WriteFault_c;
completeCmd();
}
else
{
dataReady_m = false;
++sectorPos_m;
raiseDrq();
}
break;
default:
debugss(ssWD1797, ERROR, "Unexpected cmd: %d\n", curCommand_m);
break;
}
}
void
WD1797::cmdTypeIV_Notification(unsigned int cycleCount)
{
// TODO - determine if once condition is met, does the command terminate.
if (userIf_m->readReady())
{
if (cmdIV_notReadyToReady && ((statusReg_m & stat_NotReady_c) == 1))
{
raiseIntrq();
}
// Clear notReady
statusReg_m &= ~stat_NotReady_c;
}
else
{
if (cmdIV_readyToNotReady && ((statusReg_m & stat_NotReady_c) == 0))
{
raiseIntrq();
}
// Set notReady
statusReg_m |= stat_NotReady_c;
}
if (currentDrive_m)
{
if (currentDrive_m->getIndexPulse())
{
if (!lastIndexStatus_m)
{
++indexCount_m;
if (cmdIV_indexPulse)
{
raiseIntrq();
}
}
lastIndexStatus_m = true;
}
else
{
lastIndexStatus_m = false;
}
}
}
void
WD1797::updateStatusTypeI(GenericFloppyDrive* drive)
{
statusReg_m = 0;
if (!userIf_m->readReady())
{
statusReg_m |= stat_NotReady_c;
}
else
{
statusReg_m &= ~stat_NotReady_c;
}
if (drive)
{
if (drive->isWriteProtect())
{
statusReg_m |= stat_WriteProtect_c;
}
else
{
statusReg_m &= ~stat_WriteProtect_c;
}
/// \todo head load status
if (drive->getTrackZero())
{
statusReg_m |= stat_TrackZero_c;
}
else
{
statusReg_m &= ~stat_TrackZero_c;
}
if (drive->getIndexPulse())
{
statusReg_m |= stat_IndexPulse_c;
}
else
{
statusReg_m &= ~stat_IndexPulse_c;
}
}
}
void
WD1797::setDoubleDensity(bool dd)
{
doubleDensity_m = dd;
}
unsigned long
WD1797::millisecToTicks(unsigned long ms)
{
unsigned long tps = WallClock::instance()->getTicksPerSecond();
unsigned long ticks = (tps * ms) / 1000;
return ticks;
}
void
WD1797::setCurrentDrive(GenericFloppyDrive* drive)
{
currentDrive_m = drive;
}
<file_sep>/VirtualH89/Src/Console.h
/// \file Console.h
///
/// \date Feb 6, 2016
/// \author <NAME>
///
#ifndef CONSOLE_H_
#define CONSOLE_H_
#include "Terminal.h"
/// \cond
#include <string>
/// \endcond
/// \class Console
///
/// \brief interface Console.
///
/// Base class for generic terminal.
///
class Console: public Terminal
{
public:
Console(int argc,
char** argv);
virtual ~Console();
virtual void run() = 0;
virtual void init() = 0;
virtual void reset() = 0;
std::string command(std::string cmd);
// obsolete? deprecated?
virtual void processCharacter(char ch) = 0;
virtual void display() = 0;
virtual void keypress(char ch) = 0;
virtual bool checkUpdated() = 0;
private:
};
#endif // CONSOLE_H_
<file_sep>/VirtualH89/Src/EventHandler.cpp
/// \file EventHandler.cpp
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#include "EventHandler.h"
EventHandler::EventHandler()
{
}
EventHandler::~EventHandler()
{
}
<file_sep>/VirtualH89/Src/VirtualH89App.cpp
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: VirtualH89App.cpp
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 16:38:00 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#undef wxUSE_LIBPNG
#undef wxUSE_LIBJPEG
#undef wxUSE_GIF
#undef wxUSE_INTL
#include "VirtualH89App.h"
////@begin XPM images
////@end XPM images
/*
* Application instance implementation
*/
////@begin implement app
IMPLEMENT_APP( VirtualH89App )
////@end implement app
/*
* VirtualH89App type definition
*/
IMPLEMENT_CLASS( VirtualH89App, wxApp )
/*
* VirtualH89App event table definition
*/
BEGIN_EVENT_TABLE( VirtualH89App, wxApp )
////@begin VirtualH89App event table entries
////@end VirtualH89App event table entries
END_EVENT_TABLE()
/*
* Constructor for VirtualH89App
*/
VirtualH89App::VirtualH89App()
{
Init();
}
/*
* Member initialisation
*/
void VirtualH89App::Init()
{
////@begin VirtualH89App member initialisation
////@end VirtualH89App member initialisation
}
/*
* Initialisation for VirtualH89App
*/
bool VirtualH89App::OnInit()
{
////@begin VirtualH89App initialisation
// Remove the comment markers above and below this block
// to make permanent changes to the code.
#if wxUSE_XPM
wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
wxImage::AddHandler(new wxGIFHandler);
#endif
VirtualH89Frame* mainWindow = new VirtualH89Frame( NULL );
mainWindow->Show(true);
////@end VirtualH89App initialisation
return true;
}
/*
* Cleanup for VirtualH89App
*/
int VirtualH89App::OnExit()
{
////@begin VirtualH89App cleanup
return wxApp::OnExit();
////@end VirtualH89App cleanup
}
#endif
<file_sep>/VirtualH89/Src/MMS316IntrCtrlr.cpp
///
/// \name MMS316IntrCtrlr.cpp
///
/// Implementation of the H89 interrupt controller circuits, when augmented by the
/// MMS 77316 floppy disk controller. Used only if the MMS77316 is installed.
///
/// \date Feb 8, 2016
/// \author <NAME>
///
#include "MMS316IntrCtrlr.h"
#include "logger.h"
#include "cpu.h"
MMS316IntrCtrlr::MMS316IntrCtrlr(CPU* cpu): InterruptController(cpu),
intrqRaised_m(false),
drqRaised_m(false)
{
debugss(ssMMS77316, INFO, "\n");
}
MMS316IntrCtrlr::~MMS316IntrCtrlr()
{
}
void
MMS316IntrCtrlr::setINTLine()
{
if (intLevel_m != 2 && intLevel_m != 0)
{
debugss(ssInterruptController, VERBOSE, "intLevel: %d intrqRaised_m: %d drqRaised: %d\n",
intLevel_m, intrqRaised_m, drqRaised_m);
}
if (intLevel_m != 0 || intrqRaised_m || drqRaised_m)
{
cpu_m->raiseINT();
cpu_m->continueRunning();
}
else
{
cpu_m->lowerINT();
}
}
// reading instructions for interrupts
BYTE
MMS316IntrCtrlr::readDataBus()
{
BYTE opCode = 0;
if (intrqRaised_m)
{
// RST 30H
opCode = 0xf7;
}
else if (drqRaised_m)
{
// EI
opCode = 0xfb;
}
else
{
opCode = InterruptController::readDataBus();
}
debugss(ssMMS77316, VERBOSE, "readDataBus in interrupt... returning %02x\n", opCode);
return opCode;
}
void
MMS316IntrCtrlr::setDrq(bool raise)
{
debugss(ssMMS77316, VERBOSE, "%d\n", raise);
drqRaised_m = raise;
setINTLine();
}
void
MMS316IntrCtrlr::setIntrq(bool raise)
{
debugss(ssMMS77316, VERBOSE, "%d\n", raise);
intrqRaised_m = raise;
setINTLine();
}
<file_sep>/VirtualH89/Src/RawFloppyImage.h
/// \file RawFloppyImage.h
///
/// \brief virtual Floppy Disk implementation for soft-sectored media.
/// Supports media image files that have a simplified raw-track format.
/// See GenericFloppyFormat for special format marks INDEX_AM, ID_AM, and
/// DATA_AM which are used to mark the start of respective sections of the media.
/// Gaps are typically zeroes, as opposed to other patterns used in real media.
/// NOTE: On real soft-sectored media the special marks are recorded using a
/// missing-clock method and so the real controller can easily distinguish
/// the marks from actualy data, which could otherwise match the bit pattern.
/// This implemetnation cannot do that in the image file, so it must be able to
/// determine precisely where data and address blocks beging, which means
/// each track must be identically formatted. Real images taken from real media
/// will not conform to that restriction.
///
/// \date Feb 2, 2016
///
/// \author <NAME>
///
#ifndef RAWFLOPPYIMAGE_H_
#define RAWFLOPPYIMAGE_H_
#include "GenericFloppyDisk.h"
/// \cond
#include <sys/types.h>
#include <vector>
/// \endcond
class GenericFloppyDrive;
class GenericFloppyFormat;
class GenericDiskDrive;
/// \class RawFloppyImage
///
/// \brief A virtual floppy disk
///
class RawFloppyImage: public GenericFloppyDisk
{
public:
RawFloppyImage(GenericDiskDrive* drive,
std::vector<std::string> argv);
~RawFloppyImage() override;
bool readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data) override;
bool writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result) override;
bool isReady() override;
bool findSector(BYTE side,
BYTE track,
BYTE sector) override;
void eject(const std::string name) override;
void dump(void) override;
std::string getMediaName() override;
private:
const char* imageName_m;
int imageFd_m;
BYTE* trackBuffer_m;
int bufferedTrack_m;
int bufferedSide_m;
off_t bufferOffset_m;
bool bufferDirty_m;
bool hypoTrack_m; // ST media in DT drive
bool hyperTrack_m; // DT media in ST drive
bool interlaced_m;
long gapLen_m;
long indexGapLen_m;
unsigned long writePos_m;
bool trackWrite_m;
int headPos_m;
int dataPos_m;
int dataLen_m;
void getAddrMark(BYTE* tp,
int nbytes,
int& id_tk,
int& id_sd,
int& id_sc,
int& id_sl);
bool cacheTrack(int side,
int track);
bool findMark(int mark);
bool locateSector(BYTE track,
BYTE side,
BYTE sector);
protected:
};
#endif // RAWFLOPPYIMAGE_H_
<file_sep>/VirtualH89/Src/computer.h
///
/// \name computer.h
/// \brief Base computer class.
///
/// \date Jul 16, 2012
/// \author <NAME>
///
#ifndef COMPUTER_H_
#define COMPUTER_H_
#include "h89Types.h"
class AddressBus;
/// \class Computer
///
class Computer
{
private:
public:
Computer();
virtual ~Computer();
virtual void reset() = 0;
virtual BYTE run() = 0;
virtual void init() = 0;
virtual void keypress(BYTE ch) = 0;
virtual void display() = 0;
virtual void raiseINT(int level) = 0;
virtual void lowerINT(int level) = 0;
virtual void raiseNMI(void) = 0;
virtual void continueCPU(void) = 0;
virtual void systemMutexRelease() = 0;
virtual void systemMutexAcquire() = 0;
virtual void waitCPU() = 0;
virtual AddressBus& getAddressBus() = 0;
};
#endif // COMPUTER_H_
<file_sep>/VirtualH89/Src/EventHandler.h
/// \file EventHandler.h
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#ifndef EVENTHANDLER_H_
#define EVENTHANDLER_H_
class EventHandler
{
public:
virtual int handleSignal(int signum) = 0;
EventHandler();
virtual ~EventHandler();
};
#endif // EVENTHANDLER_H_
<file_sep>/VirtualH89/Src/wd1797.h
/// \file wd1797.h
///
/// Implementation of the WD1797 FDC (floppy disk controller) chip.
///
/// \date Jan 30, 2016
/// \author <NAME>, cloned from h37.h by <NAME>
///
#ifndef WD1797_H_
#define WD1797_H_
#include "ClockUser.h"
#include "h89Types.h"
class GenericFloppyDrive;
class WD179xUserIf;
///
/// \brief Virtual Western Digital's soft-sectored floppy controller chip
///
/// Implements a virtual WD1797 floppy controller chip, requires additional
/// logic to function as a complete floppy disk controller.
///
class WD1797: public ClockUser
{
public:
WD1797(WD179xUserIf* userIf);
virtual ~WD1797() override;
virtual BYTE in(BYTE addr);
virtual void out(BYTE addr,
BYTE val);
virtual void setCurrentDrive(GenericFloppyDrive* drive);
virtual void reset(void);
void notification(unsigned int cycleCount) override;
void eject(char const* file);
void dump();
static const BYTE StatusPort_Offset_c = 0;
static const BYTE CommandPort_Offset_c = 0;
static const BYTE TrackPort_Offset_c = 1;
static const BYTE SectorPort_Offset_c = 2;
static const BYTE DataPort_Offset_c = 3;
void waitForData();
void setDoubleDensity(bool dd);
protected:
WD1797(int baseAddr = 0);
BYTE basePort_m;
static const BYTE WD1797_NumPorts_c = 4;
BYTE trackReg_m;
BYTE sectorReg_m;
BYTE dataReg_m;
BYTE cmdReg_m;
BYTE statusReg_m;
bool dataReady_m;
bool intrqRaised_m;
bool drqRaised_m;
bool headLoaded_m;
int sectorLength_m;
bool lastIndexStatus_m;
int indexCount_m;
bool stepUpdate_m;
unsigned long stepSettle_m;
int missCount_m;
/// type I parameters.
BYTE seekSpeed_m;
bool verifyTrack_m;
/// type II parameters.
bool multiple_m;
bool delay_m;
BYTE side_m;
bool deleteDAM_m;
BYTE addr_m[6];
enum Command
{
restoreCmd,
seekCmd,
stepCmd, /// shared with step in/step out.
readSectorCmd,
writeSectorCmd,
readAddressCmd,
readTrackCmd,
writeTrackCmd,
forceInterruptCmd,
// pseudo-commands/states used internally
stepDoneCmd,
noneCmd
};
Command curCommand_m;
enum Direction
{
dir_out = -1,
dir_in = 1
};
Direction stepDirection_m;
unsigned long int curPos_m;
int sectorPos_m;
void processCmd(BYTE cmd);
void processCmdTypeI(BYTE cmd);
void processCmdTypeII(BYTE cmd);
void processCmdTypeIII(BYTE cmd);
void processCmdTypeIV(BYTE cmd);
void verifyTrack(GenericFloppyDrive* drive);
void completeCmd();
void abortCmd();
unsigned long millisecToTicks(unsigned long ms);
// Controller may need to override/trap these.
virtual void raiseIntrq();
virtual void raiseDrq();
virtual void lowerIntrq();
virtual void lowerDrq();
virtual void loadHead(bool load);
///
/// Commands sent to CommandPort_c
///
static const BYTE cmd_Mask_c = 0xf0;
static const BYTE cmd_Restore_c = 0x00; // 0000 hVrr
static const BYTE cmd_SeekTrack_c = 0x10; // 0001 hVrr
static const BYTE cmd_StepRepeat_c = 0x20; // 001T hVrr
static const BYTE cmd_StepIn_c = 0x40; // 010T hVrr
static const BYTE cmd_StepOut_c = 0x60; // 011T hVrr
static const BYTE cmd_ReadSector_c = 0x80; // 100m SEC0
static const BYTE cmd_WriteSector_c = 0xa0; // 101m SECa
static const BYTE cmd_ReadAddress_c = 0xc0; // 1100 0E00
static const BYTE cmd_ReadTrack_c = 0xe0; // 1110 0E00
static const BYTE cmd_WriteTrack_c = 0xf0; // 1111 0E00
static const BYTE cmd_ForceInterrupt_c = 0xd0; // 1101 IIII (I3/I2/I1/I0)
///
/// rr - Stepping Motor Rate
/// ===============================================
/// 00 - 6 mSec
/// 01 - 12 mSec
/// 10 - 20 mSec
/// 11 - 30 mSec
///
static const BYTE maxStepSpeeds_c = 4;
static const BYTE speeds[maxStepSpeeds_c];
static const BYTE cmdop_StepMask_c = 0x03; // 0000 0011
static const BYTE cmdop_Step6ms_c = 0x00; // 0000 0000
static const BYTE cmdop_Step12ms_c = 0x01; // 0000 0001
static const BYTE cmdop_Step20ms_c = 0x02; // 0000 0010
static const BYTE cmdop_Step30ms_c = 0x03; // 0000 0011
///
/// V - Track Verify
/// ===============================================
/// 0 - No verify
/// 1 - Verify on destination
///
static const BYTE cmdop_VerifyTrack_c = 0x04;
///
/// h - Head Load Flag
/// ===============================================
/// 0 - Load Head at the beginning
/// 1 - Unload head at the beginning
///
static const BYTE cmdop_HeadLoad_c = 0x08;
///
/// T - Track Update Flag
/// ===============================================
/// 0 - No update
/// 1 - Update Track Register
///
static const BYTE cmdop_TrackUpdate_c = 0x10;
///
/// m - Multiple Record Flag
/// ===============================================
/// 0 - Single Record
/// 1 - Multiple records
///
static const BYTE cmdop_MultipleRecord_c = 0x10;
///
/// a - Data Address Mark
/// ===============================================
/// 0 - FB(DAM)
/// 1 - F8(delete DAM)
///
static const BYTE cmdop_DataAddressMark_c = 0x01;
///
/// U - Update SSO
/// ===============================================
/// 0 - Update SSO to 0
/// 1 - Update SSO to 1
///
static const BYTE cmdop_UpdateSSO_c = 0x02;
static const BYTE cmdop_UpdateSSO_Shift_c = 1;
///
/// E - 15 mSec Delay
/// ===============================================
/// 0 - No delay
/// 1 - 15 mSec Delay
///
static const BYTE cmdop_Delay_15ms_c = 0x04;
///
/// L - Sector Length Flag
/// ---------------------------------------
/// | LSB in Sector Length in ID field
/// | 00 | 01 | 10 | 11
/// ----+--------+--------+-------+-------
/// L=0 | 256 | 512 | 1024 | 128
/// L=1 | 128 | 256 | 512 | 1024
///
static const BYTE cmdop_SectorLength_c = 0x08;
///
/// Options to the Force Interrupt command
///
/// Ix
/// ===============================================
/// I3 - Immediate Interrupt, Requires a Reset
/// I2 - Index Pulse
/// I1 - Ready to Not Ready Transition
/// I0 - Not Ready to Ready Transition
///
static const BYTE cmdop_ImmediateInterrupt_c = 0x08;
static const BYTE cmdop_IndexPulse_c = 0x04;
static const BYTE cmdop_ReadyToNotReady_c = 0x02;
static const BYTE cmdop_NotReadyToReady_c = 0x01;
///
/// Status bit definitions
///
/// Type I commands Status
/// ===============================================
static const BYTE stat_NotReady_c = 0x80;
static const BYTE stat_WriteProtect_c = 0x40;
static const BYTE stat_HeadLoaded_c = 0x20;
static const BYTE stat_SeekError_c = 0x10;
static const BYTE stat_CRCError_c = 0x08;
static const BYTE stat_TrackZero_c = 0x04;
static const BYTE stat_IndexPulse_c = 0x02;
static const BYTE stat_Busy_c = 0x01;
/// Read Address Status
/// ===============================================
/// stat_NotReady_c - 0x80;
/// 0 - 0x40;
/// 0 - 0x20;
static const BYTE stat_RecordNotFound_c = 0x10;
/// stat_CRCError_c - 0x08;
static const BYTE stat_LostData_c = 0x04;
static const BYTE stat_DataRequest_c = 0x02;
/// stat_Busy_c - 0x01;
/// Read Sector Status
/// ===============================================
/// stat_NotReady_c - 0x80;
/// 0 - 0x40;
static const BYTE stat_RecordType_c = 0x20;
/// stat_RecordNotFound_c - 0x10;
/// stat_CRCError_c - 0x08;
/// stat_LostData_c - 0x04;
/// stat_DataRequest_c - 0x02;
/// stat_Busy_c - 0x01;
/// Read Track Status
/// ===============================================
/// stat_NotReady_c - 0x80;
/// 0 - 0x40;
/// 0 - 0x20;
/// 0 - 0x10;
/// 0 - 0x08;
/// stat_LostData_c - 0x04;
/// stat_DataRequest_c - 0x02;
/// stat_Busy_c - 0x01;
/// Write Sector Status
/// ===============================================
/// stat_NotReady_c - 0x80;
/// stat_WriteProtect_c - 0x40;
static const BYTE stat_WriteFault_c = 0x20;
/// stat_RecordNotFound_c - 0x10;
/// stat_CRCError_c - 0x08;
/// stat_LostData_c - 0x04;
/// stat_DataRequest_c - 0x02;
/// stat_Busy_c - 0x01;
/// Write Track Status
/// ===============================================
/// stat_NotReady_c - 0x80;
/// stat_WriteProtect_c - 0x40;
/// stat_WriteFault_c - 0x20;
/// 0 - 0x10;
/// 0 - 0x08;
/// stat_LostData_c - 0x04;
/// stat_DataRequest_c - 0x02;
/// stat_Busy_c - 0x01;
static const int sectorLengths[2][4];
static const int HeadSettleTimeInTicks_c = 100;
static const int InitialSectorPos_c = -11;
static const int ErrorSectorPos_c = -1;
private:
typedef void (WD1797::* notificationMethod)(unsigned int cycleCount);
notificationMethod curNotification;
void noneNotification(unsigned int cycleCount);
void cmdTypeI_Notification(unsigned int cycleCount);
void cmdTypeII_Notification(unsigned int cycleCount);
void cmdTypeIII_Notification(unsigned int cycleCount);
void cmdTypeIV_Notification(unsigned int cycleCount);
bool cmdIV_readyToNotReady;
bool cmdIV_notReadyToReady;
bool cmdIV_indexPulse;
WD179xUserIf* userIf_m;
GenericFloppyDrive* currentDrive_m;
unsigned long long cycleCount_m;
enum FormattingState
{
fs_none,
fs_waitingForIndex,
fs_writing
};
FormattingState formattingState_m;
bool doubleDensity_m;
bool immediateInterruptSet_m;
void updateStatusTypeI(GenericFloppyDrive* drive);
void transferData(int data);
// bool checkAddr(BYTE addr[6]);
// int sectorLen(BYTE addr[6]);
};
#endif // WD1797_H_
<file_sep>/VirtualH89/Src/GUIglut.h
#if defined(__GUIglut__) || !defined(__GUIwx__)
///
/// \name GUIglut.h
///
/// A GUI implementation based on glut.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#ifndef GUIGLUT_H_
#define GUIGLUT_H_
#include "GUI.h"
#include "h19.h"
/// \cond
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#ifdef __APPLE__
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
/// \endcond
typedef void (* tGLUTKeyboardFunc)(unsigned char Key, int x, int y);
class GUIglut: public GUI
{
public:
GUIglut();
virtual ~GUIglut() override;
// Interface functions.
virtual void GUIDisplay(void) override;
virtual void InitGUI(void) override;
virtual void StartGUI(void) override;
// Callback functions.
virtual void SetKeyboardFunc(tKeyboardFunc KeyboardFunc) override;
virtual void SetDisplayFunc(tDisplayFunc DisplayFunc) override;
virtual void SetTimerFunc(unsigned int ms, tTimerFunc TimerFunc) override;
private:
static void GLUTTimerFunc(int i);
static tDisplayFunc GUITimerFunc;
static unsigned int m_ms;
static void GLUTDisplayFunc(void);
static tDisplayFunc GUIDisplayFunc;
static void GLUTKeyboardFunc(unsigned char Key, int x, int y);
static tKeyboardFunc GUIKeyboardFunc;
static void reshape(int w,
int h);
static void special(int key,
int x,
int y);
unsigned int fontOffset_m;
unsigned char* fontTable;
};
#endif /* GUIGLUT_H_ */
#endif
<file_sep>/VirtualH89/Src/H47Drive.cpp
///
/// \name H47Disk.cpp
///
///
/// \date Jul 27, 2013
/// \author <NAME>
///
#include "H47Drive.h"
#include "logger.h"
using namespace std;
H47Drive::H47Drive(): tracks_m(maxTracks_c),
sectors_m(maxSectorsPerTrack_c),
bytes_m(maxBytesPerSector_c),
track_m(0),
sector_m(1),
byte_m(0)
{
// TODO Auto-generated constructor stub
}
H47Drive::~H47Drive()
{
// TODO Auto-generated destructor stub
}
void
H47Drive::insertDisk(shared_ptr<FloppyDisk> disk)
{
disk_m = disk;
}
void
H47Drive::getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect)
{
}
void
H47Drive::selectSide(BYTE side)
{
}
void
H47Drive::step(bool direction)
{
if (direction)
{
if (track_m < (maxTracks_c - 1))
{
++track_m;
}
debugss(ssH47Drive, INFO, "in(up) (%d)\n", track_m);
}
else
{
if (track_m)
{
--track_m;
}
debugss(ssH47Drive, INFO, "out(down) (%d)\n", track_m);
}
}
BYTE
H47Drive::readData(unsigned long pos)
{
return 0;
}
void
H47Drive::writeData(unsigned long pos,
BYTE data)
{
}
BYTE
H47Drive::readSectorData(BYTE sector,
unsigned long pos)
{
return 0;
}
<file_sep>/VirtualH89/Src/MemoryLayout.h
///
/// \file MemoryLayout.h
///
/// A container for a 64K layout of memory, for addresses 0000-FFFF, in 8K pages.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef MEMORYLAYOUT_H_
#define MEMORYLAYOUT_H_
#include "h89Types.h"
/// \cond
#include <memory>
/// \endcond
class Memory8K;
class MemoryLayout
{
public:
enum MemorySize_t
{
Mem_None,
Mem_16k,
Mem_32k,
Mem_48k,
Mem_64k
};
MemoryLayout();
void addPage(std::shared_ptr<Memory8K> mem);
void addPageAt(std::shared_ptr<Memory8K> mem,
WORD adr);
inline std::shared_ptr<Memory8K> getPageByAddress(WORD address)
{
// error if NULL?
return memPage_m[addressToPage(address)];
}
inline std::shared_ptr<Memory8K> getPage(BYTE page)
{
// error if NULL?
if (page >= numPages_c)
{
// TODO - add something for out-of-range
}
return memPage_m[page & 0x7];
}
static const BYTE pageShiftFactor_c = 13;
static const BYTE numPages_c = 8;
static BYTE addressToPage(WORD address)
{
return (address >> pageShiftFactor_c) & 0x07;
}
static WORD pageToAddress(BYTE page)
{
return page << pageShiftFactor_c;
}
protected:
std::shared_ptr<Memory8K> memPage_m[numPages_c]; // 8 8K regions in 64K addr space
};
typedef std::shared_ptr<MemoryLayout> MemoryLayout_ptr;
#endif // MEMORYLAYOUT_H_
<file_sep>/VirtualH89/Src/SignalHandler.cpp
/// \file SignalHandler.cpp
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#include "SignalHandler.h"
#include "EventHandler.h"
SignalHandler* SignalHandler::_inst;
EventHandler* SignalHandler::signalHandlers[NSIG];
SignalHandler::SignalHandler()
{
}
SignalHandler::~SignalHandler()
{
}
SignalHandler*
SignalHandler::instance(void)
{
if (!_inst)
{
_inst = new SignalHandler();
}
return (_inst);
}
EventHandler*
SignalHandler::registerHandler(int signum,
EventHandler* evtHandler)
{
static struct sigaction newact;
EventHandler* orig_evtHandler = signalHandlers[signum];
signalHandlers[signum] = evtHandler;
newact.sa_handler = dispatcher;
sigaction(signum, &newact, 0);
return (orig_evtHandler);
}
int
SignalHandler::removeHandler(int signum)
{
static struct sigaction newact;
newact.sa_handler = SIG_IGN;
sigaction(signum, &newact, 0);
signalHandlers[signum] = 0;
return (signum);
}
void
SignalHandler::dispatcher(int signum)
{
if (signalHandlers[signum] != 0)
{
signalHandlers[signum]->handleSignal(signum);
}
}
<file_sep>/VirtualH89/Src/AboutVirtualH89.h
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: AboutVirtualH89.h
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 17:10:14 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _ABOUTVIRTUALH89_H_
#define _ABOUTVIRTUALH89_H_
/*!
* Includes
*/
////@begin includes
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_ABOUTVIRTUALH89 10000
#define ID_TEXTCTRL_AboutText 10001
#define SYMBOL_ABOUTVIRTUALH89_STYLE wxCAPTION|wxSYSTEM_MENU|wxCLOSE_BOX|wxTAB_TRAVERSAL
#define SYMBOL_ABOUTVIRTUALH89_TITLE _("About Virtual Heathkit H-89 All-in-One Computer")
#define SYMBOL_ABOUTVIRTUALH89_IDNAME ID_ABOUTVIRTUALH89
#define SYMBOL_ABOUTVIRTUALH89_SIZE wxDefaultSize
#define SYMBOL_ABOUTVIRTUALH89_POSITION wxDefaultPosition
////@end control identifiers
/*!
* AboutVirtualH89 class declaration
*/
class AboutVirtualH89: public wxDialog
{
DECLARE_DYNAMIC_CLASS( AboutVirtualH89 )
DECLARE_EVENT_TABLE()
public:
/// Constructors
AboutVirtualH89();
AboutVirtualH89( wxWindow* parent, wxWindowID id = SYMBOL_ABOUTVIRTUALH89_IDNAME, const wxString& caption = SYMBOL_ABOUTVIRTUALH89_TITLE, const wxPoint& pos = SYMBOL_ABOUTVIRTUALH89_POSITION, const wxSize& size = SYMBOL_ABOUTVIRTUALH89_SIZE, long style = SYMBOL_ABOUTVIRTUALH89_STYLE );
/// Creation
bool Create( wxWindow* parent, wxWindowID id = SYMBOL_ABOUTVIRTUALH89_IDNAME, const wxString& caption = SYMBOL_ABOUTVIRTUALH89_TITLE, const wxPoint& pos = SYMBOL_ABOUTVIRTUALH89_POSITION, const wxSize& size = SYMBOL_ABOUTVIRTUALH89_SIZE, long style = SYMBOL_ABOUTVIRTUALH89_STYLE );
/// Destructor
~AboutVirtualH89();
/// Initialises member variables
void Init();
/// Creates the controls and sizers
void CreateControls();
////@begin AboutVirtualH89 event handler declarations
////@end AboutVirtualH89 event handler declarations
////@begin AboutVirtualH89 member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end AboutVirtualH89 member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin AboutVirtualH89 member variables
////@end AboutVirtualH89 member variables
};
#endif
// _ABOUTVIRTUALH89_H_
#endif
<file_sep>/VirtualH89/Src/GenericFloppyDisk.h
/// \file GenericFloppyDisk.h
///
/// \brief virtual Floppy Disk interface.
///
/// \date Feb 2, 2016
///
/// \author <NAME>
///
#ifndef GENERICFLOPPYDISK_H_
#define GENERICFLOPPYDISK_H_
#include "h89Types.h"
/// \cond
#include <string>
#include <memory>
#include <vector>
/// \endcond
class Sector;
class Track;
class GenericFloppyDisk;
typedef std::shared_ptr<GenericFloppyDisk> GenericFloppyDisk_ptr;
/// \class GenericFloppyDisk
///
/// \brief A virtual floppy disk
///
class GenericFloppyDisk
{
public:
GenericFloppyDisk();
virtual ~GenericFloppyDisk();
void setWriteProtect(bool value);
bool checkWriteProtect()
{
return writeProtect_m;
}
bool doubleDensity()
{
return doubleDensity_m;
}
virtual bool readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data) = 0;
virtual bool writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result) = 0;
virtual BYTE getRealTrackNumber(BYTE track);
virtual bool findSector(BYTE sideNum,
BYTE trackNum,
BYTE sectorNum) = 0;
virtual bool isReady() = 0;
virtual void eject(const std::string name) = 0;
virtual void dump(void) = 0;
virtual std::string getMediaName();
enum FileType_t
{
IMD,
TD0,
Unknown
};
enum DiskSize_t
{
FiveAndQuarterInch,
EightInch
};
static GenericFloppyDisk_ptr loadDiskImage(std::vector<std::string> argv);
void setDriveType(BYTE numTracks);
private:
protected:
static FileType_t determineFileType(std::string filename);
std::string imageName_m;
bool writeProtect_m;
bool doubleDensity_m;
unsigned trackLen_m;
int numTracks_m;
int numSectors_m;
int numSides_m;
int secSize_m;
int mediaSize_m;
///
bool hypoTrack_m; // ST media in DT drive
bool hyperTrack_m; // DT media in ST drive
};
#endif // GENERICFLOPPYDISK_H_
<file_sep>/VirtualH89/Src/GenericFloppyDrive.cpp
/// \file GenericFloppyDrive.cpp
///
/// Implementation of a generic floppy disk drive, should be capable of
/// supporting any type of floppy drive, 8", 5.25", DS, DT, etc.
///
/// \date Feb 2, 2016
/// \author <NAME>
///
#include "GenericFloppyDrive.h"
#include "WallClock.h"
#include "logger.h"
#include "GenericFloppyFormat.h"
#include "GenericFloppyDisk.h"
using namespace std;
GenericFloppyDrive::GenericFloppyDrive(unsigned int heads,
unsigned int tracks,
unsigned int mediaSize): numHeads_m(heads),
numTracks_m(tracks),
mediaSize_m(mediaSize),
track_m(0),
headSel_m(0),
cycleCount_m(0),
disk_m(nullptr),
writeProtected_m(false)
{
// Can this change on-the-fly?
ticksPerSec_m = WallClock::instance()->getTicksPerSecond();
if (mediaSize_m == 8)
{
driveRpm_m = 360;
rawSDBytesPerTrack_m = 6400;
}
else if (mediaSize_m == 5)
{
driveRpm_m = 300;
rawSDBytesPerTrack_m = 3200;
}
ticksPerRev_m = (ticksPerSec_m * 60) / driveRpm_m;
motor_m = (mediaSize_m == 8);
headLoaded_m = (mediaSize_m == 5);
}
GenericFloppyDrive*
GenericFloppyDrive::getInstance(std::string type)
{
unsigned int heads;
unsigned int tracks;
unsigned int mediaSize;
if (type.find("FDD_5_25") == 0)
{
mediaSize = 5;
if (type.find("ST") != std::string::npos)
{
tracks = 40;
}
else if (type.find("DT") != std::string::npos)
{
tracks = 80;
}
else
{
debugss(ssGenericFloppyDrive, ERROR, "number of tracks not specified\n");
return nullptr;
}
}
else if (type.find("FDD_8") == 0)
{
mediaSize = 8;
tracks = 77;
}
else
{
debugss(ssGenericFloppyDrive, ERROR, "disk size not specified\n");
return nullptr;
}
if (type.find("SS") != std::string::npos)
{
heads = 1;
}
else if (type.find("DS") != std::string::npos)
{
heads = 2;
}
else
{
debugss(ssGenericFloppyDrive, ERROR, "number of sides not specified\n");
return nullptr;
}
return new GenericFloppyDrive(heads, tracks, mediaSize);
}
GenericFloppyDrive::~GenericFloppyDrive()
{
}
void
GenericFloppyDrive::insertDisk(shared_ptr<GenericFloppyDisk> disk)
{
disk_m = disk;
if (disk_m)
{
disk_m->setDriveType(numTracks_m);
writeProtected_m = disk_m->checkWriteProtect();
}
else
{
writeProtected_m = false;
}
}
bool
GenericFloppyDrive::getTrackZero()
{
return (track_m == 0);
}
void
GenericFloppyDrive::step(bool direction)
{
if (direction)
{
if (track_m < numTracks_m - 1)
{
++track_m;
}
debugss(ssGenericFloppyDrive, INFO, "in(up) (%d)\n", track_m);
}
else
{
if (track_m > 0)
{
--track_m;
}
debugss(ssGenericFloppyDrive, INFO, "out(down) (%d)\n", track_m);
}
}
void
GenericFloppyDrive::selectSide(BYTE side)
{
debugss(ssGenericFloppyDrive, VERBOSE, "side: %d\n");
headSel_m = side % numHeads_m;
}
// negative data is "missing clock" detection.
int
GenericFloppyDrive::readData(bool dd,
BYTE track,
BYTE side,
BYTE sector,
int inSector)
{
int data = 0;
debugss(ssGenericFloppyDrive, INFO, "side:%d,track:%d,sector:%d,sector pos %d\n", side, track,
sector, inSector);
if (!disk_m)
{
debugss(ssGenericFloppyDrive, WARNING, "no Disk\n");
return GenericFloppyFormat::ERROR;
}
if (dd != disk_m->doubleDensity())
{
debugss(ssGenericFloppyDrive, WARNING, "DD mismatch(%d)\n", dd);
return GenericFloppyFormat::ERROR;
}
if (track_m != track || headSel_m != side)
{
debugss(ssGenericFloppyDrive, WARNING, "mismatch trk %d:%d sid %d:%d\n", track_m, track,
headSel_m, side);
}
// override FDC track/side with our own - it's the real one
if (disk_m->readData(track_m, headSel_m, sector, inSector, data))
{
debugss(ssGenericFloppyDrive, INFO,
"read passed - dd: %d, track: %d, sctor: %d, pos(%d) data(%d)\n", dd, track, sector,
inSector, data);
}
else
{
debugss(ssGenericFloppyDrive, WARNING, "readData failed\n");
}
return data;
}
int
GenericFloppyDrive::writeData(bool dd,
BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady)
{
int result = GenericFloppyFormat::NO_DATA;
if (!disk_m)
{
return GenericFloppyFormat::ERROR;
}
if (sector == 0xff)
{
if (!dd)
{
sector &= ~1;
}
}
else if (dd != disk_m->doubleDensity())
{
return GenericFloppyFormat::ERROR;
}
if ((track_m != track) || (headSel_m != side))
{
debugss(ssGenericFloppyDrive, ERROR, "track/head mismatch - track(%d - %d) head(%d - %d)\n",
track_m, track, headSel_m, side);
}
// override FDC track/side with our own - it's the real one
if (!disk_m->writeData(track_m, headSel_m, sector, inSector, data, dataReady, result))
{
debugss(ssGenericFloppyDrive, INFO, "write failed - pos(%d) data(%d)\n",
inSector, data);
}
return result;
}
void
GenericFloppyDrive::notification(unsigned int cycleCount)
{
if (disk_m == nullptr || !motor_m)
{
return;
}
cycleCount_m += cycleCount;
cycleCount_m %= ticksPerRev_m;
// TODO: what is appropriate width of index pulse?
// TODO - this should be pushed down to the floppy disk
// indexPulse_m = (cycleCount_m < 100); // approx 50uS...
indexPulse_m = (cycleCount_m < 2000); // approx 50uS...
}
unsigned long
GenericFloppyDrive::getCharPos(bool doubleDensity)
{
// if disk_m == nullptr || !motor_m then cycleCount_m won't be updating
// and so CharPos also does not update. Callers checks this.
unsigned long bytes = rawSDBytesPerTrack_m;
if (doubleDensity)
{
bytes *= 2;
}
unsigned long ticksPerByte = ticksPerRev_m / bytes;
return (cycleCount_m / ticksPerByte);
}
bool
GenericFloppyDrive::readAddress(int& trackNum,
int& sectorNum,
int& sideNum)
{
if (disk_m == nullptr || !motor_m)
{
debugss(ssGenericFloppyDrive, ERROR, "drive or motor not set %d:%d\n", disk_m == nullptr,
motor_m);
return false;
}
// consult media to see if it knows.
trackNum = disk_m->getRealTrackNumber(track_m);
sectorNum = 0; // TODO: use charPos and media to approximate
sideNum = headSel_m;
return true;
}
bool
GenericFloppyDrive::verifyTrackSector(BYTE trackNum,
BYTE sectorNum)
{
if (disk_m == nullptr || !motor_m)
{
debugss(ssGenericFloppyDrive, ERROR, "drive or motor not set %d:%d\n", disk_m == nullptr,
motor_m);
return false;
}
BYTE realTrackNum = disk_m->getRealTrackNumber(track_m);
if (realTrackNum != trackNum)
{
debugss(ssGenericFloppyDrive, ERROR, "realTrack/track: %d:%d\n", realTrackNum, trackNum);
return false;
}
return disk_m->findSector(headSel_m, realTrackNum, sectorNum);
}
void
GenericFloppyDrive::headLoad(bool load)
{
if (mediaSize_m == 8)
{
headLoaded_m = load;
}
}
void
GenericFloppyDrive::motor(bool on)
{
if (mediaSize_m == 5)
{
motor_m = on;
}
}
bool
GenericFloppyDrive::isReady()
{
return (disk_m != nullptr && disk_m->isReady());
}
bool
GenericFloppyDrive::isWriteProtect()
{
return (disk_m != nullptr && disk_m->checkWriteProtect());
}
std::string
GenericFloppyDrive::getMediaName()
{
return (disk_m != nullptr ? disk_m->getMediaName() : "");
}
void
GenericFloppyDrive::startTrackFormat(BYTE trackNum)
{
}
void
GenericFloppyDrive::getDriveStatus(bool& writeProtected,
bool& headLoaded,
bool& trackZero,
bool& indexPulse)
{
writeProtected = writeProtected_m;
headLoaded = headLoaded_m;
trackZero = (track_m == 0);
indexPulse = indexPulse_m;
}
<file_sep>/VirtualH89/Src/VirtualH89Frame.cpp
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: VirtualH89Frame.cpp
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 17:02:50 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include <wx/image.h>
#include <bitset>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "H19TextFrame.h"
////@end includes
#include "VirtualH89Frame.h"
#include "AboutVirtualH89.h"
#include "GUIwxWidgets.h"
////@begin XPM images
////@end XPM images
/*
* VirtualH89Frame type definition
*/
IMPLEMENT_CLASS( VirtualH89Frame, wxFrame )
/*
* VirtualH89Frame event table definition
*/
BEGIN_EVENT_TABLE( VirtualH89Frame, wxFrame )
////@begin VirtualH89Frame event table entries
EVT_MENU( ID_MENUITEM_FileExit, VirtualH89Frame::OnMENUITEMFileExitClick )
EVT_MENU( ID_MENUITEM_HelpAbout, VirtualH89Frame::OnMENUITEMHelpAboutClick )
////@end VirtualH89Frame event table entries
END_EVENT_TABLE()
VirtualH89Frame *TheFrame = nullptr;
int VirtualH89main(int argc, char* argv[]);
GUIwxWidgets *TheGUIwxWidgets = nullptr;
std::vector<wxBitmap> FontBitmaps;
/*
* VirtualH89Frame constructors
*/
VirtualH89Frame::VirtualH89Frame()
{
Init();
}
VirtualH89Frame::VirtualH89Frame( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create( parent, id, caption, pos, size, style );
}
/*
* VirtualH89Frame creator
*/
bool VirtualH89Frame::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin VirtualH89Frame creation
wxFrame::Create( parent, id, caption, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end VirtualH89Frame creation
return true;
}
/*
* VirtualH89Frame destructor
*/
VirtualH89Frame::~VirtualH89Frame()
{
////@begin VirtualH89Frame destruction
////@end VirtualH89Frame destruction
}
/*
* Member initialisation
*/
void VirtualH89Frame::Init()
{
////@begin VirtualH89Frame member initialisation
m_H19TextFrame = NULL;
////@end VirtualH89Frame member initialisation
}
/*
* Control creation for VirtualH89Frame
*/
void VirtualH89Frame::CreateControls()
{
////@begin VirtualH89Frame content construction
VirtualH89Frame* itemFrame1 = this;
wxMenuBar* menuBar = new wxMenuBar;
wxMenu* itemMenu3 = new wxMenu;
itemMenu3->Append(ID_MENUITEM_FileExit, _("E&xit"), wxEmptyString, wxITEM_NORMAL);
menuBar->Append(itemMenu3, _("&File"));
wxMenu* itemMenu5 = new wxMenu;
itemMenu5->Append(ID_MENUITEM_ViewConfig, _("&Config"), wxEmptyString, wxITEM_NORMAL);
itemMenu5->Enable(ID_MENUITEM_ViewConfig, false);
menuBar->Append(itemMenu5, _("View"));
wxMenu* itemMenu7 = new wxMenu;
itemMenu7->Append(ID_MENUITEM_HelpAbout, _("About"), wxEmptyString, wxITEM_NORMAL);
menuBar->Append(itemMenu7, _("Help"));
itemFrame1->SetMenuBar(menuBar);
wxBoxSizer* itemBoxSizer9 = new wxBoxSizer(wxVERTICAL);
itemFrame1->SetSizer(itemBoxSizer9);
m_H19TextFrame = new H19TextFrame( itemFrame1, ID_SCROLLEDWINDOW_H19Text, wxDefaultPosition, wxSize(640, 480), wxSUNKEN_BORDER );
m_H19TextFrame->SetForegroundColour(wxColour(255, 255, 255));
m_H19TextFrame->SetBackgroundColour(wxColour(0, 0, 0));
itemBoxSizer9->Add(m_H19TextFrame, 1, wxGROW|wxALL, 2);
////@end VirtualH89Frame content construction
// Create the VirtualH89/GUI interface engine for a wxWidgets engine
TheGUIwxWidgets = new GUIwxWidgets();
TheGUI = TheGUIwxWidgets;
// Make the frame visible to the GUI interface engine
TheFrame = this;
// Load the fonts into bitmaps.
wxImage CharImage(8, 20);
auto Pixels = CharImage.GetData();
std::bitset<8> CharBits;
for (auto Char = 0u; Char < 256u; ++Char)
{
const unsigned char *Line = fontTableForward + (Char * 20u);
for (auto y = 0u; y < 20u; ++y)
{
CharBits = Line[y];
for (auto x = 0u; x < 8u; ++x)
{
auto Index = 3u * ((y * 8u) + x);
auto Color = CharBits[7u - x] ? 255u : 0u;
Pixels[Index++] = Color; // Red
Pixels[Index++] = Color; // Green
Pixels[Index++] = 0u; // Blue
}
}
FontBitmaps.push_back(wxBitmap(CharImage));
}
// Start VirtualH89 main program.
VirtualH89main(wxApp::GetInstance()->argc, wxApp::GetInstance()->argv);
return;
}
/*
* Should we show tooltips?
*/
bool VirtualH89Frame::ShowToolTips()
{
return true;
}
/*
* Get bitmap resources
*/
wxBitmap VirtualH89Frame::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin VirtualH89Frame bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end VirtualH89Frame bitmap retrieval
}
/*
* Get icon resources
*/
wxIcon VirtualH89Frame::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin VirtualH89Frame icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end VirtualH89Frame icon retrieval
}
/*
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_HelpAbout
*/
void VirtualH89Frame::OnMENUITEMHelpAboutClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_HelpAbout in VirtualH89Frame.
// Before editing this code, remove the block markers.
event.Skip();
////@end wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_HelpAbout in VirtualH89Frame.
AboutVirtualH89 *AboutDialog = new AboutVirtualH89(this);
AboutDialog->ShowModal();
AboutDialog->Destroy();
return;
}
/*
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_FileExit
*/
void VirtualH89Frame::OnMENUITEMFileExitClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_FileExit in VirtualH89Frame.
// Before editing this code, remove the block markers.
event.Skip();
////@end wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM_FileExit in VirtualH89Frame.
Close();
return;
}
#endif
<file_sep>/VirtualH89/Src/ParallelPortConnection.cpp
///
/// \name ParallelPortConnection.cpp
///
///
/// \date Aug 17, 2013
/// \author <NAME>
///
#include "ParallelPortConnection.h"
#include "logger.h"
ParallelPortConnection::ParallelPortConnection(): link_m(0)
{
}
ParallelPortConnection::~ParallelPortConnection()
{
}
void
ParallelPortConnection::connectLink(ParallelLink* link)
{
debugss(ssParallel, INFO, "Entering\n");
if (link_m)
{
debugss(ssParallel, ERROR, "Link already in use\n");
}
link_m = link;
}
<file_sep>/VirtualH89/Src/mms77320.cpp
/// \file mms77320.cpp
///
/// Implementation of the MMS 77320 SASI adapter.
///
/// \date Feb 13, 2016
/// \author <NAME>
///
#include "mms77320.h"
#include "logger.h"
#include "H89.h"
#include "GenericSASIDrive.h"
/// \cond
#include <string.h>
/// \endcond
const char* MMS77320::MMS77320_Name_c = "MMS77320";
GenericSASIDrive*
MMS77320::getCurDrive()
{
// This could be NULL
return drives_m[control1Reg_m & ctrl_DriveSel_c];
}
MMS77320::MMS77320(int baseAddr,
int intLevel,
int switches): DiskController(baseAddr, MMS77320_NumPorts_c),
dataOutReg_m(0),
dataInReg_m(0),
control0Reg_m(0),
control1Reg_m(-1),
statusReg_m(0),
switchReg_m(switches),
ctrlBus_m(0),
curDrive_m(nullptr),
intLevel_m(intLevel)
{
for (int x = 0; x < numDisks_c; ++x)
{
drives_m[x] = nullptr;
}
}
std::vector<GenericDiskDrive*>
MMS77320::getDiskDrives()
{
// No removable drives (?) so nothing returned here...
std::vector<GenericDiskDrive*> drives;
// TODO: handle removeable drives, and return those here...
#if 0
for (int x = 0; x < numDisks_c; ++x)
{
drives.push_back(drives_m[x]); // might be null, but must preserve number.
}
#endif
return drives;
}
std::string
MMS77320::getDriveName(int index)
{
if (index < 0 || index >= numDisks_c)
{
return nullptr;
}
char buf[32];
sprintf(buf, "%s-%d", MMS77320_Name_c, index + 1);
std::string str(buf);
return str;
}
GenericDiskDrive*
MMS77320::findDrive(std::string ident)
{
if (ident.find(MMS77320_Name_c) != 0 || ident[strlen(MMS77320_Name_c)] != '-')
{
return nullptr;
}
char* e;
unsigned long x = strtoul(ident.c_str() + strlen(MMS77320_Name_c) + 1, &e, 10);
if (*e != '\0' || x == 0 || x > numDisks_c)
{
return nullptr;
}
return drives_m[x - 1];
}
MMS77320*
MMS77320::install_MMS77320(PropertyUtil::PropertyMapT& props,
std::string slot)
{
std::map<int, GenericSASIDrive*> mmsdrives;
std::string s;
int port = 0x78;
unsigned int sw = 0;
int intr = 0;
std::string dir = "";
// TODO: just look at sw501 and make it match?
// BYTE sw = h89.getIO().in(0xf2);
// if ((sw & 0x03) == 0x02) port = 0x7c;
// else if ((sw & 0x0c) == 0x08) port = 0x78;
// Technically, the user must both strap the card and set SW501 appropriately.
s = props["mms77320_port"];
if (s.compare("jp1a") == 0)
{
port &= ~0x04;
}
else if (s.compare("jp1b") == 0)
{
port |= 0x04;
}
s = props["mms77320_intr"];
if (s.compare("jp2a") == 0)
{
intr = 3;
}
else if (s.compare("jp2b") == 0)
{
intr = 4;
}
else if (s.compare("jp2c") == 0)
{
intr = 5;
}
s = props["mms77320_dipsw"];
if (!s.empty())
{
sw = (unsigned int) strtoul(s.c_str(), nullptr, 2);
}
dir = props["mms77320_dir"];
MMS77320* m320 = new MMS77320(port, intr, sw);
// First identify what drives are installed.
for (int x = 0; x < numDisks_c; ++x)
{
std::string prop = "mms77320_drive";
std::string media = dir + "/" + MMS77320_Name_c + "-";
media += ('0' + x);
prop += ('0' + x);
s = props[prop];
if (!s.empty())
{
// TODO: handle removable media case...
m320->connectDrive(x, GenericSASIDrive::getInstance(s, media, x));
}
}
debugss(ssMMS77320, ERROR, "MMS77320 at port %02x INT%d\n", port, intr);
return m320;
}
MMS77320::~MMS77320()
{
for (int x = 0; x < numDisks_c; ++x)
{
if (drives_m[x] != nullptr)
{
delete drives_m[x];
drives_m[x] = nullptr;
}
}
}
void
MMS77320::reset(void)
{
dataOutReg_m = 0;
dataInReg_m = 0;
control0Reg_m = 0;
control1Reg_m = -1;
statusReg_m = 0;
ctrlBus_m = 0;
curDrive_m = nullptr;
h89.lowerINT(intLevel_m);
// TODO: reset all drives?
}
BYTE
MMS77320::in(BYTE addr)
{
BYTE offset = getPortOffset(addr);
BYTE val = 0;
debugss(ssMMS77320, ALL, "MMS77320::in(%d)\n", addr);
if (offset == DataPort_Offset_c)
{
val = dataInReg_m;
debugss(ssMMS77320, INFO, "MMS77320::in(DataPort) %02x\n", val);
if (curDrive_m != nullptr)
{
ctrlBus_m |= GenericSASIDrive::ctl_Ack_i_c;
curDrive_m->ack(dataInReg_m, dataOutReg_m, ctrlBus_m);
}
// TODO: side-effects?
}
else if (offset == StatusPort_Offset_c)
{
val = getStatus(ctrlBus_m);
debugss(ssMMS77320, INFO, "MMS77320::in(StatusPort) %02x %s %s %s %s %s\n", val,
(val & sts_Msg_c) ? "MSG" : " ",
(val & sts_Req_c) ? "REQ" : " ",
(val & sts_Cmd_c) ? "CMD" : " ",
(val & sts_POut_c) ? "OUT" : " ",
(val & sts_Busy_c) ? "BSY" : " "
);
lowerIntrq();
// TODO; other side-effects?
}
else
{
debugss(ssMMS77320, ERROR, "MMS77320::in(Unknown - 0x%02x)\n", addr);
}
debugss_nts(ssMMS77320, INFO, " - %d(0x%x)\n", val, val);
return (val);
}
BYTE
MMS77320::getStatus(BYTE ctl)
{
BYTE status = 0;
if (ctl & GenericSASIDrive::ctl_Req_o_c)
{
status |= sts_Req_c;
}
if (ctl & GenericSASIDrive::ctl_Out_o_c)
{
status |= sts_POut_c;
}
if (ctl & GenericSASIDrive::ctl_Msg_o_c)
{
status |= sts_Msg_c;
}
if (ctl & GenericSASIDrive::ctl_Cmd_o_c)
{
status |= sts_Cmd_c;
}
if (ctl & GenericSASIDrive::ctl_Busy_o_c)
{
status |= sts_Busy_c;
}
if (ctl & GenericSASIDrive::ctl_Ack_i_c)
{
status |= sts_Ack_c;
}
// debugss(ssMMS77320, INFO, "raw getStatus %02x (ctl: %02x)\n", status, ctl);
// TODO: get ACTINT bit...
// return ~status; // or (status ^ 0xf8)...
return status;
}
void
MMS77320::out(BYTE addr,
BYTE val)
{
BYTE offset = getPortOffset(addr);
debugss(ssMMS77320, ALL, "MMS77320::out(%d, %d (0x%x))\n", addr, val, val);
if (offset == DataPort_Offset_c)
{
debugss(ssMMS77320, INFO, "MMS77320::out(DataPort) %02x\n", val);
dataOutReg_m = val;
if (curDrive_m != nullptr)
{
ctrlBus_m |= GenericSASIDrive::ctl_Ack_i_c;
curDrive_m->ack(dataInReg_m, dataOutReg_m, ctrlBus_m);
}
}
else if (offset == Control1Port_Offset_c)
{
val &= 0x0f;
debugss(ssMMS77320, INFO, "MMS77320::out(Control1Port) %02x\n", val);
bool diff = ((control1Reg_m ^ val) & ctrl_DriveSel_c) != 0;
control1Reg_m = val;
if (diff)
{
if (curDrive_m != nullptr)
{
// anything to do to de-select drive?
curDrive_m->deselect(dataInReg_m, dataOutReg_m, ctrlBus_m);
}
curDrive_m = drives_m[control1Reg_m & ctrl_DriveSel_c];
// anything else to do to select new drive?
// actual SELECT is done later, on Control0Port_Offset_c...
}
}
else if (offset == Control0Port_Offset_c)
{
val &= 0xf0;
int diffs = (control0Reg_m ^ val);
debugss(ssMMS77320, INFO, "MMS77320::out(Control0Port) %02x [%02x] (%s)\n", val, diffs,
curDrive_m != nullptr ? "OK" : "null");
control0Reg_m = val;
if (diffs && curDrive_m != nullptr)
{
if (control0Reg_m == 0)
{
ctrlBus_m &= ~GenericSASIDrive::ctl_Sel_i_c;
ctrlBus_m &= ~GenericSASIDrive::ctl_Reset_i_c;
curDrive_m->run(dataInReg_m, dataOutReg_m, ctrlBus_m);
}
else if (control0Reg_m & ctrl_ResetStart_c)
{
debugss(ssMMS77320, INFO, "RESET SASI\n");
ctrlBus_m |= GenericSASIDrive::ctl_Reset_i_c;
curDrive_m->resetSASI(dataInReg_m, dataOutReg_m, ctrlBus_m);
}
else if (control0Reg_m & ctrl_Select_c)
{
BYTE temp = (1 << (control1Reg_m & ctrl_DriveSel_c));
ctrlBus_m |= GenericSASIDrive::ctl_Sel_i_c;
curDrive_m->select(dataInReg_m, temp, ctrlBus_m);
}
}
}
else
{
debugss(ssMMS77320, ERROR, "MMS77320::out(Unknown - 0x%02x): %d\n", addr, val);
}
}
GenericSASIDrive*
MMS77320::getDrive(BYTE unitNum)
{
if (unitNum < numDisks_c)
{
return drives_m[unitNum];
}
return nullptr;
}
bool
MMS77320::connectDrive(BYTE unitNum,
GenericSASIDrive* drive)
{
bool retVal = false;
debugss(ssMMS77320, INFO, "unit (%d), drive (%p)\n", unitNum, drive);
if (unitNum < numDisks_c)
{
if (drives_m[unitNum] == nullptr)
{
drives_m[unitNum] = drive;
retVal = true;
}
else
{
debugss(ssMMS77320, ERROR, "drive already connect\n");
}
}
else
{
debugss(ssMMS77320, ERROR, "Invalid unit number (%d)\n", unitNum);
}
return (retVal);
}
bool
MMS77320::removeDrive(BYTE unitNum)
{
return (false);
}
void
MMS77320::raiseIntrq()
{
debugss(ssMMS77320, INFO, "\n");
if (intrqAllowed())
{
h89.raiseINT(intLevel_m);
h89.continueCPU();
return;
}
}
void
MMS77320::lowerIntrq()
{
debugss(ssMMS77320, INFO, "\n");
h89.lowerINT(intLevel_m);
}
std::string
MMS77320::dumpDebug()
{
std::string ret = PropertyUtil::sprintf(
"CTRL-0=%02x CTRL-1=%02x\n"
"DAT-IN=%02x DAT-OUT=%02x\n"
"STATUS=%02x\n",
control0Reg_m, control1Reg_m,
dataInReg_m, dataOutReg_m,
getStatus(ctrlBus_m));
return ret;
}
<file_sep>/VirtualH89/Src/MMS77318MemoryDecoder.cpp
///
/// \file MMS77318MemoryDecoder.cpp
///
/// Implementation of the MMS 77318 128K add-on RAM card and
/// associated decoder modification.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#include "MMS77318MemoryDecoder.h"
#include "MemoryLayout.h"
#include "RAMemory8K.h"
#include "SystemMemory8K.h"
#include "logger.h"
using namespace std;
const BYTE MMS77318MemoryDecoder::lockSeq[6] = {
0b00000100,
0b00001100,
0b00000100,
0b00001000,
0b00001100,
0b00001000
};
MMS77318MemoryDecoder::MMS77318MemoryDecoder(systemMem_ptr systemMemory): MemoryDecoder(8,
h89_gppWatchedBits_c)
{
int x;
Memory8K_ptr rd6[8];
Memory8K_ptr rd7[8];
for (x = 0; x < 8; x++)
{
rd6[x] = make_shared<RAMemory8K>(x << 13);
rd7[x] = make_shared<RAMemory8K>(x << 13);
}
// 0: RESET state, ROM at 0x0000
MemoryLayout_ptr h89_0 = make_shared<MemoryLayout>();
h89_0->addPage(systemMemory);
// add 48k of memory starting at 8k upto 56k
for (x = 1; x < 7; x++)
{
h89_0->addPage(make_shared<RAMemory8K>(x << 13));
}
// save the 48k -> 56k bank for later
shared_ptr<Memory8K> ras2_1 = h89_0->getPage(6);
h89_0->addPage(rd6[6]);
h89_0->addPage(rd6[7]);
addLayout(0, h89_0);
// 1: CP/M state, 64K RAM
MemoryLayout_ptr h89_1 = make_shared<MemoryLayout>();
h89_1->addPageAt(ras2_1, 0x0000);
for (x = 1; x < 8; ++x)
{
h89_1->addPage(h89_0->getPage(x));
}
addLayout(1, h89_1);
// MMS 77318 additional layouts:
// 2,3: Hi 56K always main, low 8K bank switched (HDOS)
MemoryLayout_ptr hdos56k_1 = make_shared<MemoryLayout>();
MemoryLayout_ptr hdos56k_2 = make_shared<MemoryLayout>();
hdos56k_1->addPage(rd7[0]);
hdos56k_2->addPage(rd6[0]);
for (x = 1; x < 8; ++x)
{
hdos56k_1->addPage(h89_1->getPage(x));
hdos56k_2->addPage(h89_1->getPage(x));
}
addLayout(2, hdos56k_1);
addLayout(3, hdos56k_2);
// 4,5: Hi 16K always main, low 48K bank switched
MemoryLayout_ptr cpm64k_16k_1 = make_shared<MemoryLayout>();
MemoryLayout_ptr cpm64k_16k_2 = make_shared<MemoryLayout>();
for (x = 0; x < 6; ++x)
{
cpm64k_16k_1->addPage(rd7[x]);
cpm64k_16k_2->addPage(rd6[x]);
}
for (; x < 8; ++x)
{
cpm64k_16k_1->addPage(h89_1->getPage(x));
cpm64k_16k_2->addPage(h89_1->getPage(x));
}
addLayout(4, cpm64k_16k_1);
addLayout(5, cpm64k_16k_2);
// 6,7: Hi 8K always main, low 56K bank switched
MemoryLayout_ptr cpm64k_8k_1 = make_shared<MemoryLayout>();
MemoryLayout_ptr cpm64k_8k_2 = make_shared<MemoryLayout>();
for (x = 0; x < 7; ++x)
{
cpm64k_8k_1->addPage(rd7[x]);
cpm64k_8k_2->addPage(rd6[x]);
}
cpm64k_8k_1->addPage(rd7[6]);
cpm64k_8k_1->addPage(h89_1->getPage(7));
cpm64k_8k_2->addPageAt(rd7[7], 0xc000);
cpm64k_8k_2->addPage(h89_1->getPage(7));
addLayout(6, cpm64k_8k_1);
addLayout(7, cpm64k_8k_2);
lockState = 1;
updateCurLayout(0);
}
MMS77318MemoryDecoder::~MMS77318MemoryDecoder()
{
}
void
MMS77318MemoryDecoder::reset()
{
MemoryDecoder::reset();
interestedBits_m = h89_gppWatchedBits_c;
lockState = 1;
}
void
MMS77318MemoryDecoder::gppNewValue(BYTE gpo)
{
debugss(ssAddressBus, INFO, "MMS77318 gpio %02x lock state %d\n", gpo, lockState);
int bnk = (gpo & h89_gppBnkSelBit0_c) ? 0x01 : 0; // LSB - a.k.a. GPIO5
if (lockState == 0)
{
bnk |= (gpo & h89_gppBnkSelBit1_c) ? 0x02 : 0; // middle bit
bnk |= (gpo & h89_gppBnkSelBit2_c) ? 0x04 : 0; // MSB
}
else
{
if ((gpo & h89_gppUnlockBits_c) == lockSeq[lockState])
{
++lockState;
debugss(ssAddressBus, INFO, "MMS77318 lock state %d\n", lockState);
if (lockState >= sizeof(lockSeq))
{
debugss(ssAddressBus, ERROR, "MMS77318 unlocked\n");
lockState = 0;
interestedBits_m = h89_gppBnkSelBits_c;
}
}
else
{
lockState = 1;
}
}
updateCurLayout(bnk);
}
<file_sep>/VirtualH89/Src/StdioProxyConsole.cpp
/// \file StdioProxyConsole.cpp
///
/// A console replacement that supports an external process as the H19.
/// Also supports a out-of-band channel for command/control messages.
/// Uses the process stdin and stout for communication with the virtual H19.
/// H19 traffic has the high bit set, while oob traffic has the high bit clear.
/// Thus, only 7-bit ASSCII is supported for each channel.
///
/// \date Feb 6, 2016
/// \author <NAME>
///
#include "StdioProxyConsole.h"
#include "H89.h"
#include "h89-io.h"
#include "logger.h"
#include "H89Operator.h"
/// \cond
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <sstream>
/// \endcond
extern const char* getopts;
/// \brief StdioProxyConsole
///
///
StdioProxyConsole::StdioProxyConsole(int argc,
char** argv):
Console(argc, argv),
logConsole(false)
{
int c;
extern char* optarg;
extern int optind;
// TODO: properly share getopt string so both main and this
// (and other modules) can ignore eachother's options...
optind = 1;
while ((c = getopt(argc, argv, getopts)) != EOF)
{
switch (c)
{
case 'l':
logConsole = true;
break;
}
}
op_m = new H89Operator();
}
StdioProxyConsole::~StdioProxyConsole() {
}
void
StdioProxyConsole::init() {
}
void
StdioProxyConsole::reset() {
}
void
StdioProxyConsole::display() {
}
void
StdioProxyConsole::processCharacter(char ch) {
}
void
StdioProxyConsole::keypress(char ch)
{
// try not to overrun the UART, but do not wait too long.
int timeout = 4000;
int sleep = 100;
while (!sendReady() && timeout > 0)
{
usleep(sleep);
timeout -= sleep;
}
sendData(ch);
}
void
StdioProxyConsole::receiveData(BYTE ch)
{
fputc(ch | 0x80, stdout);
fflush(stdout);
if (logConsole)
{
fputc(ch, console_out);
if (ch == '\n')
{
fflush(console_out);
}
}
}
bool
StdioProxyConsole::checkUpdated()
{
return false;
}
unsigned int
StdioProxyConsole::getBaudRate()
{
return SerialPortDevice::DISABLE_BAUD_CHECK;
}
void
StdioProxyConsole::run()
{
static char buf[1024];
int x = 0;
int c;
// setbuf(stdin, nullptr);
while ((c = fgetc(stdin)) != EOF)
{
if ((c & 0x80) != 0)
{
c &= 0x7f;
keypress(c);
}
else if (c == 0x0a)
{
if (x >= sizeof(buf))
{
x = sizeof(buf) - 1;
}
buf[x] = '\0';
x = 0;
std::string resp = op_m->handleCommand(buf);
fputs(resp.c_str(), stdout);
fputc('\n', stdout);
fflush(stdout);
}
else
{
if (x < sizeof(buf))
{
buf[x++] = c;
}
}
}
}
<file_sep>/VirtualH89/Src/h89-io.h
/// \file h89-io.h
///
/// \brief Interfaces between the CPU and all the I/O devices
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#ifndef H89_IO_H_
#define H89_IO_H_
#include "IOBus.h"
/// \cond
#include <vector>
/// \endcond
class IODevice;
class DiskController;
///
/// \brief %H89 IO Bus
///
/// Interfaces between the CPU and all the I/O devices
///
///
class H89_IO: public IOBus
{
public:
H89_IO();
virtual ~H89_IO() override;
std::vector<DiskController*>& getDiskDevices();
virtual bool addDiskDevice(DiskController* device);
private:
std::vector<DiskController*> dsk_devs;
};
#endif // H89_IO_H_
<file_sep>/VirtualH89/Src/H19TextFrame.h
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: H19TextFrame.h
// Purpose:
// Author:
// Modified by:
// Created: Sun 23 Apr 2017 06:59:01 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _H19TEXTFRAME_H_
#define _H19TEXTFRAME_H_
/*!
* Includes
*/
////@begin includes
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
class H19TextFrame;
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_SCROLLEDWINDOW_H19Text 10005
#define SYMBOL_H19TEXTFRAME_STYLE wxSUNKEN_BORDER
#define SYMBOL_H19TEXTFRAME_IDNAME ID_SCROLLEDWINDOW_H19Text
#define SYMBOL_H19TEXTFRAME_SIZE wxSize(640, 480)
#define SYMBOL_H19TEXTFRAME_POSITION wxDefaultPosition
////@end control identifiers
/*!
* H19TextFrame class declaration
*/
class H19TextFrame: public wxScrolledWindow
{
DECLARE_DYNAMIC_CLASS( H19TextFrame )
DECLARE_EVENT_TABLE()
public:
/// Constructors
H19TextFrame();
H19TextFrame(wxWindow* parent, wxWindowID id = ID_SCROLLEDWINDOW_H19Text, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(640, 480), long style = wxSUNKEN_BORDER);
/// Creation
bool Create(wxWindow* parent, wxWindowID id = ID_SCROLLEDWINDOW_H19Text, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(640, 480), long style = wxSUNKEN_BORDER);
/// Destructor
~H19TextFrame();
/// Initialises member variables
void Init();
/// Creates the controls and sizers
void CreateControls();
////@begin H19TextFrame event handler declarations
/// wxEVT_PAINT event handler for ID_SCROLLEDWINDOW_H19Text
void OnPaint( wxPaintEvent& event );
/// wxEVT_CHAR event handler for ID_SCROLLEDWINDOW_H19Text
void OnChar( wxKeyEvent& event );
////@end H19TextFrame event handler declarations
////@begin H19TextFrame member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end H19TextFrame member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin H19TextFrame member variables
////@end H19TextFrame member variables
};
#endif
// _H19TEXTFRAME_H_
#endif
<file_sep>/VirtualH89/Src/h17.cpp
///
/// \file h17.cpp
///
/// \brief Implements the hard-sectored disk controller - H-88-1
///
/// \date Apr 18, 2009
/// \author <NAME>
///
#include "h17.h"
#include "H89.h"
#include "logger.h"
#include "WallClock.h"
#include "DiskDrive.h"
#include "HardSectoredDisk.h"
using namespace std;
H17::H17(int baseAddr): DiskController(baseAddr, H17_NumPorts_c),
GppListener(h17_gppSideSelectBit_c),
state_m(idleState),
spinCycles_m(0),
curCharPos_m(0),
motorOn_m(false),
writeGate_m(false),
direction_m(false),
syncCharacterReceived_m(false),
receiveDataAvail_m(false),
receiverOverrun_m(false),
fillCharTransmitted_m(false),
transmitterBufferEmpty_m(true),
receiverOutputRegister_m(0),
transmitterHoldingRegister_m(0),
curDrive_m(maxDiskDrive_c),
fillChar_m(0),
syncChar_m(0xfd)
{
for (int i = 0; i < maxDiskDrive_c; ++i)
{
drives_m[i] = nullptr;
}
GppListener::addListener(this);
}
H17::~H17()
{
for (BYTE i = 0; i < maxDiskDrive_c; ++i)
{
if (drives_m[i])
{
std::string diskName = "h17_saveDisk";
diskName += ('0' + i + 1);
diskName += ".rawdisk";
drives_m[i]->ejectDisk(diskName.c_str());
}
}
}
H17*
H17::install_H17(BYTE baseAddr,
PropertyUtil::PropertyMapT& props,
std::string slot)
{
std::string s;
H17* h17 = new H17(baseAddr);
debugss(ssH17, INFO, "entering\n");
for (BYTE i = 0; i < maxDiskDrive_c; ++i)
{
std::string prop = "h17_drive";
prop += ('0' + i + 1);
s = props[prop];
if (!s.empty())
{
shared_ptr<DiskDrive> drive = DiskDrive::getInstance(s);
if (drive)
{
h17->connectDrive(i, drive);
prop = "h17_disk";
prop += ('0' + i + 1);
s = props[prop];
if (!s.empty())
{
shared_ptr<HardSectoredDisk> disk = make_shared<HardSectoredDisk>(s.c_str());
drive->insertDisk(disk);
}
}
}
}
return h17;
}
void
H17::gppNewValue(BYTE gpo)
{
selectSide((gpo & h17_gppSideSelectBit_c) ? 1 : 0);
}
BYTE
H17::in(BYTE addr)
{
BYTE val = 0;
BYTE offset = getPortOffset(addr);
switch (offset)
{
case DataPortOffset_c:
/// \todo determine if checking receiveDataAvail_m should be done.
val = receiverOutputRegister_m;
receiveDataAvail_m = false;
debugss(ssH17, INFO, " h17.in(Data) - 0x%02x\n", val);
break;
case StatusPortOffset_c:
if (transmitterBufferEmpty_m)
{
val |= TransmitterBufferEmpty_Flag;
}
if (fillCharTransmitted_m)
{
val |= FillCharTransmitted_Flag;
fillCharTransmitted_m = false;
}
if (receiverOverrun_m)
{
// \todo determine flag should be set to false after the read
val |= ReceiverOverrun_Flag;
}
if (receiveDataAvail_m)
{
val |= ReceiveDataAvail_Flag;
}
debugss(ssH17, INFO, " h17.in(Status) - 0x%02x\n", val);
break;
case SyncPortOffset_c:
// SyncPort data terminates at the controller.
val = syncChar_m;
// Based on a comment in the monitor code.. reading the port sets the searching.
state_m = seekingSyncState;
syncCharacterReceived_m = false;
debugss(ssH17, INFO, " h17.in(Sync) - 0x%02x\n", val);
break;
case ControlPortOffset_c:
// Majority of ControlPort is related to the Disk Drive, only sync detect is specific
// to the controller.
if (curDrive_m < maxDiskDrive_c)
{
// get info from the drive - if no drive attached, the auto-detection will
// correctly detect no drive.
if (drives_m[curDrive_m])
{
bool hole, trackZero, writeProtect;
drives_m[curDrive_m]->getControlInfo(spinCycles_m / CPUCyclesPerByte_c,
hole, trackZero, writeProtect);
if (hole)
{
val |= H17::ctrlHoleDetect_Flag;
}
if (trackZero)
{
val |= H17::ctrlTrackZeroDetect_Flag;
}
if (writeProtect)
{
// disk is write protected.
val |= H17::ctrlWriteProtect_Flag;
}
}
else
{
debugss(ssH17, INFO, " h17.in(Control) - No drive [%d]\n", curDrive_m);
}
}
else
{
debugss(ssH17, INFO, " h17.in(Control) - Invalid drive [%d]\n", curDrive_m);
}
// Get the sync info directly from the controller.
if (syncCharacterReceived_m)
{
val |= ctrlSyncDetect_Flag;
syncCharacterReceived_m = false;
}
debugss(ssH17, INFO, " h17.in(Control) - 0x%02x\n", val);
break;
default:
debugss(ssH17, ERROR, "h17.in(0x%02x) - invalid port\n", addr);
break;
}
return (val);
}
void
H17::out(BYTE addr,
BYTE val)
{
BYTE offset = getPortOffset(addr);
switch (offset)
{
case DataPortOffset_c:
debugss(ssH17, INFO, " h17.out(Data) - 0x%02x\n", val);
if (!(curDrive_m < maxDiskDrive_c))
{
debugss(ssH17, WARNING, " h17.out(Data) - No drive selected\n");
}
if (!transmitterBufferEmpty_m)
{
debugss(ssH17, ERROR, "Overwriting Transmitter Holding Register\n");
}
/// No error status to indicate that the THR was overwritten.
transmitterHoldingRegister_m = val;
transmitterBufferEmpty_m = false;
break;
case FillPortOffset_c:
debugss(ssH17, INFO, " h17.out(Fill) - 0x%02x\n", val);
fillChar_m = val;
break;
case SyncPortOffset_c:
debugss(ssH17, INFO, " h17.out(Sync) - 0x%02x\n", val);
syncChar_m = val;
break;
case ControlPortOffset_c:
debugss(ssH17, INFO, " h17.out(Control) -");
if (val & WriteGate_Ctrl)
{
debugss_nts(ssH17, INFO, " WR");
writeGate_m = true;
state_m = writingState;
}
else
{
writeGate_m = false;
state_m = idleState;
}
// On a real system, if multiple bits are set, multiple drives would respond to the
// request. On the virtual system, it will pick the first one to use. Selecting
// multiple bits is an error. With the right software, these 3 bits, could actually
// encode up to 7 drives (000 - would be invalid).
if (val & DriveSelect0_Ctrl)
{
debugss_nts(ssH17, INFO, " DS0");
curDrive_m = ds0;
}
else if (val & DriveSelect1_Ctrl)
{
debugss_nts(ssH17, INFO, " DS1");
curDrive_m = ds1;
}
else if (val & DriveSelect2_Ctrl)
{
debugss_nts(ssH17, INFO, " DS2");
curDrive_m = ds2;
}
else
{
debugss_nts(ssH17, INFO, " DS-");
curDrive_m = maxDiskDrive_c;
}
if (val & Direction_Ctrl) // Zero equals out.
{
debugss_nts(ssH17, INFO, " Dir-in");
direction_m = true;
}
else
{
debugss_nts(ssH17, INFO, " Dir-out");
direction_m = false;
}
if (val & MotorOn_Ctrl)
{
debugss_nts(ssH17, INFO, " MtrOn");
motorOn_m = true;
}
else
{
debugss_nts(ssH17, INFO, " MtrOff");
motorOn_m = false;
}
/// Need to terminate the debug status print, since the following bits call
/// other routines, which may also send output to the logger.
debugss_nts(ssH17, INFO, "\n");
/// \todo Determine what state the RAM is in on power-up, keep track here and only
/// notify when there is a change.
if (val & WriteEnableRAM_Ctrl)
{
h89.writeEnableH17RAM();
}
else
{
h89.writeProtectH17RAM();
}
if (val & StepCommand_Ctrl)
{
if ((curDrive_m < maxDiskDrive_c) && (drives_m[curDrive_m]))
{
drives_m[curDrive_m]->step(direction_m);
}
else
{
// all drives have been unselected...
debugss(ssH17, WARNING, " h17.out(Control) - step --No drive selected\n");
}
}
break;
default:
debugss(ssH17, ERROR, "h17.out(0x%02x, 0x%02x) - invalid port\n", addr, val);
break;
}
}
bool
H17::connectDrive(BYTE unitNum,
shared_ptr<DiskDrive> drive)
{
bool retVal = false;
debugss(ssH17, INFO, "unit (%d)\n", unitNum);
if (unitNum < maxDiskDrive_c)
{
if (drives_m[unitNum] == 0)
{
drives_m[unitNum] = drive;
retVal = true;
}
else
{
debugss(ssH17, ERROR, "drive already connect\n");
}
}
else
{
debugss(ssH17, ERROR, "Invalid unit number (%d)\n", unitNum);
}
return (retVal);
}
bool
H17::removeDrive(BYTE unitNum)
{
bool retVal = false;
debugss(ssH17, INFO, "unit (%d)\n", unitNum);
if (curDrive_m < maxDiskDrive_c)
{
if (drives_m[unitNum] != 0)
{
drives_m[unitNum] = 0;
retVal = true;
}
else
{
debugss(ssH17, WARNING, "no unit to remove (%d)\n", unitNum);
}
}
else
{
debugss(ssH17, ERROR, "Invalid unit number (%d)\n", unitNum);
}
return (retVal);
}
void
H17::selectSide(BYTE side)
{
for (int i = 0; i < maxDiskDrive_c; i++)
{
if (drives_m[i])
{
drives_m[i]->selectSide(side);
}
}
}
void
H17::notification(unsigned int cycleCount)
{
unsigned long charPos = 0;
BYTE data = 0;
if ((curDrive_m >= maxDiskDrive_c) || (!drives_m[curDrive_m]))
{
return;
}
spinCycles_m = (spinCycles_m + cycleCount) % (BytesPerTrack_c * CPUCyclesPerByte_c);
charPos = spinCycles_m / CPUCyclesPerByte_c;
if (charPos == curCharPos_m)
{
// Position hasn't changed just return
return;
}
debugss(ssH17, ALL, "New character Pos - old: %ld, new: %ld\n", curCharPos_m,
charPos);
curCharPos_m = charPos;
// handle the transmit buffer whether or not writing is going on, this is
// needed to handle drive detection.
// data variable will be used later if currently writing.
if (transmitterBufferEmpty_m)
{
data = fillChar_m;
fillCharTransmitted_m = true;
}
else
{
data = transmitterHoldingRegister_m;
transmitterBufferEmpty_m = true;
}
// if motor is not on, just bail.
if (!motorOn_m)
{
return;
}
switch (state_m)
{
case idleState:
debugss(ssH17, VERBOSE, "Idle State\n");
/// do nothing
break;
case seekingSyncState:
// check to see if character matches sync, -> set set sync found
// also load data buffer.
data = drives_m[curDrive_m]->readData(curCharPos_m);
debugss(ssH17, ALL, "Seeking Sync(disk: %d): %d\n", curDrive_m, data);
if (data == syncChar_m)
{
debugss(ssH17, INFO, "found sync\n");
receiverOutputRegister_m = data;
syncCharacterReceived_m = true;
receiveDataAvail_m = true; /// \todo determine if this should be set.
state_m = readingState;
}
break;
case readingState:
// determine if new character is to be moved into receive buffer,
// if so, determine if receive buffer is empty.
// if not, set ReceiverOverrun_Flag
// store new character in receiver buffer
//
if (receiveDataAvail_m)
{
/// \todo determine why this is coming out when idle - set back to info
debugss(ssH17, ALL, "Receiver Overrun\n");
// last data byte was not read, set overrun
receiverOverrun_m = true;
}
data = drives_m[curDrive_m]->readData(curCharPos_m);
debugss(ssH17, ALL, "Reading - Pos: %ld Data: %d\n", curCharPos_m, data);
receiverOutputRegister_m = data;
receiveDataAvail_m = true;
break;
case writingState:
drives_m[curDrive_m]->writeData(curCharPos_m, data);
break;
}
}
<file_sep>/VirtualH89/Src/h89-timer.cpp
/// \file h89-timer.cpp
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#include "h89-timer.h"
#include "computer.h"
#include "cpu.h"
#include "SignalHandler.h"
#include "WallClock.h"
#include "logger.h"
#include "config.h"
/// \cond
#include <sys/time.h>
#include <signal.h>
/// \endcond
static const int TimerInterval_c = 2000;
H89Timer::H89Timer(Computer* computer,
CPU* cpu,
unsigned char intlvl): GppListener(h89timer_gpp2msIntEnBit_c),
computer_m(computer),
cpu_m(cpu),
intEnabled_m(false),
count_m(0),
intLevel(intlvl),
thread(0)
{
// We need to start up the timer since it performs two tasks, it always provide the cpu
// with extra clock ticks to accurately emulate the speed of the processor.
// Plus, if interrupts are enabled, it will interrupt the cpu with the timer tick.
debugss(ssTimer, INFO, "\n");
SignalHandler::instance()->registerHandler(SIGALRM, this);
GppListener::addListener(this);
}
H89Timer::~H89Timer()
{
static struct itimerval tim;
debugss(ssTimer, INFO, "\n");
SignalHandler::instance()->removeHandler(SIGALRM);
tim.it_value.tv_sec = 0;
tim.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tim, nullptr);
}
void
H89Timer::reset()
{
intEnabled_m = false;
count_m = 0;
}
void
H89Timer::start()
{
static struct itimerval tim;
thread = pthread_self();
tim.it_value.tv_sec = 0;
tim.it_value.tv_usec = TimerInterval_c;
tim.it_interval.tv_sec = 0;
tim.it_interval.tv_usec = TimerInterval_c;
#if TEN_X_SLOWER
tim.it_value.tv_usec *= 20;
tim.it_interval.tv_usec *= 20;
#endif
setitimer(ITIMER_REAL, &tim, nullptr);
}
int
H89Timer::handleSignal(int signum)
{
debugss(ssTimer, ALL, "Timer Handle Signal\n");
if (signum != SIGALRM)
{
debugss(ssTimer, ERROR, "signum != SIGALRM: %d\n", signum);
return 0;
}
if (thread == 0)
{
// real thread is not set, can't do much else for now.
return 0;
}
if (thread != pthread_self())
{
// pass the signal to the correct thread.
pthread_kill(thread, SIGALRM);
return 0;
}
count_m++;
WallClock::instance()->addTimerEvent();
if (cpu_m)
{
debugss(ssTimer, VERBOSE, "adding clock ticks\n");
// must always give the CPU more cycles.
cpu_m->addClockTicks();
// Only if interrrupt is enabled.
if (intEnabled_m)
{
debugss(ssTimer, VERBOSE, "raising Interrupt\n");
computer_m->raiseINT(intLevel);
}
}
else
{
debugss(ssTimer, ERROR, "cpu_m is NULL\n");
}
return 0;
}
void
H89Timer::gppNewValue(BYTE gpo)
{
intEnabled_m = ((gpo & h89timer_gpp2msIntEnBit_c) != 0);
}
<file_sep>/VirtualH89/Src/H89.h
///
/// \file H89.h
///
/// \date Mar 8, 2009
/// \author <NAME>
///
/// \mainpage Virtual Heathkit H89 All-In-One Computer
///
/// The projects implements a virtual Heathkit H-89 Computer. Heath Company also
/// offered the same system without the floppy drive/controller as the H-88. The computer was
/// also sold under the Zenith Data Systems (ZDS) brand as the Z-89 and Z-90.
///
/// This system was sold by Heath Company and ZDS between 1979 and 1984.
///
/// Website for emulator: http://heathkit.garlanger.com/
///
#ifndef H89_H_
#define H89_H_
#include "computer.h"
#include "propertyutil.h"
/// \cond
#include <string>
#include <pthread.h>
#include <memory>
/// \endcond
// Forward declare classes to avoid a tangled mess of includes.
class ROM;
class AddressBus;
class Console;
class InterruptController;
class H89Timer;
class IOBus;
class H89_IO;
class NMIPort;
class GeneralPurposePort;
class INS8250;
class Z47Interface;
class Z47Controller;
class DiskDrive;
class CPU;
class Terminal;
class FloppyDisk;
class ParallelLink;
class SystemMemory8K;
///
/// \brief Virtual Heathkit %H89 Computer
///
/// Implements all the pieces of the H89 Computer.
///
class H89: public Computer
{
private:
AddressBus* ab;
InterruptController* interruptController;
H89Timer* timer;
H89_IO* h89io;
GeneralPurposePort* gpp;
INS8250* consolePort;
INS8250* lpPort;
INS8250* modemPort;
INS8250* auxPort;
Console* console;
Z47Interface* z47If;
Z47Controller* z47Cntrl;
ParallelLink* z47Link;
DiskDrive* driveUnitE0;
DiskDrive* driveUnitE1;
FloppyDisk* eight0;
FloppyDisk* eight1;
CPU* cpu;
std::shared_ptr<SystemMemory8K> sysMem;
/// Port Addresses
/// Base address for the H17 controller
/// Octal 174
static const BYTE H17_BaseAddress_c = 0x7c;
/// Base address for the H37 controller
/// Octal 170
static const BYTE H37_BaseAddress_c = 0x78;
/// Possible base addresses for the H47 controller
/// 0x78 - when in slot P504
static const BYTE Z47_BaseAddress_1_c = 0x78;
/// 0x7c - when in slot P506
static const BYTE Z47_BaseAddress_2_c = 0x7c;
/// Addresses for the serial ports (NOTE addresses are in OCTAL)
static const BYTE Serial_Console_c = 0350; // (0xe8)
static const BYTE Serial_Console_Interrupt_c = 3;
static const BYTE Serial_AuxPort_c = 0320; // (0xD0)
static const BYTE Serial_ModemPort_c = 0330; // (0xD8)
static const BYTE Serial_LpPort_c = 0340; // (0xE0)
/// Address for NMI Addresses, used to respond to H8 ports.
/// Octal 360-361 and 372-373
static const BYTE NMI_BaseAddress_1_c = 0xf0;
static const BYTE NMI_NumPorts_1_c = 2;
static const BYTE NMI_BaseAddress_2_c = 0xfa;
static const BYTE NMI_NumPorts_2_c = 2;
/// Address for GPP (General Purpose Port)
/// Octal 362
static const BYTE GPP_BaseAddress_c = 0xf2;
/// Frequency 2.048 MHz
static const unsigned long cpuClockRate_c = 2048000;
/// 2 mSec Interrupt
static const unsigned int clockInterruptPerSecond_c = 500;
pthread_mutex_t h89_mutex;
public:
H89();
virtual ~H89() override;
void buildSystem(Console* console, PropertyUtil::PropertyMapT props);
virtual void reset() override;
virtual BYTE run() override;
virtual void init() override;
virtual void keypress(BYTE ch) override;
virtual void display() override;
virtual void systemMutexAcquire() override;
virtual void systemMutexRelease() override;
virtual void raiseINT(int level) override;
virtual void lowerINT(int level) override;
virtual void raiseNMI(void) override;
virtual void continueCPU(void) override;
virtual void waitCPU(void) override;
std::string dumpDebug();
virtual void writeProtectH17RAM();
virtual void writeEnableH17RAM();
virtual H89_IO& getIO();
virtual AddressBus& getAddressBus() override;
virtual CPU& getCPU();
};
extern H89 h89;
#endif // H89_H_
<file_sep>/VirtualH89/Src/NMIPort.cpp
///
/// \name NMIPort.cpp
///
/// Some ports defined for the Heath H8 cause NMI to occur in the H89, this
/// allows the ROM program to handle those acesses as if the H89 is an H8.
///
/// \date Jul 15, 2012
/// \author <NAME>
///
#include "NMIPort.h"
#include "logger.h"
#include "cpu.h"
NMIPort::NMIPort(CPU* cpu,
BYTE base,
BYTE size): IODevice(base, size),
cpu_m(cpu)
{
}
NMIPort::~NMIPort()
{
}
BYTE
NMIPort::in(BYTE addr)
{
debugss(ssIO, INFO, "In: %d\n", addr);
cpu_m->raiseNMI();
/// \todo Determine the right value to return.
return (0xff);
}
void
NMIPort::out(BYTE addr,
BYTE val)
{
debugss(ssIO, INFO, "Out: %d\n", addr);
cpu_m->raiseNMI();
}
<file_sep>/VirtualH89/Src/logger.h
/// \file logger.h
///
/// \date May 6, 2009
/// \author <NAME>
///
#ifndef LOGGER_H_
#define LOGGER_H_
/// \cond
#include <cstdio>
/// \endcond
extern FILE* log_out;
extern FILE* console_out;
/// \todo - make the logger a separate thread.
/// \todo - have logger collapse repeated lines.
/// \todo - have logger create it's own file instead of being defined in main.h
class logger
{
public:
private:
logger();
~logger();
bool printToFile;
bool printToScreen;
FILE* logFile;
};
///
enum subSystems
{
ssH89,
ssMEM,
ssRAM,
ssROM,
ssZ80,
ssInterruptController,
ssH37InterruptController,
ssAddressBus,
ssIO,
ssH17,
ssH37,
ssH47,
ssH67,
ssDiskDrive,
ssH17_1,
ssH17_4,
ssH47Drive,
ssConsole,
ssH19,
ss8250,
ssSerial,
ssTimer,
ssWallClock,
ssFloppyDisk,
ssGpp,
ssParallel,
ssStdioConsole,
ssMMS77316,
ssWD1797,
ssGenericFloppyDrive,
ssRawFloppyImage,
ssMMS77320,
ssGenericSASIDrive,
ssHostFileBdos,
ssCPNetDevice,
ssSectorFloppyImage,
ssMax
};
///
/// Logging Levels
///
/// FATAL - can't be turned off if logging is enabled, an error condition that should not
/// occur.
/// ERROR - maskable errors
/// WARNING - warning that something is probably wrong
/// INFO - General info about object creation or other infrequent events.
/// VERBOSE - A large amount of logging, which may require slowing down the emulation speed
/// to not fall behind
/// ALL - Detailed logs that will generally generate MASSIVE amounts of logs, for example
/// in the ssZ80, this will enable per instruction dumping of all registers - on
/// the order of 500,000 logs per second. This will probably require running
/// at a greatly reduced speed, or on a very powerful system.
///
enum logLevel
{
FATAL = 0,
ERROR = 10,
WARNING = 20,
INFO = 30,
VERBOSE = 40,
ALL = 100
};
extern void __debugss(enum logLevel, const char* functionName, const char* fmt, ...);
extern void __debugss_nts(const char* fmt, ...);
#define debugss(subsys, level, args ...) \
if (level <= debugLevel[subsys]) \
{ \
__debugss(level, __PRETTY_FUNCTION__, args); \
}
#define debugss_nts(subsys, level, args ...) \
{ \
if (level <= debugLevel[subsys]) \
{ \
__debugss_nts(args); \
} \
}
#define chkdebuglevel(subsys, level) ((level <= debugLevel[subsys]))
extern unsigned debugLevel[ssMax];
void setDebugLevel();
void setDebug(subSystems ss,
logLevel level);
#endif // LOGGER_H_
<file_sep>/VirtualH89/Src/GenericFloppyDrive.h
/// \file GenericFloppyDrive.h
///
/// Implementation of a generic floppy disk drive, should be capable of
/// supporting any type of floppy drive, 8", 5.25", DS, DT, etc.
///
/// \date Feb 1, 2016
/// \author <NAME>
///
#ifndef GENERICFLOPPYDRIVE_H_
#define GENERICFLOPPYDRIVE_H_
#include "GenericDiskDrive.h"
#include "h89Types.h"
#include "ClockUser.h"
/// \cond
#include <memory>
/// \endcond
class GenericFloppyDisk;
///
/// \brief Virtual Generic Floppy Drive
///
/// Implements a virtual floppy disk drive. Supports 48/96 tpi 5.25",
/// 48 tpi 8", either can be SS or DS. Note, the media determines density.
///
class GenericFloppyDrive: public GenericDiskDrive, public ClockUser
{
public:
enum DriveType
{
FDD_5_25_SS_ST = 1,
FDD_5_25_SS_DT,
FDD_5_25_DS_ST,
FDD_5_25_DS_DT,
FDD_8_SS,
FDD_8_DS,
};
virtual ~GenericFloppyDrive() override;
static GenericFloppyDrive* getInstance(std::string type);
bool getTrackZero();
bool readAddress(int& trackNum,
int& sectorNum,
int& sideNum);
bool verifyTrackSector(BYTE trackNum,
BYTE sectorNum);
void step(bool direction);
void selectSide(BYTE side);
int readData(bool doubleDensity,
BYTE track,
BYTE side,
BYTE sector,
int inSector);
int writeData(bool doubleDensity,
BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady);
void insertDisk(std::shared_ptr<GenericFloppyDisk> disk) override;
void notification(unsigned int cycleCount) override;
unsigned long getCharPos(bool doubleDensity);
void headLoad(bool load); // Ignored on 5.25" drives?
void motor(bool on); // Ignored on 8" drives
void getDriveStatus(bool& writeProtected,
bool& headLoaded,
bool& trackZero,
bool& indexPulse);
bool getIndexPulse()
{
return indexPulse_m;
}
int getNumTracks() override
{
return numTracks_m;
}
int getRawBytesPerTrack() override
{
return rawSDBytesPerTrack_m;
}
bool isReady() override;
bool isWriteProtect() override;
std::string getMediaName() override;
void startTrackFormat(BYTE trackNum);
private:
unsigned int numTracks_m;
unsigned int numHeads_m;
unsigned int driveRpm_m;
unsigned int mediaSize_m;
unsigned int rawSDBytesPerTrack_m;
unsigned long ticksPerSec_m;
unsigned long ticksPerRev_m;
unsigned long long cycleCount_m;
bool indexPulse_m;
std::shared_ptr<GenericFloppyDisk> disk_m;
int headSel_m;
int track_m;
bool motor_m;
bool headLoaded_m;
bool writeProtected_m;
GenericFloppyDrive(unsigned int heads,
unsigned int tracks,
unsigned int mediaSize);
};
#endif // GENERICFLOPPYDRIVE_H_
<file_sep>/VirtualH89/Src/H88MemoryDecoder.h
///
/// \file H88MemoryDecoder.h
///
/// Basic H88 48K RAM+ROM layout, this memory decoder has no support
/// for ORG-0 functionality
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef H88MEMORYDECODER_H_
#define H88MEMORYDECODER_H_
#include "MemoryDecoder.h"
class SystemMemory8K;
class H88MemoryDecoder: public MemoryDecoder
{
public:
H88MemoryDecoder(std::shared_ptr<SystemMemory8K> systemRam,
MemoryLayout::MemorySize_t memSize = MemoryLayout::Mem_48k);
virtual ~H88MemoryDecoder() override;
private:
const static unsigned NumMemoryLayouts_c = 1;
const static BYTE gppMask_c = 0;
void gppNewValue(BYTE) override;
};
#endif // H88MEMORYDECODER_H_
<file_sep>/VirtualH89/Src/SignalHandler.h
/// \file SignalHandler.h
///
/// \date Mar 26, 2009
/// \author <NAME>
///
#ifndef SIGNALHANDLER_H_
#define SIGNALHANDLER_H_
class EventHandler;
/// \cond
#include <csignal>
/// \endcond
/// Class to handle signals. This is a singleton.
///
class SignalHandler
{
public:
static SignalHandler* instance(void);
EventHandler* registerHandler(int signum,
EventHandler* evtHandler);
int removeHandler(int signum);
private:
SignalHandler(void);
~SignalHandler(void);
static SignalHandler* _inst;
static void dispatcher(int signum);
static EventHandler* signalHandlers[NSIG];
};
#endif // SIGNALHANDLER_H_
<file_sep>/VirtualH89/Src/DiskData.h
///
/// \file DiskData.h
///
///
/// \date Sep 11, 2012
/// \author <NAME>
///
#ifndef DISKDATA_H_
#define DISKDATA_H_
#include "h89Types.h"
class DiskData
{
public:
enum DiskTypes
{
none_c = 0,
fiveHardSectored_c = 1,
fiveSoftSectored_c = 2,
eightSoftSectored_c = 3,
hardDisk_c = 4
};
DiskData(char* name);
DiskData(DiskTypes type); // what about size, tracks, sides, density, etc...
virtual ~DiskData();
virtual bool getType(DiskTypes& type);
virtual bool parse();
virtual bool checkWriteProtect();
protected:
bool fileRead_m;
bool valid_m;
DiskTypes type;
BYTE* data_m;
long long dataSize_m;
BYTE majorVersion_m;
BYTE minorVersion_m;
BYTE pointVersion_m;
BYTE distributionDiskFlag_m;
bool writeProtectedFlag_m;
BYTE imagingTypeFlag_m;
static const BYTE mandatoryFlag_c = 0x80;
static const BYTE valueFlagMask_c = 0x7f;
static const BYTE boolFlagMask_c = 0x01;
static const BYTE diskFormatType_c = 0x00;
static const BYTE diskFormatSize_c = 8;
static const BYTE flagsType_c = 0x01;
static const BYTE flagsSize_c = 3;
static const BYTE dataBlockType_c = 0x10;
unsigned int readLength(unsigned int& pos);
virtual bool readDiskFormat(unsigned int& pos);
virtual bool readFlags(unsigned int& pos);
virtual bool readDataBlock(unsigned int& pos);
virtual bool readHoleBlock(unsigned int& pos); /// \todo make this pure virtual ? why?
virtual bool readUnknownBlock(unsigned int& pos);
};
#endif // DISKDATA_H_
<file_sep>/VirtualH89/Src/GUIwxWidgets.cpp
#if defined(__GUIwx__)
///
/// \name GUIglut.h
///
/// A GUI implementation based on glut.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#include <cassert>
#include "GUIwxWidgets.h"
#include "VirtualH89Frame.h"
tKeyboardFunc GUIwxWidgets::GUIKeyboardFunc = nullptr;
tDisplayFunc GUIwxWidgets::GUIDisplayFunc;
tDisplayFunc GUIwxWidgets::GUITimerFunc;
unsigned int GUIwxWidgets::m_ms;
extern VirtualH89Frame *TheFrame;
wxThread::ExitCode wxGUIThread::Entry(void)
{
// Loop until kill by GUIwxWIdgets destructor.
for (;;)
{
Sleep(Period);
GUITimerFunc();
// If the screen changed we need to update it.
if (H19::GetH19()->checkUpdated())
{
TheFrame->Refresh();
}
}
return 0;
}
GUIwxWidgets::GUIwxWidgets()
{
fontTable = (unsigned char*) fontTableForward;
return;
}
GUIwxWidgets::~GUIwxWidgets()
{
if (Thread)
{
Thread->Kill();
delete Thread;
Thread = nullptr;
}
}
void
GUIwxWidgets::GUIDisplay(void)
{
TheFrame->Refresh();
return;
}
void
GUIwxWidgets::InitGUI(void)
{
assert(H19::GetH19());
return;
}
void
GUIwxWidgets::StartGUI(void)
{
// glutMainLoop();
return;
}
void
GUIwxWidgets::SetTimerFunc(unsigned int ms, tTimerFunc TimerFunc)
{
assert(TimerFunc);
m_ms = ms;
GUITimerFunc = TimerFunc;
if (TimerFunc)
{
Thread = new wxGUIThread(TimerFunc, ms);
Thread->Run();
}
return;
}
void
GUIwxWidgets::SetDisplayFunc(tDisplayFunc DisplayFunc)
{
assert(DisplayFunc);
GUIDisplayFunc = DisplayFunc;
return;
}
void
GUIwxWidgets::SetKeyboardFunc(tKeyboardFunc KeyboardFunc)
{
assert(KeyboardFunc);
GUIKeyboardFunc = KeyboardFunc;
return;
}
void
GUIwxWidgets::GUIwxWidgetsDisplayFunc(void)
{
assert(GUIDisplayFunc);
GUIDisplayFunc();
return;
}
#endif
<file_sep>/VirtualH89/Src/H37InterruptController.h
///
/// \file H37InterruptController.h
///
/// \brief Interrupt controller for the H37 soft-sectored disk controller
///
/// \author <NAME>
/// \date Mar. 17, 2016
///
#ifndef H37_INTERRUPT_CONTROLLER_H
#define H37_INTERRUPT_CONTROLLER_H
#include "InterruptController.h"
class H37InterruptController: public InterruptController
{
protected:
bool intrqRaised_m;
bool drqRaised_m;
bool interruptsBlocked_m;
virtual void setINTLine();
public:
H37InterruptController(CPU* cpu);
virtual ~H37InterruptController();
// read data bus for instruction to execute due to interrupt.
virtual BYTE readDataBus();
virtual void setDrq(bool raise);
virtual void setIntrq(bool raise);
virtual void blockInterrupts(bool block);
};
#endif // H37_INTERRUPT_CONTROLLER_H
<file_sep>/VirtualH89/Src/SectorFloppyImage.cpp
/// \file SectorFloppyImage.cpp
///
/// \brief virtual Floppy Disk implementation for soft-sectored media.
/// Supports media image files that have a sector image of the disk
///
/// \date Feb 2, 2016
/// \author <NAME>
///
#include "SectorFloppyImage.h"
#include "RawFloppyImage.h"
#include "GenericFloppyDrive.h"
#include "GenericFloppyFormat.h"
#include "logger.h"
/// \cond
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
/// \endcond
using namespace std;
bool
SectorFloppyImage::checkHeader(BYTE* buf, int n)
{
BYTE* b = buf;
int m = 0;
while (*b != '\n' && *b != '\0' && b - buf < n)
{
BYTE* e;
unsigned long p = strtoul((char*) b, (char**) &e, 0);
switch (tolower(*e))
{
case 'm':
if (p != 5 && p != 8)
{
break;
}
m |= 0x01;
mediaSize_m = (int) p;
break;
case 'z':
if (p != 128 && p != 256 && p != 512 && p != 1024)
{
break;
}
m |= 0x02;
secSize_m = (int) p;
break;
case 'p':
if (p == 0)
{
break;
}
m |= 0x04;
numSectors_m = (int) p;
break;
case 's':
if (p < 1 || p > 2)
{
break;
}
m |= 0x08;
numSides_m = (int) p;
break;
case 't':
if (p == 0)
{
break;
}
m |= 0x10;
numTracks_m = (int) p;
break;
case 'd':
m |= 0x20;
doubleDensity_m = (p != 0);
break;
case 'i':
m |= 0x40;
interlaced_m = (p != 0);
break;
case 'l': // optional ?
// m |= 0x80;
mediaLat_m = (int) p;
break;
default:
return false;
}
b = e + 1;
}
if (m != 0x7f)
{
debugss(ssSectorFloppyImage, INFO, "Failed to interpret header %04x\n", m);
}
return (m == 0x7f);
}
void
SectorFloppyImage::eject(const string file)
{
// flush data...
close(imageFd_m);
imageFd_m = -1;
}
void
SectorFloppyImage::dump()
{
}
// TODO: If constructor fails, the drive should not mount this disk!
SectorFloppyImage::SectorFloppyImage(GenericDiskDrive* drive,
std::vector<std::string> argv): GenericFloppyDisk(),
imageName_m(nullptr),
imageFd_m(-1),
secBuf_m(nullptr),
bufferedTrack_m(-1),
bufferedSide_m(-1),
bufferedSector_m(-1),
bufferOffset_m(0),
hypoTrack_m(false),
hyperTrack_m(false),
interlaced_m(false),
mediaLat_m(0),
secLenCode_m(0),
gapLen_m(0),
indexGapLen_m(0),
writePos_m(0),
trackWrite_m(false),
dataPos_m(0),
dataLen_m(0)
{
if (argv.size() < 1)
{
debugss(ssSectorFloppyImage, WARNING, "no file specified\n");
return;
}
const char* name = strdup(argv[0].c_str());
for (int x = 1; x < argv.size(); ++x)
{
if (argv[x].compare("rw") == 0)
{
writeProtect_m = false;
}
}
if (!writeProtect_m && access(name, W_OK) != 0)
{
debugss(ssSectorFloppyImage, WARNING, "Image not writeable: %s\n", name);
writeProtect_m = true;
}
int fd = open(name, writeProtect_m ? O_RDONLY : O_RDWR);
if (fd < 0)
{
debugss(ssSectorFloppyImage, ERROR, "unable to open file - %s\n", name);
free((void*) name);
return;
}
BYTE buf[128];
off_t end = lseek(fd, (off_t) 0, SEEK_END);
if (end == 0)
{
// empty file... can't access...
debugss(ssSectorFloppyImage, ERROR, "file is empty - %s\n", name);
free((void*) name);
return;
}
lseek(fd, end - sizeof(buf), SEEK_SET);
ssize_t x = read(fd, buf, sizeof(buf));
bool done = (x == sizeof(buf) && checkHeader(buf, sizeof(buf)));
if (!done)
{
debugss(ssSectorFloppyImage, ERROR, "file is not SectorFloppyImage (%d,%d) - %s\n", x,
errno,
name);
free((void*) name);
return;
}
hypoTrack_m = (drive->getNumTracks() > numTracks_m);
hyperTrack_m = (drive->getNumTracks() < numTracks_m);
trackLen_m = (mediaSize_m == 5 ? 3200 : 6400);
secLenCode_m = ffs(secSize_m); // 128==8, 1024==11
if (secLenCode_m > 0)
{
secLenCode_m -= 8; // 128==0, 256=1, 512=2, 1024==3
secLenCode_m &= 0x03; // just to be sure.
}
if (doubleDensity_m)
{
trackLen_m *= 2;
}
secBuf_m = new BYTE[secSize_m];
imageFd_m = fd;
imageName_m = name;
debugss(ssSectorFloppyImage, ERROR,
"mounted %d\" floppy %s: sides=%d tracks=%d spt=%d DD=%s R%s\n",
mediaSize_m, imageName_m, numSides_m, numTracks_m, numSectors_m,
doubleDensity_m ? "yes" : "no", writeProtect_m ? "O" : "W");
}
SectorFloppyImage::~SectorFloppyImage()
{
if (imageFd_m < 0)
{
return;
}
debugss(ssSectorFloppyImage, INFO, "unmounted %s\n", imageName_m);
close(imageFd_m); // check errors?
imageFd_m = -1;
}
shared_ptr<GenericFloppyDisk>
SectorFloppyImage::getDiskette(GenericDiskDrive* drive,
std::vector<std::string> argv)
{
shared_ptr<GenericFloppyDisk> gd = make_shared<SectorFloppyImage>(drive, argv);
if (!gd->isReady())
{
debugss(ssSectorFloppyImage, INFO, "%s: Falling back to RawFloppyImage\n", argv[0].c_str());
gd = make_shared<RawFloppyImage>(drive, argv);
}
return gd;
}
bool
SectorFloppyImage::cacheSector(int side, int track, int sector)
{
if (bufferedSide_m == side && bufferedTrack_m == track && bufferedSector_m == sector)
{
return true;
}
if (imageFd_m < 0)
{
return false;
}
if (bufferDirty_m && bufferedSide_m != -1 && bufferedTrack_m != -1 && bufferedSector_m != -1)
{
lseek(imageFd_m, bufferOffset_m, SEEK_SET);
ssize_t rd = write(imageFd_m, secBuf_m, secSize_m);
if (rd != secSize_m)
{
debugss(ssSectorFloppyImage, ERROR, "Unable to write to file %s\n", imageName_m);
}
bufferDirty_m = false;
}
if (side < 0 || track < 0 || sector < 0)
{
return true;
}
if (hypoTrack_m)
{
if ((track & 1) != 0)
{
return false;
}
track /= 2;
}
else if (hyperTrack_m)
{
track *= 2;
}
if (interlaced_m)
{
bufferOffset_m = ((track * numSides_m + side) * numSectors_m + sector - 1) * secSize_m;
}
else
{
bufferOffset_m = ((side * numTracks_m + track) * numSectors_m + sector - 1) * secSize_m;
}
lseek(imageFd_m, bufferOffset_m, SEEK_SET);
ssize_t rd = read(imageFd_m, secBuf_m, secSize_m);
if (rd != secSize_m)
{
bufferedSide_m = -1;
bufferedTrack_m = -1;
bufferedSector_m = -1;
return false;
}
bufferedSide_m = side;
bufferedTrack_m = track;
bufferedSector_m = sector;
return true;
}
bool
SectorFloppyImage::findSector(BYTE sideNum,
BYTE trackNum,
BYTE sectorNum)
{
return cacheSector(sideNum, trackNum, sectorNum);
}
bool
SectorFloppyImage::readData(BYTE track, BYTE side, BYTE sector, int inSector, int& data)
{
if (inSector < 0)
{
if (sector == 0xfd)
{
data = GenericFloppyFormat::ID_AM;
return true;
}
else if (sector == 0xff)
{
data = GenericFloppyFormat::INDEX_AM;
return true;
}
else if (cacheSector(side, track, sector))
{
dataPos_m = 0;
dataLen_m = dataPos_m + secSize_m;
data = GenericFloppyFormat::DATA_AM;
return true;
}
data = GenericFloppyFormat::NO_DATA;
return true;
}
if (sector == 0xfd)
{
switch (inSector)
{
case 0:
data = track;
break;
case 1:
data = side;
break;
case 2:
data = 1; // anything will do? 'sector' is 0xfd...
break;
case 3:
data = secLenCode_m;
break;
case 4:
data = 0; // CRC 1
break;
case 5:
data = 0; // CRC 2
break;
default:
data = GenericFloppyFormat::CRC;
break;
}
return true;
}
else if (sector == 0xff)
{
if (inSector < trackLen_m)
{
// TODO: implement this
data = 0;
}
else
{
data = GenericFloppyFormat::CRC;
}
return true;
}
if (dataPos_m < dataLen_m)
{
data = secBuf_m[dataPos_m++];
}
else
{
debugss(ssSectorFloppyImage, INFO, "data done %d %d %d\n", track, side, sector);
data = GenericFloppyFormat::CRC;
}
return true;
}
bool
SectorFloppyImage::writeData(BYTE track, BYTE side, BYTE sector, int inSector,
BYTE data, bool dataReady, int& result)
{
if (checkWriteProtect())
{
debugss(ssSectorFloppyImage, ERROR, "write protect\n");
return false;
}
if (trackWrite_m)
{
debugss(ssSectorFloppyImage, ERROR, "track write\n");
return false;
}
if (inSector < 0)
{
if (sector == 0xff || sector == 0xfe)
{
result = GenericFloppyFormat::ERROR;
return true;
}
else if (cacheSector(side, track, sector))
{
dataPos_m = 0;
dataLen_m = dataPos_m + secSize_m;
result = GenericFloppyFormat::DATA_AM;
return true;
}
result = GenericFloppyFormat::NO_DATA;
return true;
}
debugss(ssSectorFloppyImage, INFO, "writeData pos=%d data=%02x\n", inSector, data);
if (dataPos_m < dataLen_m)
{
if (!dataReady)
{
result = GenericFloppyFormat::NO_DATA;
}
else
{
secBuf_m[dataPos_m++] = data;
bufferDirty_m = true;
result = data;
}
}
else
{
result = GenericFloppyFormat::CRC;
}
return true;
}
bool
SectorFloppyImage::isReady()
{
return (imageFd_m >= 0);
}
std::string
SectorFloppyImage::getMediaName()
{
if (imageName_m == nullptr)
{
return "BAD";
}
return imageName_m;
}
<file_sep>/VirtualH89/Src/WallClock.h
/// \file WallClock.h
///
/// \date Apr 29, 2009
/// \author <NAME>
///
#ifndef WALLCLOCK_H_
#define WALLCLOCK_H_
/// \cond
#include <cstdio>
#include <list>
#include <atomic>
/// \endcond
class ClockUser;
/// \class WallClock
///
/// \brief Clock counting CPU cycles.
///
/// Provides a 'real-time' clock allowing times down to a cpu cycle.
///
/// WallClock is to provide the overall 'real-time' down to a cpu cycle.
///
/// This is a singleton to make sure everyone is using the one and only instance.
///
/// Note: The name is a bit misleading. This does not have anything to do with actual time,
/// but the virtual time as seen by the CPU.
class WallClock
{
private:
std::atomic_ullong clock_m; // = 0;
std::atomic_uint ticks_m;// = 0;
static WallClock* _inst;
unsigned long ticksPerSecond = 2048000;
WallClock();
~WallClock();
/// use C++11 to avoid having to define copy constructor
WallClock(WallClock const&) = delete;
WallClock& operator=(WallClock const&) = delete;
std::list<ClockUser*> users_m;
public:
bool registerUser(ClockUser* user);
bool unregisterUser(ClockUser* user);
static WallClock* instance(void);
void addTimerEvent();
void updateTicksPerSecond(unsigned long ticks);
unsigned long getTicksPerSecond()
{
return ticksPerSecond;
}
void addTicks(unsigned ticks);
long long unsigned int getClock();
long long unsigned int getElapsedTime(long long unsigned int origTime);
void printTime(FILE* file);
bool addCallback(ClockUser* user,
unsigned long long timeUs);
};
#endif // WALLCLOCK_H_
<file_sep>/VirtualH89/Src/VirtualH89App.h
#if defined(__GUIwx__)
/////////////////////////////////////////////////////////////////////////////
// Name: VirtualH89App.h
// Purpose:
// Author:
// Modified by:
// Created: Sat 22 Apr 2017 16:38:00 CDT
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _VIRTUALH89APP_H_
#define _VIRTUALH89APP_H_
/*!
* Includes
*/
////@begin includes
#include "wx/image.h"
#include "VirtualH89Frame.h"
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
////@end control identifiers
/*!
* VirtualH89App class declaration
*/
class VirtualH89App: public wxApp
{
DECLARE_CLASS( VirtualH89App )
DECLARE_EVENT_TABLE()
public:
/// Constructor
VirtualH89App();
void Init();
/// Initialises the application
virtual bool OnInit();
/// Called on exit
virtual int OnExit();
////@begin VirtualH89App event handler declarations
////@end VirtualH89App event handler declarations
////@begin VirtualH89App member function declarations
////@end VirtualH89App member function declarations
////@begin VirtualH89App member variables
////@end VirtualH89App member variables
};
/*!
* Application instance declaration
*/
////@begin declare app
DECLARE_APP(VirtualH89App)
////@end declare app
#endif
// _VIRTUALH89APP_H_
#endif
<file_sep>/VirtualH89/Src/mms77320.h
/// \file mms77320.h
///
/// Implementation of the MMS 77320 SASI adapter. Does not implement the SASI controller
/// or disk drive (or media), see GenericSASIDrive et al.
///
/// \date Feb 13, 2016
/// \author <NAME>
///
#ifndef MMS77320_H_
#define MMS77320_H_
#include "DiskController.h"
#include "propertyutil.h"
class GenericSASIDrive;
///
/// \brief Virtual soft-sectored disk controller
///
/// A virtual Magnolia Microsystems soft-sectored disk controller (MMS77320).
/// Note: this is NOT complete or even marginally functional.
///
/// The MMS77320 uses the 1797-02 controller.
///
class MMS77320: public DiskController
{
public:
static const int numDisks_c = 8;
MMS77320(int baseAddr,
int intLevel,
int switches);
virtual ~MMS77320() override;
static MMS77320* install_MMS77320(PropertyUtil::PropertyMapT& props,
std::string slot);
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual bool connectDrive(BYTE unitNum,
GenericSASIDrive* drive);
virtual bool removeDrive(BYTE unitNum);
virtual GenericSASIDrive* getDrive(BYTE unitNum);
virtual void reset(void) override;
// TODO: implement this
std::vector<GenericDiskDrive*> getDiskDrives() override;
std::string getDriveName(int index) override;
std::string getDeviceName() override
{
return MMS77320_Name_c;
}
GenericDiskDrive* findDrive(std::string ident) override;
std::string dumpDebug() override;
bool interResponder(BYTE& opCode);
protected:
static const char* MMS77320_Name_c;
private:
void raiseIntrq();
void lowerIntrq();
static const BYTE MMS77320_NumPorts_c = 3;
BYTE BasePort_m = 0xff; // TBD configured by jumpers
static const BYTE DataPort_Offset_c = 0;
static const BYTE Control0Port_Offset_c = 1;
static const BYTE StatusPort_Offset_c = 1;
static const BYTE SwitchPort_Offset_c = 2;
static const BYTE Control1Port_Offset_c = 2;
BYTE dataOutReg_m;
BYTE dataInReg_m;
BYTE control0Reg_m;
BYTE control1Reg_m;
BYTE statusReg_m;
BYTE switchReg_m;
BYTE ctrlBus_m;
BYTE getStatus(BYTE ctl);
GenericSASIDrive* getCurDrive();
GenericSASIDrive* drives_m[numDisks_c];
GenericSASIDrive* curDrive_m;
unsigned char intLevel_m; // TBD configured by jumpers
/// Bits set in cmd_Control0Port_c
static const BYTE ctrl_ResetStart_c = 0x10;
static const BYTE ctrl_EnableIntReq_c = 0x20;
static const BYTE ctrl_Select_c = 0x40;
static const BYTE ctrl_DisableAck_c = 0x80;
/// Bits set in cmd_Control1Port_c
static const BYTE ctrl_DriveSel_c = 0x07;
// Bits in statusReg_m
static const BYTE sts_Req_c = 0x80;
static const BYTE sts_POut_c = 0x40;
static const BYTE sts_Msg_c = 0x20;
static const BYTE sts_Cmd_c = 0x10;
static const BYTE sts_Busy_c = 0x08;
static const BYTE sts_Unused_c = 0x04;
static const BYTE sts_ActInt_c = 0x02;
static const BYTE sts_Ack_c = 0x01;
bool intrqAllowed()
{
return (control0Reg_m & ctrl_EnableIntReq_c) != 0;
}
};
#endif // MMS77320_H_
<file_sep>/VirtualH89/Src/h17.h
/// \file h17.h
///
/// Hard-sectored Disk Controller
///
/// \date Apr 18, 2009
/// \author <NAME>
///
#ifndef H17_H_
#define H17_H_
#include "DiskController.h"
#include "ClockUser.h"
#include "GppListener.h"
#include "propertyutil.h"
/// \cond
#include <memory>
/// \endcond
class DiskDrive;
///
/// \brief %H17 - Virtual Hard-sectored Disk Controller
///
/// A virtual hard-sectored disk controller (H-88-1), supports up to 3 disk drives (H-17-1)
/// at 102k per disk. Later (third-party) software upgrades supported disks up to 408k per
/// disk, by using a double-sided 96 tpi drive (H-17-4 or H-17-5).
///
class H17: public DiskController, public ClockUser, public GppListener
{
public:
H17(int BaseAddr);
virtual ~H17() override;
static H17* install_H17(BYTE basePort,
PropertyUtil::PropertyMapT& props,
std::string slot);
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
virtual bool connectDrive(BYTE unitNum,
std::shared_ptr<DiskDrive> drive);
virtual bool removeDrive(BYTE unitNum);
virtual void selectSide(BYTE side);
virtual void notification(unsigned int cycleCount) override;
// TODO: implement this
std::vector<GenericDiskDrive*> getDiskDrives() override
{
return *(new std::vector<GenericDiskDrive*>());
}
std::string getDeviceName() override
{
return "H17";
}
GenericDiskDrive* findDrive(std::string ident) override
{
return nullptr;
}
std::string getDriveName(int index) override
{
return "";
}
std::string dumpDebug() override
{
return "";
}
void reset() override
{
}
private:
virtual void gppNewValue(BYTE gpo) override;
static const BYTE h17_gppSideSelectBit_c = 0b01000000;
enum State
{
idleState,
seekingSyncState,
readingState,
writingState
};
State state_m;
// for the spinning of the disk
unsigned long long spinCycles_m;
unsigned long curCharPos_m;
bool motorOn_m;
bool writeGate_m;
bool direction_m;
// statuses
bool syncCharacterReceived_m;
bool receiveDataAvail_m;
bool receiverOverrun_m;
bool receiverParityErr_m; // Parity is not used in the H17 circuit
bool fillCharTransmitted_m;
bool transmitterBufferEmpty_m;
BYTE receiverOutputRegister_m;
BYTE transmitterHoldingRegister_m;
enum DiskDriveID
{
ds0 = 0,
ds1 = 1,
ds2 = 2,
maxDiskDrive_c = 3
};
DiskDriveID curDrive_m;
std::shared_ptr<DiskDrive> drives_m[maxDiskDrive_c];
BYTE fillChar_m;
BYTE syncChar_m;
///
/// Ports
///
static const BYTE H17_NumPorts_c = 4;
///
/// Data Port - Typically Port 0x7c (Octal 0174)
///
/// Receives and transmits the data characters to the USART
///
static const BYTE DataPortOffset_c = 0;
///
/// Status Port (read) - Typically Port 0x7d (Octal 0175)
/// Fill Port (write) - Typically Port 0x7d (Octal 0175)
///
/// Reads the USART status, writes set the fill character.
///
static const BYTE StatusPortOffset_c = 1;
static const BYTE FillPortOffset_c = 1;
///
/// Sync Port - Typically Port 0x7e (Octal 0176)
///
/// Reads resets the USART to search character mode
/// Writes the search character to the USART
///
static const BYTE SyncPortOffset_c = 2;
///
/// Control Port - Typically Port 0x7f (Octal 0177)
///
/// Reads the floppy disk status and sync character match and controls the floppy disk
/// with respect to it's motor, track position, and write gate.
///
static const BYTE ControlPortOffset_c = 3;
///
/// Number of CPU cycles for each read byte from the Floppy disk.
/// This is fixed on due to the single density, and rotation speed of the disk
///
static const unsigned int CPUCyclesPerByte_c = 128;
static const unsigned int BytesPerTrack_c = 3200;
/// Flag and Control Bits
///
/// Read from ControlPort_c
///
static const BYTE ctrlHoleDetect_Flag = 0x01; // from floppy disk
static const BYTE ctrlTrackZeroDetect_Flag = 0x02; // from disk drive
static const BYTE ctrlWriteProtect_Flag = 0x04; // from floppy disk
static const BYTE ctrlSyncDetect_Flag = 0x08; // from controller
///
/// Write to ControlPort_c
///
static const BYTE WriteGate_Ctrl = 0x01;
static const BYTE DriveSelect0_Ctrl = 0x02;
static const BYTE DriveSelect1_Ctrl = 0x04;
static const BYTE DriveSelect2_Ctrl = 0x08;
static const BYTE MotorOn_Ctrl = 0x10; // Controls all the drives
static const BYTE Direction_Ctrl = 0x20; // (0 = out)
static const BYTE StepCommand_Ctrl = 0x40; // (Active high)
static const BYTE WriteEnableRAM_Ctrl = 0x80; // 0 - write protected
// 1 - write enabled
///
/// Read from the StatusPort_c
///
static const BYTE ReceiveDataAvail_Flag = 0x01; // from controller
static const BYTE ReceiverOverrun_Flag = 0x02; // from controller
static const BYTE ReceiverParityErr_Flag = 0x04; // from controller, NEVER set
// on H17
static const BYTE SyncDetect_Flag = 0x08; // ??? - Manual defines it, but Heath
// software didn't use it
static const BYTE FillCharTransmitted_Flag = 0x40; // from controller
static const BYTE TransmitterBufferEmpty_Flag = 0x80; // from controller
};
#endif // H17_H_
<file_sep>/VirtualH89/Src/GUIglut.cpp
#if defined(__GUIglut__) || !defined(__GUIwx__)
///
/// \name GUIglut.h
///
/// A GUI implementation based on glut.
///
/// \date Apr 20, 2017
/// \author <NAME> and <NAME>
///
#include <cassert>
#include "GUIglut.h"
tKeyboardFunc GUIglut::GUIKeyboardFunc = nullptr;
tDisplayFunc GUIglut::GUIDisplayFunc;
tDisplayFunc GUIglut::GUITimerFunc;
unsigned int GUIglut::m_ms;
// GLUT routine used to redisplay the screen when needed.
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
GUIglut::GUIglut()
{
// Set inverted character generator for GLUT.
fontTable = (unsigned char*) fontTableInverted;
return;
}
GUIglut::~GUIglut()
{
// TODO Auto-generated destructor stub
}
void
GUIglut::GUIDisplay(void)
{
GLfloat color[3] = {1.0, 1.0, 0.0}; // amber
// GLfloat color[3] = {0.0, 1.0, 0.0}; // green
// GLfloat color[3] = { 1.0, 1.0, 1.0 }; // white
// GLfloat color[3] = { 0.5, 0.0, 1.0 }; // purple
// GLfloat color[3] = { 0.0, 0.8, 0.0 };
// GLfloat color[3] = { 0.9, 0.9, 0.0 }; // amber
glClear(GL_COLOR_BUFFER_BIT);
glColor3fv(color);
glRasterPos2i(20, 24 * 20 + 20);
glPushAttrib(GL_LIST_BIT);
glListBase(fontOffset_m);
glCallLists(26 * H19::GetH19()->cols_c, GL_UNSIGNED_INT, (GLuint*) H19::GetH19()->screen_m);
glPopAttrib();
glEnable(GL_COLOR_LOGIC_OP);
if ((!H19::GetH19()->cursorOff_m) && (H19::GetH19()->curCursor_m))
{
glRasterPos2i(20 + min(H19::GetH19()->posX_m, 79) * 8,
(24 - H19::GetH19()->posY_m) * 20 + 20);
glPushAttrib(GL_LIST_BIT);
// glEnable(GL_COLOR_LOGIC_OP);
glLogicOp(GL_COPY);
glListBase(fontOffset_m);
GLuint cursor = (H19::GetH19()->cursorBlock_m) ? (128 + 32) : 27;
glCallLists(1, GL_UNSIGNED_INT, &cursor);
glPopAttrib();
}
glLogicOp(GL_COPY);
glutSwapBuffers();
return;
}
void
GUIglut::InitGUI(void)
{
assert(H19::GetH19());
int dummy_argc = 1;
char* dummy_argv = (char*) "dummy";
glutInit(&dummy_argc, &dummy_argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(640 + 40, 500 + 40);
glutInitWindowPosition(500, 100);
glutCreateWindow((char*) "Virtual Heathkit H-89 All-in-One Computer");
glClearColor(0.0f, 0.0f, 0.0f, 0.9f);
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glBlendFunc(GL_ONE, GL_ONE);
// glBlendEquation(GL_FUNC_ADD);
glBlendColor(0.5, 0.5, 0.5, 0.9);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glShadeModel(GL_FLAT);
GLuint i;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
fontOffset_m = glGenLists(0x101);
for (i = 0; i < 0x100; i++)
{
glNewList(fontOffset_m + i, GL_COMPILE);
glBitmap(8, 20, 0.0, 0.0, 0.0, -20.0, &fontTable[i * 20]);
glEndList();
}
// Special character to wrap around.
glNewList(fontOffset_m + 0x100, GL_COMPILE);
glBitmap(8, 20, 0.0, 0.0, 8.0, 500.0, &fontTable[32 * 20]);
glEndList();
glutReshapeFunc(reshape);
glutSpecialFunc(special);
glutIgnoreKeyRepeat(1);
return;
}
void
GUIglut::StartGUI(void)
{
glutMainLoop();
return;
}
void
GUIglut::SetTimerFunc(unsigned int ms, tTimerFunc TimerFunc)
{
assert(TimerFunc);
m_ms = ms;
GUITimerFunc = TimerFunc;
glutTimerFunc(ms, GLUTTimerFunc, 1);
return;
}
void
GUIglut::GLUTTimerFunc(int i)
{
assert(GUITimerFunc);
GUITimerFunc();
// Tell glut to redisplay the scene:
if (H19::GetH19()->checkUpdated())
{
glutPostRedisplay();
}
glutTimerFunc(m_ms, GLUTTimerFunc, i);
return;
}
void
GUIglut::SetDisplayFunc(tDisplayFunc DisplayFunc)
{
assert(DisplayFunc);
GUIDisplayFunc = DisplayFunc;
glutDisplayFunc(GLUTDisplayFunc);
return;
}
void
GUIglut::GLUTDisplayFunc(void)
{
assert(GUIDisplayFunc);
GUIDisplayFunc();
return;
}
void
GUIglut::SetKeyboardFunc(tKeyboardFunc KeyboardFunc)
{
assert(KeyboardFunc);
GUIKeyboardFunc = KeyboardFunc;
glutKeyboardFunc(GLUTKeyboardFunc);
return;
}
void
GUIglut::GLUTKeyboardFunc(unsigned char Key, int x, int y)
{
assert(GUIKeyboardFunc);
GUIKeyboardFunc(Key);
return;
}
void
GUIglut::reshape(int w,
int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, w, 0.0, h, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 0.9f);
glClear(GL_COLOR_BUFFER_BIT);
}
void
GUIglut::special(int key,
int x,
int y)
{
assert(GUIKeyboardFunc);
// NOTE: GLUT has already differentiated exact keystrokes
// based on modern keyboard standards. Here we just encode
// the modern key codes into something convenient to use
// in the H19 class.
switch (key)
{
case GLUT_KEY_F1:
GUIKeyboardFunc('S' | 0x80);
break;
case GLUT_KEY_F2:
GUIKeyboardFunc('T' | 0x80);
break;
case GLUT_KEY_F3:
GUIKeyboardFunc('U' | 0x80);
break;
case GLUT_KEY_F4:
GUIKeyboardFunc('V' | 0x80);
break;
case GLUT_KEY_F5:
GUIKeyboardFunc('W' | 0x80);
break;
case GLUT_KEY_F6:
GUIKeyboardFunc('P' | 0x80);
break;
case GLUT_KEY_F7:
GUIKeyboardFunc('Q' | 0x80);
break;
case GLUT_KEY_F8:
GUIKeyboardFunc('R' | 0x80);
break;
case GLUT_KEY_HOME:
GUIKeyboardFunc('H' | 0x80);
break;
case GLUT_KEY_UP:
GUIKeyboardFunc('A' | 0x80);
break;
case GLUT_KEY_DOWN:
GUIKeyboardFunc('B' | 0x80);
break;
case GLUT_KEY_LEFT:
GUIKeyboardFunc('D' | 0x80);
break;
case GLUT_KEY_RIGHT:
GUIKeyboardFunc('C' | 0x80);
break;
default:
break;
}
return;
}
#endif
<file_sep>/VirtualH89/Src/MMS77318MemoryDecoder.h
///
/// \file MMS77318MemoryDecoder.h
///
/// Definition of the MMS 77318 128K add-on RAM card and
/// associated decoder modification.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#ifndef MMS77318MEMORYDECODER_H_
#define MMS77318MEMORYDECODER_H_
#include "MemoryDecoder.h"
class SystemMemory8K;
class MMS77318MemoryDecoder: public MemoryDecoder
{
public:
MMS77318MemoryDecoder(std::shared_ptr<SystemMemory8K> systemMemory);
virtual ~MMS77318MemoryDecoder() override;
virtual void reset() override;
private:
virtual void gppNewValue(BYTE gpo) override;
static const BYTE h89_gppBnkSelBit0_c = 0b00100000;
static const BYTE h89_gppBnkSelBit1_c = 0b00000100;
static const BYTE h89_gppBnkSelBit2_c = 0b00010000;
static const BYTE h89_gppBnkSelBits_c = (h89_gppBnkSelBit0_c |
h89_gppBnkSelBit1_c |
h89_gppBnkSelBit2_c);
static const BYTE h89_gppUnlockBits_c = 0b00001100;
static const BYTE h89_gppWatchedBits_c = (h89_gppBnkSelBits_c |
h89_gppUnlockBits_c);
int lockState;
static const BYTE lockSeq[];
};
#endif // MMS77318MEMORYDECODER_H_
<file_sep>/VirtualH89/Src/SoftSectoredDisk.cpp
///
/// \name SoftSectoredDisk.cpp
///
///
/// \date Oct 2, 2012
/// \author <NAME>
///
#include "SoftSectoredDisk.h"
#include "DiskSide.h"
#include "Track.h"
#include "Sector.h"
#include "GenericFloppyFormat.h"
#include "logger.h"
/// \cond
#include <fstream>
#include <strings.h>
#include <memory>
/// \endcond
using namespace std;
SoftSectoredDisk::SoftSectoredDisk(): GenericFloppyDisk(),
curSector_m(nullptr),
sectorPos_m(0),
sectorLength_m(0),
secLenCode_m(0),
ready_m(true)
{
}
SoftSectoredDisk::~SoftSectoredDisk()
{
}
bool
SoftSectoredDisk::findSector(BYTE sideNum,
BYTE trackNum,
BYTE sectorNum)
{
debugss(ssFloppyDisk, INFO, "findSector - side: %d track %d sector: %d\n", sideNum, trackNum,
sectorNum);
if (hypoTrack_m)
{
if ((trackNum & 1) != 0)
{
// return false;
}
trackNum /= 2;
}
else if (hyperTrack_m)
{
trackNum *= 2;
}
debugss(ssFloppyDisk, INFO, "findSector2 - side: %d track %d sector: %d\n", sideNum, trackNum,
sectorNum);
if (sideNum < numSides_m)
{
curSector_m = sideData_m[sideNum]->findSector(trackNum, sectorNum);
}
if (!curSector_m)
{
return false;
}
if (curSector_m->getHeadNum() != sideNum)
{
curSector_m = nullptr;
return false;
}
sectorLength_m = curSector_m->getSectorLength();
// TODO handle if the L options is set to '0'.
switch (sectorLength_m)
{
case 128:
secLenCode_m = 0;
break;
case 256:
secLenCode_m = 1;
break;
case 512:
secLenCode_m = 2;
break;
case 1024:
secLenCode_m = 3;
break;
default:
debugss(ssFloppyDisk, ERROR, "bad sector size: %d\n", sectorLength_m);
curSector_m = nullptr;
return false;
}
debugss(ssFloppyDisk, INFO, "findSector - found\n");
return true;
}
void
SoftSectoredDisk::addTrack(std::shared_ptr<Track> track)
{
// BYTE sideNumber = track->getSideNumber();
// BYTE trackNumber = track->getTrackNumber();
/* if ()
{
}
*/
}
bool
SoftSectoredDisk::readData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
int& data)
{
if (inSector < 0)
{
if (sector == 0xfd)
{
data = GenericFloppyFormat::ID_AM;
}
else if (sector == 0xff)
{
data = GenericFloppyFormat::INDEX_AM;
}
else if (findSector(side, track, sector))
{
sectorPos_m = 0;
data = GenericFloppyFormat::DATA_AM;
}
else
{
data = GenericFloppyFormat::NO_DATA;
}
return true;
}
if (sector == 0xfd)
{
switch (inSector)
{
case 0:
if (hypoTrack_m)
{
data = track / 2;
}
else if (hyperTrack_m)
{
data = track * 2;
}
else
{
data = track;
}
break;
case 1:
data = side;
break;
case 2:
data = 1; // anything will do? 'sector' is 0xfd...
break;
case 3:
data = secLenCode_m;
break;
case 4:
data = 0; // CRC 1
break;
case 5:
data = 0; // CRC 2
break;
default:
data = GenericFloppyFormat::CRC;
break;
}
return true;
}
else if (sector == 0xff)
{
if (inSector < sectorLength_m)
{
// TODO: implement this
data = 0;
}
else
{
data = GenericFloppyFormat::CRC;
}
return true;
}
if (sectorPos_m < sectorLength_m)
{
if (curSector_m)
{
BYTE sectorData;
curSector_m->readData(sectorPos_m++, sectorData);
data = sectorData;
}
else
{
debugss(ssFloppyDisk, ERROR, "curSector_m not set\n");
}
}
else
{
debugss(ssFloppyDisk, INFO, "data done %d %d %d\n", track, side, sector);
data = GenericFloppyFormat::CRC;
}
return true;
}
bool
SoftSectoredDisk::writeData(BYTE track,
BYTE side,
BYTE sector,
int inSector,
BYTE data,
bool dataReady,
int& result)
{
if (checkWriteProtect())
{
debugss(ssSectorFloppyImage, ERROR, "write protect\n");
return false;
}
if (inSector < 0)
{
if (sector == 0xff || sector == 0xfe)
{
result = GenericFloppyFormat::ERROR;
}
else if (findSector(side, track, sector))
{
sectorPos_m = 0;
result = GenericFloppyFormat::DATA_AM;
}
else
{
result = GenericFloppyFormat::NO_DATA;
}
return true;
}
debugss(ssSectorFloppyImage, INFO, "pos=%d data=%02x\n", inSector, data);
if (sectorPos_m < sectorLength_m)
{
if (!dataReady)
{
debugss(ssSectorFloppyImage, ERROR, "data not read pos=%d\n", inSector);
result = GenericFloppyFormat::NO_DATA;
}
else
{
if (curSector_m)
{
curSector_m->writeData(sectorPos_m++, data);
result = data;
}
else
{
debugss(ssFloppyDisk, ERROR, "curSector_m not set\n");
}
}
}
else
{
debugss(ssSectorFloppyImage, INFO, "CRC pos=%d data=%02x\n", inSector, data);
result = GenericFloppyFormat::CRC;
}
return true;
}
bool
SoftSectoredDisk::isReady()
{
return ready_m;
}
void
SoftSectoredDisk::eject(const string name)
{
// \todo implement
}
void
SoftSectoredDisk::dump(void)
{
// \todo implement
}
#if 0
SoftSectoredDisk::SoftSectoredDisk(const char* name,
DiskImageFormat format): initialized_m(false)
{
debugss(ssFloppyDisk, INFO, "Insert Disk: %s\n", name);
if (format == dif_Unknown)
{
determineDiskFormat(name, format);
}
switch (format)
{
case dif_IMD:
readIMD(name);
break;
case dif_TD0:
readTD0(name);
break;
case dif_RAW:
readRaw(name);
break;
case dif_8RAW:
readRaw8(name);
break;
default:
// Unknown format
debugss(ssFloppyDisk, ERROR, "Unknown disk format: %d\n", format);
break;
}
}
SoftSectoredDisk::SoftSectoredDisk()
{
debugss(ssFloppyDisk, INFO, "Insert Empty Disk\n");
// clear disk
bzero(rawImage_m, maxHeads_c * bytesPerTrack_c * tracksPerSide_c);
numTracks_m = tracksPerSide_c;
numHeads_m = maxHeads_c;
maxTrack_m = tracksPerSide_c;
initialized_m = true;
// setWriteProtect(false);
}
SoftSectoredDisk::~SoftSectoredDisk()
{
}
bool
SoftSectoredDisk::readData(BYTE side,
BYTE track,
unsigned long pos,
BYTE& data)
{
debugss(ssFloppyDisk, ALL, "maxTrack (%d) tracks_m(%d)\n", maxTrack_m,
numTracks_m);
// Currently only 40 and 80 are supported.
if ((maxTrack_m != 40) && (maxTrack_m != 80))
{
debugss(ssFloppyDisk, ERROR, "Invalid maxTrack: %d\n", maxTrack_m);
return false;
}
if (maxTrack_m != numTracks_m)
{
if ((maxTrack_m == 80) && (numTracks_m = 40))
{
debugss(ssFloppyDisk, INFO, "max - 80 trk_m - 40\n");
track /= 2;
}
else if ((maxTrack_m == 40) && (numTracks_m == 80))
{
debugss(ssFloppyDisk, INFO, "max - 40 trk_m - 80\n");
track *= 2;
}
}
if (initialized_m)
{
if ((track < tracksPerSide_c) && (pos < bytesPerTrack_c))
{
debugss(ssFloppyDisk, ALL, "track(%d) pos(%lu) = %d\n", track, pos,
rawImage_m[side][track][pos]);
data = rawImage_m[side][track][pos];
return true;
}
else
{
debugss(ssFloppyDisk, ERROR, "range error: track(%d) pos(%lu)\n", track, pos);
return false;
}
}
else
{
debugss(ssFloppyDisk, ERROR, "disk not initialized\n");
return false;
}
}
bool
SoftSectoredDisk::writeData(BYTE side,
BYTE track,
unsigned long pos,
BYTE data)
{
debugss(ssFloppyDisk, INFO, "maxTrack (%d) tracks_m(%d)\n", maxTrack_m, numTracks_m);
// Currently only 40 and 80 are supported.
if ((maxTrack_m != 40) && (maxTrack_m != 80))
{
debugss(ssFloppyDisk, ERROR, "Invalid maxTrack: %d\n", maxTrack_m);
return false;
}
if (maxTrack_m != numTracks_m)
{
if ((maxTrack_m == 80) && (numTracks_m = 40))
{
debugss(ssFloppyDisk, INFO, "max - 80 trk_m - 40\n");
track /= 2;
}
else if ((maxTrack_m == 40) && (numTracks_m == 80))
{
debugss(ssFloppyDisk, INFO, "max - 40 trk_m - 80\n");
track *= 2;
}
}
if (initialized_m)
{
if ((track < tracksPerSide_c) && (pos < bytesPerTrack_c))
{
debugss(ssFloppyDisk, ALL, "track(%d) pos(%lu) = %d\n", track,
pos, rawImage_m[side][track][pos]);
rawImage_m[side][track][pos] = data;
return true;
}
else
{
debugss(ssFloppyDisk, ERROR, "Out of Range - track(%d) pos(%lu)\n",
track, pos);
return false;
}
}
else
{
debugss(ssFloppyDisk, ERROR, "disk not initialized\n");
return false;
}
}
void
SoftSectoredDisk::getControlInfo(unsigned long pos,
bool& hole,
bool& writeProtect)
{
if (initialized_m)
{
hole = defaultHoleStatus(pos);
writeProtect = checkWriteProtect();
}
else
{
hole = true;
writeProtect = false;
}
debugss(ssFloppyDisk, INFO, "init: %d hole: %d wp: %d\n", initialized_m, hole, writeProtect);
}
bool
SoftSectoredDisk::defaultHoleStatus(unsigned long pos)
{
debugss(ssFloppyDisk, ALL, "pos = %ld ", pos);
// check for index hole
if (pos < 128) /// \todo ??? does this need to change based on the density
{
debugss_nts(ssFloppyDisk, ALL, "index hole\n");
return true;
}
debugss_nts(ssFloppyDisk, ALL, "no hole\n");
return false;
}
bool
SoftSectoredDisk::readTD0(const char* name)
{
debugss(ssFloppyDisk, ERROR, "Not supported\n");
return false;
}
bool
SoftSectoredDisk::readIMD(const char* name)
{
std::ifstream file;
unsigned long int fileSize;
unsigned long int pos = 0;
BYTE* buf;
debugss(ssFloppyDisk, INFO, "file: %s\n", name);
file.open(name, std::ios::binary);
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
while (buf[pos] != 0x1a)
{
if (pos == fileSize)
{
delete [] buf;
return (false);
}
}
// get past the EOF character.
pos++;
BYTE sectorOrder[256];
BYTE sectorCylMapping[256];
BYTE sectorHeadMapping[256];
unsigned char mode, cyl, head, numSec, sectorSizeKey;
int sectorSize;
bool sectorCylMap, sectorHeadMap;
Track::Density density;
Track::DataRate dataRate;
do
{
// mode
mode = buf[pos++];
switch (mode)
{
case 0:
density = Track::singleDensity;
dataRate = Track::dr_500kbps;
debugss(ssFloppyDisk, INFO, "FM/500 kbps\n");
break;
case 1:
density = Track::singleDensity;
dataRate = Track::dr_300kbps;
debugss(ssFloppyDisk, INFO, "FM/300 kbps\n");
break;
case 2:
density = Track::singleDensity;
dataRate = Track::dr_250kbps;
debugss(ssFloppyDisk, INFO, "FM/250 kbps\n");
break;
case 3:
density = Track::doubleDensity;
dataRate = Track::dr_500kbps;
debugss(ssFloppyDisk, INFO, "MFM/500 kbps\n");
break;
case 4:
density = Track::doubleDensity;
dataRate = Track::dr_300kbps;
debugss(ssFloppyDisk, INFO, "MFM/300 kbps\n");
break;
case 5:
density = Track::doubleDensity;
dataRate = Track::dr_250kbps;
debugss(ssFloppyDisk, INFO, "MFM/250 kbps\n");
break;
default:
density = Track::density_Unknown;
dataRate = Track::dr_Unknown;
debugss(ssFloppyDisk, WARNING, "Unknown density/data rate: %d\n", mode);
break;
}
cyl = buf[pos++];
debugss(ssFloppyDisk, ALL, "Cylinder: %d\n", cyl);
head = buf[pos++];
// Check flags.
sectorCylMap = ((head & 0x80) != 0);
sectorHeadMap = ((head & 0x40) != 0);
// mask off any flags
head &= 1;
debugss(ssFloppyDisk, ALL, "Head: %d\n", head);
Track* trk = new Track(head, cyl);
trk->setDataRate(dataRate);
trk->setDensity(density);
numSec = buf[pos++];
debugss(ssFloppyDisk, ALL, "Num Sectors: %d\n", numSec);
sectorSizeKey = buf[pos++];
if (sectorSizeKey < 7)
{
sectorSize = 1 << (sectorSizeKey + 7);
}
else
{
debugss(ssFloppyDisk, ERROR, "Sector Size unknown: %d\n",
sectorSizeKey);
delete [] buf;
delete trk;
return (false);
}
debugss(ssFloppyDisk, ALL, "Sector Size: %d (%d)\n", sectorSize,
sectorSizeKey);
for (int i = 0; i < numSec; i++)
{
sectorOrder[i] = buf[pos++];
}
if (sectorCylMap)
{
debugss(ssFloppyDisk, INFO, "Sector Cylinder Map Present\n");
for (int i = 0; i < numSec; i++)
{
sectorCylMapping[i] = buf[pos++];
}
}
if (sectorHeadMap)
{
debugss(ssFloppyDisk, INFO, "Sector Head Map Present\n");
for (int i = 0; i < numSec; i++)
{
sectorHeadMapping[i] = buf[pos++];
}
}
for (int i = 0; i < numSec; i++)
{
unsigned char sectorType = buf[pos++];
debugss(ssFloppyDisk, INFO, "Sector: %d(%d) Type: %d\n", sectorOrder[i], i, sectorType);
if (sectorType == 0x00)
{
// Sector Data Unavailable
debugss(ssFloppyDisk, INFO, "Sector Size unknown: %d\n", sectorSizeKey);
}
else if (sectorType > 0x08)
{
// Out of Range.
debugss(ssFloppyDisk, ERROR, "Out of Range: %d\n", sectorType);
delete [] buf;
return false;
}
else
{
BYTE type = sectorType - 1;
bool compressed = ((type & 0x01) != 0);
bool deleteData = ((type & 0x02) != 0);
bool dataError = ((type & 0x04) != 0);
BYTE sectorData[sectorSize];
if (compressed)
{
BYTE val = buf[pos++];
for (int i = 0; i < sectorSize; i++)
{
sectorData[i] = val;
}
}
else
{
for (int i = 0; i < sectorSize; i++)
{
sectorData[i] = buf[pos++];
}
}
// create sector
shared_ptr<Sector> sect = make_shared<Sector>(head,
cyl,
sectorOrder[i],
sectorSize,
§orData[0]);
// set flags
sect->setReadError(dataError);
sect->setDeletedDataAddressMark(deleteData);
// add sector to track
trk->addSector(sect);
}
}
// add track to disk
tracks_m[head].push_back(trk);
}
while (pos < fileSize);
delete [] buf;
debugss(ssFloppyDisk, INFO, "Read successful.\n");
return true;
}
bool
SoftSectoredDisk::readRaw(const char* name)
{
// Currently just supporting the RAW HDOS 3.0 disk images... 40 track, single density,
// single sided, 10 sectors/track, 256 bytes/sector.
std::ifstream file;
unsigned long int fileSize;
unsigned long int pos = 0;
BYTE* buf;
file.open(name, std::ios::binary);
if (!file.is_open())
{
debugss(ssFloppyDisk, ERROR, "Unable to open file: %s\n", name);
return false;
}
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
debugss(ssFloppyDisk, INFO, "RAW File: %s\n", name);
if (fileSize != (256 * 10 * 40))
{
debugss(ssFloppyDisk, ERROR, "Invalid File Size: %s - %ld\n", name,
fileSize);
delete [] buf;
return false;
}
for (int trk = 0; trk < 40; trk++)
{
Track* track = new Track(0, trk);
for (int sect = 0; sect < 10; sect++, pos += 256)
{
shared_ptr<Sector> sector = make_shared<Sector>(0, trk, sect, 256, &buf[pos]);
track->addSector(sector);
track->setDensity(Track::singleDensity);
track->setDataRate(Track::dr_300kbps);
}
tracks_m[0].push_back(track);
}
numTracks_m = 40;
numHeads_m = 1;
initialized_m = false;
return true;
}
bool
SoftSectoredDisk::readRaw8(const char* name)
{
// Currently just supporting the RAW 8" Disks .
int numTrks_c = 77;
int numSectors_c = 26;
int bytesPerSector_c = 128;
std::ifstream file;
unsigned long int fileSize;
unsigned long int pos = 0;
BYTE* buf;
file.open(name, std::ios::binary);
if (!file.is_open())
{
debugss(ssFloppyDisk, ERROR, "Unable to open file: %s\n", name);
return false;
}
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
debugss(ssFloppyDisk, INFO, "RAW File: %s\n", name);
switch (fileSize)
{
case 256256:
break;
case 512512:
break;
}
if (fileSize != (bytesPerSector_c * numSectors_c * numTrks_c))
{
debugss(ssFloppyDisk, ERROR, "Invalid File Size: %s - %ld\n", name,
fileSize);
delete [] buf;
return false;
}
for (int trk = 0; trk < numTrks_c; trk++)
{
Track* track = new Track(0, trk);
for (int sect = 0; sect < numSectors_c; sect++, pos += bytesPerSector_c)
{
shared_ptr<Sector> sector = make_shared<Sector>(0,
trk,
sect,
bytesPerSector_c,
&buf[pos]);
track->addSector(sector);
track->setDensity(Track::singleDensity);
track->setDataRate(Track::dr_500kbps);
}
tracks_m[0].push_back(track);
}
numTracks_m = numTrks_c;
numHeads_m = 1;
initialized_m = false;
return true;
}
void
SoftSectoredDisk::determineDiskFormat(const char* name,
DiskImageFormat& format)
{
debugss(ssFloppyDisk, INFO, "Name: %s\n", name);
/// \todo implement
format = dif_Unknown;
}
void
SoftSectoredDisk::dump()
{
debugss(ssFloppyDisk, INFO, "SoftSectored - dump\n");
for (int head = 0; head < numHeads_m; head++)
{
for (int track = 0; track < numTracks_m; track++)
{
debugss(ssFloppyDisk, INFO, " Head: %d Track: %d\n", head, track);
tracks_m[head][track]->dump();
}
}
}
bool
SoftSectoredDisk::readSectorData(BYTE side,
BYTE track,
BYTE sector,
WORD pos,
BYTE& data)
{
debugss(ssFloppyDisk, ALL, "side: %d track: %d sector: %d pos: %d\n", side, track, sector, pos);
// return tracks_m[side][track]->readSectorData(sector, pos, data);
return false;
}
void
SoftSectoredDisk::eject(const char* name)
{
}
#endif
<file_sep>/VirtualH89/Src/z80.h
/// \file z80.h
///
/// \brief Virtual Z-80 processor.
///
/// Clock accurate, all undocumented functions implemented.
/// Undocumented flags NOT implemented.
///
/// \date Mar 7, 2009
///
/// \author <NAME>
///
#ifndef Z80_H_
#define Z80_H_
#include "cpu.h"
#include "GppListener.h"
/// \cond
#include <csignal>
#include <pthread.h>
/// \endcond
class Computer;
class AddressBus;
class IOBus;
///
/// \struct RP
///
/// \brief Register Pair
///
/// A union to allow the register to appear as an unsigned word, a signed word, 2 unsigned
/// bytes, or 2 signed bytes. All without any special casting/conversions.
///
struct RP
{
union
{
/// Option 1, register appears to be 2 unsigned bytes.
struct
{
BYTE lo;
BYTE hi;
};
/// Option 2, register appears to be 2 signed bytes.
struct
{
SBYTE slo;
SBYTE shi;
};
/// Option 3, register appears to be an unsigned word.
WORD val;
/// Option 4, register appears to be a signed word.
SWORD sval;
};
};
///
/// \brief Zilog %Z80 %CPU simulator.
///
/// Complete Z80 CPU simulator based on Z80Pack. The original code was converted
/// to C++ and all of the undocumented opcodes have been implemented. Also, fixed
/// a few of the flags for opcodes like DAA.
///
class Z80: public CPU, public GppListener
{
private:
typedef void (Z80::* opCodeMethod)(void);
typedef void (Z80::* xd_cbMethod)(BYTE&);
void systemMutexCycle();
// data
Computer* computer_m;
AddressBus* ab_m;
IOBus* io_m;
// Registers
// Register Pairs (union to allow all type of accesses without casting).
RP af, bc, de, hl, wz;
RP ix, iy, sp;
// Reference variables to 'point' to the actual data in the register pair (RP).
/// Register A
BYTE& A;
/// Register A viewed as a signed byte
SBYTE& sA;
/// Register Flags
BYTE& F;
/// Full 16-bit register A and Flags
WORD& AF;
/// Register B
BYTE& B;
/// Register C
BYTE& C;
/// Full 16-bit register B and C
WORD& BC;
/// Register D
BYTE& D;
/// Register E
BYTE& E;
/// Full 16-bit register D and E
WORD& DE;
/// Register H
BYTE& H;
/// Register L
BYTE& L;
/// Full 16-bit register H and L
WORD& HL;
/// Full 16-bit register H and L accessed as a signed 16-bit value
SWORD& sHL;
BYTE& W;
SBYTE& sW;
BYTE& Z;
WORD& WZ;
BYTE& IXl;
BYTE& IXh;
WORD& IX;
BYTE& IYl;
BYTE& IYh;
WORD& IY;
WORD& SP;
/// secondary registers. These can be just words since they are always copied to the
/// primary registers before they can be accessed.
WORD _af, _bc, _de, _hl;
/// Program Counter
WORD PC;
WORD xxcb_effectiveAddress;
BYTE I; // Z80 interrupt register
bool IFF0, IFF1, IFF2; // Use a new flag - IFF0 -
// to easily handle the one instruction before EI takes effect
unsigned int R; // Z80 refresh register
BYTE Rprime;
unsigned long int ClockRate_m;
unsigned long int ticksPerSecond_m;
unsigned long int ticksPerClock_m;
bool processingIntr;
volatile sig_atomic_t ticks;
int lastInstTicks;
static const int maxNumInst = 4;
BYTE curInst[maxNumInst];
BYTE curInstByte;
BYTE lastInstByte;
enum instructionPrefix
{
ip_none,
ip_dd,
ip_fd
};
enum cpuMode
{
cm_reset,
cm_running,
cm_singleStep,
cm_halt
};
cpuMode mode;
instructionPrefix prefix;
BYTE IM;
int cpu_state, int_type;
static const opCodeMethod op_code[256];
static const opCodeMethod op_cb[256];
static const opCodeMethod op_ed[256];
static const opCodeMethod op_xxcb[32];
virtual void gppNewValue(BYTE gpo) override;
static const BYTE z80_gppSpeedSelBit_c = 0b00010000;
public:
Z80(Computer* computer,
int clockRate,
int ticksPerSecond);
virtual ~Z80() override;
std::string dumpDebug() override;
virtual void continueRunning(void) override;
virtual void waitState(void) override;
virtual void reset(void) override;
virtual BYTE execute(WORD numInst = 0) override;
virtual BYTE step(void) override;
virtual void raiseNMI(void) override;
virtual void addClockTicks(void) override;
virtual void setAddressBus(AddressBus* ab) override;
virtual void setIOBus(IOBus* io) override;
virtual void setSpeedup(int factor) override;
virtual void enableFast() override;
virtual void raiseINT() override;
virtual void lowerINT() override;
void traceInstructions(void);
protected:
/// Signed Flag
static const BYTE S_FLAG = 0x80;
/// Zero Flag
static const BYTE Z_FLAG = 0x40;
/// Unused Flag 2
static const BYTE N2_FLAG = 0x20;
/// Half-carry Flag
static const BYTE H_FLAG = 0x10;
/// Unused Flag 1
static const BYTE N1_FLAG = 0x08;
/// Parity Flag
static const BYTE P_FLAG = 0x04;
/// Negative Flag
static const BYTE N_FLAG = 0x02;
/// Carry Flag
static const BYTE C_FLAG = 0x01;
///
/// Table to contains the values for Z, S, and P flags. This is done to reduce
/// duplicated code and to be slightly faster, than the individual settings of
/// the flags.
///
static const BYTE ZSP[256];
// 8-bit Register related
BYTE& getReg8(BYTE val);
BYTE& getCoreReg8(BYTE val);
BYTE getReg8Val(BYTE val);
BYTE getCoreReg8Val(BYTE val);
// 16-bit Register related
WORD& getReg16(BYTE val);
WORD& getCoreReg16(BYTE val);
WORD& getHLReg16(void);
WORD getHLReg16Val(void);
WORD getXYReg16Val(void);
WORD getIndirectAddr(void);
WORD getReg16Val(BYTE val);
WORD getCoreReg16Val(BYTE val);
WORD& getReg16qq(BYTE val);
WORD& getCoreReg16qq(BYTE val);
WORD getReg16qqVal(BYTE val);
WORD getCoreReg16qqVal(BYTE val);
BYTE getBit(BYTE val);
bool checkCondition(BYTE val);
// Routines related to the stack.
void PUSH(WORD x);
void POP(WORD& x);
// Routines related to FLAGS.
void SET_FLAGS(BYTE flags);
void CLEAR_FLAGS(BYTE flags);
bool CHECK_FLAGS(BYTE flags);
void UPDATE_FLAGS(BYTE setFlags,
BYTE clearFlags);
void COND_FLAGS(bool cond,
BYTE flags);
void SET_ZSP_FLAGS(BYTE val);
/// Memory related instructions
/// \brief read next instruction byte and increment PC, if not processing interrupt
BYTE readInst(void);
BYTE readMEM(WORD addr);
void writeMEM(WORD addr,
BYTE val);
WORD readWord(WORD addr);
void writeWord(WORD addr,
WORD value);
BYTE READn(void);
SBYTE sREADn(void);
WORD READnn(void);
private:
// Types of interrupts
const int Intr_NMI = 0x01;
const int Intr_INT = 0x02;
// operation of simulated CPU
enum
{
STOPPED_C = 0,
RUN_C = 1,
HALT_C = 2,
SINGLE_STEP_C = 3,
POWEROFF_C = 255
};
/// \todo - move this outside of the z80 class.
unsigned int speedUpFactor_m;
bool fast_m;
// -------------------------
//
// generic routines (i.e. multiple opcodes call them )
//
// This routines share common code and are inlined to help avoid performance
// impact.
//
inline void op_add_reg16(WORD &,
WORD);
inline void op_and(const BYTE);
inline void op_or(const BYTE);
inline void op_xor(const BYTE);
inline void op_add(const BYTE);
inline void op_adc(const BYTE);
inline void op_sub(const BYTE);
inline void op_sbc(const BYTE);
inline void op_cp(const BYTE);
inline void op_inc(BYTE&);
inline void op_dec(BYTE&);
inline void op_srl(BYTE&);
inline void op_sla(BYTE&);
inline void op_undoc_sll(BYTE&);
inline void op_rl(BYTE&);
inline void op_rr(BYTE&);
inline void op_rrc(BYTE&);
inline void op_rlc(BYTE&);
inline void op_sra(BYTE&);
inline void op_in_ic(BYTE&);
// -------------------------
//
// All one byte opcodes.
//
void op_ld_x_x(void);
void op_ld_x_n(void);
void op_ld_xx_nn(void);
void op_inc_x(void);
void op_dec_x(void);
void op_nop(void);
void op_halt(void);
void op_scf(void);
void op_ccf(void);
void op_cpl(void);
void op_daa(void);
void op_ei(void);
void op_di(void);
void op_in(void);
void op_out(void);
void op_ld_a_ibc(void);
void op_ld_a_ide(void);
void op_ld_a_inn(void);
void op_ld_ibc_a(void);
void op_ld_ide_a(void);
void op_ld_inn_a(void);
void op_ld_ihl_x(void);
void op_ld_ihl_n(void);
void op_ld_x_ihl(void);
void op_ld_sp_hl(void);
void op_ld_hl_inn(void);
void op_ld_inn_hl(void);
void op_inc_xx(void);
void op_dec_xx(void);
void op_add_hl_xx(void);
void op_and_x(void);
void op_and_ihl(void);
void op_and_n(void);
void op_or_x(void);
void op_or_ihl(void);
void op_or_n(void);
void op_xor_x(void);
void op_xor_ihl(void);
void op_xor_n(void);
void op_add_x(void);
void op_add_ihl(void);
void op_add_n(void);
void op_adc_x(void);
void op_adc_ihl(void);
void op_adc_n(void);
void op_sub_x(void);
void op_sub_ihl(void);
void op_sub_n(void);
void op_sbc_x(void);
void op_sbc_ihl(void);
void op_sbc_n(void);
void op_cp_x(void);
void op_cp_ihl(void);
void op_cp_n(void);
void op_inc_ihl(void);
void op_dec_ihl(void);
void op_rlc_a(void);
void op_rrc_a(void);
void op_rl_a(void);
void op_rr_a(void);
void op_ex_de_hl(void);
void op_ex_af_af(void);
void op_exx(void);
void op_ex_isp_hl(void);
void op_push_xx(void);
void op_pop_xx(void);
void op_jp(void);
void op_jp_hl(void);
void op_jr(void);
void op_djnz(void);
void op_call(void);
void op_ret(void);
void op_jp_cc(void);
void op_call_cc(void);
void op_ret_cc(void);
void op_jr_z(void);
void op_jr_nz(void);
void op_jr_c(void);
void op_jr_nc(void);
void op_rst(void);
// routines to handle prefix instructions.
void op_cb_handle(void);
void op_dd_handle(void);
void op_ed_handle(void);
void op_fd_handle(void);
void op_ed_nop(void);
//
// Instructions with CB prefix
//
void op_srl_x(void);
void op_srl_ihl(void);
void op_sla_x(void);
void op_sla_ihl(void);
void op_rl_x(void);
void op_rl_ihl(void);
void op_rr_x(void);
void op_rr_ihl(void);
void op_rrc_x(void);
void op_rrc_ihl(void);
void op_rlc_x(void);
void op_rlc_ihl(void);
void op_sra_x(void);
void op_sra_ihl(void);
void op_sb_n(BYTE& val);
void op_sb_n_x(void);
void op_sb_n_ihl(void);
void op_rb_n(BYTE& val);
void op_rb_n_x(void);
void op_rb_n_ihl(void);
void op_tb_n(BYTE m,
BYTE bit);
void op_tb_n_x(void);
void op_tb_n_ihl(void);
//
// undocumented CB instructions
//
void op_sll_x(void);
void op_sll_ihl(void);
//
// ED Prefix instructions
//
void op_im0(void);
void op_im1(void);
void op_im2(void);
void op_reti(void);
void op_retn(void);
void op_neg(void);
void op_in_x_c(void);
void op_out_c_x(void);
void op_in_f_ic(void);
void op_out_c_0(void);
void op_ini(void);
void op_inir(void);
void op_ind(void);
void op_indr(void);
void op_outi(void);
void op_otir(void);
void op_outd(void);
void op_otdr(void);
void op_ld_a_i(void);
void op_ld_a_r(void);
void op_ld_i_a(void);
void op_ld_r_a(void);
void op_ld_xx_inn(void);
void op_ld_inn_xx(void);
void op_adc16(WORD op);
void op_sbc16(WORD op);
void op_adc_hl_xx(void);
void op_sbc_hl_xx(void);
void op_ldi(void);
void op_ldir(void);
void op_ldd(void);
void op_lddr(void);
void op_cpi(void);
void op_cpir(void);
void op_cpd(void);
void op_cpdr(void);
void op_rld_ihl(void);
void op_rrd_ihl(void);
//
// DD CB prefix instructions
// FD CB prefix instructions
//
void op_tb_n_xx_d(void);
void op_rb_n_xx_d(void);
void op_sb_n_xx_d(void);
void op_rlc_xx_d(void);
void op_rrc_xx_d(void);
void op_rl_xx_d(void);
void op_rr_xx_d(void);
void op_sla_xx_d(void);
void op_sll_xx_d(void);
void op_sra_xx_d(void);
void op_srl_xx_d(void);
void op_xxx_xx_d(xd_cbMethod operation);
};
#endif // Z80_H_
<file_sep>/VirtualH89/Src/disasm.h
/// \file disasm.h
///
/// \date May 2, 2009
/// \author <NAME>
///
#ifndef DISASM_H_
#define DISASM_H_
#include "h89Types.h"
BYTE disass(WORD adr);
#endif // DISASM_H_
<file_sep>/VirtualH89/Src/DiskData.cpp
///
/// \file DiskData.cpp
///
///
/// \date Sep 11, 2012
/// \author <NAME>
///
#include "DiskData.h"
#include "logger.h"
/// \cond
#include <fstream>
#include <iostream>
#include <string>
/// \endcond
using namespace std;
DiskData::DiskData(char* name): fileRead_m(false),
valid_m(false),
data_m(0),
dataSize_m(0),
writeProtectedFlag_m(false)
{
ifstream inFile;
// read and store entire file
inFile.open(name, ios::in | ios::binary | ios::ate);
if (inFile.is_open())
{
fileRead_m = true;
dataSize_m = inFile.tellg();
data_m = new BYTE[dataSize_m];
inFile.seekg(0, ios::beg);
inFile.read((char*) data_m, dataSize_m);
inFile.close();
}
}
#if 0
DiskData::DiskData(): fileRead_m(false),
valid_m(true),
data_m(0),
dataSize_m(0),
writeProtectedFlag_m(false)
{
createBlank();
}
#endif
DiskData::~DiskData()
{
}
bool
DiskData::parse()
{
unsigned int pos;
if (!fileRead_m)
{
debugss(ssFloppyDisk, ERROR, "File could not be read\n");
return false;
}
if (dataSize_m < 20) /// \todo determine the minimum size.
{
debugss(ssFloppyDisk, ERROR, "Invalid file size: %lld\n", dataSize_m);
return false;
}
if ((data_m[0] != 'H') || (data_m[2] != '7') || (data_m[3] == 'D'))
{
debugss(ssFloppyDisk, ERROR, "Invalid file signature %c%c%c%c\n", data_m[0],
data_m[1], data_m[2], data_m[3]);
return false;
}
switch (data_m[1])
{
case '1':
debugss(ssFloppyDisk, INFO, "Reading an H17D file.\n");
break;
case '3':
case '4':
case '6':
debugss(ssFloppyDisk, ERROR, "Disk format H%c7D not currently supported\n",
data_m[1]);
return false;
default:
debugss(ssFloppyDisk, ERROR, "Invalid file signature %c%c%c%c\n", data_m[0],
data_m[1], data_m[2], data_m[3]);
return false;
}
majorVersion_m = data_m[4];
minorVersion_m = data_m[5];
pointVersion_m = data_m[6];
debugss(ssFloppyDisk, INFO, "Parsing version: %d.%d.%d\n", majorVersion_m,
minorVersion_m,
pointVersion_m);
pos = 7;
// per spec, blocks must be in order. This is type "0", must be first.
if (data_m[pos] == diskFormatType_c)
{
pos++;
readDiskFormat(pos);
}
else
{
// disk Format Type is missing - not an error, assume standard
// 40 track/single-sided raw format.
}
// this is type "1" must be next.
if (data_m[pos] == flagsType_c)
{
pos++;
if (!readFlags(pos))
{
return false;
}
}
else
{
// no flag block, assume default.
}
while ((pos < dataSize_m) && (data_m[pos] <= dataBlockType_c))
{
if (data_m[pos++] == dataBlockType_c)
{
if (!readDataBlock(pos))
{
return false;
}
}
else
{
if (!readUnknownBlock(pos))
{
// block was mandatory... abort out.
return false;
}
}
}
while (pos < dataSize_m)
{
if (!readUnknownBlock(pos))
{
// block was mandatory... abort out.
return false;
}
}
return true;
}
unsigned int
DiskData::readLength(unsigned int& pos)
{
unsigned int tmp = 0;
tmp = data_m[pos++] << 24;
tmp |= data_m[pos++] << 16;
tmp |= data_m[pos++] << 8;
tmp |= data_m[pos++];
return tmp;
}
bool
DiskData::readDiskFormat(unsigned int& pos)
{
BYTE flags = data_m[pos++];
if ((flags & mandatoryFlag_c) == mandatoryFlag_c)
{
debugss(ssFloppyDisk, WARNING, "Missing Mandatory Flag\n");
}
unsigned int blockLength = readLength(pos);
if (blockLength != diskFormatSize_c)
{
debugss(ssFloppyDisk, ERROR, "Invalid size block: %d expected: %d\n",
blockLength, diskFormatSize_c);
return false;
}
// For the current version,
return true;
}
bool
DiskData::readFlags(unsigned int& pos)
{
BYTE flags = data_m[pos++];
if ((flags & mandatoryFlag_c) == mandatoryFlag_c)
{
debugss(ssFloppyDisk, WARNING, "Missing Mandatory Flag\n");
}
unsigned int blockLength = readLength(pos);
if (blockLength < flagsSize_c)
{
debugss(ssFloppyDisk, ERROR, "Block too short: %d\n", blockLength);
return false;
}
// First is the write protection
writeProtectedFlag_m = ((data_m[pos++] & boolFlagMask_c) == boolFlagMask_c);
// Second is the Distribution Flag
distributionDiskFlag_m = (data_m[pos++] & valueFlagMask_c);
// Third is the source of the track data
imagingTypeFlag_m = (data_m[pos++] & valueFlagMask_c);
// now we must go through the rest of the flags, if any
blockLength -= flagsSize_c;
while (blockLength--)
{
// go through any other flags and check for any mandatory flags, if so, fail
if ((data_m[pos++] & mandatoryFlag_c) == mandatoryFlag_c)
{
return false;
}
}
// end of block, processing passed.
return true;
}
bool
DiskData::readDataBlock(unsigned int& pos)
{
BYTE flags = data_m[pos++];
if ((flags & mandatoryFlag_c) == mandatoryFlag_c)
{
debugss(ssFloppyDisk, WARNING, "Missing Mandatory Flag\n");
}
unsigned int blockLength = readLength(pos);
if (blockLength < diskFormatSize_c)
{
debugss(ssFloppyDisk, ERROR, "Block too short: %d\n", blockLength);
return false;
}
return true;
}
bool
DiskData::readHoleBlock(unsigned int& pos)
{
BYTE flags = data_m[pos++];
if ((flags & mandatoryFlag_c) == mandatoryFlag_c)
{
debugss(ssFloppyDisk, WARNING, "Missing Mandatory Flag\n");
}
unsigned int blockLength = readLength(pos);
/// \todo implement hole block.
pos += blockLength;
// since we don't actually read it yet, we must return failure if we encounter one.
return false;
// return true;
}
bool
DiskData::readUnknownBlock(unsigned int& pos)
{
BYTE flags = data_m[pos++];
debugss(ssFloppyDisk, WARNING, "Unknown block type: 0x%02x\n", data_m[pos - 1]);
if (flags & mandatoryFlag_c)
{
debugss(ssFloppyDisk, ERROR, "Mandatory Block(0x%2x) - Fatal Error.\n", data_m[pos - 2]);
// Encountered a mandatory block we don't know how to process - abort.
return false;
}
// Not mandatory, so skip it.
unsigned int blockLength = readLength(pos);
pos += blockLength;
return true;
}
bool
DiskData::checkWriteProtect()
{
return writeProtectedFlag_m;
}
bool
DiskData::getType(DiskTypes& type)
{
type = fiveHardSectored_c;
return true;
}
<file_sep>/VirtualH89/Src/FloppyDisk.h
/// \file FloppyDisk.h
///
/// \brief Base virtual Floppy Disk
///
/// \date May 19, 2009
///
/// \author <NAME>
///
#ifndef FLOPPYDISK_H_
#define FLOPPYDISK_H_
#include "h89Types.h"
/// \class FloppyDisk
///
/// \brief A virtual floppy disk base class.
///
class FloppyDisk
{
public:
FloppyDisk();
FloppyDisk(const char* name);
virtual ~FloppyDisk();
virtual bool readData(BYTE side,
BYTE track,
unsigned long pos,
BYTE& data) = 0;
virtual bool writeData(BYTE side,
BYTE track,
unsigned long pos,
BYTE data) = 0;
virtual void getControlInfo(unsigned long pos,
bool& hole,
bool& writeProtect) = 0;
virtual void setWriteProtect(bool value);
virtual bool checkWriteProtect(void);
virtual bool readSectorData(BYTE side,
BYTE track,
BYTE sector,
WORD pos,
BYTE& data) = 0;
virtual void eject(const char* name) = 0;
virtual void dump(void) = 0;
virtual void setMaxTrack(BYTE maxTrack);
virtual void setMaxPosition(unsigned int maxPosition);
private:
bool writeProtect_m;
protected:
BYTE maxTrack_m;
unsigned int maxPos_m;
};
#endif // FLOPPYDISK_H_
<file_sep>/VirtualH89/Src/CPNetDevice.cpp
/// \file CPNetDevice.cpp
///
/// Virtual access to host filesystem via CP/Net-style I/O device.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#include "CPNetDevice.h"
#include "HostFileBdos.h"
#include "logger.h"
/// \cond
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <fnmatch.h>
/// \endcond
///
/// User (CP/M) prootocol:
///
/// Init/reset:
/// OUT ctrlPort ; RESET device
/// IN dataPort ; get clientId (only valid after RESET)
/// STA myClientId ; save for CP/Net
/// ; other initialization...
///
/// Send:
/// MVI C,dataPort
/// LXI H,msgbuf
/// MVI B,5 ; header length
/// OUTIR ; send header
/// LDA msgbuf+4 ; msg size (-1)
/// INR A
/// MOV B,A
/// OUTIR ; send message body
/// IN statusPort
/// ANI 02h ; cmd overrun bit
/// RZ ; message accepted
/// ; error case
///
/// Receive:
/// IN statusPort
/// ANI 01h ; data ready
/// JZ Receive
/// MVI C,dataPort
/// LXI H,msgbuf
/// MVI B,5 ; header length
/// INIR ; get header
/// LDA msgbuf+4 ; msg size (-1)
/// INR A
/// MOV B,A
/// INIR ; get message body
/// IN statusPort
/// ANI 04h ; rcv overrun bit
/// RZ ; message OK
/// ; error case
///
/// For reference, standard CP/Net message header is:
/// +0 format code (00 = CP/Net send, 01 = response)
/// +1 dest node ID (server or this client, depending on direction)
/// +2 src node ID (this client or server, '')
/// +3 CP/Net, MP/M, CP/M BDOS function number
/// +4 msg size - 1 (00 = 1, FF = 256)
/// +5... message body
///
CPNetDevice::CPNetDevice(int base, int cid):
IODevice(base, 2),
clientId(cid),
header((struct NetworkServer::ndos*) buffer),
bufIx(0),
msgLen(0),
respLen(0),
initDev(false)
{
}
CPNetDevice::~CPNetDevice()
{
}
void
CPNetDevice::addServer(BYTE serverId, NetworkServer* server)
{
servers[serverId] = server;
}
CPNetDevice*
CPNetDevice::install_CPNetDevice(PropertyUtil::PropertyMapT& props)
{
std::string s;
int cid = 0xfe; // OK default if we have no network connections
s = props["cpnetdevice_port"];
if (s.empty())
{
return nullptr;
}
int port = 0x18;
unsigned long p = strtoul(s.c_str(), nullptr, 0);
if (p <= 255)
{
port = p & 0x0ff;
}
else
{
debugss(ssCPNetDevice, ERROR, "Invalid port %02x, using default\n", p);
}
s = props["cpnetdevice_clientid"];
if (!s.empty())
{
unsigned long c = strtoul(s.c_str(), nullptr, 0);
if (c > 0x00 && c < 0xff)
{
cid = c & 0x0ff;
}
else
{
debugss(ssCPNetDevice, ERROR, "Invalid CP/Net client ID \"%s\"\n", s.c_str());
}
}
debugss(ssCPNetDevice, ERROR, "Creating CPNetDevice device at port %02x, client ID %02x\n",
port, cid);
CPNetDevice* cpnd = new CPNetDevice(port, cid);
PropertyUtil::PropertyMapT::iterator it = props.begin();
for (; it != props.end(); ++it)
{
// property syntax: cpnetdevice_server## = ClassId [args...]
// where '##' is serverId in hex.
if (it->first.compare(0, 18, "cpnetdevice_server") == 0)
{
BYTE sid;
unsigned long si = strtoul(it->first.substr(18).c_str(), nullptr, 16);
// TODO: check for conflicts/duplicates?
if (si < 255)
{
sid = si & 0x0ff;
}
else
{
debugss(ssCPNetDevice, ERROR, "Invalid Server ID %02x: skipping %s\n", si,
it->second.c_str());
continue;
}
debugss(ssCPNetDevice, ERROR, "Server %02x: %s\n", sid, it->second.c_str());
std::vector<std::string> args = PropertyUtil::splitArgs(it->second);
if (args[0].compare("HostFileBdos") == 0)
{
NetworkServer* nws = new HostFileBdos(props, args, sid, cid);
cpnd->addServer(sid, nws);
}
// } else if args[0].compare("Socket") == 0)
// {
// NetworkServer *nws = new SocketServer(props, args, sid, cid);
// cpnd->addServer(sid, nws);
}
}
return cpnd;
}
void
CPNetDevice::reset()
{
initDev = false;
bufIx = 0;
msgLen = 0;
respLen = 0;
}
BYTE
CPNetDevice::in(BYTE adr)
{
BYTE off = getPortOffset(adr);
BYTE val = 0x00;
if (off == statusPortOffset)
{
initDev = false;
if (respLen > 0)
{
val |= sts_DataReady;
}
if (respLen < 0)
{
val |= sts_RespUnderrun;
}
if (msgLen == BUFFER_OVERRUN)
{
val |= sts_CmdOverrun;
}
if (val != 0)
{
// any of these conditions mean the client must do work.
debugss(ssCPNetDevice, INFO, "statusPort = %02x\n", val);
return val;
}
// must be waiting for a response, check and see...
// Should never get here for synchronous server handlers (e.g. CPNetDevice).
int len = checkRecvMsg(clientId, buffer, sizeof(buffer));
if (len > 0)
{
// This includes any failures or errors, must be returned as CP/Net errors.
respLen = sizeof(*header) + header->msize + 1;
val |= sts_DataReady;
}
else if (len < 0)
{
debugss(ssCPNetDevice, ERROR, "Unexpected failure of checkRecvMsg()\n");
}
return val;
}
if (off == dataPortOffset)
{
if (initDev)
{
val = clientId;
initDev = false;
return val;
}
initDev = false;
// works for 'respLen == 0' (no data) case also.
if (bufIx < respLen)
{
val = buffer[bufIx++];
if (bufIx >= respLen)
{
debugss(ssCPNetDevice, INFO, "Response finished: %02x %02x %02x %02x %02x : %02x\n",
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
respLen = 0;
bufIx = 0;
}
}
else
{
// error condition: reading bytes that don't exist.
debugss(ssCPNetDevice, INFO, "Response overrun %d/%d\n", bufIx, respLen);
respLen = -1;
bufIx = 0;
}
return val;
}
debugss(ssCPNetDevice, ERROR, "Invalid port address %02x\n", adr);
return val;
}
void
CPNetDevice::swapIds(struct NetworkServer::ndos* header)
{
BYTE temp = header->mdid;
header->mdid = header->msid;
header->msid = temp;
}
void
CPNetDevice::out(BYTE adr, BYTE val)
{
BYTE off = getPortOffset(adr);
initDev = false;
if (off == statusPortOffset)
{
// reset / resync. other functions needed?
initDev = true; // send clientId on next input data port.
bufIx = 0;
msgLen = 0;
respLen = 0;
return;
}
if (off == dataPortOffset)
{
if (respLen > 0)
{
// response was not yet consumed.
// force error?
msgLen = BUFFER_OVERRUN;
return;
}
if (bufIx < ndosLen)
{
buffer[bufIx++] = val;
if (bufIx >= ndosLen)
{
msgLen = ndosLen + header->msize + 1;
debugss(ssCPNetDevice, INFO, "Setting msglen to %d\n", msgLen);
debugss(ssCPNetDevice, INFO, "Recv hdr: %02x %02x %02x %02x %02x\n",
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);
}
return;
}
if (bufIx < msgLen)
{
debugss(ssCPNetDevice, INFO, "Recv data[%d] %02x\n", bufIx, val);
buffer[bufIx++] = val;
if (bufIx >= msgLen)
{
// we have something to do...
debugss(ssCPNetDevice, INFO, "Command: %02x %02x %02x %02x %02x : %02x\n",
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
if (header->mcode != 0)
{
// We only handle CP/Net messages, but not sure how to indicate
// an error to client for others...
debugss(ssCPNetDevice, ERROR, "Not a CP/Net message\n");
header->mcode |= 0x01;
swapIds(header);
buffer[5] = 0xff;
header->msize = 1 - 1;
}
else
{
int len = sendMsg(buffer, msgLen);
if (len == 0)
{
// indicates async message sent - wait for recv later.
// but currently we don't support that.
bufIx = 0;
msgLen = 0;
return;
}
else if (len < 0)
{
debugss(ssCPNetDevice, ERROR, "Unexpected failure in sendMsg()\n");
// no response is coming, do something...
header->mcode |= 0x01;
swapIds(header);
buffer[5] = 0xff;
header->msize = 1 - 1;
}
header->msize = len - 1;
header->mcode |= 0x01;
swapIds(header);
}
bufIx = 0;
msgLen = 0;
respLen = sizeof(*header) + header->msize + 1;
debugss(ssCPNetDevice, INFO, "Response: %02x %02x %02x %02x %02x : %02x\n",
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
}
// don't do anything, just wait for receiver to execute command?
return;
}
// too many bytes - probably some lost/aborted message.
// need to remember error condition for later.
debugss(ssCPNetDevice, INFO, "Command buffer overrun %d/%d\n", bufIx, msgLen);
msgLen = BUFFER_OVERRUN;
return;
}
debugss(ssCPNetDevice, ERROR, "Invalid port address %02x\n", adr);
}
int
CPNetDevice::checkRecvMsg(BYTE clientId, BYTE* msgbuf, int len)
{
// TODO: interate over servers and call checkRecvMsg on each...
// server message should include these already? but clientId may not be
// known to servers.
// header->mcode = 1; // CP/Net response
// header->mdid = clientId;
// header->msid = serverId;
// header->mfunc = 0; // TODO: save last func? get from
// header->msize = len - 1;
return 0;
}
int
CPNetDevice::sendMsg(BYTE* msgbuf, int len)
{
struct NetworkServer::ndos* hdr = (struct NetworkServer::ndos*) msgbuf;
NetworkServer* nws = servers[hdr->mdid];
if (nws == nullptr)
{
debugss(ssCPNetDevice, ERROR, "Attempting to send to non-existent server %02x\n",
hdr->mdid);
return -1; // reasonable?
}
debugss(ssCPNetDevice, INFO, "Message: %02x %02x %02x %02x %02x : %02x\n",
msgbuf[0], msgbuf[1], msgbuf[2], msgbuf[3], msgbuf[4], msgbuf[5]);
return nws->sendMsg(msgbuf, len);
}
<file_sep>/VirtualH89/Src/GenericFloppyDisk.cpp
/// \file GenericFloppyDisk.cpp
///
/// \brief virtual Floppy Disk interface.
///
/// \date Feb 2, 2016
/// \author <NAME>
///
#include <algorithm>
#include "GenericFloppyDisk.h"
#include "IMDFloppyDisk.h"
#include "TD0FloppyDisk.h"
#include "logger.h"
using namespace std;
GenericFloppyDisk::GenericFloppyDisk(): writeProtect_m(false),
doubleDensity_m(false),
numTracks_m(0),
numSectors_m(0),
numSides_m(0),
secSize_m(0),
mediaSize_m(0),
hypoTrack_m(false),
hyperTrack_m(false)
{
}
GenericFloppyDisk::~GenericFloppyDisk()
{
}
GenericFloppyDisk::FileType_t
GenericFloppyDisk::determineFileType(std::string filename)
{
// Currently just using file extension to choose
// look for last period
size_t pos = filename.rfind('.');
// check if none was found.
if (pos == string::npos)
{
return Unknown;
}
// extract the extension
std::string extension = filename.substr(pos + 1);
// convert to lower case.
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
if (extension == "imd")
{
return IMD;
}
if (extension == "td0")
{
return TD0;
}
// Doesn't match an existing known format.
return Unknown;
}
GenericFloppyDisk_ptr
GenericFloppyDisk::loadDiskImage(vector<string> argv)
{
if (argv.size() < 1)
{
debugss(ssFloppyDisk, WARNING, "no file specified\n");
return nullptr;
}
string filename(argv[0]);
FileType_t fileType = determineFileType(filename);
switch (fileType)
{
case IMD:
return IMDFloppyDisk::getDiskette(argv);
case TD0:
return TD0FloppyDisk::getDiskette(argv);
case Unknown:
return nullptr;
}
}
void
GenericFloppyDisk::setDriveType(BYTE numTracks)
{
// Check if drive/disk match
if (numTracks == numTracks_m)
{
// they match
hypoTrack_m = false;
hyperTrack_m = false;
}
else if ((numTracks == 40) && (numTracks_m == 80))
{
// drive is only 40 tracks but disk is 80.
hyperTrack_m = true;
hypoTrack_m = false;
}
else if ((numTracks == 80) && (numTracks_m == 40))
{
// drive is 80 tracks and disk is 40.
hyperTrack_m = false;
hypoTrack_m = true;
}
else
{
debugss(ssFloppyDisk, ERROR, "unknown drive/disk tracks: %d/%d\n", numTracks, numTracks_m);
}
}
void
GenericFloppyDisk::setWriteProtect(bool value)
{
writeProtect_m = value;
}
BYTE
GenericFloppyDisk::getRealTrackNumber(BYTE track)
{
// possibly update track if format mismatch between drive and disk
if (hyperTrack_m)
{
// skip every other track
return track * 2;
}
else if (hypoTrack_m)
{
// read each track twice
return track / 2;
}
return track;
}
string
GenericFloppyDisk::getMediaName()
{
if (imageName_m.empty())
{
return "NONE";
}
return imageName_m;
}
<file_sep>/VirtualH89/Src/cpu.cpp
/// \file cpu.cpp
///
/// \date Mar 7, 2009
/// \author <NAME>
///
#include "cpu.h"
CPU::CPU()
{
}
CPU::~CPU()
{
}
<file_sep>/VirtualH89/Src/NMIPort.h
///
/// \name NMIPort.h
///
/// \brief Non-Maskable Interrupt port
///
/// \date Jul 15, 2012
/// \author <NAME>
///
#ifndef NMIPORT_H_
#define NMIPORT_H_
#include "IODevice.h"
class CPU;
///
/// \brief Non-Maskable-Interrupt (NMI) Port
///
/// On the H89, a few of the ports defined on the H8 are not implemented. In order to
/// allow software to function on both system, when these addresses are accessed a NMI
/// is generated.
///
class NMIPort: public virtual IODevice
{
public:
NMIPort(CPU* cpu,
BYTE base,
BYTE size);
virtual ~NMIPort() override;
virtual BYTE in(BYTE addr) override;
virtual void out(BYTE addr,
BYTE val) override;
void reset() override
{
}
private:
CPU* cpu_m;
};
#endif /// NMIPORT_H_
<file_sep>/Makefile
SOURCES = $(wildcard VirtualH89/Src/*.cpp)
CHECK = `which scan-build`
UNCRUSTIFY = uncrustify
OBJECTS = $(subst .cpp,.o,$(SOURCES))
.PHONY: clean check uncrust
all: v89
v89: $(OBJECTS)
$(CXX) -o $@ $(OBJECTS) -lpthread -lGL -lglut
CXXFLAGS = -g -std=c++11
clean:
rm -f *.o *.orig
check:
$(CHECK) -stats -load-plugin alpha.cplusplus.VirtualCall -load-plugin alpha.deadcode.UnreachableCode -maxloop 20 -k --use-analyzer Xcode -o check xcodebuild
uncrust:
$(UNCRUSTIFY) -c VirtualH89/uncrust.cfg --no-backup VirtualH89/Src/*.cpp VirtualH89/Src/*.h
<file_sep>/VirtualH89/Src/GeneralPurposePort.cpp
///
/// \file GeneralPurposePort.cpp
///
/// \date Apr 20, 2009
/// \author <NAME>
///
#include "GeneralPurposePort.h"
#include "logger.h"
#include "propertyutil.h"
#include "GppListener.h"
#include "computer.h"
using namespace std;
GeneralPurposePort::GeneralPurposePort(Computer* computer): IODevice(GPP_BaseAddress_c,
GPP_NumPorts_c),
portBits_m(0),
computer_m(computer)
{
dipsw_m = (Mtr89_MemoryTest_Off_c | Mtr89_Port170_Z_89_47_c);
}
GeneralPurposePort::GeneralPurposePort(Computer* computer,
string settings): IODevice(GPP_BaseAddress_c,
GPP_NumPorts_c),
portBits_m(0),
computer_m(computer)
{
// TODO: verify a binary string and/or handle other formats/nmenonics.
dipsw_m = strtol(settings.c_str(), nullptr, 2);
}
GeneralPurposePort::~GeneralPurposePort()
{
}
void
GeneralPurposePort::reset()
{
// do not change 'dispsw_m'!
// portBits_m = 0; // must actually call out()... side-effects...
out(GPP_BaseAddress_c, 0);
}
BYTE
GeneralPurposePort::in(BYTE addr)
{
/// The general purpose port returns the value of SW501.
/// This varies depending on the monitor ROM.
///
/// MTR-88
///
/// Only bits 5-8 are defined for the MTR-88
///
/// bits 4-0 - Undefined.
///
/// bit 5 - force the memory test.
/// 0 - normal operation
/// 1 - memory test
///
/// bit 7 & 6 define the baud rate
/// 00 - 9600
/// 01 - 19,200
/// 10 - 38,400
/// 11 - 57,600
///
///
/// MTR-89
///
/// bits 1 & 0 - Controller in Port 0174(0x7c)/0177(0x7f)
///
/// 00 - H-88-1
/// 01 - H/Z-47 controller
/// 10 - Undefined
/// 11 - Undefined
///
/// bits 3 & 2 - Controller in Port 0170(0x78)/0173(0x7b)
///
/// 00 - Not in use.
/// 01 - H/Z-47 controller
/// 10 - Undefined
/// 11 - Undefined
///
/// bit 4 - Primary boot device
///
/// 0 - Port 0174/0177 (H-88-1)
/// 1 - Port 0170/0173 (H/Z-47)
///
/// bit 5 - Memory Test
///
/// 0 - Perform Memory test upon boot-up
/// 1 - Normal operation
///
/// bit 6 - Console Baud rate
///
/// 0 - 9600
/// 1 - 19200
///
/// bit 7 - Auto boot.
///
/// 0 - Normal (no auto boot)
/// 1 - Auto boot.
///
///
/// MTR-90
///
/// Same as MTR-89 except for bits 0-3
///
/// bits 1 & 0 - Controller in Port 0174(0x7c)/0177(0x7f)
///
/// 00 - H-88-1
/// 01 - Z-89-47
/// 10 - Z-89-67
/// 11 - Undefined
///
/// bits 3 & 2 - Controller in Port 0170(0x78)/0173(0x7b)
///
/// 00 - Z-89-37
/// 01 - Z-89-47
/// 10 - Z-89-67
/// 11 - Undefined
///
BYTE val = 0;
if (verifyPort(addr))
{
val = dipsw_m;
}
return val;
}
void
GeneralPurposePort::out(BYTE addr,
BYTE val)
{
if (verifyPort(addr))
{
// from the manual, writing to this port clears the interrupt.
computer_m->lowerINT(1);
BYTE diffs = portBits_m ^ val;
portBits_m = val;
if (val & gpp_SingleStepInterrupt_c)
{
debugss(ssGpp, WARNING, "Single Step Interrupt - not implemented.\n");
/// \todo - implement single step interrupt..
}
if (diffs != 0)
{
GppListener::notifyListeners(val, diffs);
}
}
}
string
GeneralPurposePort::dumpDebug()
{
string ret = PropertyUtil::sprintf("GP-OUT=%02x GP-IN=%02x\n", portBits_m, dipsw_m);
return ret;
}
<file_sep>/VirtualH89/Src/EightInchDisk.h
///
/// \name EightInchDisk.h
///
///
/// \date Aug 5, 2013
/// \author <NAME>
///
#ifndef EIGHTINCHDISK_H_
#define EIGHTINCHDISK_H_
#include "SoftSectoredDisk.h"
#if 0
class EightInchDisk: public SoftSectoredDisk
{
public:
EightInchDisk();
EightInchDisk(const char* name,
SoftSectoredDisk::DiskImageFormat format);
virtual ~EightInchDisk();
// virtual bool readData(BYTE side, BYTE track, unsigned int pos, BYTE &data);
// virtual bool writeData(BYTE side, BYTE track, unsigned int pos, BYTE data);
// virtual void getControlInfo(unsigned int pos, bool &hole, bool &writeProtect);
// virtual void setWriteProtect(bool value);
// virtual bool checkWriteProtect(void);
// virtual bool readSectorData(BYTE side, BYTE track, BYTE sector, unsigned int pos, BYTE &data);
// virtual void eject(const char *name);
// virtual void dump(void);
private:
};
#endif
#endif // EIGHTINCHDISK_H_
<file_sep>/VirtualH89/Src/MemoryLayout.cpp
///
/// \file MemoryLayout.cpp
///
/// \author <NAME>
/// \date May 8, 2016
///
#include "MemoryLayout.h"
#include "NilMemory8K.h"
using namespace std;
MemoryLayout::MemoryLayout()
{
for (int x = 0; x < 8; ++x)
{
memPage_m[x] = make_shared<NilMemory8K>(pageToAddress(x));
}
}
void
MemoryLayout::addPage(shared_ptr<Memory8K> mem)
{
// error if not NULL?
memPage_m[addressToPage(mem->getBase())] = mem;
}
void
MemoryLayout::addPageAt(shared_ptr<Memory8K> mem, WORD address)
{
// error if not NULL?
memPage_m[addressToPage(address)] = mem;
}
<file_sep>/VirtualH89/Src/IOBus.h
///
/// \file IOBus.h
///
/// \author <NAME>
/// \date April 16, 2016.
///
/// Copyright © 2016 <NAME>. All rights reserved.
///
#ifndef IOBUS_H
#define IOBUS_H
#include "h89Types.h"
class IODevice;
class DiskController;
class IOBus
{
public:
IOBus();
virtual ~IOBus();
virtual bool addDevice(IODevice* device);
virtual bool removeDevice(IODevice* device);
virtual void reset();
virtual BYTE in(BYTE addr);
virtual void out(BYTE addr,
BYTE val);
protected:
IODevice* iodevices[256];
};
#endif // IOBUS_H
<file_sep>/VirtualH89/Src/Console.cpp
/// \file Console.cpp
///
/// \date Feb 6, 2016
///
/// \author <NAME>
///
#include "Console.h"
extern const char* getopts;
Console::Console(int argc,
char** argv)
{
}
Console::~Console()
{
}
std::string
Console::command(std::string cmd)
{
// TODO: develop protocol of commands,
// e.g. "list all disk drives and media" and "mount new media".
// placeholder to fix error under mac os x and xcode.
return "";
}
<file_sep>/VirtualH89/Src/DiskController.h
/// \file DiskController.h
///
/// A wrapper for an IODevice that allows it to be distinguished from other,
/// non-storage, I/O Devices. Requires some methods for handling mounted media.
///
/// \date Feb 8, 2016
/// \author <NAME>
///
#ifndef DISKCONTROLLER_H_
#define DISKCONTROLLER_H_
#include "IODevice.h"
/// \cond
#include <vector>
#include <string>
/// \endcond
class GenericDiskDrive;
/// \todo - determine if interrupt level for the device should be here, or if we subclass
/// this to a IOIntrDevice.
/// I'm thinking subclass it with InterruptDevice.
///
/// \brief Abstract Disk Controller I/O device .
///
/// Base class for all Disk Controller I/O devices.
///
class DiskController: public IODevice
{
public:
///
/// \param base Base address for the I/O device
/// \param numPorts The number of addresses used by the device.
///
DiskController(BYTE base,
BYTE numPorts);
DiskController() = delete;
virtual ~DiskController();
// Return list of all connected disk drives.
virtual std::vector<GenericDiskDrive*> getDiskDrives() = 0;
// Return the nmemonic identifier for this device.
// For example "H17" or "MMS77316".
virtual std::string getDeviceName() = 0;
// Return the disk drive associated with identifer,
// in the form of <deviceName>"-"<driveNumber>.
// Drive numbers start at "1".
virtual GenericDiskDrive* findDrive(std::string ident) = 0;
// Return the "standard" name for disk drive 'index' (0-n).
// This is the same name as will match in findDrive().
// Default if not overriden is getDeviceName()+"-"+<index+1>.
virtual std::string getDriveName(int index) = 0;
virtual std::string dumpDebug() = 0;
protected:
private:
};
#endif // DISKCONTROLLER_H_
<file_sep>/VirtualH89/Src/Sector.cpp
///
/// \name Sector.cpp
///
///
/// \date Jun 22, 2013
/// \author <NAME>
///
#include "Sector.h"
#include "logger.h"
/// \cond
#include <iostream>
/// \endcond
Sector::Sector(BYTE headNum,
BYTE trackNum,
BYTE sectorNum,
WORD sectorLength,
BYTE* data): headNum_m(headNum),
trackNum_m(trackNum),
sectorNum_m(sectorNum),
deletedDataAddressMark_m(false),
readError_m(false),
valid_m(false),
sectorLength_m(sectorLength)
{
data_m = new BYTE[sectorLength_m];
if (data_m)
{
valid_m = true;
for (int i = 0; i < sectorLength_m; i++)
{
data_m[i] = data[i];
}
}
}
Sector::Sector(BYTE headNum,
BYTE trackNum,
BYTE sectorNum,
WORD sectorLength,
BYTE data): headNum_m(headNum),
trackNum_m(trackNum),
sectorNum_m(sectorNum),
deletedDataAddressMark_m(false),
readError_m(false),
valid_m(false),
sectorLength_m(sectorLength)
{
data_m = new BYTE[sectorLength_m];
if (data_m)
{
valid_m = true;
for (int i = 0; i < sectorLength_m; i++)
{
data_m[i] = data;
}
}
}
Sector::~Sector()
{
if (data_m)
{
delete[] data_m;
}
valid_m = false;
}
void
Sector::setDeletedDataAddressMark(bool val)
{
deletedDataAddressMark_m = val;
}
void
Sector::setReadError(bool val)
{
readError_m = val;
}
bool
Sector::getDeletedDataAddressMark()
{
return deletedDataAddressMark_m;
}
bool
Sector::getReadError()
{
return readError_m;
}
void
Sector::dump()
{
debugss(ssFloppyDisk, INFO, "Sector dump - Side: %d Track: %d Sector: %d\n",
headNum_m, trackNum_m, sectorNum_m);
char printable[17];
printable[16] = 0;
for (int i = 0; i < sectorLength_m; i++)
{
if ((i % 16) == 0)
{
debugss(ssFloppyDisk, INFO, " 0x%04x: ", i);
}
else
{
if ((i % 8) == 0)
{
debugss_nts(ssFloppyDisk, INFO, " ");
}
}
// store printable char for end of line
printable[i % 16] = (isprint(data_m[i])) ? data_m[i] : '.';
// print hex value
debugss_nts(ssFloppyDisk, INFO, "%02x", data_m[i]);
if (((i + 1) % 16) == 0)
{
debugss_nts(ssFloppyDisk, INFO, " %s\n", printable);
}
}
}
BYTE
Sector::getSectorNum()
{
return sectorNum_m;
}
WORD
Sector::getSectorLength()
{
return sectorLength_m;
}
BYTE
Sector::getHeadNum()
{
return headNum_m;
}
BYTE
Sector::getTrackNum()
{
return trackNum_m;
}
bool
Sector::readData(WORD pos,
BYTE& data)
{
debugss(ssFloppyDisk, INFO, "pos: %d\n", pos);
if (pos < sectorLength_m)
{
data = data_m[pos];
debugss(ssFloppyDisk, INFO, "Valid pos: %d 0x%02x\n", data, data);
return true;
}
return false;
}
bool
Sector::writeData(WORD pos,
BYTE data)
{
debugss(ssFloppyDisk, INFO, "pos: %d\n", pos);
if (pos < sectorLength_m)
{
data_m[pos] = data;
debugss(ssFloppyDisk, INFO, "Valid pos: %d 0x%02x\n", pos, data);
return true;
}
debugss(ssFloppyDisk, ERROR, "pos: %d sectorLength_m: %d\n", pos, sectorLength_m);
return false;
}
<file_sep>/VirtualH89/Src/SectorFloppyImage.h
/// \file SectorFloppyImage.h
///
/// \brief virtual Floppy Disk implementation for soft-sectored media.
/// Supports media image files that have a sector image of the disk.
///
/// \date Feb 2, 2016
///
/// \author <NAME>
///
#ifndef SECTORFLOPPYIMAGE_H_
#define SECTORFLOPPYIMAGE_H_
#include "h89Types.h"
#include "GenericFloppyDisk.h"
/// \cond
#include <sys/types.h>
#include <string>
#include <vector>
#include <memory>
/// \endcond
class GenericDiskDrive;
/// \class SectorFloppyImage
///
/// \brief A virtual floppy disk
///
class SectorFloppyImage: public GenericFloppyDisk
{
public:
SectorFloppyImage(GenericDiskDrive* drive, std::vector<std::string> argv);
virtual ~SectorFloppyImage() override;
static std::shared_ptr<GenericFloppyDisk> getDiskette(GenericDiskDrive* drive,
std::vector<std::string> argv);
bool readData(BYTE track, BYTE side, BYTE sector, int inSector, int& data) override;
bool writeData(BYTE track, BYTE side, BYTE sector, int inSector,
BYTE data, bool dataReady, int& result) override;
bool findSector(BYTE side,
BYTE track,
BYTE sector) override;
bool isReady() override;
void eject(const std::string name) override;
void dump(void) override;
std::string getMediaName() override;
private:
const char* imageName_m;
int imageFd_m;
BYTE* secBuf_m;
int bufferedTrack_m;
int bufferedSide_m;
int bufferedSector_m;
off_t bufferOffset_m;
bool bufferDirty_m;
bool hypoTrack_m; // ST media in DT drive
bool hyperTrack_m; // DT media in ST drive
bool interlaced_m;
int mediaLat_m;
BYTE secLenCode_m;
int gapLen_m;
int indexGapLen_m;
unsigned long writePos_m;
bool trackWrite_m;
int dataPos_m;
int dataLen_m;
bool checkHeader(BYTE* buf, int n);
bool cacheSector(int side, int track, int sector);
protected:
};
#endif // SECTORFLOPPYIMAGE_H_
<file_sep>/VirtualH89/Src/propertyutil.cpp
// Java-Style Properties in C++
//
// (c) <NAME>
// Senzee 5
// http://senzee.blogspot.com
#include "propertyutil.h"
/// \cond
#include <sstream>
#include <fstream>
#include <exception>
#include <cstdarg>
#include <memory>
/// \endcond
void
PropertyUtil::read(const char* filename,
PropertyMapT& map)
{
std::ifstream file(filename);
if (!file)
{
throw std::exception();
}
read(file, map);
file.close();
}
void
PropertyUtil::read(std::istream& is,
PropertyMapT& map)
{
if (!is)
{
throw std::exception();
}
char ch = 0;
ch = is.get();
while (!is.eof())
{
switch (ch)
{
case '#':
case '!':
do
{
ch = is.get();
}
while (!is.eof() && ch >= 0 && ch != '\n' && ch != '\r');
continue;
case '\n':
case '\r':
case ' ':
case '\t':
ch = is.get();
continue;
}
// Read the key
std::ostringstream key, val;
while (!is.eof() && ch >= 0 && ch != '=' && ch != ':' &&
ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r')
{
key << ch;
ch = is.get();
}
while (!is.eof() && (ch == ' ' || ch == '\t'))
{
ch = is.get();
}
if (!is.eof() && (ch == '=' || ch == ':'))
{
ch = is.get();
}
while (!is.eof() && (ch == ' ' || ch == '\t'))
{
ch = is.get();
}
// Read the value
while (!is.eof() && ch >= 0 && ch != '\n' && ch != '\r')
{
int next = 0;
if (ch == '\\')
{
ch = is.get();
switch (ch)
{
case '\r':
ch = is.get();
if (ch != '\n' && ch != ' ' && ch != '\t')
{
continue;
}
// fall through
case '\n':
ch = is.get();
while (!is.eof() && (ch == ' ' || ch == '\t'))
{
is >> ch;
}
continue;
case 't':
ch = '\t';
next = is.get();
break;
case 'n':
ch = '\n';
next = is.get();
break;
case 'r':
ch = '\r';
next = is.get();
break;
case 'u':
{
ch = is.get();
while (!is.eof() && ch == 'u')
{
is >> ch;
}
int d = 0;
loop:
for (int i = 0; !is.eof() && i < 4; i++)
{
next = is.get();
switch (ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
d = (d << 4) + ch - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
d = (d << 4) + 10 + ch - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
d = (d << 4) + 10 + ch - 'A';
break;
default:
goto loop;
}
ch = is.get();
}
ch = d;
break;
}
default:
next = is.get();
break;
}
}
else
{
next = is.get();
}
val << ch;
ch = next;
}
// if (DEBUG)
// std::cout << "key:" << key.str() << "|value:" << val.str() << std::endl;
map[key.str()] = val.str();
}
}
void
PropertyUtil::write(const char* filename,
PropertyMapT& map,
const char* header)
{
std::ofstream file(filename);
write(file, map, header);
file.close();
}
void
PropertyUtil::write(std::ostream& os,
PropertyMapT& map,
const char* header)
{
if (header != nullptr)
{
os << '#' << header << std::endl;
}
os << '#';
os << " <date> " << std::endl;
for (iterator it = map.begin(), end = map.end(); it != end; ++it)
{
const std::string& key = (*it).first,
& val = (*it).second;
os << key << '=';
bool empty = false;
for (size_t i = 0, sz = val.size(); i < sz; i++)
{
char ch = val[i];
switch (ch)
{
case '\\':
os << '\\' << '\\';
break;
case '\t':
os << '\\' << 't';
break;
case '\n':
os << '\\' << 'n';
break;
case '\r':
os << '\\' << 'r';
break;
default:
if (ch < ' ' || ch >= 127 || (empty && ch == ' '))
{
os << '\\' << 'u'
<< m_hex((ch >> 12) & 0x0f) << m_hex((ch >> 8) & 0x0f)
<< m_hex((ch >> 4) & 0x0f) << m_hex((ch >> 0) & 0x0f);
}
else
{
os << ch;
}
}
empty = false;
}
os << std::endl;
}
}
void
PropertyUtil::print(std::ostream& os,
PropertyMapT& map)
{
iterator it = map.begin(), end = map.end();
for (; it != end; ++it)
{
os << (*it).first << "=" << (*it).second << std::endl;
}
}
std::vector<std::string> PropertyUtil::splitArgs(std::string prop)
{
std::vector<std::string> args;
std::istringstream ss(prop);
std::string arg;
while (ss >> arg)
{
args.push_back(arg);
}
return args;
}
std::string
PropertyUtil::combineArgs(std::vector<std::string> args,
int start)
{
std::string str;
for (int x = start; x < args.size(); ++x)
{
if (x > start)
{
str += ' ';
}
str += args[x];
}
return str;
}
std::vector<std::string> PropertyUtil::shiftArgs(std::vector<std::string> args,
int start)
{
std::vector<std::string> oargs;
for (int x = start; x < args.size(); ++x)
{
oargs.push_back(args[x]);
}
return oargs;
}
std::string
PropertyUtil::sprintf(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
size_t size = vsnprintf(nullptr, 0, fmt, vl) + 1;
va_end(vl);
std::unique_ptr<char[]> buf(new char[size]);
va_start(vl, fmt);
vsnprintf(buf.get(), size, fmt, vl);
va_end(vl);
return std::string(buf.get(), buf.get() + size - 1);
}
<file_sep>/VirtualH89/Src/GenericDiskDrive.h
/// \file GenericDiskDrive.h
///
/// Interface for a floppy disk drive, supporting methods for handling
/// mounted media.
///
/// \date Feb 1, 2016
/// \author <NAME>
///
#ifndef GENERICDISKDRIVE_H_
#define GENERICDISKDRIVE_H_
/// \cond
#include <string>
#include <memory>
/// \endcond
class GenericFloppyDisk;
///
/// \brief Virtual Generic Disk Drive
///
/// Implements a virtual floppy disk drive. Supports 48/96 tpi 5.25",
/// 48 tpi 8", either can be SS or DS. Note, the media determines density.
///
class GenericDiskDrive
{
public:
GenericDiskDrive();
virtual ~GenericDiskDrive();
virtual std::string getMediaName() = 0;
virtual void insertDisk(std::shared_ptr<GenericFloppyDisk> disk) = 0;
// Returns the number of raw bytes per track, lowest density.
virtual int getRawBytesPerTrack() = 0;
virtual int getNumTracks() = 0;
virtual bool isReady() = 0;
virtual bool isWriteProtect() = 0;
private:
};
#endif // GENERICDISKDRIVE_H_
<file_sep>/VirtualH89/Src/H88MemoryDecoder.cpp
///
/// \file H88MemoryDecoder.cpp
///
/// Basic memory layout of bare-bones H88 48K RAM system.
///
/// \date Mar 05, 2016
/// \author <NAME>
///
#include "H88MemoryDecoder.h"
#include "Memory8K.h"
#include "SystemMemory8K.h"
#include "logger.h"
using namespace std;
/// H88 without support for ORG-0
H88MemoryDecoder::H88MemoryDecoder(std::shared_ptr<SystemMemory8K> systemRam,
MemoryLayout::MemorySize_t memSize): MemoryDecoder(
NumMemoryLayouts_c,
gppMask_c)
{
// only one layout if H89 doesn't have ORG-0
MemoryLayout_ptr h89_0 = make_shared<MemoryLayout>();
// addLayout(0, make_shared<H88MemoryLayout>(systemRam, memSize));
// ROM at 0x0000
h89_0->addPage(systemRam);
unsigned numBanks;
switch (memSize)
{
case MemoryLayout::Mem_16k:
debugss(ssMEM, INFO, "16k memory specified\n");
numBanks = 2;
break;
case MemoryLayout::Mem_32k:
debugss(ssMEM, INFO, "32k memory specified\n");
numBanks = 4;
break;
case MemoryLayout::Mem_48k:
debugss(ssMEM, INFO, "48k memory specified\n");
numBanks = 6;
break;
case MemoryLayout::Mem_64k:
debugss(ssMEM, ERROR, "Invalid 64k memory specified\n");
numBanks = 6;
break;
default:
debugss(ssMEM, ERROR, "Invalid memory specified\n");
numBanks = 6;
break;
}
for (int x = 0; x < numBanks; ++x)
{
h89_0->addPage(make_shared<RAMemory8K>(MemoryLayout::pageToAddress(x + 1)));
}
addLayout(0, h89_0);
}
H88MemoryDecoder::~H88MemoryDecoder()
{
}
void
H88MemoryDecoder::gppNewValue(BYTE)
{
// do nothing, this memory decoder doesn't support ORG-0 functionality
}
<file_sep>/VirtualH89/Src/HostFileBdos.h
/// \file HostFileBdos.h
///
/// Virtual access to host filesystem via CP/Net-style I/O device.
///
/// \date Feb 19, 2016
/// \author <NAME>
///
#ifndef HOSTFILEBDOS_H_
#define HOSTFILEBDOS_H_
#include "NetworkServer.h"
#include "propertyutil.h"
/// \cond
#include <dirent.h>
#include <string>
/// \endcond
#define BDOS_FUNC(name) \
int name(uint8_t * msgbuf, int len); \
static int name(HostFileBdos * thus, uint8_t * msgbuf, int len) { \
return thus->name(msgbuf, len); \
}
// An instance of HostFileBdos represents a client-server pair.
// This is typically a dedicated network connection (e.g. socket),
// but may also be an informal pairing such as a virtual machine's
// "connection" to the native host.
class HostFileBdos: public NetworkServer
{
public:
HostFileBdos(PropertyUtil::PropertyMapT& props,
std::vector<std::string> args, uint8_t srvId, uint8_t cltId);
virtual ~HostFileBdos() override;
virtual int checkRecvMsg(uint8_t clientId, uint8_t* msgbuf, int len) override;
virtual int sendMsg(uint8_t* msgbuf, int len) override;
private:
char* dir;
uint8_t serverId;
uint8_t clientId;
struct fcb
{
uint8_t drv;
uint8_t name[11];
uint8_t ext;
uint8_t s1[2];
uint8_t rc;
union
{
uint8_t d0[16];
struct
{
uint16_t fd;
uint16_t fd_;
int oflags;
};
};
uint8_t cr;
uint8_t rr[3];
} __attribute__((packed));
struct fcbdate
{
uint16_t date;
uint8_t hour, min;
} __attribute__((packed));
struct cpmdate
{
uint16_t date;
uint8_t hour, min, sec;
} __attribute__((packed));
struct sfcbs
{
struct fcbdate atim;
struct fcbdate utim;
uint8_t pwmode;
uint8_t reserved;
} __attribute__((packed));
struct sfcb
{
uint8_t drv; // always 0x21
struct sfcbs fcbs[3];
uint8_t reserved;
} __attribute__((packed));
struct dirl
{
uint8_t drv; // always 0x20
uint8_t name[11];
uint8_t ext; // mode byte
uint8_t s1[2]; // 0x00 0x00
uint8_t rc; // 0x00
uint8_t pwd[8]; // <PASSWORD>
struct fcbdate ctim;
struct fcbdate utim;
} __attribute__((packed));
struct search
{
int iter;
int lastit;
int endit;
uint8_t maxdc; // 3 or 4, depending on timestamps (SFCBs)
uint8_t drv;
uint8_t usr;
uint8_t ext;
uint8_t full;
uint8_t cpm3;
off_t size;
struct find
{
DIR* dir;
char pat[16];
char path[1024];
int dirlen;
} find;
};
struct dpb
{
uint16_t spt;
uint8_t bsh;
uint8_t blm;
uint8_t exm;
uint16_t dsm;
uint16_t drm;
uint8_t al0;
uint8_t al1;
uint16_t cks;
uint16_t off;
} __attribute__((packed));
static const int DEF_BLS_SH = 14; // 2^14 = 16K
static const int DEF_BLS = (1 << DEF_BLS_SH);
static const int DEF_NBLOCKS = 128; // keep alloc vec small, disk size 2M
static const int DEF_NFILE = 32; // Probably never need even 8.
static const uint8_t dirMode = 0b01100001;
static int(*bdosFunctions[256])(HostFileBdos*, uint8_t*, int);
uint16_t curDma;
void* curDmaReal;
uint16_t curDsk;
uint16_t curUsr;
uint16_t curROVec;
uint16_t curLogVec;
struct search curSearch;
struct dpb curDpb;
int phyExt; // phy ext size, recs
int openFiles[DEF_NFILE];
char fileName[sizeof((struct dirent*) 0)->d_name];
char pathName[PATH_MAX];
struct sfcb sFcb;
BDOS_FUNC(getDPB);
BDOS_FUNC(writeProt);
BDOS_FUNC(resetDrive);
BDOS_FUNC(getROVec);
BDOS_FUNC(getAllocVec);
BDOS_FUNC(getLoginVec);
BDOS_FUNC(selectDisk);
BDOS_FUNC(openFile);
BDOS_FUNC(closeFile);
BDOS_FUNC(searchNext);
BDOS_FUNC(searchFirst);
BDOS_FUNC(deleteFile);
BDOS_FUNC(readSeq);
BDOS_FUNC(writeSeq);
BDOS_FUNC(createFile);
BDOS_FUNC(renameFile);
BDOS_FUNC(readRand);
BDOS_FUNC(writeRand);
BDOS_FUNC(setRandRec);
BDOS_FUNC(compFileSize);
BDOS_FUNC(setFileAttrs);
BDOS_FUNC(accessDrive);
BDOS_FUNC(freeDrive);
BDOS_FUNC(writeRandZF);
BDOS_FUNC(lockRec);
BDOS_FUNC(unlockRec);
BDOS_FUNC(getFreeSp);
BDOS_FUNC(flushBuf);
BDOS_FUNC(freeBlks);
BDOS_FUNC(truncFile);
BDOS_FUNC(login);
BDOS_FUNC(logoff);
BDOS_FUNC(setCompAttrs);
BDOS_FUNC(getServCfg);
BDOS_FUNC(setDefPwd);
BDOS_FUNC(getDirLab);
BDOS_FUNC(readFStamps);
BDOS_FUNC(getTime);
// Utility functions
int cpmDrive(char* buf, int drive);
int cpmFilename(char* buf, int user, char* file);
int cpmPath(char* buf, int drive, int user, char* file);
char* cpmNameFound(struct search::find* find);
char* cpmPathFound(struct search::find* find);
void cpmFindInit(struct search::find* find, int drive, char* pattern);
const char* cpmFind(struct search::find* find);
void getFileName(char* dst, struct fcb* fcb);
void getAmbFileName(char* dst, struct fcb* fcb, uint8_t usr);
void copyOutDir(uint8_t* dma, const char* name);
int fullSearch(uint8_t* dirbuf, struct search* search, const char* ff);
int copyOutSearch(uint8_t* buf, const char* name);
const char* commonSearch(struct search* search);
const char* doSearch(struct search* search);
const char* startSearch(struct fcb* fcb, struct search* search, uint8_t u);
void seekFile(struct fcb* fcb);
int openFileFcb(struct fcb* fcb, uint8_t u);
int newFileFcb();
int locFileFcb(struct fcb* fcb);
void putFileFcb(struct fcb* fcb, int ix, int fd);
int getFileFcb(struct fcb* fcb);
int closeFileFcb(struct fcb* fcb);
int makeFileFcb(struct fcb* fcb, uint8_t u);
void unix2cpmdate(time_t unx, struct cpmdate* cpm);
};
#endif // HOSTFILEBDOS_H_
<file_sep>/VirtualH89/Src/SerialPortDevice.cpp
/// \file SerialPortDevice.cpp
///
/// \date Apr 23, 2009
/// \author <NAME>
///
#include "SerialPortDevice.h"
#include "INS8250.h"
#include "logger.h"
SerialPortDevice::SerialPortDevice(): port_m(0)
{
}
SerialPortDevice::~SerialPortDevice()
{
}
void
SerialPortDevice::attachPort(INS8250* port)
{
port_m = port;
}
bool
SerialPortDevice::sendReady()
{
return port_m != nullptr && port_m->receiveReady();
}
bool
SerialPortDevice::sendData(BYTE data)
{
if (port_m)
{
port_m->receiveData(data);
return true;
}
debugss(ssSerial, WARNING, "port_m is NULL\n");
return false;
}
<file_sep>/VirtualH89/Src/DiskSide.cpp
//
// DiskSide.cpp
// VirtualH89
//
// Created by <NAME> on 6/27/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#include "DiskSide.h"
#include "Track.h"
#include "Sector.h"
#include "logger.h"
using namespace std;
DiskSide::DiskSide(BYTE sideNum): sideNum_m(sideNum)
{
debugss(ssFloppyDisk, INFO, "%s: sideNum = %d\n", __FUNCTION__, sideNum);
if (sideNum > 1)
{
debugss(ssFloppyDisk, ERROR, "%s: out of range - sideNum = %d\n", __FUNCTION__, sideNum);
}
}
DiskSide::~DiskSide()
{
}
bool
DiskSide::addTrack(std::shared_ptr<Track> track)
{
unsigned long curSize = trackData_m.size();
// we expect the tracks in order, warn if that is not the case.
if (track->getTrackNumber() != curSize)
{
debugss(ssFloppyDisk, WARNING, "%s: unexpected trackNum: %d curSize: %d\n",
__FUNCTION__, track->getTrackNumber(), curSize);
}
// add it anyways
trackData_m.push_back(track);
return true;
}
std::shared_ptr<Sector>
DiskSide::findSector(BYTE trackNum, BYTE sectorNum)
{
debugss(ssFloppyDisk, INFO, "findSector - track %d sector: %d\n", trackNum, sectorNum);
if (trackNum >= trackData_m.size())
{
return nullptr;
}
shared_ptr<Track> track = trackData_m[trackNum];
// Normally they should be in order, but nothing in the file format guarantees that
if (track->getTrackNumber() != trackNum)
{
track = nullptr;
// not found where expected, lets see if we can find the matching track
for (shared_ptr<Track> testTrack : trackData_m)
{
if (testTrack->getTrackNumber() == trackNum)
{
debugss(ssFloppyDisk, INFO, "found\n");
track = testTrack;
break;
}
}
}
if (!track)
{
return nullptr;
}
return track->findSector(sectorNum);
}
<file_sep>/VirtualH89/Src/Terminal.cpp
/// \file Terminal.cpp
///
/// \date Apr 12, 2009
///
/// \author <NAME>
///
#include "Terminal.h"
Terminal::Terminal()
{
}
Terminal::~Terminal()
{
}
<file_sep>/VirtualH89/Src/EightInchDisk.cpp
///
/// \name EightInchDisk.cpp
///
///
/// \date Aug 5, 2013
/// \author <NAME>
///
#if 0
#include "EightInchDisk.h"
#include "logger.h"
#include "Track.h"
#include "Sector.h"
/// \cond
#include <iostream> // std::cout
#include <fstream> // std::ifstream
/// \endcond
using namespace std;
EightInchDisk::EightInchDisk()
{
// TODO Auto-generated constructor stub
}
EightInchDisk::EightInchDisk(const char* name,
SoftSectoredDisk::DiskImageFormat format): SoftSectoredDisk(name,
format)
{
}
EightInchDisk::~EightInchDisk()
{
// TODO Auto-generated destructor stub
}
#if 0
bool
EightInchDisk::readRaw8(const char* name)
{
// Currently just supporting the RAW HDOS 3.0 disk images... 40 track, single density,
// single sided, 10 sectors/track, 256 bytes/sector.
ifstream file;
unsigned long int fileSize;
unsigned long int pos = 0;
BYTE* buf;
file.open(name, ios::binary);
if (!file.is_open())
{
debugss(ssFloppyDisk, ERROR, "%Unable to open file: %s\n", name);
return false;
}
file.seekg(0, ios::end);
fileSize = file.tellg();
file.seekg(0, ios::beg);
buf = new BYTE[fileSize];
file.read((char*) buf, fileSize);
file.close();
debugss(ssFloppyDisk, INFO, "RAW File: %s - Size: %lu\n", name, fileSize);
switch (fileSize)
{
case 256256: // 1 side, 77 track, 26 sectors, 128 byte - FM
break;
case 512512: // 1 side, 77 track, 26 sectors, 256 byte - MFM
// 1 side, 77 track, x sectors, 256 byte - FM
break;
}
if (fileSize != (256 * 10 * 40))
{
debugss(ssFloppyDisk, ERROR, "Invalid File Size: %s - %ld\n", name,
fileSize);
delete [] buf;
return false;
}
for (int trk = 0; trk < 40; trk++)
{
Track* track = new Track(0, trk);
for (int sect = 0; sect < 10; sect++, pos += 256)
{
Sector* sector = new Sector(0, trk, sect, 256, &buf[pos]);
track->addSector(sector);
track->setDensity(Track::singleDensity);
track->setDataRate(Track::dr_300kbps);
}
tracks_m[0].push_back(track);
}
numTracks_m = 40;
numHeads_m = 1;
initialized_m = false;
return true;
}
#endif
#if 0
bool
EightInchDisk::readData(BYTE side,
BYTE track,
unsigned int pos,
BYTE& data)
{
return false;
}
bool
EightInchDisk::writeData(BYTE side,
BYTE track,
unsigned int pos,
BYTE data)
{
return false;
}
void
EightInchDisk::getControlInfo(unsigned int pos,
bool& hole,
bool& writeProtect)
{
}
void
EightInchDisk::setWriteProtect(bool value)
{
}
bool
EightInchDisk::checkWriteProtect(void)
{
return true;
}
bool
EightInchDisk::readSectorData(BYTE side,
BYTE track,
BYTE sector,
unsigned int pos,
BYTE& data)
{
return false;
}
void
EightInchDisk::eject(const char* name)
{
}
void
EightInchDisk::dump(void)
{
SoftSectoredDisk::dump();
}
#endif
#endif
<file_sep>/VirtualH89/Src/IODevice.h
/// \file IODevice.h
///
/// \date Apr 20, 2009
/// \author <NAME>
///
#ifndef IODEVICE_H_
#define IODEVICE_H_
#include "h89Types.h"
/// \todo - determine if interrupt level for the device should be here, or if we subclass
/// this to a IOIntrDevice.
/// I'm thinking subclass it with InterruptDevice.
///
/// \brief Abstract I/O device .
///
/// Base class for all I/O devices.
///
class IODevice
{
public:
///
/// \param base Base address for the I/O device
/// \param numPorts The number of addresses used by the device.
///
IODevice(BYTE base,
BYTE numPorts);
virtual ~IODevice();
///
/// Read from specified port
///
/// \param[in] addr Address of port to read
///
/// \retval The value read from the device at the specified address.
virtual BYTE in(BYTE addr) = 0;
///
/// Write to specified port
///
/// \param[in] addr Address of port to write
/// \param[in] val Value to write to the board
///
virtual void out(BYTE addr, BYTE val) = 0;
///
/// Gets configured base address
///
/// \return The configured base address for this device
///
virtual BYTE getBaseAddress(void);
///
/// Gets number of ports
///
/// \return The number of ports this device uses.
///
virtual BYTE getNumPorts(void);
///
/// Verify of the specified address maps to this device
///
/// \param[in] addr The address to verify
/// \return If specified address maps to this device
/// \retval true - Address maps to this device
/// \retval false - Address does no map to this device.
///
virtual bool verifyPort(BYTE addr);
///
/// Determine the offset of a given port based on
/// the base address.
///
/// \param[in] addr The address used to determine the offset
/// \retval offset of the port.
///
virtual BYTE getPortOffset(BYTE addr);
// System RESET, may be ignored by device - if appropiate
virtual void reset() = 0;
protected:
///
/// Base Address for the device
///
BYTE baseAddress_m;
///
/// Number of ports used by this device
///
BYTE numPorts_m;
private:
/// Hide default constructor.
IODevice();
};
#endif // IODEVICE_H_
<file_sep>/VirtualH89/Src/StdioConsole.cpp
/// \file StdioConsole.cpp
///
/// \date Feb 6, 2016
/// \author <NAME>
///
#include "StdioConsole.h"
#include "logger.h"
/// \cond
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
/// \endcond
extern const char* getopts;
/// \brief StdioConsole
///
///
StdioConsole::StdioConsole(int argc,
char** argv): Console(argc, argv)
{
}
StdioConsole::~StdioConsole()
{
}
void
StdioConsole::init()
{
}
void
StdioConsole::reset()
{
}
void
StdioConsole::display()
{
}
void
StdioConsole::processCharacter(char ch)
{
}
void
StdioConsole::keypress(char ch)
{
if (ch == 0x0a)
{
ch = 0x0d;
}
sendData(ch);
}
void
StdioConsole::receiveData(BYTE ch)
{
static int mode = 0;
if (mode > 0)
{
if (ch == 'Z')
{
sendData('K');
mode = -1;
}
else
{
mode = 0;
}
}
else if (mode == 0 && ch == 0x1b)
{
++mode;
}
else
{
fputc(ch, stdout);
fflush(stdout);
}
}
bool
StdioConsole::checkUpdated()
{
return false;
}
unsigned int
StdioConsole::getBaudRate()
{
return SerialPortDevice::DISABLE_BAUD_CHECK;
}
void
StdioConsole::run()
{
int ret;
int c;
struct termios termios0;
struct termios termios;
fprintf(stdout, "Press ESC to quit.\n");
fflush(stdout);
setbuf(stdin, nullptr);
ret = tcgetattr(0, &termios);
if (ret == 0)
{
memcpy(&termios0, &termios, sizeof(termios0));
termios.c_lflag &= ~ICANON;
termios.c_lflag &= ~ECHO;
ret = tcsetattr(0, 0, &termios);
}
while ((c = fgetc(stdin)) != EOF)
{
if (c == 0x1b)
{
break;
}
keypress(c);
}
if (ret == 0)
{
tcsetattr(0, 0, &termios0);
}
}
<file_sep>/VirtualH89/Src/H47Drive.h
///
/// \name H47Drive.h
///
///
/// \date Jul 27, 2013
/// \author <NAME>
///
#ifndef H47DISK_H_
#define H47DISK_H_
#include "DiskDrive.h"
#include "h89Types.h"
/// \cond
#include <memory>
/// \endcond
class H47Drive: public DiskDrive
{
public:
H47Drive();
virtual ~H47Drive() override;
virtual void getControlInfo(unsigned long pos,
bool& hole,
bool& trackZero,
bool& writeProtect) override;
virtual void selectSide(BYTE side) override;
virtual void step(bool direction) override;
virtual BYTE readData(unsigned long pos) override;
virtual void writeData(unsigned long pos,
BYTE data) override;
virtual BYTE readSectorData(BYTE sector,
unsigned long pos) override;
virtual void insertDisk(std::shared_ptr<FloppyDisk> disk) override;
private:
static const unsigned int maxTracks_c = 77;
static const unsigned int maxSectorsPerTrack_c = 26;
static const unsigned int maxBytesPerSector_c = 256;
static const unsigned int sectorsPerTrack_c = 8;
unsigned int tracks_m;
unsigned int sectors_m;
unsigned int bytes_m;
unsigned int track_m;
unsigned int sector_m;
unsigned int byte_m;
BYTE data_m[maxTracks_c][maxSectorsPerTrack_c][maxBytesPerSector_c];
};
#endif // H47DRIVE_H_
| 258d3714d321572b6d4fe1cf7a6462d44fd333d7 | [
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 170 | C++ | mgarlanger/VirtualH89 | 093ebb6be8a2d2a37b6e2e59f16b7c422b71665d | ef6db117ba08c8ec0a456f96d61180a64c9352bc |
refs/heads/master | <file_sep>from bs4 import BeautifulSoup
import requests
import datetime
import os
import sched, time
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
urlSIMM = ("https://www.medellin.gov.co/simm/mapas/camaras.html")
r = requests.get(urlSIMM)
s = sched.scheduler(time.time, time.sleep)
def _load_Cams(sc):
logging.info('Starting scraper on {}...'.format(urlSIMM))
html = r.content
soup = BeautifulSoup(html, 'html.parser')
cams = []
onlineCams = soup.find_all(class_="cameraThumb")
success = 0
paths = 0
logging.info('Cheking paths...')
logging.info('Scraper was started!')
for online in onlineCams:
urlCam = online.find('img').get('src')
cams.append(('{}'.format((urlCam.split('/')[-1]))))
logging.info('Cam {} found!'.format(urlCam))
nowFolder = datetime.datetime.now().strftime('%Y_%m_%d')
nowFile = datetime.datetime.now().strftime('%H:%M:%S')
for cam in cams:
#response = requests.get(urlCam)
camName = (cam.replace('imagen', 'cam'))
folderName = camName.replace('.jpg','')
file_name = '{}_{}_{}'.format(nowFolder,nowFile,camName)
pathDirs = (('{}/{}'.format(folderName,nowFolder)))
try:
if not os.path.exists('{}/{}'.format(folderName,nowFolder)):
os.makedirs('{}/{}'.format(folderName,nowFolder))
logging.info('New path: {} was create.'.format(pathDirs))
response = requests.get(urlCam)
success = 0
if response.status_code == 200:
if cam in urlCam:
with open(os.path.join(folderName,nowFolder,file_name), 'wb') as f:
f.write(response.content)
logging.info('Downloading {}'.format(urlCam))
success =+1
logging.info('{} saved in {} as {} at {}'.format(folderName,file_name,pathDirs,nowFile))
#s.enter(0, 0, _load_Cams, (sc,))
#logging.info('{} cam(s) scraped'.format(success))
#s.enter(0, 0, _load_Cams, (s,))
#s.run()
except:
pass
s.enter(0, 0, _load_Cams, (sc,))
logging.info('{} cam(s) scraped'.format(success))
logging.info('{} cam(s) scraped'.format(paths))
s.enter(0, 0, _load_Cams, (s,))
s.run()
if __name__ == '__main__':
_load_Cams() | 6e1b648d88c79616896d8ef4bc87aeef46ba80f4 | [
"Python"
] | 1 | Python | alkeyandro/python_projects | 4763c218fd377f8498b1f701b0cad14de1ed2e68 | bee85b5ba706dcd7ad4806e280b4dd6d4003d9bc |
refs/heads/master | <file_sep>def square_array(array)
index = 0
while array[index] do
array[index] = array[index] ** 2
index += 1
end
array
end | 80b1520589d15c4b6a22f4fb45c58c5477817c6c | [
"Ruby"
] | 1 | Ruby | steve-alex/programming-univbasics-4-square-array-london-web-082619 | 3e211ca8e5626faaa450960309a8e31f0040352e | c6d07b31664e20915c1895ee02fd5040605e0df0 |
refs/heads/master | <file_sep><?php
namespace dwa15p3\Http\Controllers;
use Illuminate\Http\Request;
use dwa15p3\Http\Requests;
use Faker\Factory as Faker;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getCreate()
{
return view('users.index');
}
public function postCreate(Request $request)
{
// Validation
$this->validate($request, [
'nUsers' => 'required|numeric|min:1|max:99',
]);
// If validation passes...
$nUsers = $request->input('nUsers');
// Booleans for options
$birthdate = $request->input('birthdate');
$phone = $request->input('phone');
$profile = $request->input('profile');
// Create Faker instance
$faker = Faker::create();
// Array to hold generated results
$generated = '';
for ($i = 0; $i < $nUsers; $i++) {
// Generate a user
// to hold optional fields
$gBirthdate = '';
$gProfile = '';
$gPhone = '';
if($birthdate) { $gBirthdate = $faker->date($format = 'm-d-Y', $max = 'now'); }
if($phone) { $gPhone = $faker->phoneNumber; }
if($profile) { $gProfile = $faker->paragraph(10, true); }
$generated[] = array(
'name' => $faker->name,
'birthdate' => $gBirthdate,
'phone' => $gPhone,
'profile' => $gProfile,
);
}
return view('users.response')->with ('generated', $generated);
}
}
?>
<file_sep><?php
// default index page: no controller, just get the welcome view
Route::get('/', function() {
return view('welcome');
});
// User Generator
// start page
Route::get('/users', 'UsersController@getCreate');
// results
Route::post('/users', 'UsersController@postCreate');
// Lorem-Ipsum generator
// start page
Route::get('/lorem', 'LoremController@getCreate');
// results
Route::post('/lorem', 'LoremController@postCreate');
?>
<file_sep><?php
namespace dwa15p3\Http\Controllers;
use dwa15p3\Http\Controllers\Controller;
class BookController extends Controller {
/**
* Responds to requests to GET /books
*/
public function getIndex() {
return view('books');
}
/**
* Responds to requests to GET /books/show/{id}
*/
public function getShow($title = null) {
return view('books.show')->with('title', $title);
}
/**
* Responds to requests to GET /books/create
*/
public function getCreate() {
return view('books.create');
}
/**
* Responds to requests to POST /books/create
*/
public function postCreate() {
return 'Process adding new book';
}
}
<file_sep># P3: Developer's Best Friend
## Live URL
<http://p3.brownryan.com>
## Description
A Developer's Best Friend tool including a random user generator and a LoremIpsum text generator.
## Demo
<https://youtu.be/nTKl29KOQl0>
## Details for teaching team
No login required.
## Outside code
* PureCSS min: http://purecss.io/
<file_sep><?php
namespace dwa15p3\Http\Controllers;
use Illuminate\Http\Request;
use dwa15p3\Http\Requests;
use Faker\Factory as Faker;
class LoremController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getCreate()
{
return view('lorem.index');
}
public function postCreate(Request $request)
{
// Validation
$this->validate($request, [
'nSentences' => 'required|numeric|min:1|max:99',
'nParagraphs' => 'required|numeric|min:1|max:99',
]);
// If validation passes...
// Store options locally
$nSentences = $request->input('nSentences');
$nParagraphs = $request->input('nParagraphs');
$variation = $request->input('variation');
// Create Faker instance
$faker = Faker::create();
// Array to hold generated
$generated = '';
for ($i = 0; $i < $nParagraphs; $i++) {
// Generate a paragraph
$generated[] = $faker->paragraph($nSentences, $variation);
}
return view('lorem.response')->with ('generated', $generated);
}
}
?>
| 00e3cb1e245347d65dfd2e25c028d991e02578b0 | [
"Markdown",
"PHP"
] | 5 | PHP | rcb4t2/dwa15p3 | d50af93490490dfd48360fe5566816d3dfb44e94 | 3f4144dfc12cd21e8367bb48884c33a8fe8bc7de |
refs/heads/master | <repo_name>dkw5877/SwiftyContainerViewController<file_sep>/SwiftyContainerViewController/TableViewController.swift
//
// TableViewController.swift
// SwiftyContainerViewController
//
// Created by user on 12/30/14.
// Copyright (c) 2014 someCompanyNameHere. All rights reserved.
//
import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let window = UIApplication.sharedApplication().delegate?.window??
//self.tableView = UITableView(frame: CGRectMake(0, 0, 600, 600), style: UITableViewStyle.Plain)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellID")
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cellID")
cell.textLabel?.text = indexPath.description;
return cell
}
}
<file_sep>/SwiftyContainerViewController/CollectionViewController.swift
//
// CollectionViewController.swift
// SwiftyContainerViewController
//
// Created by user on 12/30/14.
// Copyright (c) 2014 someCompanyNameHere. All rights reserved.
//
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
private let cellID = "collectionCellID"
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.registerNib(UINib(nibName: "CollectionViewCell", bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: cellID)
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as CollectionViewCell
cell.backgroundColor = UIColor.blueColor()
return cell;
}
}
<file_sep>/SwiftyContainerViewController/ViewController.swift
//
// ViewController.swift
// SwiftyContainerViewController
//
// Created by user on 12/30/14.
// Copyright (c) 2014 someCompanyNameHere. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var currentClientView = UIViewController()
var animateOn = false
var selectedSegmentIndex = 0
var content = [UIViewController]()
@IBOutlet weak var animateButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let imageVC = ImageContentViewController(nibName: "ImageContentViewController", bundle: nil)
let tableVC = TableViewController(nibName: "TableViewController", bundle: nil)
let collectionVC = CollectionViewController(nibName: "CollectionViewController", bundle: nil)
self.displayContentViewController(tableVC)
self.content = [tableVC, imageVC, collectionVC]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func animateViewTransition(sender: AnyObject) {
self.animateOn = !self.animateOn;
if (self.animateOn) {
self.animateButton.backgroundColor = UIColor.greenColor()
}else {
self.animateButton.backgroundColor = UIColor.clearColor()
}
}
@IBAction func didSelectSegment(sender: AnyObject) {
if (self.animateOn) {
self.cycleFromViewControllerToViewController(self.content[self.selectedSegmentIndex],newViewController: self.content[sender.selectedSegmentIndex])
self.selectedSegmentIndex = sender.selectedSegmentIndex
} else {
//manually swap the views in and out based on the selected segment (no animation)
self.hideContentViewController(self.content[self.selectedSegmentIndex])
self.selectedSegmentIndex = sender.selectedSegmentIndex
self.displayContentViewController(self.content[self.selectedSegmentIndex])
}
}
func displayContentViewController(content:UIViewController){
//first add the new content view controller as a child
self.addChildViewController(content)
//set the frame for the new view controller, parents always size children
content.view.frame = self.frameForContentController()
//add the contents view to the parent view hierarcy
self.view.addSubview(content.view)
//store reference to detail view controller
self.currentClientView = content
//notify child that it now has a parent view
content.didMoveToParentViewController(self)
}
func hideContentViewController(content:UIViewController){
//notify view it will no longer have a parent
content.willMoveToParentViewController(nil)
//remove the view from the parents hierarchy
content.view.removeFromSuperview()
//remove the view controller from the parent's list of childrend
content.removeFromParentViewController()
}
func cycleFromViewControllerToViewController(oldViewController:UIViewController, newViewController:UIViewController){
//inform old view controller that it will no longer have a parent
oldViewController.willMoveToParentViewController(nil)
//add the new child view controller
self.addChildViewController(newViewController)
//set the new view controllers frame
newViewController.view.frame = self.newViewStartFrame()
let endFrame = self.oldViewEndFrame()
self.transitionFromViewController(oldViewController, toViewController: newViewController, duration: 1.50, options:UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
//new view will take the place of the old view
newViewController.view.frame = oldViewController.view.frame;
oldViewController.view.frame = endFrame;
}) { (Bool) -> Void in
//Remove the old view controller
oldViewController.removeFromParentViewController()
//set the new vc as the current
self.currentClientView = newViewController;
newViewController.didMoveToParentViewController(self)
}
}
func frameForContentController() -> CGRect{
return CGRectMake(0 , 100, self.view.bounds.width, self.view.bounds.height - 100)
}
func newViewStartFrame()->CGRect{
return CGRectMake(-self.view.frame.size.width, 100, self.currentClientView.view.frame.size.width, self.currentClientView.view.frame.size.height)
}
func oldViewEndFrame()->CGRect{
return CGRectMake(self.view.frame.size.width, 100, self.currentClientView.view.frame.size.width, self.currentClientView.view.frame.size.height)
}
}
| ecf781883f8fb566cf9d7b8d93f076c8abfa035b | [
"Swift"
] | 3 | Swift | dkw5877/SwiftyContainerViewController | aa8fbb383037d3947b20b38363e387898c8fc5e0 | bf3292ba6c214cba0c55eb6ac6f8aa984e378120 |
refs/heads/master | <repo_name>dipikaspatil/Database_Systems<file_sep>/Backend_Source_Code--PLSQL/Package_Body_Spec/STUDENT_REGISTRATION_SYSTEM_SPEC.sql
CREATE OR REPLACE PACKAGE STUDENT_REGISTRATION_SYSTEM AS
/*
Global Types
*/
TYPE REF_CURSOR IS REF CURSOR;
-- COMMON EXCEPTION
EXCP_INVALID_B# EXCEPTION;
EXCP_INVALID_CLASSID EXCEPTION;
EXCP_INVALID_STUDENT_ENROLL EXCEPTION;
EXCP_INVALID_SEM_CLASS EXCEPTION;
EXCP_INVALID_DROP_PREREQ EXCEPTION;
EXCP_INVALID_DROP_LAST_CLASS EXCEPTION;
EXCP_INVALID_DROP_LAST_STUDENT EXCEPTION;
EXCP_CLASS_IS_FULL EXCEPTION;
EXCP_EXCEEDED_ENROLLMENT EXCEPTION;
EXCP_PREREQ_NOT_SATISFIED EXCEPTION;
EXCP_INVALID_DEPTCODE_COURSE# EXCEPTION;
/*
* Procedures to display the tuples in each of the seven tables for this project.
*/
PROCEDURE SHOW_STUDENTS(REF_CURSOR_STUDENTS OUT REF_CURSOR);
PROCEDURE SHOW_TAS(REF_CURSOR_TAS OUT REF_CURSOR);
PROCEDURE SHOW_COURSES(REF_CURSOR_COURSES OUT REF_CURSOR);
PROCEDURE SHOW_CLASSES(REF_CURSOR_CLASSES OUT REF_CURSOR);
PROCEDURE SHOW_ENROLLMENTS(REF_CURSOR_ENROLLMENTS OUT REF_CURSOR);
PROCEDURE SHOW_PREREQUISITES(REF_CURSOR_PREREQUISITES OUT REF_CURSOR);
PROCEDURE SHOW_LOGS(REF_CURSOR_LOGS OUT REF_CURSOR);
/*
* Procedure to list B#, first name and last name of the TA of the class for a given class
*/
PROCEDURE CLASS_TA(CLASSID_IN IN CLASSES.CLASSID%TYPE,
TA_B#_OUT OUT CLASSES.TA_B#%TYPE,
FIRST_NAME_OUT OUT STUDENTS.FIRST_NAME%TYPE,
LAST_NAME_OUT OUT STUDENTS.LAST_NAME%TYPE);
/*
* Procedure to list all prerequisite courses for given course (with dept_code and course#)
* Including both direct and indirect prerequisite courses
*/
PROCEDURE CLASS_PREREQ(DEPT_CODE_IN IN PREREQUISITES.DEPT_CODE%TYPE,
COURSE#_IN IN PREREQUISITES.COURSE#%TYPE,
PRE_REQ_OUT OUT VARCHAR2);
/*
* Procedure to Enroll Student for given class
*/
PROCEDURE ENROLL_STUDENT(B#_IN IN STUDENTS.B#%TYPE,
CLASSID_IN IN CLASSES.CLASSID%TYPE);
/*
* Procedure to drop a student from a class
*/
PROCEDURE DELETE_STUDENT_ENROLLMENT(B#_IN IN STUDENTS.B#%TYPE,
CLASSID_IN IN CLASSES.CLASSID%TYPE);
/*
* Procedure to delete Student
*/
PROCEDURE DELETE_STUDENT(B#_IN IN STUDENTS.B#%TYPE);
END;
/
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/README.md
## STUDENT REGISTRATION SYSTEM
#### JSP, Servlet, Java Frontend Source Code
--------------------------------------------------------------------------------------------------------------------
#### JAVA Instructions (Eclipse IDE and Tomcat is required to run the project):
* Open Eclipse and direct it to empty workspace folder.
* Copy attached "StudentRegistrationSystem" complete folder to above workspace.
* Click on New -> Import -> General -> Existing Projects into Workspace.
* Browse to folder where "StudentRegistrationSystem" is copied in Select Root directory option.
* Create new Tomcat server instance using Eclipse Server tab and add "StudentRegistrationSystem" project inside it.
* Right click on "StudentRegistrationSystem" project and "Run As -> Run on Server"
--------------------------------------------------------------------------------------------------------------------<file_sep>/Backend_Source_Code--PLSQL/Triggers/TRIG_ON_DEL_STUD_DEL_ENROLL.sql
CREATE OR REPLACE TRIGGER TRIG_ON_DEL_STUD_DEL_ENROLL
BEFORE DELETE ON STUDENTS
FOR EACH ROW
BEGIN
DELETE FROM ENROLLMENTS WHERE UPPER(B#) = UPPER(:OLD.B#);
END;
/
<file_sep>/README.md
## STUDENT REGISTRATION SYSTEM (SRS Application)
#### General Information:
* This Application is developed by Team of 3 members where we worked in below phases:
* Requirement gathering and understanding phase.
* Analysis and planning phase.
* Development phase.
* Testing phase.
* Defect fixing phase.
* Demo phase.
--------------------------------------------------------------------------------------------------------------------
#### High Level Architecture:
* We followed Model View Controller (MVC) architecture in order to implement SRS application.
* View
* Using JSP (Java Server Pages) to create frontend GUI to interact with users.
* Controller
* Using Java Servlets to call DB operator classes and redirect result to appropriate JSP pages.
* Model
* Using JDBC connections and calling respective DB procedures in order to perform user's request.
* JSPs are dynamic web pages where we can write HTML as well as Java codes.
* Using HTTP method "post" to transfer form elements from frontend to backend.
* Every functionality is implemented in separate files (JSP, Servlet, DB operation class) for modularity.
* Handled messages displayed via DBMS_OUTPUT from backend in Java code DBMS_OUTPUT GET_LINE procedure call.
* Basic validations like empty fields entries are done at frontend side.
* Majority of functionalities to manipulation DB data and related validations are implemented at backend side.
#### Development Phase Plan and Activities:
* We followed below steps during project planning phase of SRS application:
* Discussed and decided to use JSP as frontend, JDBC connectivity and Oracle PL/SQL backend.
* Discussed and decided to use "BitBucket" version control tool to maintain project source code both for backend and frontend components.
* Discussed and decided to use PL/SQL Developer IDE to develop database objects like package, procedures, functions, sequence, triggers and test cases (SQL scripts).
* Discussed and decided to use Eclipse IDE to develop web application project including JSPs, Java Servlets and Java JDBC connectivity related model classes.
| Meeting Date | Meeting Location | Activities |
|:--------------:|:--------------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Nov 6th, 2018 | Library Meeting Room | Created BitBucket repositories and base package for SRS [NM]. Included procedures to display table tuples [VM]. Implementation of procedure to get TA details using classid [DP]. |
| Nov 10th, 2018 | Library Meeting Room | Test case for “class_ta” and code formatting [VM]. Included ref cursor in show_tables + it'd test case [DP]. Data population for test case and Java web project setup [NM]. |
| Nov 11th, 2018 | Library Meeting Room | Included implementation of “prerequisite course” procedure [NM]. Included partial implementation - “enroll student” procedure [VM]. Implemented display table fields in Java and DB connectivity [DP]. |
| Nov 12th, 2018 | Library Meeting Room | Partial implementation of “Drop enrollments” without trigger [DP]. “Show_Students” functionality testing at front end side [VM]. Fixing of “Show_Students” DB defects and test cases [NM]. |
| Nov 13th, 2018 | Library Meeting Room | Implementation and testing of “Drop Student Enrollment” from backend and frontend side [DP] [VM] [NM]. |
| Nov 14th, 2018 | Library Meeting Room | Implementation of validation 8 for Enroll_Student procedure [DP]. Test case + related sql script to check student enrollments [NM]. Implementation of TA Details functionality at frontend [VM]. |
| Nov 15th, 2018 | Library Meeting Room | Testing for triggers while enrolling student at backend [VM]. Implementation of Display Class Prerequisite at frontend [DP]. Partial code and testing of Delete Student at frontend [NM]. |
| Nov 19th, 2018 | Library Meeting Room | Combined implementation of Enroll and Delete Student Enrollment with complete testing from frontend and backend [DP] [VM] [NM]. |
| Nov 26th, 2018 | Library Meeting Room | Combined implementation of Delete Student with complete testing from frontend and backend [DP] [VM] [NM]. |
| Nov 28th, 2018 | Library Meeting Room | Thorough testing of all the procedures, triggers and fixed defects together from frontend and backend side [NM] [VM] [DP]. |
| Nov 29th, 2018 | Library Meeting Room | Project Report and final DB setup for demo [VM] [NM] [DP]. |
* Team Members Roles and Responsibilities:
* All team members worked together in same meeting room to develop and test SRS application from frontend and backend side.
* Activities done by team members is mentioned in above table with respective initials.
* <NAME> [NM]
* <NAME> [DP]
* <NAME> [VM]
--------------------------------------------------------------------------------------------------------------------
#### Outline of Backend PL-SQL Code
* **DB Package Name** - STUDENT_REGISTRATION_SYSTEM
* Procedures to display the tuples from each of the seven tables. These procedures return REF CURSOR as OUT parameter which is used at front-end side to display tuples of seven DB tables.
* PROCEDURE SHOW_STUDENTS(REF_CURSOR_STUDENTS OUT REF_CURSOR);
* PROCEDURE SHOW_TAS(REF_CURSOR_TAS OUT REF_CURSOR);
* PROCEDURE SHOW_COURSES(REF_CURSOR_COURSES OUT REF_CURSOR);
* PROCEDURE SHOW_CLASSES(REF_CURSOR_CLASSES OUT REF_CURSOR);
* PROCEDURE SHOW_ENROLLMENTS(REF_CURSOR_ENROLLMENTS OUT REF_CURSOR);
* PROCEDURE SHOW_PREREQUISITES(REF_CURSOR_PREREQUISITES OUT REF_CURSOR);
* PROCEDURE SHOW_LOGS(REF_CURSOR_LOGS OUT REF_CURSOR);
* Global Types -
* TYPE REF_CURSOR IS REF CURSOR;
* This REF CURSOR is returned from individual procedure as select query.
* Procedure to display B#, first name and last name of the TA for input classid.
* PROCEDURE CLASS_TA(CLASSID_IN IN CLASSES.CLASSID%TYPE,
TA_B#_OUT OUT CLASSES.TA_B#%TYPE,
FIRST_NAME_OUT OUT STUDENTS.FIRST_NAME%TYPE,
LAST_NAME_OUT OUT STUDENTS.LAST_NAME%TYPE);
* Validations:
* If the class does not have a TA, report "The class has no TA."
* If the provided classid is invalid (i.e., not in the Classes table), report "The classid is invalid."
* Procedure returns all direct and indirect prerequisite courses.
* PROCEDURE CLASS_PREREQ(DEPT_CODE_IN IN PREREQUISITES.DEPT_CODE%TYPE,
COURSE#_IN IN PREREQUISITES.COURSE#%TYPE, PRE_REQ_OUT OUT VARCHAR2);
* Validation:
* If the provided (dept_code, course#) is invalid, report "dept_code || course# does not exist."
* Procedure handles enrollment of a student into a class.
* PROCEDURE ENROLL_STUDENT(B#_IN IN STUDENTS.B#%TYPE,
CLASSID_IN IN CLASSES.CLASSID%TYPE);
* Validations:
* If the student is not in the Students table, report "The B# is invalid."
* If the classid is not in the classes table, report "The classid is invalid."
* If the class is not offered in the current semester (i.e., Fall 2018), reject the enrollment and report "Cannot enroll into a class from a previous semester."
* If the class is already full before the enrollment request, reject the enrollment request and report "The class is already full."
* If the student is already in the class, report "The student is already in the class."
* If the student is already enrolled in four other classes in the same semester and the same year, report "The student will be overloaded with the new enrollment." but still allow the student to be enrolled.
* If the student is already enrolled in five other classes in the same semester and the same year, report "Students cannot be enrolled in more than five classes in the same semester." and reject the enrollment.
* If the student has not completed the required prerequisite courses with at least a grade C, reject the enrollment and report "Prerequisite not satisfied."
* Procedure handles deletion of a student from enrollment table.
* PROCEDURE DELETE_STUDENT_ENROLLMENT(B#_IN IN STUDENTS.B#%TYPE,
CLASSID_IN IN CLASSES.CLASSID%TYPE);
* Validations:
* If the student is not in the Students table, report "The B# is invalid."
* If the classid is not in the Classes table, report "The classid is invalid."
* If the student is not enrolled in the class, report "The student is not enrolled in the class."
* If the class is not offered in Fall 2018, reject the drop attempt and report "Only enrollment in the current semester can be dropped."
* If dropping the student from the class would cause a violation of the prerequisite requirement for another class, reject the drop attempt and report "The drop is not permitted because another class the student registered uses it as a prerequisite." In all the other cases, the student will be dropped from the class.
* If the class is the last class for the student, report "This student is not enrolled in any classes."
* If the student is the last student in the class, report "The class now has no students."
* Procedure handles deletion of a student from the Students table based on a given B#.
* PROCEDURE DELETE_STUDENT(B#_IN IN STUDENTS.B#%TYPE);
* Validation:
* If the student is not in the Students table, report "The B# is invalid."
* Related DB Objects - these objects are not part of package and used in application.
* Sequence to generate log# automatically when new log records are inserted in log table.
* LOG_SEQ_GENERATOR
* Trigger to make entry in log table on deletion of enrollment table entry.
* TRIG_ON_DEL_ENROLL_INS_LOGS
* Trigger to decrease class size in CLASSES table on deletion of enrollment table entry.
* TRIG_ON_DEL_ENROLL_UPD_CLASSES
* Trigger to delete TA table entry on deletion of STUDENT table entry.
* TRIG_ON_DEL_STUDENTS_DEL_TA
* Trigger to make entry in log table on deletion of TA table entry.
* TRIG_ON_DEL_TAS_INS_LOGS
* Trigger to make TA column entry NULL in CLASSES table on deletion of TA table entry.
* TRIG_ON_DEL_TAS_UPD_CLASSES
* Trigger to make entry in log table on insertion of enrollment table entry.
* TRIG_ON_INS_ENROLL_INS_LOGS
* Trigger to increase class size in CLASSES table on insertion of ENROLLMENTS table.
* TRIG_ON_INS_ENROLL_UPD_CLASSES
* Trigger to make entry in log table on update of CLASSES table entry.
* TRIG_ON_UPD_CLASSES_INS_LOGS
* Trigger to delete enrollment on deleting student entry.
* TRIG_ON_DEL_STUD_DEL_ENROLL
--------------------------------------------------------------------------------------------------------------------
#### Outline of Frontend and Java Code
* Below is the directory structure snippet for Java Dynamic Web Project using Model View Controller architecture model:

--------------------------------------------------------------------------------------------------------------------<file_sep>/Backend_Source_Code--PLSQL/SQL_Script/DB_Basic_Setup.sql
drop table enrollments;
drop table classes;
drop table tas;
drop table prerequisites;
drop table courses;
drop table students;
drop table logs;
DROP TRIGGER TRIG_ON_DEL_ENROLL_INS_LOGS;
DROP TRIGGER TRIG_ON_DEL_ENROLL_UPD_CLASSES;
DROP TRIGGER TRIG_ON_INS_ENROLL_INS_LOGS;
DROP TRIGGER TRIG_ON_INS_ENROLL_UPD_CLASSES;
DROP TRIGGER TRIG_ON_DEL_STUDENTS_INS_LOGS;
DROP TRIGGER TRIG_ON_DEL_STUDENTS_DEL_TA;
DROP TRIGGER TRIG_ON_DEL_STUD_DEL_ENROLL;
DROP TRIGGER TRIG_ON_DEL_TAS_INS_LOGS;
DROP TRIGGER TRIG_ON_DEL_TAS_UPD_CLASSES;
DROP TRIGGER TRIG_ON_UPD_CLASSES_INS_LOGS;
DROP SEQUENCE LOG_SEQ_GENERATOR;
DROP PACKAGE STUDENT_REGISTRATION_SYSTEM;
create table students (B# char(4) primary key check (B# like 'B%'),
first_name varchar2(15) not null, last_name varchar2(15) not null, status varchar2(10)
check (status in ('freshman', 'sophomore', 'junior', 'senior', 'MS', 'PhD')),
gpa number(3,2) check (gpa between 0 and 4.0), email varchar2(20) unique,
bdate date, deptname varchar2(4) not null);
create table tas (B# char(4) primary key references students,
ta_level varchar2(3) not null check (ta_level in ('MS', 'PhD')),
office varchar2(10));
create table courses (dept_code varchar2(4), course# number(3)
check (course# between 100 and 799), title varchar2(20) not null,
primary key (dept_code, course#));
create table classes (classid char(5) primary key check (classid like 'c%'),
dept_code varchar2(4) not null, course# number(3) not null,
sect# number(2), year number(4), semester varchar2(8)
check (semester in ('Spring', 'Fall', 'Summer 1', 'Summer 2')), limit number(3),
class_size number(3), room varchar2(10), ta_B# char(4) references tas,
foreign key (dept_code, course#) references courses on delete cascade,
unique(dept_code, course#, sect#, year, semester), check (class_size <= limit));
create table enrollments (B# char(4) references students, classid char(5) references classes,
lgrade varchar2(2) check (lgrade in ('A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-','D',
'F', 'I')), primary key (B#, classid));
create table prerequisites (dept_code varchar2(4) not null,
course# number(3) not null, pre_dept_code varchar2(4) not null,
pre_course# number(3) not null,
primary key (dept_code, course#, pre_dept_code, pre_course#),
foreign key (dept_code, course#) references courses on delete cascade,
foreign key (pre_dept_code, pre_course#) references courses on delete cascade);
create table logs (log# number(4) primary key, op_name varchar2(10) not null, op_time date not null,
table_name varchar2(12) not null, operation varchar2(6) not null, key_value varchar2(10));
insert into students values ('B001', 'Anne', 'Broder', 'junior', 3.17, '<EMAIL>', '17-JAN-90', 'CS');
insert into students values ('B002', 'Terry', 'Buttler', 'senior', 3.0, '<EMAIL>', '28-MAY-89', 'Math');
insert into students values ('B003', 'Tracy', 'Wang', 'senior', 4.0, '<EMAIL>','06-AUG-93', 'CS');
insert into students values ('B004', 'Barbara', 'Callan', 'junior', 2.5, '<EMAIL>', '18-OCT-91', 'Math');
insert into students values ('B005', 'Jack', 'Smith', 'MS', 3.2, '<EMAIL>', '18-OCT-91', 'CS');
insert into students values ('B006', 'Terry', 'Zillman', 'PhD', 4.0, '<EMAIL>', '15-JUN-88', 'Biol');
insert into students values ('B007', 'Becky', 'Lee', 'senior', 4.0, '<EMAIL>', '12-NOV-92', 'CS');
insert into students values ('B008', 'Tom', 'Baker', 'freshman', null, '<EMAIL>', '23-DEC-96', 'CS');
insert into students values ('B009', 'Ben', 'Liu', 'MS', 3.8, '<EMAIL>', '18-MAR-92', 'Math');
insert into students values ('B010', 'Sata', 'Patel', 'MS', 3.9, '<EMAIL>', '12-OCT-90', 'CS');
insert into students values ('B011', 'Art', 'Chang', 'PhD', 4.0, '<EMAIL>', '08-JUN-89', 'CS');
insert into students values ('B012', 'Tara', 'Ramesh', 'PhD', 3.98, '<EMAIL>', '29-JUL-91', 'Math');
insert into tas values ('B005', 'MS', 'EB G26');
insert into tas values ('B009', 'MS', 'WH 112');
insert into tas values ('B010', 'MS', 'EB G26');
insert into tas values ('B011', 'PhD','EB P85');
insert into tas values ('B012', 'PhD','WH 112');
insert into courses values ('CS', 432, 'database systems');
insert into courses values ('Math', 314, 'discrete math');
insert into courses values ('CS', 240, 'data structure');
insert into courses values ('Math', 221, 'calculus I');
insert into courses values ('CS', 532, 'database systems');
insert into courses values ('CS', 552, 'operating systems');
insert into courses values ('Biol', 425, 'molecular biology');
insert into classes values ('c0001', 'CS', 432, 1, 2018, 'Fall', 2, 1, 'LH 005', 'B005');
insert into classes values ('c0002', 'Math', 314, 1, 2018, 'Spring', 4, 4, 'LH 009', 'B012');
insert into classes values ('c0003', 'Math', 314, 2, 2018, 'Spring', 4, 2, 'LH 009', 'B009');
insert into classes values ('c0004', 'CS', 432, 2, 2018, 'Fall', 2, 2, 'SW 222', 'B005');
insert into classes values ('c0005', 'CS', 240, 1, 2017, 'Spring', 3, 2, 'LH 003', 'B010');
insert into classes values ('c0006', 'CS', 532, 1, 2018, 'Fall', 3, 2, 'LH 005', 'B011');
insert into classes values ('c0007', 'Math', 221, 1, 2017, 'Fall', 7, 6, 'WH 155', null);
insert into classes values ('c0008', 'CS', 552, 1, 2018, 'Fall', 1, 0, 'EB R15', null);
insert into classes values ('c0009', 'CS', 240, 1, 2018, 'Fall', 2, 1, 'EB R15', null);
insert into prerequisites values ('Math', '314', 'Math', '221');
insert into prerequisites values ('CS', '432', 'Math', '314');
insert into prerequisites values ('CS', '532', 'Math', '314');
insert into prerequisites values ('CS', '552', 'CS', '240');
insert into enrollments values ('B001', 'c0001', null);
insert into enrollments values ('B001', 'c0003', 'B');
insert into enrollments values ('B001', 'c0007', 'B+');
insert into enrollments values ('B002', 'c0002', 'B');
insert into enrollments values ('B002', 'c0007', 'B');
insert into enrollments values ('B003', 'c0004', null);
insert into enrollments values ('B003', 'c0002', 'A-');
insert into enrollments values ('B003', 'c0007', 'B');
insert into enrollments values ('B004', 'c0004', null);
insert into enrollments values ('B004', 'c0005', 'B+');
insert into enrollments values ('B004', 'c0003', 'A');
insert into enrollments values ('B004', 'c0007', 'A');
insert into enrollments values ('B005', 'c0006', null);
insert into enrollments values ('B005', 'c0002', 'B');
insert into enrollments values ('B005', 'c0007', 'B');
insert into enrollments values ('B006', 'c0006', null);
insert into enrollments values ('B006', 'c0002', 'A');
insert into enrollments values ('B006', 'c0007', 'A-');
insert into enrollments values ('B007', 'c0005', 'C');
insert into enrollments values ('B008', 'c0009', null);
COMMIT;<file_sep>/Backend_Source_Code--PLSQL/README.md
## STUDENT REGISTRATION SYSTEM
#### PL/SQL Backend Source Code
--------------------------------------------------------------------------------------------------------------------
#### PL/SQL Instructions (Complete Setup):
* **COMMAND TO SETUP COMPLETE DB IN ONE GO**:
* start DB_Full_Setup
--------------------------------------------------------------------------------------------------------------------
#### PL/SQL Instructions (One-by-One Setup):
* **COMMAND TO SETUP DB OBJECTS ONE BY ONE**:
* **Command to setup database (Drop all tables, triggers, sequence and creation / insertion of tables)**:
* start DB_Basic_Setup
* **Command to create and start Sequence**:
* start Log_Sequence
* **Command to create and start Triggers**:
* start TRIG_ON_DEL_ENROLL_INS_LOGS
* start TRIG_ON_DEL_ENROLL_UPD_CLASSES
* start TRIG_ON_DEL_STUD_DEL_ENROLL
* start TRIG_ON_DEL_STUDENTS_DEL_TA
* start TRIG_ON_DEL_STUDENTS_INS_LOGS
* start TRIG_ON_DEL_TAS_INS_LOGS
* start TRIG_ON_DEL_TAS_UPD_CLASSES
* start TRIG_ON_INS_ENROLL_INS_LOGS
* start TRIG_ON_INS_ENROLL_UPD_CLASSES
* start TRIG_ON_UPD_CLASSES_INS_LOGS
* **Command to create Package Specification**:
* start STUDENT_REGISTRATION_SYSTEM_SPEC
* **Command to create Package Body**:
* start STUDENT_REGISTRATION_SYSTEM_BODY
--------------------------------------------------------------------------------------------------------------------<file_sep>/Backend_Source_Code--PLSQL/Triggers/TRIG_ON_DEL_TAS_UPD_CLASSES.sql
/*
Trigger to make TA column entry NULL in CLASSES table on deletion of TA table entry
*/
CREATE OR REPLACE TRIGGER TRIG_ON_DEL_TAS_UPD_CLASSES
BEFORE DELETE ON TAS
FOR EACH ROW
DECLARE
CURSOR C1 IS
SELECT CLASSID FROM CLASSES WHERE UPPER(TA_B#) = UPPER(:OLD.B#);
L_TA_CNT NUMBER;
BEGIN
FOR C1_REC IN C1 LOOP
UPDATE CLASSES SET TA_B# = NULL WHERE CLASSID = C1_REC.CLASSID;
END LOOP;
END;
/
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/beans/Course.java
package beans;
/**
* POJO Class to represent Course content in Courses DB Table
*/
public class Course {
/**
* Private Data Members
*/
private String deptCode;
private int courseNumber;
private String title;
/**
* Overridden toString() method
*/
@Override
public String toString() {
return deptCode + "\t\t" + Integer.toString(courseNumber) + "\t\t" + title;
}
/**
* Getters and Setters
*/
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public int getCourseNumber() {
return courseNumber;
}
public void setCourseNumber(int courseNumber) {
this.courseNumber = courseNumber;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<file_sep>/Backend_Source_Code--PLSQL/Triggers/TRIG_ON_DEL_STUDENTS_DEL_TA.sql
/*
Trigger to delete TA table entry on deletion of STUDENT table entry
*/
CREATE OR REPLACE TRIGGER TRIG_ON_DEL_STUDENTS_DEL_TA
BEFORE DELETE ON STUDENTS
FOR EACH ROW
DECLARE
CURSOR C1 IS
SELECT COUNT(1) FROM TAS WHERE UPPER(B#) = UPPER(:OLD.B#);
L_TA_CNT NUMBER;
BEGIN
OPEN C1;
FETCH C1
INTO L_TA_CNT;
CLOSE C1;
IF L_TA_CNT = 1 THEN
DELETE FROM TAS WHERE UPPER(B#) = UPPER(:OLD.B#);
END IF;
END;
/
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/dboperations/DeleteStudentEnrollment.java
package dboperations;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import dbconutil.DBManagerOracle;
/**
* Class to Delete Enrollment of Student from specific Class
*/
public class DeleteStudentEnrollment {
/**
* Method to call DB procedure to delete input Student's enrollment from specific ClassId
* @param conn
* @param bNumber
* @param classId
* @return
* @throws SQLException
*/
public static List<String> deleteStudentEnrollment(Connection conn, String bNumber, String classId) throws SQLException {
// Local variable
String query = "begin student_registration_system.delete_student_enrollment(:1, :2); end;";
// Enable DBMS_OUTPUT
DBManagerOracle.enableDbmsOutput(conn);
// Prepare to call stored procedure
CallableStatement cs = conn.prepareCall(query);
// Set bNumber and classId as input parameter
cs.setString(1, bNumber);
cs.setString(2, classId);
// Execute the stored procedure
cs.executeQuery();
// Print DBMAS_OUTPUT contents on Standard Output
String dbmsOutputContent = DBManagerOracle.getDbmsOutputContent(conn);
// Disable DBMS_OUTPUT
DBManagerOracle.disableDbmsOutput(conn);
List<String> deleteStudentEnrollmentList = new ArrayList<>();
if (dbmsOutputContent != null) {
//System.out.println("DBMS Output --> " + dbmsOutputContent);
if (dbmsOutputContent.startsWith("MSG")) {
deleteStudentEnrollmentList.add("Warning");
deleteStudentEnrollmentList.add(dbmsOutputContent);
} else {
deleteStudentEnrollmentList.add("Error");
deleteStudentEnrollmentList.add(dbmsOutputContent);
}
} else {
deleteStudentEnrollmentList.add("Error");
deleteStudentEnrollmentList.add("Some unexpected problem occured.");
}
return deleteStudentEnrollmentList;
}
}
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/beans/Prerequisite.java
package beans;
/**
* POJO Class to represent Prerequisite content in Prerequisites DB Table
*/
public class Prerequisite {
/**
* Private Data Members
*/
private String deptCode;
private int courseNumber;
private String preDeptCode;
private int preCourseNumber;
/**
* Overridden toString() method
*/
@Override
public String toString() {
return deptCode + "\t\t" + Integer.toString(courseNumber) + "\t\t" + preDeptCode + Integer.toString(preCourseNumber);
}
/**
* Getters and Setters
*/
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public int getCourseNumber() {
return courseNumber;
}
public void setCourseNumber(int courseNumber) {
this.courseNumber = courseNumber;
}
public String getPreDeptCode() {
return preDeptCode;
}
public void setPreDeptCode(String preDeptCode) {
this.preDeptCode = preDeptCode;
}
public int getPreCourseNumber() {
return preCourseNumber;
}
public void setPreCourseNumber(int preCourseNumber) {
this.preCourseNumber = preCourseNumber;
}
}
<file_sep>/Backend_Source_Code--PLSQL/Triggers/TRIG_ON_DEL_ENROLL_UPD_CLASSES.sql
/*
Trigger to decrease class size in CLASSES table on deletion of enrollment table entry
*/
CREATE OR REPLACE TRIGGER TRIG_ON_DEL_ENROLL_UPD_CLASSES
AFTER DELETE ON ENROLLMENTS
FOR EACH ROW
BEGIN
UPDATE CLASSES
SET CLASS_SIZE = CLASS_SIZE - 1
WHERE CLASSID = :OLD.CLASSID;
END;
/
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/dboperations/DisplayClassTADetails.java
package dboperations;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import dbconutil.DBManagerOracle;
/**
* Class to display TA details for specific ClassId
*/
public class DisplayClassTADetails {
/**
* Method to return TA details for input ClassId
* @param conn, classId
* @return TA Details
* @throws SQLException
*/
public static List<String> showClassTaDetails(Connection conn, String classId) throws SQLException {
// Local variable
String query = "begin student_registration_system.class_ta(:1, :2, :3, :4); end;";
// Enable DBMS_OUTPUT
DBManagerOracle.enableDbmsOutput(conn);
// Prepare to call stored procedure
CallableStatement cs = conn.prepareCall(query);
// Set classId as input parameter
cs.setString(1, classId);
// register the out parameter (second, third and fourth parameters)
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.VARCHAR);
// Execute the stored procedure
cs.executeQuery();
// Print DBMAS_OUTPUT contents on Standard Output
String dbmsOutputContent = DBManagerOracle.getDbmsOutputContent(conn);
// Disable DBMS_OUTPUT
DBManagerOracle.disableDbmsOutput(conn);
List<String> taDeatilsList = new ArrayList<>();
if (dbmsOutputContent != null) {
//System.out.println("DBMS Output --> " + dbmsOutputContent);
taDeatilsList.add("Error");
taDeatilsList.add(dbmsOutputContent);
} else {
String bNumber = cs.getString(2);
String firstName = cs.getString(3);
String lastName = cs.getString(4);
// Save TA details in List of string
if (bNumber != null) {
taDeatilsList.add(bNumber);
}
if (firstName != null) {
taDeatilsList.add(firstName);
}
if (lastName != null) {
taDeatilsList.add(lastName);
}
}
return taDeatilsList;
}
}
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/dboperations/DisplayClassPrerequisite.java
package dboperations;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import dbconutil.DBManagerOracle;
/**
* Class to display Course Prerequisites for input DEPT_CODE and COURSE#
*/
public class DisplayClassPrerequisite {
/**
* Method to return Prerequisite courses for input DEPT_CODE and COURSE#
* @param conn
* @param deptCode
* @param courseNumber
* @return
* @throws SQLException
*/
public static List<String> getCoursePrerequisite(Connection conn, String deptCode, int courseNumber) throws SQLException {
// Local variable
String query = "begin student_registration_system.class_prereq(:1, :2, :3); end;";
// Enable DBMS_OUTPUT
DBManagerOracle.enableDbmsOutput(conn);
// Prepare to call stored procedure
CallableStatement cs = conn.prepareCall(query);
// Set dept_code and course# as input parameter
cs.setString(1, deptCode);
cs.setInt(2, courseNumber);
// register the out parameter
cs.registerOutParameter(3, Types.VARCHAR);
// Execute the stored procedure
cs.executeQuery();
// Print DBMAS_OUTPUT contents on Standard Output
String dbmsOutputContent = DBManagerOracle.getDbmsOutputContent(conn);
// Disable DBMS_OUTPUT
DBManagerOracle.disableDbmsOutput(conn);
List<String> prereqList = new ArrayList<>();
if (dbmsOutputContent != null) {
//System.out.println("DBMS Output --> " + dbmsOutputContent);
prereqList.add("Error");
prereqList.add(dbmsOutputContent);
} else {
String prereqStr = cs.getString(3);
if (prereqStr != null && !prereqStr.equals("")) {
String prereqArr[]= prereqStr.split(",");
// Save Prerequisite Courses in List of string
for (String prereq : prereqArr) {
prereqList.add(prereq.trim());
}
}
}
return prereqList;
}
}
<file_sep>/Backend_Source_Code--PLSQL/Triggers/TRIG_ON_INS_ENROLL_UPD_CLASSES.sql
/*
Trigger to increase class size in CLASSES table on insertion of ENROLLMENTS table entry
*/
CREATE OR REPLACE TRIGGER TRIG_ON_INS_ENROLL_UPD_CLASSES
AFTER INSERT ON ENROLLMENTS
FOR EACH ROW
BEGIN
UPDATE CLASSES
SET CLASS_SIZE = CLASS_SIZE + 1
WHERE CLASSID = :NEW.CLASSID;
END;
/
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/servlets/LoginServlet.java
package servlets;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dbconutil.OraConnection;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default Constructor
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
}
/**
* Method to display Login Page
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Forward request to login page
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
disp.forward(request, response);
}
/**
* Method to validate credentials and create DB connection
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Retrieve request parameters coming from Front End - View
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean hasError = false;
String errorMessage = null;
// Validate username, password and establish oracle DB connection
if (username == null || password == null || username.length() == 0 || password.length() == 0) {
hasError = true;
errorMessage = "Required username and password.";
} else {
try {
OraConnection oConn = new OraConnection(username, password);
oConn.createConnection();
} catch(SQLException ex) {
ex.printStackTrace();
hasError = true;
errorMessage = ex.getMessage();
}
}
// Condition check for valid/ invalid credentials
if (hasError) {
// Forward loaded error request to login page
request.setAttribute("errorMessage", errorMessage);
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
disp.forward(request, response);
} else {
// Redirect to Student Registration System home page
response.sendRedirect(request.getContextPath() + "/srsHomeServlet");
}
}
}
<file_sep>/Frontend_Source_Code--JSP_Servlet_Java/StudentRegistrationSystem/src/servlets/DisplayTableContentServlet.java
package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Classes;
import beans.Course;
import beans.Enrollment;
import beans.Log;
import beans.Prerequisite;
import beans.Student;
import beans.Ta;
import dbconutil.OraConnection;
import dboperations.DisplayTableContents;
/**
* Servlet implementation class DisplayTableContentServlet
*/
@WebServlet("/displayTableContentServlet")
public class DisplayTableContentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default Constructor
* @see HttpServlet#HttpServlet()
*/
public DisplayTableContentServlet() {
super();
}
/**
* Method to display Table Contents Page
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Forward request to login page
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/displayTableContent.jsp");
disp.forward(request, response);
}
/**
* Method to invoke DB procedure as per the request from UI and return response to UI
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Local variables
boolean hasError = false;
String errorMessage = null;
List<Student> studentsList = null;
List<Ta> taList = null;
List<Course> courseList = null;
List<Classes> classList = null;
List<Enrollment> enrollmentList = null;
List<Prerequisite> prereqList = null;
List<Log> logList = null;
String tableName = request.getParameter("tablename");
Connection conn = OraConnection.dbConnection;
// Validation for empty input from front end side
if (tableName == null || tableName.length() == 0) {
hasError = true;
errorMessage = "Please select valid tablename from dropdown.";
} else {
// Call respective DB procedure using respective Model class
try {
if ("students".equalsIgnoreCase(tableName)) {
studentsList = DisplayTableContents.showStudents(conn);
} else if ("tas".equalsIgnoreCase(tableName)) {
taList = DisplayTableContents.showTas(conn);
} else if ("courses".equalsIgnoreCase(tableName)) {
courseList = DisplayTableContents.showCourses(conn);
} else if ("classes".equalsIgnoreCase(tableName)) {
classList = DisplayTableContents.showClasses(conn);
} else if ("enrollments".equalsIgnoreCase(tableName)) {
enrollmentList = DisplayTableContents.showEnrollments(conn);
} else if ("prerequisites".equalsIgnoreCase(tableName)) {
prereqList = DisplayTableContents.showPrerequisites(conn);
} else if ("logs".equalsIgnoreCase(tableName)) {
logList = DisplayTableContents.showLogs(conn);
}
} catch(SQLException ex) {
ex.printStackTrace();
hasError = true;
errorMessage = ex.getMessage();
}
}
// Condition check for valid/ invalid credentials
if (hasError) {
// Forward loaded error to same page
request.setAttribute("errorMessage", errorMessage);
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/displayTableContent.jsp");
disp.forward(request, response);
} else {
// Forward extracted result to same front end
if ("students".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "STUDENTS");
request.setAttribute("studentsList", studentsList);
/*for (Student stud : studentsList) {
System.out.println(stud);
}*/
} else if ("tas".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "TAs");
request.setAttribute("taList", taList);
/*for (Ta ta : taList) {
System.out.println(ta);
}*/
} else if ("courses".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "COURSES");
request.setAttribute("courseList", courseList);
/*for (Course course : courseList) {
System.out.println(course);
}*/
} else if ("classes".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "CLASSES");
request.setAttribute("classList", classList);
/*for (Classes cl : classList) {
System.out.println(cl);
}*/
} else if ("enrollments".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "ENROLLMENTS");
request.setAttribute("enrollmentList", enrollmentList);
/*for (Enrollment enroll : enrollmentList) {
System.out.println(enroll);
}*/
} else if ("prerequisites".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "PREREQUISITES");
request.setAttribute("prereqList", prereqList);
/*for (Prerequisite prereq : prereqList) {
System.out.println(prereq);
}*/
} else if ("logs".equalsIgnoreCase(tableName)) {
request.setAttribute("tableName", "LOGS");
request.setAttribute("logList", logList);
/*for (Log log : logList) {
System.out.println(log);
}*/
}
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/displayTableContent.jsp");
disp.forward(request, response);
}
}
}
<file_sep>/Backend_Source_Code--PLSQL/Sequence/Log_Sequence.sql
-- Create sequence for Log table
/*
Sequence to generate log# automatically when new log records are inserted in log table
*/
create sequence LOG_SEQ_GENERATOR
minvalue 1
maxvalue 9999999999999999999999999999
start with 100
increment by 1
cache 20;
| 241c60928aaeb96dabe156df6f6d3c3c057da991 | [
"Markdown",
"SQL",
"Java"
] | 18 | SQL | dipikaspatil/Database_Systems | 373ade411850bf6edc33447c3cba41c5f2d80914 | d606bb291136a46e22dd7b6c9f5643377ccc5ec8 |
refs/heads/master | <file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
namespace faravaghi\datatables;
use Yii;
use Closure;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\ActionColumn;
/**
* ActionColumn is a column for the [[GridView]] widget that displays buttons for viewing and manipulating the items.
*
* To add an ActionColumn to the gridview, add it to the [[GridView::columns|columns]] configuration as follows:
*
* ```php
* 'columns' => [
* // ...
* [
* 'class' => ActionColumn::className(),
* // you may configure additional properties here
* ],
* ]
* ```
*
* @author <NAME> <<EMAIL>>
* @since 2.0
*/
class EActionColumn extends ActionColumn
{
/**
* Initializes the default button rendering callbacks.
*/
protected function initDefaultButtons()
{
if (!isset($this->buttons['view'])) {
$this->buttons['view'] = function ($url, $model, $key) {
$options = array_merge([
'class' => 'view-link hint--top hint--rounded hint--success',
'title' => Yii::t('yii', 'View'),
'data-hint' => Yii::t('yii', 'View'),
'data-toggle' => 'modal',
'data-target' => '#view-modal',
'data-pjax' => '0',
], $this->buttonOptions);
return Html::a('<span class="glyphicon glyphicon-eye-open font-green"></span>', $url, $options);
};
}
if (!isset($this->buttons['update'])) {
$this->buttons['update'] = function ($url, $model, $key) {
$options = array_merge([
'class' => 'hint--top hint--rounded hint--warning',
'title' => Yii::t('yii', 'Update'),
'data-hint' => Yii::t('yii', 'Update'),
'data-pjax' => '0',
], $this->buttonOptions);
return Html::a('<span class="glyphicon glyphicon-pencil font-yellow"></span>', $url, $options);
};
}
if (!isset($this->buttons['delete'])) {
$this->buttons['delete'] = function ($url, $model, $key) {
$options = array_merge([
'class' => 'hint--top hint--rounded hint--error',
'title' => Yii::t('yii', 'Delete'),
'data-hint' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
// 'data-callback' =>
'data-pjax' => '1',
], $this->buttonOptions);
return Html::a('<span class="glyphicon glyphicon-trash font-red-pink"></span>', $url, $options);
};
}
}
}
<file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
return [
"(filtered from _MAX_ total entries)" => "(مطالب گزيده شده از مجموع _MAX_ عدد)",
": activate to sort column ascending" => ": به ترتیب صعودی ستون را انتخاب کنید",
": activate to sort column descending" => ": به ترتیب نزولی ستون را انتخاب کنید",
"Actions" => "عملیات",
"First" => "اولين",
"Last" => "آخرين",
"Next" => "بعدی",
"Previous" => "قبلی",
"All" => "همه",
"Loading..." => "درحال فراخوانی...",
"No data available in table" => "درکمال تاسف ، هيچ مطلبي يافت نشد",
"No matching records found" => "هيچ گزينه اي يافت نشد",
"Processing..." => "درحال پردازش اطلاعات...",
"Search:" => "جستجو:",
"Show _MENU_ entries" => "نمایش _MENU_ در صفحه",
"Showing 0 to 0 of 0 entries" => "نمایش 0 از 0 در 0 صفحه",
"Showing _START_ to _END_ of _TOTAL_ entries" => "نمايش _START_ تا _END_ از _TOTAL_ مطلب",
"Only related" => "Only related",
"History" => "تاریخچه",
"Refresh" => "بارگزاری",
"Operations" => "عملیات",
"Configure" => "تنظیمات",
"Print" => "چاپ",
"<h6>Print view</h6><p>Please use your browser's print function to print this table. Press escape when finished."=>"<h6>مشاهده نسخه قابل چاپ</h6><p>برای چاپ این جدول از گزینه پرینت مرورگرتان استفاده نمایید. هنگامی که چاپ به پایان رسید کلید ESc را فشار دهید.",
"<h6>Table copied</h6>" => "<h6>جدول در حافظه کپی شد</h6>",
"Save as CSV" => "ذخیره به صورت CSV",
"Save as Excel" => "خروجی اکسل",
"Save to PDF" => "خروجی PDF",
"Copy to Clipboard" => "کپی در حافظه",
"Add new" => "افزودن",
'Select all' => 'انتخاب همه',
'Deselect all' => 'لغو انتخاب همه',
'Select on page' => 'انتخاب در صفحه',
'Deselect on page' => 'لغو انتخاب در صفحه',
];
<file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
namespace faravaghi\datatables;
use yii\web\AssetBundle;
/**
* Asset for the DataTables JQuery plugin
* @author <NAME> <<EMAIL>>
*/
class DataTablesAsset extends AssetBundle
{
public $sourcePath = '@bower/datatables';
public $css = [
// 'rezvan/global/plugins/datatables/datatables.min.css',
];
public $js = [
'media/js/jquery.dataTables.js',
];
public $depends = [
'yii\web\JqueryAsset',
];
}<file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
namespace faravaghi\datatables;
use Yii;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\CheckboxColumn;
/**
* ECheckboxColumn displays a column of checkboxes in a grid view.
*
* To add a CheckboxColumn to the [[GridView]], add it to the [[GridView::columns|columns]] configuration as follows:
*
* ```php
* 'columns' => [
* // ...
* [
* 'class' => 'faravaghi\datatables\ECheckBoxColumn',
* // you may configure additional properties here
* ],
* ]
* ```
*
* Users may click on the checkboxes to select rows of the grid. The selected rows may be
* obtained by calling the following JavaScript code:
*
* ```javascript
* var keys = table.$('input[type="checkbox"]').serialize();
* // keys is an array consisting of the keys associated with the selected rows
* ```
*
* @author <NAME> <<EMAIL>>
* @since 1.0
*/
class ECheckBoxColumn extends CheckboxColumn
{
/**
* Renders the header cell content.
* The default implementation simply renders [[header]].
* This method may be overridden to customize the rendering of the header cell.
* @return string the rendering result
*/
protected function renderHeaderCellContent()
{
$name = $this->name;
if (substr_compare($name, '[]', -2, 2) === 0) {
$name = substr($name, 0, -2);
}
if (substr_compare($name, ']', -1, 1) === 0) {
$name = substr($name, 0, -1) . '_all]';
} else {
$name .= '_all';
}
$id = $this->grid->options['id'];
$_allSelectJs = <<< JS
$('.select-on-check-all').on('click', function(){
var rows = table.rows({ 'search': 'applied' }).nodes();
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
$('#$id tbody').on('change', 'input[type="checkbox"]', function(){
if(!this.checked){
var el = $('.select-on-check-all').get(0);
if(el && el.checked && ('indeterminate' in el)){
el.indeterminate = true;
}
}
});
JS;
$this->grid->getView()->registerJs($_allSelectJs);
if ($this->header !== null || !$this->multiple) {
return parent::renderHeaderCellContent();
} else {
return Html::checkBox($name, false, ['class' => 'select-on-check-all']);
}
}
}<file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
namespace faravaghi\datatables;
use yii\web\AssetBundle;
/**
* Asset for the DataTables TableTools JQuery plugin
* @author <NAME> <<EMAIL>>
*/
class DataTablesTableToolsAsset extends AssetBundle
{
public $sourcePath = '@bower/datatables-tabletools';
public $css = [
// "css/dataTables.tableTools.css",
];
public $js = [
"js/dataTables.tableTools.js",
];
public $depends = [
'yii\web\JqueryAsset',
'faravaghi\datatables\DataTablesAsset',
];
}<file_sep><?php
/**
* @copyright dadeh kavi rezvan Co.
* @author <NAME> <<EMAIL>>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @package yii2-widget-datatables
*/
namespace faravaghi\datatables;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\db\ActiveQuery;
use yii\base\InvalidConfigException;
/**
* Datatables Yii2 widget
* @author <NAME> <<EMAIL>>
*/
class DataTables extends \yii\grid\GridView
{
/**
* @var array the HTML attributes for the container tag of the datatables view.
* The "tag" element specifies the tag name of the container element and defaults to "div".
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = [];
/**
* @var array the HTML attributes for the datatables table element.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $tableOptions = [
'class' => 'table table-striped table-bordered dataTable no-footer dtr-inline',
'cellspacing' => '0',
'width' => '100%'
];
/**
* @var array the HTML attributes for the datatables table element.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $clientOptions = [];
/**
* @var array of Columns that you want sort with this field
*/
public $sortableColumn = [];
/**
* @var array of Columns that search on its
*/
public $searchableColumn = [];
/**
* Initializes the datatables widget disabling some GridView options like
* search, sort and pagination and using DataTables JS functionalities
* instead.
*/
public function init()
{
parent::init();
$this->registerTranslations();
/**
* init clientOptions:
*/
$clientOptions = [
/*'processing' => true,
'ordering' => false,*/
'order' => [
[ 1, 'asc' ]
],
'serverSide'=> true,
'lengthMenu'=> [
[10, 20, 50, -1],
[10, 20, 50, self::t('edt','All')]
],
'columnDefs'=> [
[
'orderable' => false,
'targets' => [0, count($this->columns) - 1]
]
],
'sPaginationType' => 'bootstrap',
'responsive'=>true,
'dom'=> "<'row'<'col-md-12'<'dt-buttons hidden-xs'T>>><'row'<'col-md-6 col-sm-6 col-xs-6'l><'col-md-6 col-sm-6 col-xs-6'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-5 col-xs-12'i><'col-md-7 col-sm-7 col-xs-12'p>>",
'tableTools'=>[
'aButtons'=> [
[
'sExtends'=> 'copy',
'sButtonText'=> self::t('edt','Copy to Clipboard'),
'sButtonClass' => 'dt-button buttons-copy buttons-flash btn red btn-outline',
'sInfo' => self::t('edt', '<h6>Table copied</h6>')
],
/*[
'sExtends'=> 'csv',
'sButtonText'=> Self::t('edt','Save to CSV')
],*/
[
'sExtends'=> 'xls',
'sButtonText'=> self::t('edt','Save as Excel'),
'sButtonClass' => 'dt-button buttons-excel buttons-flash btn yellow btn-outline',
'oSelectorOpts'=> ['page'=> 'current']
],
/*[
'sExtends'=> 'pdf',
'sButtonText'=> self::t('edt','Save to PDF'),
'sButtonClass' => 'dt-button buttons-pdf buttons-html5 btn green btn-outline',
],*/
[
'sExtends'=> 'print',
'sButtonText'=> self::t('edt','Print'),
'sButtonClass' => 'dt-button buttons-print btn dark btn-outline',
'sInfo'=> self::t('edt',"<h6>Print view</h6><p>Please use your browser's print function to print this table. Press escape when finished."),
],
]
],
'language'=>[
'processing' => self::t('edt', 'Processing...'),
'search' => self::t('edt', 'Search:'),
'lengthMenu' => self::t('edt','Show _MENU_ entries'),
'info' => self::t('edt','Showing _START_ to _END_ of _TOTAL_ entries'),
'infoEmpty' => self::t('edt','Showing 0 to 0 of 0 entries'),
'infoFiltered' => self::t('edt','(filtered from _MAX_ total entries)'),
'infoPostFix' => '',
'loadingRecords'=> self::t('edt','Loading...'),
'zeroRecords' => self::t('edt','No matching records found'),
'emptyTable' => self::t('edt','No data available in table'),
'paginate' => [
'first' => self::t('edt','First'),
'previous' => self::t('edt','Previous'),
'next' => self::t('edt','Next'),
'last' => self::t('edt','Last'),
],
'aria' => [
'sortAscending' => self::t('edt',': activate to sort column ascending'),
'sortDescending'=> self::t('edt',': activate to sort column descending'),
]
]
];
/**
* Merge Defualt Client Options and User definition:
*/
$this->clientOptions = array_merge($clientOptions, $this->getClientOptions());
//disable filter model by grid view
// $this->filterModel = null;
//layout showing only items
$this->layout = "{items}";
//the table id must be set
if (!isset($this->tableOptions['id'])) {
$this->tableOptions['id'] = $this->getId();
}
}
/**
* Runs the widget.
*/
public function run()
{
$view = $this->getView();
$id = $this->tableOptions['id'];
/**
* Load ClientOptions:
*/
$clientOptions = $this->getClientOptions();
//Bootstrap3 Asset by default
DataTablesBootstrapAsset::register($view);
//TableTools Asset if needed
if (isset($clientOptions["tableTools"]) || (isset($clientOptions["dom"]) && strpos($clientOptions["dom"], 'T')>=0)){
$tableTools = DataTablesTableToolsAsset::register($view);
//SWF copy and download path overwrite
$clientOptions["tableTools"]["sSwfPath"] = $tableTools->baseUrl."/swf/copy_csv_xls_pdf.swf";
}
$options = Json::encode($clientOptions);
$view->registerJs("var table = $('#$id').DataTable($options);" , \yii\web\View::POS_END);
$view->registerJs('$(\'body\').append(\'<div tabindex="-1" role="dialog" class="fade modal" id="view-modal"><div class="modal-dialog modal-lg"><div class="modal-content"></div></div></div>\');');
//base list view run
if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) {
$content = preg_replace_callback("/{\\w+}/", function ($matches) {
// $content = $this->renderSection($matches[0]);
$content = $this->renderItems();
return $content === false ? $matches[0] : $content;
}, $this->layout);
} else {
$content = $this->renderEmpty();
}
$tag = ArrayHelper::remove($this->options, 'tag', 'div');
echo Html::tag($tag, $content);
}
public function registerTranslations()
{
$i18n = \Yii::$app->i18n;
$i18n->translations['@vendor/faravaghi/datatables/*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'fa',
'basePath' => __DIR__ . '/messages',
'fileMap' => [
'@vendor/faravaghi/datatables/edt' => 'edt.php',
],
];
}
public static function t($category, $message, $params = [], $language = null)
{
return \Yii::t('@vendor/faravaghi/datatables/' . $category, $message, $params, $language);
}
/**
* Returns the options for the datatables view JS widget.
* @return array the options
*/
protected function getClientOptions()
{
return $this->clientOptions;
}
/**
* Renders the table body.
* @return string the rendering result.
*/
public function renderTableBody()
{
$clientOptions = $this->getClientOptions();
if (isset($clientOptions['serverSide']) && $clientOptions['serverSide'] == true) {
$colspan = count($this->columns);
$this->emptyText = self::t('edt', 'Loading...');
return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
}
else{
return parent::renderTableBody();
}
}
/**
* Returns formatted dataset from dataProvider in an array
* instead of rendering a HTML table. @see renderTableBody
*
* @access public
* @param int $draw
* @return void
*/
public function getFormattedData($draw) {
$result = array();
/*$returnData = array();
$returnData = array(
'draw' => $draw,
'recordsTotal' => $this->dataProvider->getTotalCount(),
'recordsFiltered' => $this->dataProvider->getTotalCount(),
'data' => $result,
);
return $returnData;*/
$request = \Yii::$app->request;
$originalQuery = $this->dataProvider->query;
$filterQuery = clone $originalQuery;
$filterQuery->where = null;
$search = $request->getQueryParam('search', ['value' => null, 'regex' => false]);
$columns = $request->getQueryParam('columns', []);
$order = $request->getQueryParam('order', []);
$filterQuery = $this->applyFilter($filterQuery, $columns, $search);
$filterQuery = $this->applyOrder($filterQuery, $columns, $order);
if (!empty($originalQuery->where)) {
$filterQuery->andWhere($originalQuery->where);
}
$actionQuery = clone $filterQuery;
$this->dataProvider->query = $filterQuery;
// echo "<pre>";print_r($actionQuery->createCommand()->sql);echo "</pre>";die();
try {
$models = $this->dataProvider->getModels();
$keys = $this->dataProvider->getKeys();
foreach ($models as $index => $model) {
$key = $keys[$index];
$rows = array();
foreach($this->columns as $column) {
$rows[] = $column->renderDataCell($model, $key, $index);
}
$result[] = $rows;
}
$response = [
'draw' => (int)$draw,
'recordsTotal' => (int)$originalQuery->count(),
'recordsFiltered' => (int)$actionQuery->count(),
'data' => $result,
];
}
catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
return $response;
}
/**
* @param ActiveQuery $query
* @param array $columns
* @param array $order
* @return ActiveQuery
*/
public function applyOrder(ActiveQuery $query, $columns, $order)
{
if (isset($this->applyOrder) && $this->applyOrder !== null) {
return call_user_func($this->applyOrder, $query, $columns, $order);
}
foreach ($order as $key => $item) {
$sort = $item['dir'] == 'desc' ? SORT_DESC : SORT_ASC;
// $query->addOrderBy([$columns[$item['column']]['data'] => $sort]);
if($this->sortableColumn[$item['column']] != NULL){
$query->addOrderBy([$this->sortableColumn[$item['column']] => $sort]);
}
}
return $query;
}
/**
* @param ActiveQuery $query
* @param array $columns
* @param array $search
* @return ActiveQuery
* @throws InvalidConfigException
*/
public function applyFilter(ActiveQuery $query, $columns, $search)
{
if (isset($this->applyFilter) && $this->applyFilter !== null) {
return call_user_func($this->applyFilter, $query, $columns, $search);
}
/** @var \yii\db\ActiveRecord $modelClass */
$modelClass = $query->modelClass;
$schema = $modelClass::getTableSchema()->columns;
foreach ($columns as $column) {
if ($column['searchable'] == 'true' && array_key_exists($column['data'], $schema) !== false) {
$value = empty($search['value']) ? $column['search']['value'] : $search['value'];
$query->orFilterWhere(['like', $column['data'], $value]);
}
}
if(!empty($this->searchableColumn)){
foreach ($this->searchableColumn as $column) {
$query->orFilterWhere(['like', $column, $search['value']]);
}
}
return $query;
}
}
| 24b97c9a6e77f70d7759b26716deb3e93517c7c1 | [
"PHP"
] | 6 | PHP | faravaghi/yii2-widget-datatables | 5bba81b45944e812355114a560089a10524e8496 | 5fd7ab279b320e04f5ba1dcc4acea1f1a1eee8de |
refs/heads/master | <file_sep># crime-over-time
How Did Birth Control, Abortion Policies, and Lead Emissions Affect the US?
<file_sep>create table codes (
MSN varchar,
Description varchar,
Unit varchar
);
create table data (
Data_Status varchar,
State varchar,
MSN varchar,
_1960 varchar,
_1961 varchar,
_1962 varchar,
_1963 varchar,
_1964 varchar,
_1965 varchar,
_1966 varchar,
_1967 varchar,
_1968 varchar,
_1969 varchar,
_1970 varchar,
_1971 varchar,
_1972 varchar,
_1973 varchar,
_1974 varchar,
_1975 varchar,
_1976 varchar,
_1977 varchar,
_1978 varchar,
_1979 varchar,
_1980 varchar,
_1981 varchar,
_1982 varchar,
_1983 varchar,
_1984 varchar,
_1985 varchar,
_1986 varchar,
_1987 varchar,
_1988 varchar,
_1989 varchar,
_1990 varchar,
_1991 varchar,
_1992 varchar,
_1993 varchar,
_1994 varchar,
_1995 varchar,
_1996 varchar,
_1997 varchar,
_1998 varchar,
_1999 varchar,
_2000 varchar,
_2001 varchar,
_2002 varchar,
_2003 varchar,
_2004 varchar,
_2005 varchar,
_2006 varchar,
_2007 varchar,
_2008 varchar,
_2009 varchar,
_2010 varchar,
_2011 varchar,
_2012 varchar,
_2013 varchar,
_2014 varchar,
_2015 varchar,
_2016 varchar
);<file_sep>import React, {Component} from 'react';
//import PropTypes from 'prop-types';
import * as d3 from "d3";
//import {withStyles} from '@material-ui/styles';
var crime = require('./data/CrimeStatebyState.js').default;
var gas = require('./data/gas_data_filtered.js').default;
var states = require('./data/states.js').default;
var states_reversed = require('./data/states_reversed.js').default;
class LineChart extends Component {
/*
constructor(props) {
super(props);
};
*/
componentDidMount() {/*update the graph after the component mounts (and the svg is created)*/
this.update();
}
hideStates = (state) => {
this.svg.selectAll("path").filter(function (d) {
return !d3.select(this).attr("class").includes(state);
}).style("opacity", 0.1);
};
showStates = () => {
this.svg.selectAll("path").style("opacity", 0.9);
};
updateScale = (selState) => {
// Add Text
console.log(selState);
this.svg.selectAll(".statename").remove();
this.svg.append("text").attr("class", "statename").attr("x", 10).attr("y", 5).text(selState);
// Update Crime Scale
let data = this.crimeFiltered.filter((d) => Object.keys(d)[0] === selState);
this.yScale.domain([0, Math.max.apply(Math, data[0][selState].map(function (o) {
return o["Violent Crime rate"];
}))]);
this.yAxisCrime.transition().duration(500).call(d3.axisLeft(this.yScale));
this.svg.selectAll(".c-dot")
.data(this.crimeFiltered.filter(f => Object.keys(f)[0] === selState))
.transition()
.duration(500)
.style("fill", "none")
.attr("class", function (d) {
return "c-dot" + " " + states_reversed[Object.keys(d)[0]];
}).attr("d", (d) => {
var unknownKey = Object.keys(d)[0];
return this.line1(d[unknownKey]);
}).style("opacity", 1);
this.svg.selectAll(".c-dot")
.data(this.crimeFiltered.filter(f => Object.keys(f)[0] === selState))
.exit()
.remove();
// Update Gas Scale
let result = 1000;
var key = Object.keys(states).filter(function (key) {
return states[key] === selState
})[0];
this.gasFiltered.forEach(function (d) {
if (d[58].value === key) {
result = Math.max.apply(Math, d.slice(0, 57).map(function (o) {
return o.value;
}))
}
});
this.yScale1.domain([0, result]);
this.yAxisGas.transition().duration(500).call(d3.axisRight(this.yScale1));
this.svg.selectAll(".g-dot")
.data(this.gasFiltered.filter(f => {
return f[58].value === key;
}))
.transition()
.duration(500)
.style("fill", "none")
.attr("class", function (d) {
return "g-dot" + " " + d[58].value;
}).attr("d", (d) => {
return this.line(d.slice(0, 57));
}).style("opacity", 1);
this.svg.selectAll(".g-dot")
.data(this.gasFiltered.filter(f => {
return f[58].value === key;
}))
.exit()
.remove()
};
update = () => {
var filterState = "none";
this.gasFiltered = [];
this.crimeFiltered = [];
this.gasFiltered = gas.filter(d => d.msn === "MGTCP" && d.state !== "US");
for (var key in this.gasFiltered) {
if (this.gasFiltered.hasOwnProperty(key)) {
this.gasFiltered[key] = d3.map(this.gasFiltered[key]).entries();
}
}
this.crimeFiltered = crime;
var margin = {top: 50, right: 100, bottom: 50, left: 70}
, width = 1100 - margin.left - margin.right // Use the window's width
, height = 600 - margin.top - margin.bottom; // Use the window's height
this.xScale = d3.scaleLinear()
.range([0, width]); // output
this.yScale = d3.scaleLinear()
.range([height, 0]); // output
this.yScale1 = d3.scaleLinear().range([height, 0]);
this.xScale.domain([1960, 2014]);
this.yScale.domain([0, d3.max(crime, function (d) {
return 2900;
})]);
if (filterState === "none") {
Array.prototype.maxByKey = function (k) {
var m = this.reduce((m, o, i) => o[k] > m[1] ? [i, o[k]] : m, [0, Number.MIN_VALUE]);
return this[m[0]];
};
let maxObj = this.gasFiltered.map(a => a.maxByKey("value")).maxByKey("value");
this.yScale1.domain([0, d3.max(this.gasFiltered[0], function (d) {
return maxObj.value;
})]);
} else {
this.yScale1.domain([0, 7000]);
}
this.svg = d3.select(this.refs.linechart).on("dblclick", () => {this.svg.selectAll("*").remove(); this.update()})
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// this.svg.selectAll("*")
// .remove();
this.xAxis = this.svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(this.xScale).tickFormat(d3.format("d")));
this.yAxisCrime = this.svg.append("g")
.attr("class", "y axis")
.style("stroke", "red")
.call(d3.axisLeft(this.yScale)); // Create an axis component with d3.axisLeft
this.yAxisGas = this.svg.append("g")
.attr("class", "axisRed")
.style("stroke", "grey")
.attr("transform", "translate( " + width + ", 0 )")
.call(d3.axisRight(this.yScale1));
// Crime
this.line1 = d3.line()
.x((d, i) => {
return this.xScale(d["Year"]);
}) // set the x values for the line generator
.y((d) => {
return this.yScale(d["Violent Crime rate"]);
}) // set the y values for the line generator
// .curve(d3.curveMonotoneX) // apply smoothing to the line
this.crimeLines = this.svg.selectAll(".c-dot")
.data(this.crimeFiltered)
.enter().append("path")
// .filter(function (d) {
//
// return Object.keys(d)[0] === "Texas"
// })
.style("fill", "none")
.attr("class", function (d) {
return "c-dot" + " " + states_reversed[Object.keys(d)[0]];
}).attr("d", (d) => {
var unknownKey = Object.keys(d)[0];
return this.line1(d[unknownKey]);
})
.style("stroke", function (d) {
return "red";
})
.style("stroke-width", 2.5)
.style("opacity", 0.6)
.on("mouseover", (d) => {
this.svg.append("text").attr("class", "statename").attr("x", 10).attr("y", 5).text(Object.keys(d)[0]);
d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 8);
this.hideStates(states_reversed[Object.keys(d)[0]]);
})
.on("mouseout", (d) => {
this.svg.selectAll(".statename").remove();
d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 2.5);
this.showStates();
}).on("click", (d) => {
this.updateScale(Object.keys(d)[0]);
});
this.line = d3.line()
.x((d) => {
return this.xScale(d["key"]);
})
.y((d) => {
return this.yScale1(d["value"]);
});
this.gasLines = this.svg.selectAll(".g-dot")
.data(this.gasFiltered)
.enter().append("path")
// .filter(function (d) {
// return d[58].value === "AK"
// })
.style("fill", "none")
.attr("class", function (d) {
return "g-dot" + " " + d[58].value;
})
.attr("d", (d) => {
return this.line(d.slice(0, 55));
})
.style("stroke", "grey")
.style("opacity", 0.8)
.style("stroke-width", 2.5)
.on("mouseover", (d) => {
d3.selectAll("." + d[58].value).style("stroke-width", 8);
this.hideStates(d[58].value);
this.svg.append("text").attr("class", "statename").attr("x", 10).attr("y", 5).text(states[d[58].value]);
})
.on("mouseout", (d) => {
this.svg.selectAll(".statename").remove();
d3.selectAll("." + d[58].value).style("stroke-width", 2.5);
this.showStates();
})
.on("click", (d) => {
this.updateScale(states[d[58].value]);
});
// text label for the x axis
this.svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top - 20) + ")")
.style("text-anchor", "middle")
.text("Date");
this.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("fill","red")
.text("Crime Rate (per 100,000 people)");
this.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", width + margin.right - 20)
.attr("x",0 - (height / 2))
.style("fill","grey")
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Lead (grams purchased as Gasoline)");
};
render() {
return (
<div ref={((mount) => {
if (mount && (this.mount === undefined)) {
this.mount = mount;
this.setState({})
}
this.mount = mount;
})} style={{width:"100%", height:"600px"}}>
<svg ref="linechart"
height={"600px"}
width={"1100px"}/>
</div>
);
}
}
export default LineChart;<file_sep>INSERT INTO codes (MSN,Description,Unit) VALUES
('ABICB','Aviation gasoline blending components consumed by the industrial sector','Billion Btu'),
('ABICP','Aviation gasoline blending components consumed by the industrial sector','Thousand barrels'),
('ARICB','Asphalt and road oil consumed by the industrial sector','Billion Btu'),
('ARICD','Asphalt and road oil price in the industrial sector','Dollars per million Btu'),
('ARICP','Asphalt and road oil consumed by the industrial sector','Thousand barrels'),
('ARICV','Asphalt and road oil expenditures in the industrial sector','Million dollars'),
('ARTCB','Asphalt and road oil total consumption','Billion Btu'),
('ARTCD','Asphalt and road oil average price all sectors','Dollars per million Btu'),
('ARTCP','Asphalt and road oil total consumption','Thousand barrels'),
('ARTCV','Asphalt and road oil total expenditures','Million dollars'),
('ARTXB','Asphalt and road oil total end-use consumption','Billion Btu'),
('ARTXD','Asphalt and road oil average price all end-use sectors','Dollars per million Btu'),
('ARTXP','Asphalt and road oil total end-use consumption','Thousand barrels'),
('ARTXV','Asphalt and road oil total end-use expenditures','Million dollars'),
('AVACB','Aviation gasoline consumed by the transportation sector','Billion Btu'),
('AVACD','Aviation gasoline price in the transportation sector','Dollars per million Btu'),
('AVACP','Aviation gasoline consumed by the transportation sector','Thousand barrels'),
('AVACV','Aviation gasoline expenditures in the transportation sector','Million dollars'),
('AVTCB','Aviation gasoline total consumption','Billion Btu'),
('AVTCD','Aviation gasoline average price all sectors','Dollars per million Btu'),
('AVTCP','Aviation gasoline total consumption','Thousand barrels'),
('AVTCV','Aviation gasoline total expenditures','Million dollars'),
('AVTXB','Aviation gasoline total end-use consumption','Billion Btu'),
('AVTXD','Aviation gasoline average price all end-use sectors','Dollars per million Btu'),
('AVTXP','Aviation gasoline total end-use consumption','Thousand barrels'),
('AVTXV','Aviation gasoline total end-use expenditures','Million dollars'),
('BMTCB','Biomass total consumption','Billion Btu'),
('BQICB','Normal butane consumed by the industrial sector','Billion Btu'),
('BQICP','Normal butane consumed by the industrial sector','Thousand barrels'),
('BQTCB','Normal butane total consumption','Billion Btu'),
('BQTCP','Normal butane total consumption','Thousand barrels'),
('BYICB','Butylene from refineries consumed by the industrial sector','Billion Btu'),
('BYICP','Butylene from refineries consumed by the industrial sector','Thousand barrels'),
('BYTCB','Butylene from refineries total consumption','Billion Btu'),
('BYTCP','Butylene from refineries total consumption','Thousand barrels'),
('CCEXB','Coal coke exported from the United States ','Billion Btu'),
('CCEXD','Coal coke exports average price United States','Dollars per million Btu'),
('CCEXP','Coal coke exported from the United States ','Thousand short tons'),
('CCEXV','Coal coke exports expenditures United States','Million dollars'),
('CCIMB','Coal coke imported into the United States','Billion Btu'),
('CCIMD','Coal coke imports average price United States','Dollars per million Btu'),
('CCIMP','Coal coke imported into the United States','Thousand short tons'),
('CCIMV','Coal coke imports expenditures United States','Million dollars'),
('CCNIB','Coal coke net imports into the United States','Billion Btu'),
('CCNIP','Coal coke net imports into the United States','Thousand short tons'),
('CCNIV','Coal coke net imports expenditures United States','Million dollars'),
('CLACB','Coal consumed by the transportation sector','Billion Btu'),
('CLACD','Coal price in the transportation sector','Dollars per million Btu'),
('CLACK','Factor for converting coal consumed by the transportation sector from physical units to Btu','Million Btu per short ton'),
('CLACP','Coal consumed by the transportation sector','Thousand short tons'),
('CLACV','Coal expenditures in the transportation sector','Million dollars'),
('CLCCB','Coal consumed by the commercial sector','Billion Btu'),
('CLCCD','Coal price in the commercial sector','Dollars per million Btu'),
('CLCCP','Coal consumed by the commercial sector','Thousand short tons'),
('CLCCV','Coal expenditures in the commercial sector','Million dollars'),
('CLEIB','Coal consumed by the electric power sector','Billion Btu'),
('CLEID','Coal price in the electric power sector','Dollars per million Btu'),
('CLEIK','Factor for converting coal consumed by the electric power sector from physical units to Btu','Million Btu per short ton'),
('CLEIP','Coal consumed by the electric power sector','Thousand short tons'),
('CLEIV','Coal expenditures in the electric power sector','Million dollars'),
('CLHCK','Factor for converting coal consumed by the residential and commercial sectors from physical units to Btu','Million Btu per short ton'),
('CLICB','Coal consumed by the industrial sector','Billion Btu'),
('CLICD','Coal price in the industrial sector','Dollars per million Btu'),
('CLICP','Coal consumed by the industrial sector','Thousand short tons'),
('CLICV','Coal expenditures in the industrial sector','Million dollars'),
('CLISB','Coal consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('CLKCB','Coal consumed at coke plants (coking coal)','Billion Btu'),
('CLKCD','Coal price at coke plants','Dollars per million Btu'),
('CLKCK','Factor for converting coal carbonized at coke plants from physical units to Btu','Million Btu per short ton'),
('CLKCP','Coal consumed at coke plants (coking coal)','Thousand short tons'),
('CLKCV','Coal expenditures at coke plants','Million dollars'),
('CLOCB','Coal consumed by industrial users other than coke plants','Billion Btu'),
('CLOCD','Coal price in the industrial sector other than coke plants','Dollars per million Btu'),
('CLOCK','Factor for converting coal consumed by industrial users other than coke plants from physical units to Btu','Million Btu per short ton'),
('CLOCP','Coal consumed by industrial users other than coke plants','Thousand short tons'),
('CLOCV','Coal expenditures in the industrial sector other than coke plants','Million dollars'),
('CLOSB','Coal consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('CLPRB','Coal production','Billion Btu'),
('CLPRK','Factor for converting coal production from physical units to Btu','Million Btu per short ton'),
('CLPRP','Coal production','Thousand short tons'),
('CLRCB','Coal consumed by the residential sector','Billion Btu'),
('CLRCD','Coal price in the residential sector','Dollars per million Btu'),
('CLRCP','Coal consumed by the residential sector','Thousand short tons'),
('CLRCV','Coal expenditures in the residential sector','Million dollars'),
('CLRFB','Coal consumed as refinery fuel','Billion Btu'),
('CLSCB','Coal total consumption adjusted for process fuel','Billion Btu'),
('CLTCB','Coal total consumption','Billion Btu'),
('CLTCD','Coal average price all sectors','Dollars per million Btu'),
('CLTCP','Coal total consumption','Thousand short tons'),
('CLTCV','Coal total expenditures','Million dollars'),
('CLTXB','Coal total end-use consumption','Billion Btu'),
('CLTXD','Coal average price all end-use sectors','Dollars per million Btu'),
('CLTXP','Coal total end-use consumption','Thousand barrels'),
('CLTXV','Coal total end-use expenditures','Million dollars'),
('COICB','Crude oil consumed by the industrial sector','Billion Btu'),
('COICP','Crude oil consumed by the industrial sector','Thousand barrels'),
('COPRK','Factor for converting crude oil production from physical units to Btu','Million Btu per barrel'),
('DFACB','Distillate fuel oil consumed by the transportation sector','Billion Btu'),
('DFACD','Distillate fuel oil price in the transportation sector','Dollars per million Btu'),
('DFACP','Distillate fuel oil consumed by the transportation sector','Thousand barrels'),
('DFACV','Distillate fuel oil expenditures in the transportation sector','Million dollars'),
('DFCCB','Distillate fuel oil consumed by the commercial sector','Billion Btu'),
('DFCCD','Distillate fuel oil price in the commercial sector','Dollars per million Btu'),
('DFCCP','Distillate fuel oil consumed by the commercial sector','Thousand barrels'),
('DFCCV','Distillate fuel oil expenditures in the commercial sector','Million dollars'),
('DFEIB','Distillate fuel oil consumed by the electric power sector','Billion Btu'),
('DFEID','Distillate fuel oil price in the electric power sector','Dollars per million Btu'),
('DFEIP','Distillate fuel oil consumed by the electric power sector','Thousand barrels'),
('DFEIV','Distillate fuel oil expenditures in the electric power sector','Million dollars'),
('DFICB','Distillate fuel oil consumed by the industrial sector','Billion Btu'),
('DFICD','Distillate fuel oil price in the industrial sector','Dollars per million Btu'),
('DFICP','Distillate fuel oil consumed by the industrial sector','Thousand barrels'),
('DFICV','Distillate fuel oil expenditures in the industrial sector','Million dollars'),
('DFISB','Distillate fuel oil consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('DFRCB','Distillate fuel oil consumed by the residential sector','Billion Btu'),
('DFRCD','Distillate fuel oil price in the residential sector','Dollars per million Btu'),
('DFRCP','Distillate fuel oil consumed by the residential sector','Thousand barrels'),
('DFRCV','Distillate fuel oil expenditures in the residential sector','Million dollars'),
('DFRFB','Distillate fuel oil consumed as refinery fuel','Billion Btu'),
('DFSCB','Distillate fuel oil total consumption adjusted for process fuel','Billion Btu'),
('DFTCB','Distillate fuel oil total consumption','Billion Btu'),
('DFTCD','Distillate fuel oil average price all sectors','Dollars per million Btu'),
('DFTCK','Factor converting distillate fuel oil physical units to Btu United States only','Million Btu per barrel'),
('DFTCP','Distillate fuel oil total consumption','Thousand barrels'),
('DFTCV','Distillate fuel oil total expenditures','Million dollars'),
('DFTXB','Distillate fuel oil total end-use consumption','Billion Btu'),
('DFTXD','Distillate fuel oil average price all end-use sectors','Dollars per million Btu'),
('DFTXP','Distillate fuel oil total end-use consumption','Thousand barrels'),
('DFTXV','Distillate fuel oil total end-use expenditures','Million dollars'),
('ELEXB','Electricity exported from the United States','Billion Btu'),
('ELEXD','Electricity exports average price','Dollars per million Btu'),
('ELEXP','Electricity exported from the United States','Million kilowatthours'),
('ELEXV','Electricity exports expenditures','Million dollars'),
('ELIMB','Electricity imported into the United States','Billion Btu'),
('ELIMD','Electricity imports average price','Dollars per million Btu'),
('ELIMP','Electricity imported into the United States','Million kilowatthours'),
('ELIMV','Electricity imports expenditures','Million dollars'),
('ELISB','Net interstate flow of electricity and associated losses (negative and positive values)','Billion Btu'),
('ELISP','Net interstate flow of of electricity','Million kilowatthours'),
('ELNIB','Net imports of electricity into the United States','Billion Btu'),
('ELNIP','Net imports of electricity into the United States','Million kilowatthours'),
('EMACB','Fuel ethanol excluding denaturant consumed by the transportation sector ','Billion Btu'),
('EMACV','Fuel ethanol excluding denaturant expenditures in the transportation sector (through 1992)','Million dollars'),
('EMCCB','Fuel ethanol excluding denaturant consumed by the commercial sector ','Billion Btu'),
('EMCCV','Fuel ethanol excluding denaturant expenditures in the commercial sector (through 1992)','Million dollars'),
('EMFDB','Biomass inputs (feedstock) for the production of fuel ethanol','Billion Btu'),
('EMICB','Fuel ethanol excluding denaturant consumed by the industrial sector ','Billion Btu'),
('EMICV','Fuel ethanol excluding denaturant expenditures in the industrial sector (through 1992)','Million dollars'),
('EMLCB','Energy losses and co-products from the production of fuel ethanol','Billion Btu'),
('EMTCB','Fuel ethanol excluding denaturant total consumption','Billion Btu'),
('EMTCV','Fuel ethanol excluding denaturant total expenditures (through 1992)','Million dollars'),
('ENACP','Fuel ethanol including denaturant consumed by the transportation sector','Thousand barrels'),
('ENCCP','Fuel ethanol including denaturant consumed by the commercial sector','Thousand barrels'),
('ENICP','Fuel ethanol including denaturant consumed by the industrial sector','Thousand barrels'),
('ENPRP','Fuel ethanol production including denaturant','Thousand barrels'),
('ENTCK','Factor for converting fuel ethanol consumption from physical units to Btu','Million Btu per barrel'),
('ENTCP','Fuel ethanol including denaturant total consumption','Thousand barrels'),
('EQICB','Ethane consumed by the industrial sector','Billion Btu'),
('EQICP','Ethane consumed by the industrial sector','Thousand barrels'),
('EQTCB','Ethane total consumption','Billion Btu'),
('EQTCP','Ethane total consumption','Thousand barrels'),
('ESACB','Electricity consumed by (i.e. sold to) the transportation sector','Billion Btu'),
('ESACD','Electricity price in the transportation sector','Dollars per million Btu'),
('ESACP','Electricity consumed by (i.e. sold to) the transportation sector','Million kilowatthours'),
('ESACV','Electricity expenditures in the transportation sector','Million dollars'),
('ESCCB','Electricity consumed by (i.e. sold to) the commercial sector','Billion Btu'),
('ESCCD','Electricity price in the commercial sector','Dollars per million Btu'),
('ESCCP','Electricity consumed by (i.e. sold to) the commercial sector','Million kilowatthours'),
('ESCCV','Electricity expenditures in the commercial sector','Million dollars'),
('ESICB','Electricity consumed by (i.e. sold to) the industrial sector','Billion Btu'),
('ESICD','Electricity price in the industrial sector','Dollars per million Btu'),
('ESICP','Electricity consumed by (i.e. sold to) the industrial sector','Million kilowatthours'),
('ESICV','Electricity expenditures in the industrial sector','Million dollars'),
('ESISB','Electricity sales to the industrial sector excluding refinery use','Billion Btu'),
('ESRCB','Electricity consumed by (i.e. sold to) the residential sector','Billion Btu'),
('ESRCD','Electricity price in the residential sector','Dollars per million Btu'),
('ESRCP','Electricity consumed by (i.e. sold to) the residential sector','Million kilowatthours'),
('ESRCV','Electricity expenditures in the residential sector','Million dollars'),
('ESRFB','Electricity consumed by refineries','Billion Btu'),
('ESSCB','Electricity total consumption adjusted for process fuel','Billion Btu'),
('ESTCB','Electricity total consumption (i.e. retail sales)','Billion Btu'),
('ESTCD','Electricity average price all sectors','Dollars per million Btu'),
('ESTCP','Electricity total consumption (i.e. retail sales)','Million kilowatthours'),
('ESTCV','Electricity total expenditures','Million dollars'),
('ESTXB','Electricity total end-use consumption (i.e. retail sales)','Billion Btu'),
('ESTXD','Electricity average price all end-use sectors','Dollars per million Btu'),
('ESTXP','Electricity total end-use consumption (i.e. retail sales)','Million kilowatthours'),
('ESTXV','Electricity total end-use expenditures','Million dollars'),
('EYICB','Ethylene from refineries consumed by the industrial sector','Billion Btu'),
('EYICP','Ethylene from refineries consumed by the industrial sector','Thousand barrels'),
('EYTCB','Ethylene from refineries total consumption','Billion Btu'),
('EYTCP','Ethylene from refineries total consumption','Thousand barrels'),
('FFETK','Fossil fueled steam-electric power plant conversion factor United States only','Thousand Btu per kilowatthour'),
('FFTCB','Fossil fuels total consumption','Billion Btu'),
('FNICB','Petrochemical feedstocks naphtha less than 401° F consumed by the industrial sector','Billion Btu'),
('FNICD','Petrochemical feedstocks naphtha less than 401° F price in the industrial sector','Dollars per million Btu'),
('FNICP','Petrochemical feedstocks naphtha less than 401° F consumed by the industrial sector','Thousand barrels'),
('FNICV','Petrochemical feedstocks naphtha less than 401° F expenditures in the industrial sector','Million dollars'),
('FOICB','Petrochemical feedstocks other oils equal to or greater than 401° F consumed by the industrial sector','Billion Btu'),
('FOICD','Petrochemical feedstocks other oils equal to or greater than 401° F price in the industrial sector','Dollars per million Btu'),
('FOICP','Petrochemical feedstocks other oils equal to or greater than 401° F consumed by the industrial sector','Thousand barrels'),
('FOICV','Petrochemical feedstocks other oils equal to or greater than 401° F expenditures in the industrial sector','Million dollars'),
('FSICB','Petrochemical feedstocks still gas consumed by the industrial sector','Billion Btu'),
('FSICD','Petrochemical feedstocks still gas price in the industrial sector','Dollars per million Btu'),
('FSICP','Petrochemical feedstocks still gas consumed by the industrial sector','Thousand barrels'),
('FSICV','Petrochemical feedstocks still gas expenditures in the industrial sector','Million dollars'),
('GDPRV','Current-dollar gross domestic product','Million dollars'),
('GDPRX','Real gross domestic product','Million chained (2009) dollars'),
('GECCB','Geothermal energy consumed by the commercial sector','Billion Btu'),
('GEEGB','Geothermal energy consumed for electricity generation by the electric power sector','Billion Btu'),
('GEEGP','Geothermal electricity net generation in the electric power sector','Million kilowatthours'),
('GEICB','Geothermal energy consumed by the industrial sector','Billion Btu'),
('GERCB','Geothermal energy consumed by the residential sector','Billion Btu'),
('GETCB','Geothermal energy total consumption','Billion Btu'),
('GETXB','Geothermal energy total end-use consumption','Billion Btu'),
('HLACB','Hydrocarbon gas liquids consumed by the transportation sector','Billion Btu'),
('HLACD','Hydrocarbon gas liquids price in the transportation sector','Dollars per million Btu'),
('HLACP','Hydrocarbon gas liquids consumed by the transportation sector','Thousand barrels'),
('HLACV','Hydrocarbon gas liquids expenditures in the transportation sector','Million dollars'),
('HLCCB','Hydrocarbon gas liquids consumed by the commercial sector','Billion Btu'),
('HLCCD','Hydrocarbon gas liquids price in the commercial sector','Dollars per million Btu'),
('HLCCP','Hydrocarbon gas liquids consumed by the commercial sector','Thousand barrels'),
('HLCCV','Hydrocarbon gas liquids expenditures in the commercial sector','Million dollars'),
('HLICB','Hydrocarbon gas liquids consumed by the industrial sector','Billion Btu'),
('HLICD','Hydrocarbon gas liquids price in the industrial sector','Dollars per million Btu'),
('HLICK','Average conversion factor for industrial consumption of hydrocarbon gas liquids','Million Btu per barrel'),
('HLICP','Hydrocarbon gas liquids consumed by the industrial sector','Thousand barrels'),
('HLICV','Hydrocarbon gas liquids expenditures in the industrial sector','Million dollars'),
('HLISB','Hydrocarbon gas liquids consumed by the industrial sector adjusted for processed fuel','Billion Btu'),
('HLRCB','Hydrocarbon gas liquids consumed by the residential sector','Billion Btu'),
('HLRCD','Hydrocarbon gas liquids price in the residential sector','Dollars per million Btu'),
('HLRCP','Hydrocarbon gas liquids consumed by the residential sector','Thousand barrels'),
('HLRCV','Hydrocarbon gas liquids expenditures in the residential sector','Million dollars'),
('HLRFB','Hydrocarbon gas liquids consumed as refinery fuel and intermediate products','Billion Btu'),
('HLSCB','Hydrocarbon gas liquids total consumption adjusted for processed fuel','Billion Btu'),
('HLTCB','Hydrocarbon gas liquids total consumption','Billion Btu'),
('HLTCD','Hydrocarbon gas liquids average price all sectors','Dollars per million Btu'),
('HLTCK','Factor for converting hydrocarbon gas liquids physical units to Btu','Million Btu per barrel'),
('HLTCP','Hydrocarbon gas liquids total consumption','Thousand barrels'),
('HLTCV','Hydrocarbon gas liquids total expenditures','Million dollars'),
('HLTXB','Hydrocarbon gas liquids total end-use consumption','Billion Btu'),
('HLTXD','Hydrocarbon gas liquids average price all end-use sectors','Dollars per million Btu'),
('HLTXP','Hydrocarbon gas liquids total end-use consumption','Thousand barrels'),
('HLTXV','Hydrocarbon gas liquids total end-use expenditures','Million dollars'),
('HYCCB','Hydropower consumed by the commercial sector','Billion Btu'),
('HYCCP','Hydroelectricity net generation in the commercial sector','Million kilowatthours'),
('HYEGB','Hydropower consumed for electricity generation by the electric power sector','Billion Btu'),
('HYEGP','Hydroelectricity net generation in the electric power sector','Million kilowatthours'),
('HYICB','Hydropower consumed by the industrial sector','Billion Btu'),
('HYICP','Hydroelectricity net generation in the industrial sector','Million kilowatthours'),
('HYTCB','Hydropower total consumption','Billion Btu'),
('HYTCP','Hydroelectricity total net generation','Million kilowatthours'),
('HYTXB','Hydropower total end-use consumption','Billion Btu'),
('HYTXP','Hydroelectricity net generation total end-use sectors','Million kilowatthours'),
('IQICB','Isobutane consumed by the industrial sector','Billion Btu'),
('IQICP','Isobutane consumed by the industrial sector','Thousand barrels'),
('IQTCB','Isobutane total consumption','Billion Btu'),
('IQTCP','Isobutane total consumption','Thousand barrels'),
('IYICB','Isobutylene from refineries consumed by the industrial sector','Billion Btu'),
('IYICP','Isobutylene from refineries consumed by the industrial sector','Thousand barrels'),
('IYTCB','Isobutylene from refineries total consumption','Billion Btu'),
('IYTCP','Isobutylene from refineries total consumption','Thousand barrels'),
('JFACB','Jet fuel consumed by the transportation sector','Billion Btu'),
('JFACD','Jet fuel price in the transportation sector','Dollars per million Btu'),
('JFACP','Jet fuel consumed by the transportation sector','Thousand barrels'),
('JFACV','Jet fuel expenditures in the transportation sector','Million dollars'),
('JFTCB','Jet fuel total consumption','Billion Btu'),
('JFTCD','Jet fuel average price all sectors','Dollars per million Btu'),
('JFTCP','Jet fuel total consumption','Thousand barrels'),
('JFTCV','Jet fuel total expenditures','Million dollars'),
('JFTXB','Jet fuel total end-use consumption','Billion Btu'),
('JFTXD','Jet fuel average price all end-use sectors','Dollars per million Btu'),
('JFTXP','Jet fuel total end-use consumption','Thousand barrels'),
('JFTXV','Jet fuel total end-use expenditures','Million dollars'),
('KSCCB','Kerosene consumed by the commercial sector','Billion Btu'),
('KSCCD','Kerosene price in the commercial sector','Dollars per million Btu'),
('KSCCP','Kerosene consumed by the commercial sector','Thousand barrels'),
('KSCCV','Kerosene expenditures in the commercial sector','Million dollars'),
('KSICB','Kerosene consumed by the industrial sector','Billion Btu'),
('KSICD','Kerosene price in the industrial sector','Dollars per million Btu'),
('KSICP','Kerosene consumed by the industrial sector','Thousand barrels'),
('KSICV','Kerosene expenditures in the industrial sector','Million dollars'),
('KSRCB','Kerosene consumed by the residential sector','Billion Btu'),
('KSRCD','Kerosene price in the residential sector','Dollars per million Btu'),
('KSRCP','Kerosene consumed by the residential sector','Thousand barrels'),
('KSRCV','Kerosene expenditures in the residential sector','Million dollars'),
('KSTCB','Kerosene total consumption','Billion Btu'),
('KSTCD','Kerosene average price all sectors','Dollars per million Btu'),
('KSTCP','Kerosene total consumption','Thousand barrels'),
('KSTCV','Kerosene total expenditures','Million dollars'),
('KSTXB','Kerosene total end-use consumption','Billion Btu'),
('KSTXD','Kerosene average price all end-use sectors','Dollars per million Btu'),
('KSTXP','Kerosene total end-use consumption','Thousand barrels'),
('KSTXV','Kerosene total end-use expenditures','Million dollars'),
('LOACB','The transportation sectors share of electrical system energy losses','Billion Btu'),
('LOCCB','The commercial sectors share of electrical system energy losses','Billion Btu'),
('LOICB','The industrial sectors share of electrical system energy losses','Billion Btu'),
('LORCB','The residential sectors share of electrical system energy losses','Billion Btu'),
('LOTCB','Total electrical system energy losses','Billion Btu'),
('LOTXB','Total electrical system energy losses allocated to the end-use sectors','Billion Btu'),
('LUACB','Lubricants consumed by the transportation sector','Billion Btu'),
('LUACD','Lubricants price in the transportation sector','Dollars per million Btu'),
('LUACP','Lubricants consumed by the transportation sector','Thousand barrels'),
('LUACV','Lubricants expenditures in the transportation sector','Million dollars'),
('LUICB','Lubricants consumed by the industrial sector','Billion Btu'),
('LUICD','Lubricants price in the industrial sector','Dollars per million Btu'),
('LUICP','Lubricants consumed by the industrial sector','Thousand barrels'),
('LUICV','Lubricants expenditures in the industrial sector','Million dollars'),
('LUTCB','Lubricants total consumption','Billion Btu'),
('LUTCD','Lubricants average price all sectors','Dollars per million Btu'),
('LUTCP','Lubricants total consumption','Thousand barrels'),
('LUTCV','Lubricants average price all sectors','Million dollars'),
('LUTXB','Lubricants total end-use consumption','Billion Btu'),
('LUTXD','Lubricants average price all end-use sectors','Dollars per million Btu'),
('LUTXP','Lubricants total end-use consumption','Thousand barrels'),
('LUTXV','Lubricants total end-use expenditures','Million dollars'),
('MBICB','Motor gasoline blending components consumed by the industrial sector','Billion Btu'),
('MBICP','Motor gasoline blending components consumed by the industrial sector','Thousand barrels'),
('MBTCK','Factor converting motor gasoline blending components physical units to Btu United States only','Million Btu per barrel'),
('MGACB','Motor gasoline consumed by the transportation sector','Billion Btu'),
('MGACD','Motor gasoline price in the transportation sector','Dollars per million Btu'),
('MGACP','Motor gasoline consumed by the transportation sector','Thousand barrels'),
('MGACV','Motor gasoline expenditures in the transportation sector','Million dollars'),
('MGCCB','Motor gasoline consumed by the commercial sector','Billion Btu'),
('MGCCD','Motor gasoline price in the commercial sector','Dollars per million Btu'),
('MGCCP','Motor gasoline consumed by the commercial sector','Thousand barrels'),
('MGCCV','Motor gasoline expenditures in the commercial sector','Million dollars'),
('MGICB','Motor gasoline consumed by the industrial sector','Billion Btu'),
('MGICD','Motor gasoline price in the industrial sector','Dollars per million Btu'),
('MGICP','Motor gasoline consumed by the industrial sector','Thousand barrels'),
('MGICV','Motor gasoline expenditures in the industrial sector','Million dollars'),
('MGTCB','Motor gasoline total consumption','Billion Btu'),
('MGTCD','Motor gasoline average price all sectors','Dollars per million Btu'),
('MGTCK','Factor converting motor gasoline physical units to Btu United States only','Million Btu per barrel'),
('MGTCP','Motor gasoline total consumption','Thousand barrels'),
('MGTCV','Motor gasoline total expenditures','Million dollars'),
('MGTPV','Motor gasoline expenditures per capita','Dollars'),
('MGTXB','Motor gasoline total end-use consumption','Billion Btu'),
('MGTXD','Motor gasoline average price all end-use sectors','Dollars per million Btu'),
('MGTXP','Motor gasoline total end-use consumption','Thousand barrels'),
('MGTXV','Motor gasoline total end-use expenditures','Million dollars'),
('MMTCB','Motor gasoline total consumption excluding fuel ethanol','Billion Btu'),
('MSICB','Miscellaneous petroleum products consumed by the industrial sector','Billion Btu'),
('MSICD','Miscellaneous petroleum products price in the industrial sector','Dollars per million Btu'),
('MSICP','Miscellaneous petroleum products consumed by the industrial sector','Thousand barrels'),
('MSICV','Miscellaneous petroleum products expenditures in the industrial sector','Million dollars'),
('NAICB','Natural gasoline consumed by the industrial sector (through 1983)','Billion Btu'),
('NAICP','Natural gasoline consumed by the industrial sector (through 1983)','Thousand barrels'),
('NGACB','Natural gas consumed by the transportation sector ','Billion Btu'),
('NGACD','Natural gas price in the transportation sector','Dollars per million Btu'),
('NGACP','Natural gas consumed by the transportation sector','Million cubic feet'),
('NGACV','Natural gas expenditures in the transportation sector','Million dollars'),
('NGASB','Natural gas consumed by the transportation sector adjusted for process fuel','Billion Btu'),
('NGCCB','Natural gas consumed by (delivered to) the commercial sector','Billion Btu'),
('NGCCD','Natural gas price in the commercial sector','Dollars per million Btu'),
('NGCCP','Natural gas consumed by (delivered to) the commercial sector','Million cubic feet'),
('NGCCV','Natural gas expenditures in the commercial sector','Million dollars'),
('NGEIB','Natural gas consumed by the electric power sector','Billion Btu'),
('NGEID','Natural gas price in the electric power sector','Dollars per million Btu'),
('NGEIK','Factor for converting natural gas consumed by the electric power sector from physical units to Btu','Thousand Btu per cubic foot'),
('NGEIP','Natural gas consumed by the electric power sector','Million cubic feet'),
('NGEIV','Natural gas expenditures in the electric power sector','Million dollars'),
('NGICB','Natural gas consumed by (delivered to) the industrial sector','Billion Btu'),
('NGICD','Natural gas price in the industrial sector','Dollars per million Btu'),
('NGICP','Natural gas consumed by (delivered to) the industrial sector','Million cubic feet'),
('NGICV','Natural gas expenditures in the industrial sector','Million dollars'),
('NGISB','Natural gas consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('NGLPB','Natural gas consumed as lease and plant fuel','Billion Btu'),
('NGMPB','Natural gas marketed production','Billion Btu'),
('NGMPK','Conversion factor for natural gas marketed production','Thousand Btu per cubic feet'),
('NGMPP','Natural gas marketed production','Million cubic feet'),
('NGPZB','Natural gas for pipeline and distribution use','Billion Btu'),
('NGRCB','Natural gas consumed by (delivered to) the residential sector','Billion Btu'),
('NGRCD','Natural gas price in the residential sector','Dollars per million Btu'),
('NGRCP','Natural gas consumed by (delivered to) the residential sector','Million cubic feet'),
('NGRCV','Natural gas expenditures in the residential sector','Million dollars'),
('NGRFB','Natural gas consumed as refinery fuel ','Billion Btu'),
('NGSCB','Natural gas total consumption adjusted for process fuel','Billion Btu'),
('NGTCB','Natural gas total consumption','Billion Btu'),
('NGTCD','Natural gas average price all sectors','Dollars per million Btu'),
('NGTCK','Factor for converting natural gas total consumption from physical units to Btu','Thousand Btu per cubic foot'),
('NGTCP','Natural gas total consumption','Million cubic feet'),
('NGTCV','Natural gas total expenditures','Million dollars'),
('NGTXB','Natural gas total end-use consumption','Billion Btu'),
('NGTXD','Natural gas average price all end-use sectors','Dollars per million Btu'),
('NGTXK','Factor for converting natural gas consumed by all sectors other than electric power from physical units to Btu','Thousand Btu per cubic foot'),
('NGTXP','Natural gas total end-use consumption','Million cubic feet'),
('NGTXV','Natural gas total end-use expenditures','Million dollars'),
('NNTCB','Natural gas total consumption (excluding supplemental gaseous fuels)','Billion Btu'),
('NUEGB','Nuclear energy consumed for electricity generation by the electric power sector','Billion Btu'),
('NUEGD','Nuclear fuel price in the electric power sector','Dollars per million Btu'),
('NUEGP','Nuclear electricity net generation in the electric power sector','Million kilowatthours'),
('NUEGV','Nuclear fuel expenditures in the electric power sector','Million dollars'),
('NUETB','Nuclear energy consumed for electricity generation total','Billion Btu'),
('NUETD','Nuclear fuel average price all sectors','Dollars per million Btu'),
('NUETK','Factor for converting electricity generated from nuclear power from physical units to Btu United States only','Thousand Btu per kilowatthour'),
('NUETP','Nuclear electricity total net generation','Million kilowatthours'),
('NUETV','Nuclear fuel total expenditures','Million dollars'),
('OHICD','Other hydrocarbon gas liquids (other than propane) price in the industrial sector','Dollars per million Btu'),
('OHICV','Other hydrocarbon gas liquids (other than propane) expenditures in the industrial sector','Million dollars'),
('OPICB','Other petroleum products consumed by the industrial sector','Billion Btu'),
('OPICD','Other petroleum products average price in the industrial sector','Dollars per million Btu'),
('OPICP','Other petroleum products consumed by the industrial sector','Thousand barrels'),
('OPICV','Other petroleum products total expenditures in the industrial sector','Million dollars'),
('OPISB','Other petroleum products consumed by the industrial sector excluding refinery fuel and intermediate products','Billion Btu'),
('OPSCB','Other petroleum products total consumption adjusted for refinery fuel and intermediate products','Billion Btu'),
('OPTCB','Other petroleum products total consumption','Billion Btu'),
('OPTCD','Other petroleum products average price all sectors','Dollars per million Btu'),
('OPTCP','Other petroleum products total consumption','Thousand barrels'),
('OPTCV','Other petroleum products total expenditures','Million dollars'),
('OPTXB','Other petroleum products total end-use consumption','Billion Btu'),
('OPTXD','Other petroleum products average price all end-use sectors','Dollars per million Btu'),
('OPTXP','Other petroleum products total end-use consumption','Thousand barrels'),
('OPTXV','Other petroleum products total end-use expenditures','Million dollars'),
('P1ICB','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" consumed by the industrial sector"','Billion Btu'),
('P1ICD','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" average price in the industrial sector"','Dollars per million Btu'),
('P1ICP','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" consumed by the industrial sector"','Thousand barrels'),
('P1ICV','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" expenditures in the industrial sector"','Million dollars'),
('P1ISB','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" consumed by the industrial sector excluding refinery fuel and intermediate products"','Billion Btu'),
('P1SCB','"Asphalt and road oil kerosene lubricants petroleum coke and ""other petroleum products"" total consumption adjusted for process fuel and intermediate products"','Billion Btu'),
('P1TCB','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total consumption"','Billion Btu'),
('P1TCD','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" average price all sectors"','Dollars per million Btu'),
('P1TCP','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total consumption"','Thousand barrels'),
('P1TCV','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total expenditures"','Million dollars'),
('P1TXB','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total end-use consumption"','Billion Btu'),
('P1TXD','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" average price all end-use sectors"','Dollars per million Btu'),
('P1TXP','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total end-use consumption"','Thousand barrels'),
('P1TXV','"Asphalt and road oil aviation gasoline kerosene lubricants petroleum coke and ""other petroleum products"" total end-use expenditures"','Million dollars'),
('P5RFB','Other petroleum products (SG and PC consumed as process fuel and AB MB PP and UO consumed as intermediate products)','Billion Btu'),
('PAACB','All petroleum products consumed by the transportation sector','Billion Btu'),
('PAACD','All petroleum products average price in the transportation sector','Dollars per million Btu'),
('PAACK','Factor for converting all petroleum products consumed by the transportation sector from physical units to Btu United States only','Million Btu per barrel'),
('PAACP','All petroleum products consumed by the transportation sector','Thousand barrels'),
('PAACV','All petroleum products total expenditures in the transportation sector','Million dollars'),
('PACCB','All petroleum products consumed by the commercial sector','Billion Btu'),
('PACCD','All petroleum products average price in the commercial sector','Dollars per million Btu'),
('PACCK','Factor for converting all petroleum products consumed by the commercial sector from physical units to Btu United States only','Million Btu per barrel'),
('PACCP','All petroleum products consumed by the commercial sector','Thousand barrels'),
('PACCV','All petroleum products total expenditures in the commercial sector','Million dollars'),
('PAEIB','All petroleum products consumed by the electric power sector','Billion Btu'),
('PAEID','All petroleum products average price in the electric power sector','Dollars per million Btu'),
('PAEIK','Factor for converting all petroleum products consumed by the electric power sector from physical units to Btu United States only','Million Btu per barrel'),
('PAEIP','All petroleum products consumed by the electric power sector','Thousand barrels'),
('PAEIV','All petroleum products total expenditures in the electric power sector','Million dollars'),
('PAICB','All petroleum products consumed by the industrial sector','Billion Btu'),
('PAICD','All petroleum products average price in the industrial sector','Dollars per million Btu'),
('PAICK','Factor for converting all petroleum products consumed by the industrial sector from physical units to Btu United States only','Million Btu per barrel'),
('PAICP','All petroleum products consumed by the industrial sector','Thousand barrels'),
('PAICV','All petroleum products total expenditures in the industrial sector','Million dollars'),
('PAISB','All petroleum products consumed by the industrial sector excluding process fuel and intermediate products','Billion Btu'),
('PAPRB','Crude oil production (including lease condensate)','Billion Btu'),
('PAPRP','Crude oil production (including lease condensate)','Thousand barrels'),
('PARCB','All petroleum products consumed by the residential sector','Billion Btu'),
('PARCD','All petroleum products average price in the residential sector','Dollars per million Btu'),
('PARCK','Factor for converting all petroleum products consumed by the residential sector from physical units to Btu United States only','Million Btu per barrel'),
('PARCP','All petroleum products consumed by the residential sector','Thousand barrels'),
('PARCV','All petroleum products total expenditures in the residential sector','Million dollars'),
('PASCB','All petroleum products total consumption adjusted for process fuel and intermediate products','Billion Btu'),
('PATCB','All petroleum products total consumption','Billion Btu'),
('PATCD','All petroleum products average price all sectors','Dollars per million Btu'),
('PATCK','Factor for converting all petroleum products total consumption from physical units to Btu United States only','Million Btu per barrel'),
('PATCP','All petroleum products total consumption','Thousand barrels'),
('PATCV','All petroleum products total expenditures','Million dollars'),
('PATXB','All petroleum products total end-use consumption','Billion Btu'),
('PATXD','All petroleum products average price all end-use sectors','Dollars per million Btu'),
('PATXP','All petroleum products total end-use consumption','Thousand barrels'),
('PATXV','All petroleum products total end-use expenditures','Million dollars'),
('PCCCB','Petroleum coke consumed by the commercial sector','Billion Btu'),
('PCCCD','Petroleum coke price in the commercial sector','Dollars per million Btu'),
('PCCCP','Petroleum coke consumed by the commercial sector','Thousand barrels'),
('PCCCV','Petroleum coke expenditures in the commercial sector','Million dollars'),
('PCCTK','Factor converting petroleum coke catalyst coke physical units to Btu United States only','Million Btu per barrel'),
('PCEIB','Petroleum coke consumed by the electric power sector','Billion Btu'),
('PCEID','Petroleum coke price in the electric power sector','Dollars per million Btu'),
('PCEIP','Petroleum coke consumed by the electric power sector','Thousand barrels'),
('PCEIV','Petroleum coke expenditures in the electric power sector','Million dollars'),
('PCICB','Petroleum coke consumed by the industrial sector','Billion Btu'),
('PCICD','Petroleum coke price in the industrial sector','Dollars per million Btu'),
('PCICP','Petroleum coke consumed by the industrial sector','Thousand barrels'),
('PCICV','Petroleum coke expenditures in the industrial sector','Million dollars'),
('PCISB','Petroleum coke consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('PCMKK','Factor converting petroleum coke marketable coke physical units to Btu United States only','Million Btu per barrel'),
('PCRFB','Petroleum coke consumed as refinery fuel','Billion Btu'),
('PCSCB','Petroleum coke total consumption adjusted for process fuel','Billion Btu'),
('PCTCB','Petroleum coke total consumption','Billion Btu'),
('PCTCD','Petroleum coke average price all sectors','Dollars per million Btu'),
('PCTCP','Petroleum coke total consumption','Thousand barrels'),
('PCTCV','Petroleum coke total expenditures','Million dollars'),
('PCTXB','Petroleum coke total end-use consumption','Billion Btu'),
('PCTXD','Petroleum coke average price all end-use sectors','Dollars per million Btu'),
('PCTXP','Petroleum coke total end-use consumption','Thousand barrels'),
('PCTXV','Petroleum coke total end-use expenditures','Million dollars'),
('PEACD','Primary energy average price in the transportation sector','Dollars per million Btu'),
('PEACV','Primary energy total expenditures in the transportation sector','Million dollars'),
('PEASB','Primary energy consumed by the transportation sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('PECCD','Primary energy average price in the commercial sector','Dollars per million Btu'),
('PECCV','Primary energy total expenditures in the commercial sector','Million dollars'),
('PECSB','Primary energy consumed by the commercial sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('PEEID','Primary energy average price in the electric power sector','Dollars per million Btu'),
('PEEIV','Primary energy total expenditures in the electric power sector','Million dollars'),
('PEICD','Primary energy average price in the industrial sector','Dollars per million Btu'),
('PEICV','Primary energy total expenditures in the industrial sector','Million dollars'),
('PEISB','Primary energy consumed by the industrial sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('PERCD','Primary energy average price in the residential sector','Dollars per million Btu'),
('PERCV','Primary energy total expenditures in the residential sector','Million dollars'),
('PERSB','Primary energy consumed by the residential sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('PESCB','Primary energy total consumption adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('PETCD','Primary energy average price all sectors','Dollars per million Btu'),
('PETCV','Primary energy total expenditures','Million dollars'),
('PETXD','Primary energy average price all end-use sectors','Dollars per million Btu'),
('PETXV','Primary energy total end-use expenditures','Million dollars'),
('PLICB','Plant condensate consumed by the industrial sector','Billion Btu'),
('PLICP','Plant condensate consumed by the industrial sector','Thousand barrels'),
('PMTCB','All petroleum products total consumption excluding fuel ethanol','Billion Btu'),
('PPICB','Natural gasoline (pentanes plus) consumed by the industrial sector','Billion Btu'),
('PPICP','Natural gasoline (pentanes plus) consumed by the industrial sector','Thousand barrels'),
('PPTCB','Natural gasoline (pentanes plus) total consumption','Billion Btu'),
('PPTCP','Natural gasoline (pentanes plus) total consumption','Thousand barrels'),
('PQACB','Propane consumed by the transportation sector','Billion Btu'),
('PQACD','Propane price in the transportation sector','Dollars per million Btu'),
('PQACP','Propane consumed by the transportation sector','Thousand barrels'),
('PQACV','Propane expenditures in the transportation sector','Million dollars'),
('PQCCB','Propane consumed by the commercial sector','Billion Btu'),
('PQCCD','Propane price in the commercial sector','Dollars per million Btu'),
('PQCCP','Propane consumed by the commercial sector','Thousand barrels'),
('PQCCV','Propane expenditures in the commercial sector','Million dollars'),
('PQICB','Propane consumed by the industrial sector','Billion Btu'),
('PQICD','Propane price in the industrial sector','Dollars per million Btu'),
('PQICP','Propane consumed by the industrial sector','Thousand barrels'),
('PQICV','Propane expenditures in the industrial sector','Million dollars'),
('PQISB','Propane consumed in the industrial sector excluding refinery fuel','Billion Btu'),
('PQRCB','Propane consumed by the residential sector','Billion Btu'),
('PQRCD','Propane price in the residential sector','Dollars per million Btu'),
('PQRCP','Propane consumed by the residential sector','Thousand barrels'),
('PQRCV','Propane expenditures in the residential sector','Million dollars'),
('PQRFB','Propane consumed as refinery fuel','Billion Btu'),
('PQSCB','Propane total consumption adjusted for process fuel','Billion Btu'),
('PQTCB','Propane total consumption','Billion Btu'),
('PQTCD','Propane average price all sectors','Dollars per million Btu'),
('PQTCP','Propane total consumption','Thousand barrels'),
('PQTCV','Propane total expenditures','Million dollars'),
('PQTXB','Propane total end-use consumption','Billion Btu'),
('PQTXD','Propane average price all end-use sectors','Dollars per million Btu'),
('PQTXP','Propane total end-use consumption','Thousand barrels'),
('PQTXV','Propane total end-use expenditures','Million dollars'),
('PYICB','Propylene from refineries consumed by the industrial sector','Billion Btu'),
('PYICP','Propylene from refineries consumed by the industrial sector','Thousand barrels'),
('PYTCB','Propylene from refineries total consumption','Billion Btu'),
('PYTCP','Propylene from refineries total consumption','Thousand barrels'),
('REPRB','Renewable energy production','Billion Btu'),
('RETCB','Renewable energy total consumption','Billion Btu'),
('RFACB','Residual fuel oil consumed by the transportation sector','Billion Btu'),
('RFACD','Residual fuel oil price in the transportation sector','Dollars per million Btu'),
('RFACP','Residual fuel oil consumed by the transportation sector','Thousand barrels'),
('RFACV','Residual fuel oil expenditures in the transportation sector','Million dollars'),
('RFCCB','Residual fuel oil consumed by the commercial sector','Billion Btu'),
('RFCCD','Residual fuel oil price in the commercial sector','Dollars per million Btu'),
('RFCCP','Residual fuel oil consumed by the commercial sector','Thousand barrels'),
('RFCCV','Residual fuel oil expenditures in the commercial sector','Million dollars'),
('RFEIB','Residual fuel oil consumed by the electric power sector','Billion Btu'),
('RFEID','Residual fuel oil price in the electric power sector','Dollars per million Btu'),
('RFEIP','Residual fuel oil consumed by the electric power sector','Thousand barrels'),
('RFEIV','Residual fuel oil expenditures in the electric power sector','Million dollars'),
('RFICB','Residual fuel oil consumed by the industrial sector','Billion Btu'),
('RFICD','Residual fuel oil price in the industrial sector','Dollars per million Btu'),
('RFICP','Residual fuel oil consumed by the industrial sector','Thousand barrels'),
('RFICV','Residual fuel oil expenditures in the industrial sector','Million dollars'),
('RFISB','Residual fuel oil consumed by the industrial sector excluding refinery fuel','Billion Btu'),
('RFRFB','Residual fuel oil consumed as refinery fuel','Billion Btu'),
('RFSCB','Residential fuel oil total consumption excluding process fuel','Billion Btu'),
('RFTCB','Residual fuel oil total consumption','Billion Btu'),
('RFTCD','Residual fuel oil average price all sectors','Dollars per million Btu'),
('RFTCP','Residual fuel oil total consumption','Thousand barrels'),
('RFTCV','Residual fuel oil total expenditures','Million dollars'),
('RFTXB','Residual fuel oil total end-use consumption','Billion Btu'),
('RFTXD','Residual fuel oil average price all end-use sectors','Dollars per million Btu'),
('RFTXP','Residual fuel oil total end-use consumption','Thousand barrels'),
('RFTXV','Residual fuel oil total end-use expenditures','Million dollars'),
('ROPRB','Renewable energy production other than fuel ethanol','Billion Btu'),
('SFCCB','Supplemental gaseous fuels consumed by the commercial sector','Billion Btu'),
('SFEIB','Supplemental gaseous fuels consumed by the electric power sector','Billion Btu'),
('SFINB','Supplemental gaseous fuels consumed by the industrial sector','Billion Btu'),
('SFRCB','Supplemental gaseous fuels consumed by the residential sector','Billion Btu'),
('SFTCB','Supplemental gaseous fuels total consumption','Billion Btu'),
('SGICB','Still gas consumed by the industrial sector','Billion Btu'),
('SGICP','Still gas consumed by the industrial sector','Thousand barrels'),
('SNICB','Special naphthas consumed by the industrial sector','Billion Btu'),
('SNICD','Special naphthas price in the industrial sector','Dollars per million Btu'),
('SNICP','Special naphthas consumed by the industrial sector','Thousand barrels'),
('SNICV','Special naphthas expenditures in the industrial sector','Million dollars'),
('SOCCB','Solar energy consumed by the commercial sector','Billion Btu'),
('SOCCP','Solar thermal and photovoltaic electricity net generation in the commercial sector','Million kilowatthours'),
('SOEGB','Solar energy consumed for electricity generation by the electric power sector','Billion Btu'),
('SOEGP','Solar thermal and photovoltaic electricity net generation in the electric power sector','Million kilowatthours'),
('SOICB','Solar energy consumed by the industrial sector','Billion Btu'),
('SOICP','Solar thermal and photovoltaic electricity net generation in the industrial sector','Million kilowatthours'),
('SOR7P','Solar photovoltaic electricity generation by small-scale applications in the residential sector','Million kilowatthours'),
('SORCB','Solar energy consumed by the residential sector','Billion Btu'),
('SOTCB','Solar energy total consumption','Billion Btu'),
('SOTGP','Solar thermal and photovoltaic electricity total net generation','Million kilowatthours'),
('SOTXB','Solar energy total end-use consumption','Billion Btu'),
('TEACB','Total energy consumed by the transportation sector','Billion Btu'),
('TEACD','Total energy average price in the transportation sector','Dollars per million Btu'),
('TEACV','Total energy expenditures in the transportation sector','Million dollars'),
('TEAPB','Total energy consumption per capita in the transportation sector','Million Btu'),
('TECCB','Total energy consumed by the commercial sector','Billion Btu'),
('TECCD','Total energy average price in the commercial sector','Dollars per million Btu'),
('TECCV','Total energy expenditures in the commercial sector','Million dollars'),
('TECPB','Total energy consumption per capita in the commercial sector','Million Btu'),
('TEEIB','Total energy consumed by the electric power sector','Billion Btu'),
('TEGDS','Energy expenditures as percent of current-dollar GDP','Percent'),
('TEICB','Total energy consumed by the industrial sector','Billion Btu'),
('TEICD','Total energy average price in the industrial sector','Dollars per million Btu'),
('TEICV','Total energy expenditures in the industrial sector','Million dollars'),
('TEIPB','Total energy consumption per capita in the industrial sector','Million Btu'),
('TEPFB','Total energy used as process fuel and other consumption that has no direct fuel costs','Billion Btu'),
('TEPRB','Total energy production','Billion Btu'),
('TERCB','Total energy consumed by the residential sector','Billion Btu'),
('TERCD','Total energy average price in the residential sector','Dollars per million Btu'),
('TERCV','Total energy total expenditures in the residential sector','Million dollars'),
('TERFB','Total energy used as refinery fuel and intermediate products','Billion Btu'),
('TERPB','Total energy consumption per capita in the residential sector','Million Btu'),
('TETCB','Total energy consumption','Billion Btu'),
('TETCD','Total energy average price','Dollars per million Btu'),
('TETCV','Total energy expenditures','Million dollars'),
('TETGR','Total energy consumed per dollar of real gross domestic product','Thousand Btu per chained (2009) dollar'),
('TETPB','Total energy consumption per capita','Million Btu'),
('TETPV','Total energy expenditures per capita','Dollars'),
('TETXB','Total end-use energy consumption','Billion Btu'),
('TETXD','Total end-use energy average price','Dollars per million Btu'),
('TETXV','Total end-use energy expenditures','Million dollars'),
('TNACB','Total energy consumed by the transportation sector excluding the sectors share of electrical system energy losses','Billion Btu'),
('TNASB','Total net energy consumed by the transportation sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('TNCCB','Total energy consumed by the commercial sector excluding the sectors share of electrical system energy losses','Billion Btu'),
('TNCSB','Total net energy consumed by the commercial sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('TNICB','Total energy consumed by the industrial sector excluding the sectors share of electrical system energy losses','Billion Btu'),
('TNISB','Total net energy consumed by the industrial sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('TNRCB','Total energy consumed by the residential sector excluding the sectors share of electrical system energy losses','Billion Btu'),
('TNRSB','Total net energy consumed by the residential sector adjusted for process fuel intermediate products and fuels with no direct cost','Billion Btu'),
('TNSCB','Total primary energy and electricity consumed','Billion Btu'),
('TNTXB','Total primary energy and electricity consumed by the end-use sectors','Billion Btu'),
('TPOPP','Resident population including Armed Forces','Thousand'),
('UOICB','Unfinished oils consumed by the industrial sector','Billion Btu'),
('UOICP','Unfinished oils consumed by the industrial sector','Thousand barrels'),
('USICB','Unfractionated streams consumed by the industrial sector','Billion Btu'),
('USICP','Unfractionated streams consumed by the industrial sector','Thousand barrels'),
('WDCCB','Wood consumed by the commercial sector','Billion Btu'),
('WDEIB','Wood consumed by the electric power sector','Billion Btu'),
('WDEXB','Densified biomass exports','Billion Btu'),
('WDICB','Wood consumed by the industrial sector','Billion Btu'),
('WDPRB','Wood energy production','Billion Btu'),
('WDRCB','Wood consumed by the residential sector','Billion Btu'),
('WDRCD','Wood price in the residential sector','Dollars per million Btu'),
('WDRCP','Wood consumed by the residential sector','Thousand cords'),
('WDRCV','Wood expenditures in the residential sector ','Million dollars'),
('WDRSB','Wood consumed in the residential sector at a cost','Billion Btu'),
('WDRXB','Wood consumed in the residential sector at no cost','Billion Btu'),
('WDTCB','Wood total consumption','Billion Btu'),
('WSCCB','Waste consumed by the commercial sector total','Billion Btu'),
('WSEIB','Waste consumed by the electric power sector','Billion Btu'),
('WSICB','Waste energy consumed by the industrial sector total','Billion Btu'),
('WSTCB','Waste total consumption','Billion Btu'),
('WWCCB','Wood and waste consumed in the commercial sector','Billion Btu'),
('WWCCD','Wood and waste price in the commercial sector','Dollars per million Btu'),
('WWCCV','Wood and waste expenditures in the commercial sector','Million dollars'),
('WWCSB','Wood and waste consumed in the commercial sector at a cost','Billion Btu'),
('WWCXB','Wood and waste consumed in the commercial sector at no cost','Billion Btu'),
('WWEIB','Wood and waste consumed by the electric power sector','Billion Btu'),
('WWEID','Wood and waste price in the electric power sector','Dollars per million Btu'),
('WWEIV','Wood and waste expenditures in the electric power sector','Million dollars'),
('WWICB','Wood and waste consumed in the industrial sector total','Billion Btu'),
('WWICD','Wood and waste price in the industrial sector','Dollars per million Btu'),
('WWICV','Wood and waste expenditures in the industrial sector','Million dollars'),
('WWISB','Wood and waste consumed in the industrial sector at a cost','Billion Btu'),
('WWIXB','Wood and waste consumed in the industrial sector at no cost','Billion Btu'),
('WWSCB','Wood and waste total consumption adjusted for fuels with no direct cost','Billion Btu'),
('WWTCB','Wood and waste total consumption','Billion Btu'),
('WWTCD','Wood and waste average price all sectors','Dollars per million Btu'),
('WWTCV','Wood and waste total expenditures','Million dollars'),
('WWTXB','Wood and waste total end-use consumption','Billion Btu'),
('WWTXD','Wood and waste average price all end-use sectors','Dollars per million Btu'),
('WWTXV','Wood and waste total end-use expenditures','Million dollars'),
('WXICB','Waxes consumed by the industrial sector','Billion Btu'),
('WXICD','Waxes price in the industrial sector','Dollars per million Btu'),
('WXICP','Waxes consumed by the industrial sector','Thousand barrels'),
('WXICV','Waxes expenditures in the industrial sector','Million dollars'),
('WYCCB','Wind energy consumed by the commercial sector','Billion Btu'),
('WYCCP','Wind electricity net generation in the commercial sector','Million kilowatthours'),
('WYEGB','Wind energy consumed for electricity generation by the electric power sector','Billion Btu'),
('WYEGP','Wind electricity net generation in the electric power sector','Million kilowatthours'),
('WYICB','Wind energy consumed by the industrial sector','Billion Btu'),
('WYICP','Wind electricity net generation in the industrial sector','Million kilowatthours'),
('WYTCB','Wind energy total consumption','Billion Btu'),
('WYTCP','Wind electricity total net generation','Million kilowatthours'),
('WYTXB','Wind energy total end-use consumption','Billion Btu'),
('WYTXP','Wind energy total end-use net generation','Million kilowatthours');<file_sep>import React, {Component} from 'react';
//import PropTypes from 'prop-types';
import * as d3 from "d3";
//import {withStyles} from '@material-ui/styles';
var crime = require('./data/CrimeStatebyState.js').default;
//var gas = require('./data/gas_data_filtered.js').default;
//var states = require('./data/states.js').default;
var states_reversed = require('./data/states_reversed.js').default;
var abortions = require('./data/abortions.js').default;
var abortions1960 = require('./data/abortions1960.js').default;
class LineChartAbortion extends Component {
constructor(props) {
super(props);
};
componentDidMount() {/*update the graph after the component mounts (and the svg is created)*/
this.update();
}
hideStates = (state) => {
this.svg.selectAll("path").filter(function (d) {
return !d3.select(this).attr("class").includes(state) && !d3.select(this).attr("class").includes("t-dot");
}).style("opacity", 0.1);
};
showStates = () => {
this.svg.selectAll("path").style("opacity", 0.9);
};
moveBack = () => {
if (this.dc) {
this.svg.selectAll("*").remove();
this.update();
return;
}
this.dc = true;
console.log("here");
this.xScale.domain([1960, 1984]);
this.xAxis.transition().duration(500).call(d3.axisBottom(this.xScale).tickFormat(d3.format("d")));
this.svg.selectAll(".endab").remove();
this.svg.selectAll(".legab").attr("x1", this.xScale(1973))
.attr("x2", this.xScale(1973));
this.svg.selectAll(".abor").attr("transform", "translate(550,-180) rotate(90)");
this.svg.selectAll(".a-dot").remove();
this.line_1960.remove();
var lineMoved = d3.line()
.x((d, i) => {
return this.xScale(d["Year"] - 20);
}) // set the x values for the line generator
.y((d) => {
return this.yScale(d[this.CRIME_HYP]);
}) // set the y values for the line generator
// .curve(d3.curveMonotoneX) // apply smoothing to the line
// this.crimeFilteredTwice = crime.map(a => {
// let newObject = {};
// Object.keys(a).forEach(propertyKey => {
// newObject[propertyKey] = a[propertyKey];
// });
// return newObject;
// });
this.crimeFilteredTwice.forEach(function (s) {
//console.log(s);
var unknownKey = Object.keys(s)[0];
s[unknownKey] = s[unknownKey].filter(function (el) {
return el.Year > 1979;
})
});
this.svg.selectAll(".c-dot")
.data(this.crimeFilteredTwice)
.transition()
.duration(500)
.style("fill", "none")
.attr("class", function(d){
return "c-dot" + " " + states_reversed[Object.keys(d)[0]];
})
.attr("d", (d) => {
var unknownKey = Object.keys(d)[0];
return lineMoved(d[unknownKey]);
});
this.svg.selectAll(".c-dot")
.data(this.crimeFiltered)
.exit()
.remove();
}
update = (sel_crime = 'Violent Crime rate') => {
this.CRIME_HYP = sel_crime;
this.dc = false;
//console.log(d3);
var data = d3.csvParse(abortions);
var data1960 = d3.csvParse(abortions1960);
//console.log(data1960);
this.grouped = d3.nest()
.key(function (d) {
return d.state_id;
})
.entries(data);
//console.log(this.grouped);
this.crimeFiltered = [];
this.crimeFiltered = crime;
var margin = {top: 50, right: 60, bottom: 50, left: 60}
, width = 1100 - margin.left - margin.right // Use the window's width
, height = 600 - margin.top - margin.bottom; // Use the window's height
this.crimeFilteredTwice = crime.map(a => {
let newObject = {};
Object.keys(a).forEach(propertyKey => {
newObject[propertyKey] = a[propertyKey];
});
return newObject;
});
this.crimeFilteredTwice.forEach(function (s) {
//console.log(s);
var unknownKey = Object.keys(s)[0];
s[unknownKey] = s[unknownKey].filter(function (el) {
return el.Year < 2005;
})
});
this.xScale = d3.scaleLinear()
.range([0, width]); // output
this.yScale = d3.scaleLinear()
.range([height, 0]); // output
this.yScale1 = d3.scaleLinear().range([height, 0]);
this.xScale.domain([1960, 2004]);
let max = Number.NEGATIVE_INFINITY;
this.crimeFilteredTwice.forEach((s) => {
//console.log(s);
var unknownKey = Object.keys(s)[0];
s[unknownKey].forEach((d) => {
if (d[this.CRIME_HYP] > max) {
max = d[this.CRIME_HYP];
}
//console.log(d);
});
});
this.yScale.domain([0, max]);
this.yScale1.domain([0, 100]);
this.svg = d3.select(this.refs.linechart).on("dblclick", () => {
this.moveBack();
})
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
;
this.xAxis = this.svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(this.xScale).tickFormat(d3.format("d")));
this.yAxisCrime = this.svg.append("g")
.attr("class", "y axis")
.style("stroke", "red")
.call(d3.axisLeft(this.yScale)); // Create an axis component with d3.axisLeft
this.yAxisAb = this.svg.append("g")
.attr("class", "axisRed")
.style("stroke", "grey")
.attr("transform", "translate( " + width + ", 0 )")
.call(d3.axisRight(this.yScale1));
// Crime
this.line1 = d3.line()
.x((d, i) => {
return this.xScale(d["Year"]);
}) // set the x values for the line generator
.y((d) => {
return this.yScale(d[this.CRIME_HYP]);
}) // set the y values for the line generator
// .curve(d3.curveMonotoneX) // apply smoothing to the line
//console.log(this.crimeFiltered);
//this.crimeFilteredTwice = Object.assign(crime)
// this.grouped.forEach(function(s){
// console.log(s);
// s["values"] = s["values"].filter(function (el){
// return el.first_year < 2001;
// })
// });
//console.log(this.crimeFiltered);
this.crimeLines = this.svg.selectAll(".c-dot")
.data(this.crimeFilteredTwice)
.enter().append("path")
.filter(function (d) {
//console.log(d);
return true;
})
.style("fill", "none")
.attr("class", function (d) {
return "c-dot" + " " + states_reversed[Object.keys(d)[0]];
}).attr("d", (d) => {
var unknownKey = Object.keys(d)[0];
return this.line1(d[unknownKey]);
})
.style("stroke", function (d) {
return "red";
})
.style("stroke-width", 2.5)
.style("opacity", 0.6)
.on("mouseover", (d) => {
d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 8);
this.hideStates(states_reversed[Object.keys(d)[0]]);
this.svg.append("text").attr("class", "statename").attr("x", 10).attr("y", 5).text(Object.keys(d)[0]);
})
.on("mouseout", (d) => {
this.svg.selectAll(".statename").remove();
d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 2.5);
this.showStates();
});
// .on("mouseover", (d) => {
// this.svg.append("text").attr("class","statename").attr("x",10).attr("y",5).text(Object.keys(d)[0]);
// d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 8);
// this.hideStates(states_reversed[Object.keys(d)[0]]);
// })
// .on("mouseout", (d) => {
// this.svg.selectAll(".statename").remove();
// d3.selectAll("." + states_reversed[Object.keys(d)[0]]).style("stroke-width", 2.5);
// this.showStates();
// }).on("click", (d) => {
// this.updateScale(Object.keys(d)[0]);
// })
;
this.line = d3.line()
.x((d) => {
return this.xScale(d["first_year"]);
})
.y((d) => {
return this.yScale1(d["datum"]);
});
this.abLines = this.svg.selectAll(".a-dot")
.data(this.grouped)
.enter().append("path")
// .filter(function (d) {
// return d[58].value === "AK"
// })
.style("fill", "none")
.attr("class", function (d) {
return "a-dot " + d.values[0].state_id;
})
.attr("d", (d) => {
//console.log(d.values);
// var unknownKey = Object.keys(d)[0];
return this.line(d.values);
})
.style("stroke", function (d) {
//console.log(d.values);
if (d.values[0].state_id === "US") {
return "darkgray";
} else {
return "grey";
}
})
.style("opacity", 0.7)
.style("stroke-width", 2.5)
.on("mouseover", (d) => {
d3.selectAll("." + d.values[0].state_id).style("stroke-width", 8);
this.hideStates(d.values[0].state_id);
this.svg.append("text").attr("class", "statename").attr("x", 10).attr("y", 5).text(d.values[0].state_name);
})
.on("mouseout", (d) => {
this.svg.selectAll(".statename").remove();
d3.selectAll("." + d.values[0].state_id).style("stroke-width", 2.5);
this.showStates();
});
// .on("click", (d) => {
// this.updateScale(states[d[58].value]);
// })
// Axes
// text label for the x axis
this.svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top - 20) + ")")
.style("text-anchor", "middle")
.text("Date");
this.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("fill","red")
.text("Crime Rate (per 100,000 people)");
this.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", width + margin.right - 20)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("fill","grey")
.text("Abortion Rate (per 1000 women)");
this.line1960 = d3.line()
.x((d) => {
return this.xScale(d["year"]);
})
.y((d) => {
return this.yScale1(d["rate"]);
});
this.line_1960 = this.svg.append("path")
.datum(data1960)
.style("fill", "none")
.attr("class", function (d) {
return "t-dot";
})
.attr("d", (d) => {
//console.log(d);
//console.log(d.values);
// var unknownKey = Object.keys(d)[0];
return this.line1960(d);
})
.style("stroke", "darkgray")
.style("opacity", 0.7)
.style("stroke-width", 9);
this.svg.append("line")
.attr("x1", this.xScale(1995))
.attr("y1", height)
.attr("x2", this.xScale(1995))
.attr("y2", 0)
.attr("class", "endab")
.style("stroke-dasharray", ("8, 10"))
.style("stroke", "green")
.style("stroke-width", 3);
this.svg.append("line")
.attr("x1", this.xScale(1973))
.attr("y1", height)
.attr("x2", this.xScale(1973))
.attr("y2", 0)
.attr("class", "legab")
.style("stroke", "green")
.style("stroke-width", 3)
.style("stroke-dasharray", ("8, 10"))
.on("mouseover", () => {
})
.on("mouseout", () => {
//this.svg.selectAll(".abor").remove();
});
// this.svg.append("rect")
// .attr("x",this.xScale(1973))
// .attr("y",0)
// .attr("width",this.xScale(1995)-this.xScale(1973))
// .attr("height",height)
// .style("fill","green")
// .style("opacity","0.1");
this.svg.append("text").attr("class", "abor").attr("transform", "translate(" + this.xScale(1973.3) + ",-150)" + "rotate(90)").attr("x", this.xScale(1973)).attr("y", 0).text("Abortion Legalized").style("width", "20px").style("text-anchor", "end");
this.svg.append("text").attr("class", "endab").attr("transform", "translate(" + this.xScale(1995.3) + ",-700)" + "rotate(90)").attr("x", this.xScale(1995)).attr("y", 0).text("Crime Decrease").style("width", "20px").style("text-anchor", "end");
var crimeMenu = d3.select("#dropdown");
var options = ["Violent Crime rate", "Motor vehicle theft rate", "Larceny-theft rate", "Burglary rate", "Property crime rate", "Aggravated assault rate", "Robbery rate"];
d3.selectAll("select").remove();
crimeMenu
.append("select")
.selectAll("option")
.data(options)
.enter()
.append("option")
.attr("value", function (d) {
console.log(d);
return d;
})
.text(function (d) {
return d;
})
.property("selected", (d) => {
return d === this.CRIME_HYP;
});
var _this = this;
crimeMenu.on('change', function () {
var selectedCrime = d3.select(this)
.select("select")
.property("value");
console.log(selectedCrime);
_this.svg.selectAll("*").remove();
_this.update(selectedCrime);
});
};
render() {
return (
<div ref={((mount) => {
if (mount && (this.mount === undefined)) {
this.mount = mount;
this.setState({})
}
this.mount = mount;
})} style={{width: "100%", height: "600px"}}>
<div id="dropdown"></div>
<svg ref="linechart"
height={"600px"}
width={"1100px"}/>
</div>
);
}
}
export default LineChartAbortion;<file_sep>self.__precacheManifest = [
{
"revision": "d88043b94138f05545f0",
"url": "/crime-over-time/static/js/runtime~main.d88043b9.js"
},
{
"revision": "7dabbc6c58c25160a909",
"url": "/crime-over-time/static/js/main.7dabbc6c.chunk.js"
},
{
"revision": "878ac71c55db00d65041",
"url": "/crime-over-time/static/js/2.878ac71c.chunk.js"
},
{
"revision": "7dabbc6c58c25160a909",
"url": "/crime-over-time/static/css/main.3050c53e.chunk.css"
},
{
"revision": "6aba8b5099551a5f60e7c7321727bd3a",
"url": "/crime-over-time/index.html"
}
]; | 2656dc490bd91821e7ea53fa5967ff4c9d462183 | [
"Markdown",
"SQL",
"JavaScript"
] | 6 | Markdown | qwertey6/crime-over-time | 3a426c5d6bc62751505e1ce4b1a3cecb9a2e6e09 | 62dfe668a6039e3a2a7c164c96f33a8d3d431939 |
refs/heads/master | <file_sep>/* Drop Tables */
DROP TABLE IF EXISTS account CASCADE;
DROP TABLE IF EXISTS client CASCADE;
DROP TABLE IF EXISTS credit_card CASCADE;
DROP TABLE IF EXISTS disposition CASCADE;
DROP TABLE IF EXISTS district CASCADE;
DROP TABLE IF EXISTS loan CASCADE;
DROP TABLE IF EXISTS permanent_order CASCADE;
DROP TABLE IF EXISTS transaction CASCADE;
/* Create Tables */
CREATE TABLE account(
account_id integer NOT NULL,
district_id integer NULL,
frequency varchar(20) NULL,
date date NULL
)
;
CREATE TABLE client(
client_id integer NOT NULL,
district_id integer NULL,
birth_number varchar(6) NULL
);
CREATE TABLE credit_card(
card_id integer NOT NULL,
disp_id integer NULL,
type varchar(20) NULL,
issued date NULL
);
CREATE TABLE disposition(
disp_id integer NOT NULL,
client_id integer NULL,
account_id integer NULL,
type varchar(20) NULL
);
CREATE TABLE district(
district_id integer NOT NULL,
district_name varchar(20) NULL,
region varchar(20) NULL,
inhabitants integer NULL,
municipalities1 integer NULL,
municipalities2 integer NULL,
municipalities3 integer NULL,
municipalities4 integer NULL,
cities integer NULL,
ratio_of_urban double precision NULL,
salary integer NULL,
unemployment95 varchar(10) NULL,
unemployment96 varchar(10) NULL,
enterpreneurs integer NULL,
crimes95 varchar(10) NULL,
crimes96 integer NULL
);
CREATE TABLE loan(
loan_id integer NOT NULL,
account_id integer NULL,
date date NULL,
amount integer NULL,
duration integer NULL,
payments double precision NULL,
status char(1) NULL
);
CREATE TABLE permanent_order(
order_id integer NOT NULL,
account_id integer NULL,
bank_to varchar(2) NULL,
account_to varchar(50) NULL,
amount double precision NULL,
k_symbol varchar(20) NULL
);
CREATE TABLE transaction(
trans_id integer NOT NULL,
account_id integer NULL,
date date NULL,
type varchar(20) NULL,
operation varchar(20) NULL,
amount double precision NULL,
balance double precision NULL,
k_symbol varchar(20) NULL,
bank varchar(2) NULL,
account varchar(50) NULL
);
<file_sep>/* ---------------------------------------------------- */
/* Generated by Enterprise Architect Version 14.1 */
/* Created On : 14-kvý-2020 16:28:17 */
/* DBMS : PostgreSQL */
/* ---------------------------------------------------- */
/* Drop Tables */
DROP TABLE IF EXISTS "Account_Dimension" CASCADE
;
DROP TABLE IF EXISTS "Client_Dimension" CASCADE
;
DROP TABLE IF EXISTS "Credit_Card_Dimension" CASCADE
;
DROP TABLE IF EXISTS "Datamart_Facts" CASCADE
;
DROP TABLE IF EXISTS "District_Dimension" CASCADE
;
DROP TABLE IF EXISTS "Permanent_Order_Dimension" CASCADE
;
DROP TABLE IF EXISTS "Transaction_Dimension" CASCADE
;
/* Create Tables */
CREATE TABLE "Account_Dimension"
(
account_pk bigint NOT NULL,
frequency varchar(20) NULL,
date date NULL,
district_id bigint NULL
)
;
CREATE TABLE "Client_Dimension"
(
client_pk bigint NOT NULL,
birth_number varchar(6) NULL,
district_id bigint NULL
)
;
CREATE TABLE "Credit_Card_Dimension"
(
card_pk bigint NOT NULL,
type varchar(20) NULL,
issued date NULL
)
;
CREATE TABLE "Datamart_Facts"
(
fact_pk bigint NOT NULL,
account_fk bigint NULL,
client_fk bigint NULL,
card_fk bigint NULL,
order_fk bigint NULL,
trans_fk bigint NULL,
district_fk bigint NULL,
total_amount bigint NULL,
total_paid_finished integer NULL,
total_unpaid_finished integer NULL,
total_paid_unfinished integer NULL,
total_unpaid_unfinished integer NULL
)
;
CREATE TABLE "District_Dimension"
(
district_pk bigint NOT NULL,
district_name varchar(20) NULL,
region varchar(20) NULL,
inhabitants integer NULL,
municipalities1 integer NULL,
municipalities2 integer NULL,
municipalities3 integer NULL,
municipalities4 integer NULL,
cities integer NULL,
ratio_of_urban double precision NULL,
salary integer NULL,
unemployment95 double precision NULL,
unemployment96 double precision NULL,
enterpreneurs integer NULL,
crimes95 integer NULL,
crimes96 integer NULL
)
;
CREATE TABLE "Permanent_Order_Dimension"
(
order_pk bigint NOT NULL,
bank_to varchar(2) NULL,
account_to varchar(50) NULL,
amount double precision NULL,
k_symbol varchar(20) NULL
)
;
CREATE TABLE "Transaction_Dimension"
(
trans_pk bigint NOT NULL,
date date NULL,
type varchar(20) NULL,
operation varchar(20) NULL,
amount double precision NULL,
balance double precision NULL,
k_symbol varchar(20) NULL,
bank varchar(2) NULL,
account varchar(50) NULL
)
;
/* Create Primary Keys, Indexes, Uniques, Checks */
ALTER TABLE "Account_Dimension" ADD CONSTRAINT "PK_Account_Dimension"
PRIMARY KEY (account_pk)
;
ALTER TABLE "Client_Dimension" ADD CONSTRAINT "PK_Client_Dimension"
PRIMARY KEY (client_pk)
;
ALTER TABLE "Credit_Card_Dimension" ADD CONSTRAINT "PK_Credit_Card_Dimension"
PRIMARY KEY (card_pk)
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT "PK_Datamart_Facts"
PRIMARY KEY (fact_pk)
;
CREATE INDEX "IXFK_Datamart_Facts_Account_Dimension" ON "Datamart_Facts" (account_fk ASC)
;
CREATE INDEX "IXFK_Datamart_Facts_Client_Dimension" ON "Datamart_Facts" (client_fk ASC)
;
CREATE INDEX "IXFK_Datamart_Facts_Credit_Card_Dimension" ON "Datamart_Facts" (card_fk ASC)
;
CREATE INDEX "IXFK_Datamart_Facts_District_Dimension" ON "Datamart_Facts" (district_fk ASC)
;
CREATE INDEX "IXFK_Datamart_Facts_Permanent_Order_Dimension" ON "Datamart_Facts" (order_fk ASC)
;
CREATE INDEX "IXFK_Datamart_Facts_Transaction_Dimension" ON "Datamart_Facts" (trans_fk ASC)
;
ALTER TABLE "District_Dimension" ADD CONSTRAINT "PK_District_Dimension"
PRIMARY KEY (district_pk)
;
ALTER TABLE "Permanent_Order_Dimension" ADD CONSTRAINT "PK_Permanent_Order_Dimension"
PRIMARY KEY (order_pk)
;
ALTER TABLE "Transaction_Dimension" ADD CONSTRAINT "PK_Transaction_Dimension"
PRIMARY KEY (trans_pk)
;
/* Create Foreign Key Constraints */
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT account_fk
FOREIGN KEY (account_fk) REFERENCES "Account_Dimension" (account_pk) ON DELETE No Action ON UPDATE No Action
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT card_fk
FOREIGN KEY (card_fk) REFERENCES "Credit_Card_Dimension" (card_pk) ON DELETE No Action ON UPDATE No Action
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT client_fk
FOREIGN KEY (client_fk) REFERENCES "Client_Dimension" (client_pk) ON DELETE No Action ON UPDATE No Action
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT district_fk
FOREIGN KEY (district_fk) REFERENCES "District_Dimension" (district_pk) ON DELETE No Action ON UPDATE No Action
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT order_fk
FOREIGN KEY (order_fk) REFERENCES "Permanent_Order_Dimension" (order_pk) ON DELETE No Action ON UPDATE No Action
;
ALTER TABLE "Datamart_Facts" ADD CONSTRAINT transaction_fk
FOREIGN KEY (trans_fk) REFERENCES "Transaction_Dimension" (trans_pk) ON DELETE No Action ON UPDATE No Action
;
<file_sep>CREATE MATERIALIZED VIEW datamart.Datamart_Facts AS (
SELECT t_client.client_tk,
t_disposition.disp_k,
t_district.district_tk,
sum(t_loan.amount) AS total_amount,
count(
CASE
WHEN t_loan.status = 'A'::bpchar THEN t_loan.status
ELSE NULL::bpchar
END) AS total_paid_finished,
count(
CASE
WHEN t_loan.status = 'B'::bpchar THEN t_loan.status
ELSE NULL::bpchar
END) AS total_unpaid_finished,
count(
CASE
WHEN t_loan.status = 'C'::bpchar THEN t_loan.status
ELSE NULL::bpchar
END) AS total_paid_unfinished,
count(
CASE
WHEN t_loan.status = 'D'::bpchar THEN t_loan.status
ELSE NULL::bpchar
END) AS total_unpaid_unfinished
FROM t_loan
JOIN t_account ON t_account.account_tk = t_loan.account_id
JOIN t_disposition ON t_disposition.account_id = t_account.account_tk
JOIN t_client ON t_disposition.client_id = t_client.client_tk
JOIN t_district ON t_client.district_id = t_district.district_tk
GROUP BY t_loan.status, t_client.client_tk, t_disposition.disp_tk, t_district.district_tk
)
REFRESH MATERIALIZED VIEW datamart.Datamart_Facts<file_sep># Semestrální práce část 1 - Analýza dat, návrh entitního a DB modelu.
## Zadání
Výstup:
1) textový popis zdrojových dat - tzn. detailní popis jednotlivých atributů včetně datových typů, business názvů a business popisu dat
2) entitní model targetu
3) DB model stage a targetu v CASE nástroji
## Textový popis zdrojových dat
Textový popis se nachází v souboru EDWFinancialPopisDat.pdf
## Entitní model targetu
Entitní model targetu lze nalézt v souboru EntityTargetModel.bmp případně v /Ostatni/EntityModel.eapx
## Databázový model stage
Entitní model targetu lze nalézt v souboru DbStageModel.bmp případně v /Ostatni/StageModel.eapx
## Databázový model targetu
Entitní model targetu lze nalézt v souboru DbTargetModel.bmp případně v /Ostatni/LogicModel.eapx<file_sep># Semestrální práce část 2 - DLM, ETL.
## Zadání
Výstup:
1) datová logická mapa integrovaných dat - názvy atributů v source systému, názvy atributů v target DB, typ historizace apod.
2) upravené DDL s technickými sloupci a správnými klíči
3) ETL procesy pro stage i target (ukázka historizace všech typů) - jeden job, který bude spouštět ostatní transformace, které nahrávají jednotlivé tabulky (co transformace, to tabulka, transformace se nacházejí v transakci)
## Datová logická mapa (DLM)
Datová logická mapa se nachází v souboru DLM/DLM.xlsx
## DDL
DDL pro stage databázi se nachází v souboru DDL/StageDDL.sql
DDL s technickými sloupci a správnými klíči pro target databázi se nachází v souboru DDL/TargetDDL.sql
## ETL procesy
ETL procesy pro stage se nachází ve složce ETL/STAGE
ETL procesy pro target se nachází ve složce ETL/TARGET
Job, který spouští všechny transformace se nachází ce složce ETL/JOBS
Pro běh transformací jsou potřebné dvě proměnné prostředí $FINANCIAL_DATA a $ETL_DATA. V proměnné $FINANCIAL_DATA musí být uložena cesta k původně zadaným datasetům. V proměnné $ETL_DATA musí být uložena cesta k adresáři, ve kterém se nachází všechny transformace. Všechny transformace se musí nacházet v jednom adresáři.
## Ostatní
Ve složce FINANCIAL_DATA se nachází původní datasety potřebné pro ETL procesy pro stage. Ve složce MODELS se nachází upravený model pro stage i target. Oba modely jsou uloženy v .png formátu.
<file_sep>/* Drop Tables */
DROP TABLE IF EXISTS "t_account" CASCADE;
DROP TABLE IF EXISTS "t_client" CASCADE;
DROP TABLE IF EXISTS "t_credit_card" CASCADE;
DROP TABLE IF EXISTS "t_disposition" CASCADE;
DROP TABLE IF EXISTS "t_district" CASCADE;
DROP TABLE IF EXISTS "t_loan" CASCADE;
DROP TABLE IF EXISTS "t_permanent_order" CASCADE;
DROP TABLE IF EXISTS "t_transaction" CASCADE;
/* Sequences */
CREATE SEQUENCE seq_account
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_client
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_disposition
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_loan
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_district
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_credit_card
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_transaction
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
CREATE SEQUENCE seq_permanent_order
INCREMENT 1
MINVALUE 0
MAXVALUE 9000000000000000000
START 1
CACHE 1;
/* Create Tables */
CREATE TABLE "t_account"(
account_bk bigint NOT NULL,
frequency varchar(20) NULL,
date date NULL,
district_id bigint NULL,
account_tk bigint NOT NULL DEFAULT nextval('seq_account'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_client"(
client_bk bigint NOT NULL,
birth_number varchar(6) NULL,
district_id bigint NULL,
client_tk bigint NOT NULL DEFAULT nextval('seq_client'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_credit_card"(
card_bk bigint NOT NULL,
type varchar(20) NULL,
issued date NULL,
disp_id bigint NULL,
card_tk bigint NOT NULL DEFAULT nextval('seq_credit_card'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_disposition"
(
disp_bk bigint NOT NULL,
type varchar(20) NULL,
account_id bigint NULL,
client_id bigint NULL,
disp_tk bigint NOT NULL DEFAULT nextval('seq_disposition'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_district"(
district_bk bigint NOT NULL,
district_name varchar(20) NULL,
region varchar(20) NULL,
inhabitants integer NULL,
municipalities1 integer NULL,
municipalities2 integer NULL,
municipalities3 integer NULL,
municipalities4 integer NULL,
cities integer NULL,
ratio_of_urban double precision NULL,
salary integer NULL,
unemployment95 double precision NULL,
unemployment96 double precision NULL,
enterpreneurs integer NULL,
crimes95 integer NULL,
crimes96 integer NULL,
district_tk bigint NOT NULL DEFAULT nextval('seq_district'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_loan"(
loan_bk bigint NOT NULL,
date date NULL,
amount integer NULL,
duration integer NULL,
payments double precision NULL,
status char(1) NULL,
account_id bigint NULL,
loan_tk bigint NOT NULL DEFAULT nextval('seq_loan'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_permanent_order"(
order_bk bigint NOT NULL,
bank_to varchar(2) NULL,
account_to varchar(50) NULL,
amount double precision NULL,
k_symbol varchar(20) NULL,
account_id bigint NULL,
order_tk bigint NOT NULL DEFAULT nextval('seq_permanent_order'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
CREATE TABLE "t_transaction"(
trans_bk integer NOT NULL,
date date NULL,
type varchar(20) NULL,
operation varchar(20) NULL,
amount double precision NULL,
balance double precision NULL,
k_symbol varchar(20) NULL,
bank varchar(2) NULL,
account varchar(50) NULL,
account_id bigint NULL,
trans_tk bigint NOT NULL DEFAULT nextval('seq_transaction'::regclass),
version bigint,
date_from timestamp without time zone,
date_to timestamp without time zone,
last_update timestamp without time zone);
/* Create Primary Keys, Indexes, Uniques, Checks */
ALTER TABLE "t_account" ADD CONSTRAINT "PK_t_account" PRIMARY KEY (account_tk);
CREATE INDEX "IXFK_t_account_t_district" ON "t_account" (district_id ASC);
ALTER TABLE "t_client" ADD CONSTRAINT "PK_t_client" PRIMARY KEY (client_tk);
CREATE INDEX "IXFK_t_client_t_district" ON "t_client" (district_id ASC);
ALTER TABLE "t_credit_card" ADD CONSTRAINT "PK_t_credit_card" PRIMARY KEY (card_tk);
CREATE INDEX "IXFK_t_credit_card_t_disposition" ON "t_credit_card" (disp_id ASC);
ALTER TABLE "t_disposition" ADD CONSTRAINT "PK_t_disposition" PRIMARY KEY (disp_tk);
CREATE INDEX "IXFK_t_disposition_t_account" ON "t_disposition" (account_id ASC);
CREATE INDEX "IXFK_t_disposition_t_client" ON "t_disposition" (client_id ASC);
ALTER TABLE "t_district" ADD CONSTRAINT "PK_t_district" PRIMARY KEY (district_tk);
ALTER TABLE "t_loan" ADD CONSTRAINT "PK_t_loan" PRIMARY KEY (loan_tk);
CREATE INDEX "IXFK_t_loan_t_account" ON "t_loan" (account_id ASC);
ALTER TABLE "t_permanent_order" ADD CONSTRAINT "PK_t_permanent_order" PRIMARY KEY (order_tk);
CREATE INDEX "IXFK_t_permanent_order_t_account" ON "t_permanent_order" (account_id ASC);
ALTER TABLE "t_transaction" ADD CONSTRAINT "PK_t_transaction" PRIMARY KEY (trans_tk);
CREATE INDEX "IXFK_t_transaction_t_account" ON "t_transaction" (account_id ASC);
/* Create Foreign Key Constraints */
ALTER TABLE "t_account" ADD CONSTRAINT "FK_t_account_t_district" FOREIGN KEY (district_id) REFERENCES "t_district" (district_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_client" ADD CONSTRAINT "FK_t_client_t_district" FOREIGN KEY (district_id) REFERENCES "t_district" (district_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_credit_card" ADD CONSTRAINT "FK_t_credit_card_t_disposition" FOREIGN KEY (disp_id) REFERENCES "t_disposition" (disp_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_disposition" ADD CONSTRAINT "FK_t_disposition_t_account" FOREIGN KEY (account_id) REFERENCES "t_account" (account_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_disposition" ADD CONSTRAINT "FK_t_disposition_t_client" FOREIGN KEY (client_id) REFERENCES "t_client" (client_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_loan" ADD CONSTRAINT "FK_t_loan_t_account" FOREIGN KEY (account_id) REFERENCES "t_account" (account_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_permanent_order" ADD CONSTRAINT "FK_t_permanent_order_t_account" FOREIGN KEY (account_id) REFERENCES "t_account" (account_tk) ON DELETE No Action ON UPDATE No Action;
ALTER TABLE "t_transaction" ADD CONSTRAINT "FK_t_transaction_t_account" FOREIGN KEY (account_id) REFERENCES "t_account" (account_tk) ON DELETE No Action ON UPDATE No Action;
<file_sep># Semestrální práce část 3 - Datamart + dashboard.
## Zadání
Výstup:
1) model datamartu v CASE nástroji
2) DDL datamartu
3) business popis navrženého datamartu - obsažené atributy, smysl datamartu
4) dashboard v Power BI ve formátu .pbix
5) písemné zodpovězení libovolných 2 ze 3 zadaných otázek pomocí dashboardu
6) písemný popis odevzdaného dashboardu, případně demonstrace výstupů pomocí videa (není potřeba nějak natáčet sebe, stačí pouze smysluplně klikat a komentovat dashboard) - silně doporučené
## Model datamartu v CASE nástroji
Model datamartu se nachází v souborech DatamartModel.png a DatamartModel.eapx
## DDL datamartu
DDL datamartu se nachází v souboru DatamartDDL.sql
## Business popis navrženého datamartu - obsažené atributy, smysl datamartu
Business popis navrženého datamartu se nachází v souboru DatamartBusinessPopis.pdf
| 3a9aa1cd2b4f56b6ccaed8cd31ff214573bc89f1 | [
"Markdown",
"SQL"
] | 7 | SQL | chvostom/datovy_sklad | cda3a20acdc1e14c69275854eb4119af82933862 | 770f0f4e9798588405f166a56f6d627fd46f2e22 |
refs/heads/main | <repo_name>madyciss/machine_learning_model<file_sep>/main.py
"""nom = "Mady"
print("Je m'appelle " + nom)
print("Mon nom c'est bien " + nom + " CISSE")
prenom = input("Quel est ton prenom? ")
print("Je m'appelle " + prenom)
print("Mon nom c'est bien " + prenom + " CISSE")"""
"""ton_nom = input ("Quel est vous nom? ")
ton_age = input("Quel est vous age? ")
print("vous vous appellez " + ton_nom + ", vous avez " + ton_age + "ans")"""
""" # Convertir un entier en une chaine de caractére
# ton_nom = input ("Quel est vous nom? ")
# ton_age = input("Quel est vous age? ")
age = 25
annee_prochaine = age + 1
print("vous avez " + str(age) + "ans.")
print("Année prochaine, vous aurez " + str(annee_prochaine) + "ans.")"""
"""
# Convertir une chaine de caractére en entier
# ton_nom = input ("Quel est vous nom? ")
age = input("Quel est vous age? ")
# age = 25
try:
annee_prochaine = int(age) + 1
except:
print("ERREUR: vous devez entrer un nomber")
else:
print("vous avez " + str(age) + "ans.")
print("Année prochaine, vous aurez " + str(annee_prochaine) + " ans.")
"""
# La boucle while: "tant que"
"""
n = 0
while(n < 10):
print("La valeur de n:" + str(n))
n = n + 1
"""
"""mot_de_pass = ""
while not mot_de_pass == "password":
mot_de_pass = input("Entrer votre mot de passe: ")
print("Votre de passe est correte, vous avez accée à votre compte")"""
"""votre_nom = ""
while votre_nom == "":
votre_nom = input("Quel est votre nom? ")
print("Votre nom est " + votre_nom)"""
def demander_nom():
nom = ""
while nom == "":
nom = input("Quel est votre nom? ")
return nom
def demander_age(nom_personne):
age_int = 0
while age_int == 0:
age_str = input("nom_personne " + "quel est votre age? ")
age_int = int(age_str)
return age_int
def affichage(nom, age):
print()
print("vous vous appellez " + nom + ", vous avez " + str(age) + " ans")
print("Année prochaine, vous aurez " + str(age + 1) + " ans.")
if age == 17:
print("Vous etes mineur")
elif 1 < age < 3:
print("Vous etes un bebe")
else:
print("Vous ete majeur")
nom1 = demander_nom()
nom2 = demander_nom()
age1 = demander_age(nom1)
age2 = demander_age(nom2)
affichage(nom1, age1)
affichage(nom2, age2)
| 049eee063ac0cf51961fa0c9ab0131f5ffe30663 | [
"Python"
] | 1 | Python | madyciss/machine_learning_model | d046a95753f48935f9c7ba2d2fb3695802e53666 | e8217d381a22c2541900eb50376db3af16479040 |
refs/heads/master | <repo_name>joship18/ML<file_sep>/dt.py
import numpy as np
import pandas as pd
df = pd.read_csv("iris.csv")
#df.head()
from pandas.api.types import is_numeric_dtype
for i in range(df.shape[1]):
if(is_numeric_dtype(df.iloc[:,i])):
mask = df.iloc[:, i] < df.iloc[:, i].median()
df.ix[mask, i] = 0
df.ix[~mask, i] = 1
#df.head()
df = df.dropna()
mask = np.random.rand(len(df)) < 0.8
train = df.loc[mask]
test = df.loc[~mask]
def entropy(vec):
m = len(vec)
E = vec.value_counts()
n = len(E)
E = E/m
E = - E*np.log2(E)
return (E.sum() / np.log2(n))
def find_best_split(df):
best_gain = 0
best_attribute = None
current_entropy = entropy(df.iloc[:,-1])
n_features = df.shape[1] - 1
if(n_features == 0):
return best_gain, best_attribute
n_rows = df.shape[0]
for i in range(n_features):
entropy_after_split = 0
attribute_values = df.iloc[:,i].unique()
for j in attribute_values:
mask = (df.iloc[:,i] == j)
entropy_after_split = entropy_after_split + (len(mask[mask == True]) / n_rows )* entropy(df.ix[mask,-1])
gain = current_entropy - entropy_after_split
if(gain > best_gain):
best_gain = gain
best_attribute = i
return best_gain, best_attribute
def partition(df, attribute):
partitioned_data = {}
attribute_values = df.iloc[:,attribute].unique()
for i in attribute_values:
mask = (df.iloc[:,attribute] == i)
partitioned_data[i] = (df.loc[mask, :])
for i in range(len(partitioned_data)):
partitioned_data[i].drop(list(df)[attribute], axis=1)
return partitioned_data
class Leaf_node:
def __init__(self, df):
self.prediction = {}
X = df.iloc[:, -1].mode()
n = len(X)
for i in X:
self.prediction[i] = 100/n
class Decision_node:
def __init__(self, attribute):
self.attribute = attribute
self.children = {}
def add_child(self, df, value):
self.children[value] = df
def build_tree(df):
gain, attribute = find_best_split(df)
if(gain == 0):
return Leaf_node(df)
partitioned_data = partition(df, attribute)
X = Decision_node(list(df)[attribute])
for i in range(len(partitioned_data)):
X.add_child(build_tree(partitioned_data[i]), i)
return X
head = build_tree(train)
def predict(test, head):
correct_predictions = 0
for i in test.index:
node = head
while(isinstance(node, Leaf_node) == False):
Z = test.loc[i,node.attribute]
node = node.children[Z]
print("actual class: {} \t predicted class: {}" .format(test.loc[i, "species"], node.prediction))
if(test.loc[i, "species"] in node.prediction):
correct_predictions += 1
print("\naccuracy = {}%\n" .format(correct_predictions*100/len(test)))
predict(test, head)
| 72123887135fe96134db0b652b7b3d442567756b | [
"Python"
] | 1 | Python | joship18/ML | 5da67023c557927f0756f78163861d511ca1be3b | ab9b381cfc3a7400caaa8a9ceb19ae7f2e83e6fa |
refs/heads/master | <repo_name>NDM-123/wargame-a<file_sep>/Soldier.cpp
//
// Created by Naor on 5/21/2020.
//
#include <iostream>
#include"Board.hpp"
using namespace std;
<file_sep>/ParamedicCommander.hpp
#pragma once
#include "Soldier.hpp"
class ParamedicCommander : public Soldier {
public:
ParamedicCommander(int pn): Soldier(pn, 200, 100) {}
void attack(vector<vector<Soldier*>> &b, pair<int,int> location);
};
<file_sep>/Soldier.hpp
//
// Created by Naor on 5/21/2020.
//
#ifndef WARGAME_A_MASTER_SOLDIER_HPP
#define WARGAME_A_MASTER_SOLDIER_HPP
#pragma once
#include <stdexcept>
#include <math.h>
#include <vector>
using namespace std;
class Soldier {
//private:
public:
unsigned int soldierId;
unsigned int initial_health;
unsigned int damage;
unsigned int cur_hel;
Soldier(unsigned int sid, unsigned int h, int d) : soldierId(sid), initial_health(h), damage(d) { }
virtual ~Soldier() {
}
virtual void attack (std::vector<std::vector<Soldier*>> &soldi, pair<int,int> location) = 0;
unsigned int getSoldierId() {return soldierId;}
unsigned int getHealth() {return cur_hel;}
void setHealth(unsigned int health) {cur_hel=initial_health;}///////////////
unsigned int getDamage(){ return damage;}
double distance(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2){
return sqrt(pow(x1 - x2,2) + pow(y1 - y2,2));}
};
#endif //WARGAME_A_MASTER_SOLDIER_HPP
<file_sep>/Paramedic.cpp
#include <iostream>
#include "Paramedic.hpp"
using namespace std;
void Paramedic::attack(vector<vector<Soldier*>> &board, pair<int,int> location){
double dist=0;
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier* soldi = board[i][j];
dist=distance( i,j,location.first,location.second);
if (soldi != NULL &&soldi->Soldier::getSoldierId() == board[location.first][location.second]->Soldier::getSoldierId()&&dist==1)
soldi->Soldier::setHealth(soldi->initial_health);
}
}
}
<file_sep>/FootSoldier.hpp
#pragma once
#include "Soldier.hpp"
class FootSoldier : public Soldier {
public:
FootSoldier(int pn): Soldier(pn, 100, 10) {}
void attack(vector<vector<Soldier*>> &b, pair<int,int> location);
};
<file_sep>/SniperCommander.cpp
#include <iostream>
#include "Board.hpp"
#include "FootSoldier.hpp"
#include "Paramedic.hpp"
#include "ParamedicCommander.hpp"
#include "FootCommander.hpp"
#include "SniperCommander.hpp"
#include "Sniper.hpp"
#include "Soldier.hpp"
using namespace std;
void SniperCommander::attack(vector<vector<Soldier*>> &board, pair<int,int> location){
int maxhel=0;
Soldier *attack_it;
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier *soldi = board[i][j];
if (soldi != NULL &&soldi->Soldier::getSoldierId() != board[location.first][location.second]->Soldier::getSoldierId()&&maxhel<soldi->Soldier::getHealth())
maxhel=soldi->Soldier::getHealth();
attack_it=soldi;
}
}
if (FootCommander* pF=dynamic_cast<FootCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (Sniper* pF=dynamic_cast<Sniper*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (SniperCommander* pF=dynamic_cast<SniperCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (Paramedic* pF=dynamic_cast<Paramedic*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (ParamedicCommander* pF=dynamic_cast<ParamedicCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
/////wake up all snipers
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier *soldi = board[i][j];
Sniper* pF;
SniperCommander* pFc;
if (soldi != NULL &&soldi->Soldier::getSoldierId() == this->soldierId&&(pF==dynamic_cast<Sniper*>(soldi)||pFc==dynamic_cast<SniperCommander*>(soldi))){
pair<int,int> loc;
loc.first=i;
loc.second=j;
soldi->attack(board, loc);}
}
}
}
<file_sep>/FootSoldier.cpp
#include <iostream>
using namespace std;
#include "Board.hpp"
#include "FootSoldier.hpp"
#include "Paramedic.hpp"
#include "ParamedicCommander.hpp"
#include "FootCommander.hpp"
#include "SniperCommander.hpp"
#include "Sniper.hpp"
#include "Soldier.hpp"
void FootSoldier::attack(vector<vector<Soldier*>> &board, pair<int,int> location){
double mindist=0;
Soldier *attack_it;
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier *soldi = board[i][j];
double dist=Soldier::distance( i,j,location.first,location.second);
if (soldi != NULL &&soldi->Soldier::getSoldierId() != board[location.first][ location.second]->Soldier::getSoldierId()&&mindist>dist)
mindist=dist;
attack_it=soldi;
}
}
if (FootCommander* pF=dynamic_cast<FootCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (Sniper* pF=dynamic_cast<Sniper*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (SniperCommander* pF=dynamic_cast<SniperCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (Paramedic* pF=dynamic_cast<Paramedic*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
if (ParamedicCommander* pF=dynamic_cast<ParamedicCommander*>(attack_it)){
attack_it->Soldier::setHealth(this->damage);
}
}
<file_sep>/Board.cpp
#include "Board.hpp"
namespace WarGame
{
bool Board::has_soldiers(uint pn) const
{
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier* soldi = (*this)[{i, j}];
if (soldi != NULL && soldi->getSoldierId() == pn)
return true;
}
}
return false;
}
Soldier*& Board::operator[](std::pair<int,int> location)
{
return board[location.first][location.second];
}
Soldier* Board::operator[](std::pair<int,int> location) const
{
return board[location.first][location.second];
}
void Board::move(uint pn, std::pair<int,int> source, MoveDIR direction)
{
if(source.first<0 || source.first>=board.size()|| source.second<0 || source.second>=board[source.first].size()) {
throw invalid_argument("Action is forbidden,out of Board");
}
Soldier* soldi = (*this)[source];
if(soldi==nullptr || soldi->getSoldierId() != pn)throw invalid_argument("invalid argument");
pair<int, int> dest;
switch (direction)
{
case Up:
dest= make_pair(source.first+1, source.second);
break;
case Down:
dest= make_pair(source.first-1, source.second);
break;
case Left:
dest= make_pair(source.first, source.second-1);
break;
case Right:
dest= make_pair(source.first, source.second+1);
break;
}
if(dest.first<0 || dest.first>=board.size()|| dest.second<0 || dest.second>=board[dest.first].size())
throw invalid_argument("Outside of the board");
if (soldi==nullptr||soldi->getSoldierId()!=pn||(*this)[dest]!=nullptr){
throw invalid_argument("cant do");}
(*this)[source] = nullptr;
if((*this)[dest] != nullptr) throw runtime_error("stepping on other soldier!\n");
(*this)[dest] = soldi;
(*this)[source] = nullptr;
soldi->attack(board, dest);
}
}
<file_sep>/ParamedicCommander.cpp
#include <iostream>
using namespace std;
#include "Board.hpp"
#include "Paramedic.hpp"
#include "ParamedicCommander.hpp"
void ParamedicCommander::attack(vector<vector<Soldier*>> &board, pair<int,int> location){
double dist=0;
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier* soldi = board[i][j];
dist=distance( i,j,location.first,location.second);
if (soldi != NULL &&soldi->Soldier::getSoldierId() == board[location.first][location.second]->Soldier::getSoldierId()&&dist==1)
soldi->Soldier::setHealth(soldi->initial_health);
}
}
/////wake up all paramedics
for(int i= 0; i< board.size(); ++i){
for(int j=0; j< board[i].size(); ++j) {
Soldier* soldi = board[i][j];
Paramedic* pF;
ParamedicCommander* pFc;
if((soldi != NULL &&soldi->Soldier::getSoldierId() == this->soldierId) &&(pF ==dynamic_cast< Paramedic*>(soldi)||pFc==dynamic_cast<ParamedicCommander*>(soldi))){
pair<int,int> loc;
loc.first=i;
loc.second=j;
soldi->attack(board, loc);
}
}
}
}
| 5a13fcec7a34416c0490bfff4df70a957b096184 | [
"C++"
] | 9 | C++ | NDM-123/wargame-a | 11c64393d98cf90dd780e22bcb3ad48abaed44ac | 899b98d33ba19d65a028d7213ed1aba40aa5c4c4 |
refs/heads/master | <repo_name>ltpech/random_number<file_sep>/get_number.rb
# Get My Number Game
# Written by: you!
puts "Welcome to 'Get My Number!'"
print "What`s your name? "
input = gets
name = input.chomp
puts "Welcome, #{name}!"
#puts input.inspect
#p input
# Сохранение рандомного числа в переменнную
puts "I have got a random number beetwen 1 - 100"
puts "Can you guess it?"
target = rand(100) + 1
#p target
num_guesses = 0 # попытки
guessed_it = false #признак продолжения игры
until num_guesses == 10 || guessed_it
puts "#{10 - num_guesses} guesses left "
print "Make a guess: "
guess = gets.to_i
if ( guess < target)
puts "Ooops. You guess was LOW"
elsif( guess > target )
puts "Ooops. You guess was HIGH"
else
puts "Good job, #{name}! You guessed my number in #{10 - num_guesses}!
"
guessed_it = true
end
num_guesses += 1
end
unless guessed_it
puts "Sorry. You didn't get my number. (It was #{target}.)"
end
| ba081deecfa2afbf34d5e4d27671af85cdc7ab89 | [
"Ruby"
] | 1 | Ruby | ltpech/random_number | b50a29b80d0d0fd6c7d4d466941be65c1e7c45b3 | 6093e444e9ea0520e59fa284557ab19b59b0bde3 |
refs/heads/master | <repo_name>ckddls1321/play_pytorch<file_sep>/data/pets.py
pets = DataBlock(blocks = (ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=RandomSplitter(seed=42),
get_y=using_attr(RegexLabeller(r'(.+)_\d+.jpg$'),
'name'),
item_tfms=Resize(460),
batch_tfms=aug_transforms(size=224, min_scale=0.75))
dls = pets.dataloaders(path/"images")
<file_sep>/data/lsun.py
from pathlib import Path
from fastai.vision import *
from fastai.vision.gan import *
from fastai.metrics import *
from matplotlib import pyplot as plt
def lsun(batch_size=128,imgsize=64, **kwargs):
# path = untar_data(URLs.LSUN_BEDROOMS)
path = url2path(URLs.LSUN_BEDROOMS)
print(path)
dataset = (GANItemList.from_folder(path, noise_sz=100)
.no_split()
.label_from_func(noop)
.transform(tfms=[[crop_pad(size=imgsize, row_pct=(0, 1), col_pct=(0, 1))], []], size=imgsize, tfm_y=True)
.databunch(bs=batch_size)
.normalize(stats=[torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5])], do_x=False, do_y=True))
return dataset
<file_sep>/utils/__init__.py
from .optimizers import get_optimizer
from .autoaugment import *
from .fastai_cb_extension import *
from .fastai_schedulers import *<file_sep>/data/widerface.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.datasets import *
from fastai.metrics import *
import collections
__all__ = ['widerface']
wider_stat = ([0.483, 0.454, 0.404], [1,1,1])
def get_annotations_wider_txt(fname, prefix=None):
id2images, id2bboxes, id2cats = {}, collections.defaultdict(list), collections.defaultdict(list)
img_id = 0
cat_id = 1
categories = [{"id": 1, "name": 'face'}]
with open(str(fname), 'r') as f:
while True:
image_file = f.readline()
if not image_file:
break
image_file = image_file.replace('\n','')
image = {}
image['id'] = img_id
img_id +=1
image['file_name'] = Path(image_file).name
nBBox = f.readline()
i = 0
while i < int(nBBox):
x1, y1, w, h, _, _, _, _, _, _ = [int(i) for i in f.readline().split()]
if w > 0 and h > 0:
id2bboxes[image['id']].append([y1, x1, y1+h, x1+w])
id2cats[image['id']].append('face')
i = i + 1
if int(nBBox) == 0:
x1, y1, w, h, _, _, _, _, _, _ = [int(i) for i in f.readline().split()]
id2images[image['id']] = ifnone(prefix, '') + image['file_name']
ids = list(id2images.keys())
return [id2images[k] for k in ids], [[id2bboxes[k], id2cats[k]] for k in ids]
def widerface(batch_size=32, imgsize=256, **kwargs):
wider_path = Path('/datasets/widerface/')
train_images, train_lbl_bbox = get_annotations_wider_txt(wider_path / 'wider_face_split/wider_face_train_bbx_gt.txt')
val_images, val_lbl_bbox = get_annotations_wider_txt(wider_path / 'wider_face_split/wider_face_val_bbx_gt.txt')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
# get_valid_func = lambda o: o.name in val_images
# fnames = get_image_files(wider_path/ 'train',recurse=False)
data = (ObjectItemList.from_folder(wider_path / 'train')
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(wider_stat))
return data
<file_sep>/data/stanford.py
from pathlib import Path
from fastai.vision import *
from fastai.metrics import *
def stanford_cars(batch_size=256,imgsize=224, **kwargs):
# path = untar_data(URLs.CARS)
path = url2path(URLs.MNIST)
dataset = ImageDataBunch.from_folder(path,valid='test',ds_tfms=get_transforms(),bs=batch_size).normalize(imagenet_stats)
return dataset
<file_sep>/data/coco.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.datasets import *
from fastai.metrics import *
__all__ =['coco_tiny','coco_2017', 'coco_2014']
coco_stat =([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])
def coco_tiny(batch_size=8, imgsize=300, **kwargs):
# path = untar_data(URLs.COCO_TINY)
path = url2path(URLs.COCO_TINY)
images, lbl_bbox = get_annotations(path / 'train.json')
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path)
.split_by_rand_pct()
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(coco_stat))
return data
def coco_2014(batch_size=8, imgsize=300, **kwargs):
path = Path('/datasets/coco/')
train_images, train_lbl_bbox = get_annotations(path / 'annotations/instances_train2014.json')
val_images, val_lbl_bbox = get_annotations(path / 'annotations/instances_val2014.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path)
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(coco_stat))
return data
def coco_2017(batch_size=8, imgsize=300, **kwargs):
path = Path('/datasets/coco/')
train_images, train_lbl_bbox = get_annotations(path / 'annotations/instances_train2017.json')
val_images, val_lbl_bbox = get_annotations(path / 'annotations/instances_val2017.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
# import shutil
# target_path = Path('/datasets/coco/')
# for img in train_images:
# shutil.copy(str(path/'train2017'/img),str(target_path / 'train'/ img))
# for img in val_images:
# shutil.copy(str(path/'val2017'/img),str(target_path / 'valid'/ img))
# print("All copied")
# exit()
data = (ObjectItemList.from_folder(path)
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(coco_stat))
return data
<file_sep>/data/object365.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.datasets import *
from fastai.metrics import *
__all__ =['object365','object365_tiny']
coco_stat =([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])
def object365(batch_size=8, imgsize=300, **kwargs):
path = Path('/datasets/object365')
train_images, train_lbl_bbox = get_annotations(path / 'objects365_train.json')
val_images, val_lbl_bbox = get_annotations(path / 'objects365_val.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path)
.split_by_rand_pct()
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(coco_stat))
return data
def object365_tiny(batch_size=8, imgsize=300, **kwargs):
path = Path('/datasets/object365_tiny')
train_images, train_lbl_bbox = get_annotations(path / 'objects365_Tiny_train.json')
val_images, val_lbl_bbox = get_annotations(path / 'objects365_Tiny_val.json')
# test_images, test_lbl_bbox = get_annotations(path / 'objects365_Tiny_Testset_images_list.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path)
.split_by_rand_pct()
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(coco_stat))
return data
<file_sep>/configs/cifar10/seresnet20.py
total_epochs = 70
total_bs = 256
img_size = 32
log_level = 'INFO'
load_from = None
resume_from = None
dataset_type = 'cifar10'
model = dict(
type='seresnet20_cifar10',
pretrained=False
)
work_dir = './work_dirs/' + dataset_type + '_' + model['type']
loss = "CrossEntropyLoss"
metric = ["accuracy","error_rate"]
# optimizer = dict(type='SGD',lr=0.1, momentum=0.9, weight_decay=1e-4)
optimizer = dict(type='AdamW',lr=3e-3, betas=(0.9,0.99), eps=1e-8, weight_decay=0.4)
# lr_config = dict(policy='cosine',iter=total_epochs,warmup_ratio=0.1)
lr_config = dict(policy='cyclic',iter=total_epochs,warmup_ratio=0.1,div_factor=10,pct_start=0.5)
<file_sep>/utils/fastai_schedulers.py
from fastai.callbacks import *
from fastai.callback import *
def fit_warmup_restart(learn, n_cycles, lr, mom, cycle_len, cycle_mult):
n = len(learn.data.train_dl)
phases = [(TrainingPhase(n * (cycle_len * cycle_mult**i))
.schedule_hp('lr', lr, anneal=annealing_cos)
.schedule_hp('mom', mom)) for i in range(n_cycles)]
sched = GeneralScheduler(learn, phases)
learn.callbacks.append(sched)
if cycle_mult != 1:
total_epochs = int(cycle_len * (1 - (cycle_mult)**n_cycles)/(1-cycle_mult))
else: total_epochs = n_cycles * cycle_len
learn.fit(total_epochs)
def fit_warmup_cosannealing(learn, lr, total_epochs, warmup_ratio=0.1):
n = len(learn.data.train_dl)
phases = [
(TrainingPhase(total_epochs * warmup_ratio * n).schedule_hp('lr', (lr / 1e4, lr), anneal=annealing_linear)),
(TrainingPhase(n * total_epochs * (1-warmup_ratio)).schedule_hp('lr', lr, anneal=annealing_cos))
]
sched = GeneralScheduler(learn, phases)
learn.callbacks.append(sched)
learn.fit(total_epochs)
def fit_warmup_multistep(learn, lr, gamma, step, total_epochs, warmup_ratio=0.1):
n = len(learn.data.train_dl)
<file_sep>/data/mnist.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def mnist(batch_size=512,imgsize=28, **kwargs):
tfms = ([*rand_pad(3, imgsize, mode='zeros')],[])
# path = untar_data(URLs.MNIST)
path = url2path(URLs.MNIST)
dataset = ImageDataBunch.from_folder(path,valid='test',ds_tfms=tfms,size=imgsize, bs=batch_size).normalize()
return dataset
def fashionmnist(data_root= Path.home()/'projects/DL/DB', batch_size=512,imgsize=28, **kwargs):
tfms = ([*rand_pad(3, imgsize, mode='zeros')],[])
path = data_root / 'fashionmnist'
dataset = ImageDataBunch.from_folder(path,valid='test',ds_tfms=tfms,size=imgsize, bs=batch_size).normalize()
return dataset
<file_sep>/train_fastai.py
# Imports
from icevision.all import *
import icedata
# Load the PennFudan dataset
path = icedata.pennfudan.load_data()
# Load the PETS dataset
path = icedata.pets.load_data()
# Load the Birds dataset
path = icedata.birds.load_data()
# Load the Fridge Objects dataset
path = icedata.fridge.load_data()
# Installing IceVision
# !pip install icevision[all] icedata
# Imports
from icevision.all import *
import icedata
# Load the PETS dataset
path = icedata.pets.load_data()
# Get the class_map, a utility that maps from number IDs to classs names
class_map = icedata.pets.class_map()
# PETS parser: provided out-of-the-box
parser = icedata.pets.parser(data_dir=path, class_map=class_map)
train_records, valid_records = parser.parse(data_splitter)
# shows images with corresponding labels and boxes
show_records(train_records[:6], ncols=3, class_map=class_map, show=True)
# Define transforms - using Albumentations transforms out of the box
train_tfms = tfms.A.Adapter(
[*tfms.A.aug_tfms(size=384, presize=512), tfms.A.Normalize()]
)
valid_tfms = tfms.A.Adapter([*tfms.A.resize_and_pad(size), tfms.A.Normalize()])
# Create both training and validation datasets
train_ds = Dataset(train_records, train_tfms)
valid_ds = Dataset(valid_records, valid_tfms)
# Create both training and validation dataloaders
train_dl = faster_rcnn.train_dl(train_ds, batch_size=16, num_workers=4, shuffle=True)
valid_dl = faster_rcnn.valid_dl(valid_ds, batch_size=16, num_workers=4, shuffle=False)
# Create model
# Backbones
backbone = backbones.resnet_fpn.resnet18(pretrained=True)
# backbone = backbones.resnet_fpn.resnet34(pretrained=True)
# backbone = backbones.resnet_fpn.resnet50(pretrained=True) # Default
# backbone = backbones.resnet_fpn.resnet101(pretrained=True)
# backbone = backbones.resnet_fpn.resnet152(pretrained=True)
# backbone = backbones.resnet_fpn.resnext50_32x4d(pretrained=True)
# backbone = backbones.resnet_fpn.resnext101_32x8d(pretrained=True)
# backbone = backbones.resnet_fpn.wide_resnet50_2(pretrained=True)
# backbone = backbones.resnet_fpn.wide_resnet101_2(pretrained=True)
# Model
model = faster_rcnn.model(backbone=backbone, num_classes=len(class_map))
# Define metrics
metrics = [COCOMetric(metric_type=COCOMetricType.bbox)]
# Train using fastai2
learn = faster_rcnn.fastai.learner(
dls=[train_dl, valid_dl], model=model, metrics=metrics
)
learn.fine_tune(10, lr=1e-4)
# COCO Example
# pip install icevision[all] icedata
from icevision.all import *
url = "https://cvbp.blob.core.windows.net/public/datasets/object_detection/odFridgeObjects.zip"
dest_dir = "fridge"
# Loading Data
data_dir = icedata.load_data(url, dest_dir)
# Parser
class_map = ClassMap(["milk_bottle", "carton", "can", "water_bottle"])
parser = parsers.voc(annotations_dir=data_dir / "odFridgeObjects/annotations/",
images_dir=data_dir / "odFridgeObjects/images",
class_map=class_map)
# Records
train_records, valid_records = parser.parse()
# Transforms
train_tfms = tfms.A.Adapter([*tfms.A.aug_tfms(size=384, presize=512), tfms.A.Normalize()])
valid_tfms = tfms.A.Adapter([*tfms.A.resize_and_pad(384), tfms.A.Normalize()])
# Datasets
train_ds = Dataset(train_records, train_tfms)
valid_ds = Dataset(valid_records, valid_tfms)
# DataLoaders
train_dl = efficientdet.train_dl(train_ds, batch_size=16, num_workers=4, shuffle=True)
valid_dl = efficientdet.valid_dl(valid_ds, batch_size=16, num_workers=4, shuffle=False)
# Model and Metrics
model = efficientdet.model(model_name="tf_efficientdet_lite0", num_classes=len(class_map), img_size=size)
metrics = [COCOMetric(metric_type=COCOMetricType.bbox)]
# Training using Fastai
learn = efficientdet.fastai.learner(dls=[train_dl, valid_dl], model=model, metrics=metrics)
learn.fine_tune(50, 1e-2, freeze_epochs=20)
# Inference
# DataLoader
infer_dl = efficientdet.infer_dl(valid_ds, batch_size=8)
# Predict
samples, preds = efficientdet.predict_dl(model, infer_dl)
# Show samples
imgs = [sample["img"] for sample in samples]
show_preds(
imgs=imgs[:6],
preds=preds[:6],
class_map=class_map,
denormalize_fn=denormalize_imagenet,
ncols=3,
)
<file_sep>/data/cifar.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
import torch
from torch.utils import data
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data.distributed import DistributedSampler
from utils import CIFAR10Policy
def cifar10(batch_size=512,imgsize=32, **kwargs):
tfms = ([*rand_pad(4, imgsize), flip_lr(p=0.5)],[])
# path = untar_data(URLs.CIFAR)
path = url2path(URLs.CIFAR)
dataset = ImageDataBunch.from_folder(path,valid='test',ds_tfms=tfms,bs=batch_size).normalize(cifar_stats)
return dataset
def cifar100(batch_size=512,imgsize=32, **kwargs):
tfms = ([*rand_pad(4, imgsize), flip_lr(p=0.5)],[])
# path = untar_data(URLs.CIFAR_100)
path = url2path(URLs.CIFAR_100)
dataset = ImageDataBunch.from_folder(path,valid='test',ds_tfms=tfms,bs=batch_size).normalize(cifar_stats)
return dataset
def cifar10_pytorch(data_root, batch_size, imgsize=32, is_distributed=False):
workers = min(16, num_cpus())
<file_sep>/utils/lrschedulers.py
import math
import torch
import torch.optim.lr_scheduler
from functools import partial
__all__ = ['get_lrscheduler']
def get_lrscheduler(config, optimizer):
scheduler = getattr(torch.optim.lr_scheduler, config['type'])
if config['type'].lower() == 'steplr':
scheduler = scheduler(optimizer,step_size=config['step_size'],gamma=config['gamma'],last_epoch=-1)
return scheduler
if __name__ == '__main__':
net = torch.nn.Conv2d(3,16,3)
optimizer = torch.optim.SGD(net.parameters(),lr=0.01)
config = {'type':'StepLR','step_size':5,'gamma':0.8}
get_lrscheduler(config,optimizer)
<file_sep>/train_mmcv.py
import logging
import os
from argparse import ArgumentParser
from collections import OrderedDict
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn.functional as F
from torch.nn.parallel import DataParallel, DistributedDataParallel
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torchvision import datasets, transforms
from mmcv import Config
from mmcv.runner import DistSamplerSeedHook, Runner
from fastai.metrics import *
from pytorchcv.model_provider import get_model as ptcv_get_model
import data
def batch_processor(model, data, train_mode):
img, label = data
label = label.cuda(non_blocking=True)
pred = model(img)
loss = F.cross_entropy(pred, label)
acc_top1 = top_k_accuracy(pred, label, 1)
acc_top5 = top_k_accuracy(pred, label, 5)
log_vars = OrderedDict()
log_vars['loss'] = loss.item()
log_vars['acc_top1'] = acc_top1.item()
log_vars['acc_top5'] = acc_top5.item()
outputs = dict(loss=loss, log_vars=log_vars, num_samples=img.size(0))
return outputs
def get_logger(log_level):
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=log_level)
logger = logging.getLogger()
return logger
def init_dist(backend='nccl', **kwargs):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
rank = int(os.environ['RANK'])
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(rank % num_gpus)
dist.init_process_group(backend=backend, **kwargs)
def parse_args():
parser = ArgumentParser(description='Train CIFAR-10 classification')
parser.add_argument('config', help='train config file path')
parser.add_argument('--launcher',choices=['none', 'pytorch'],default='none',help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
return parser.parse_args()
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
logger = get_logger(cfg.log_level)
# init distributed environment if necessary
if args.launcher == 'none':
dist = False
logger.info('Disabled distributed training.')
else:
dist = True
init_dist(**cfg.dist_params)
world_size = torch.distributed.get_world_size()
rank = torch.distributed.get_rank()
if rank != 0:
logger.setLevel('ERROR')
logger.info('Enabled distributed training.')
try:
dataset = getattr(data, cfg.dataset_type)
train_loader, val_loader = dataset(cfg.data_root, batch_size = cfg.total_bs, imgsize=cfg.img_size)
except:
print("Dataset Type {} are Not Implemented. ")
exit()
# build model
try:
model = ptcv_get_model(cfg.model.type, pretrained=cfg.model.pretrained)
except:
print("Model Not Implemented. ")
exit()
if dist:
model = DistributedDataParallel(model.cuda(), device_ids=[torch.cuda.current_device()])
else:
model = DataParallel(model, device_ids=cfg.gpus).cuda()
# build runner and register hooks
runner = Runner(model,batch_processor,cfg.optimizer,cfg.work_dir,log_level=cfg.log_level)
runner.register_training_hooks(
lr_config=cfg.lr_config,
optimizer_config=cfg.optimizer_config,
checkpoint_config=cfg.checkpoint_config,
log_config=cfg.log_config)
if dist:
runner.register_hook(DistSamplerSeedHook())
# load param (if necessary) and run
if cfg.get('resume_from') is not None:
runner.resume(cfg.resume_from)
elif cfg.get('load_from') is not None:
runner.load_checkpoint(cfg.load_from)
runner.run([train_loader, val_loader], cfg.workflow, cfg.total_epochs)
if __name__ == '__main__':
main()<file_sep>/data/camvid.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def camvid(batch_size,imgsize=(360,480),**kwargs):
path = url2path(URLs.CAMVID)
path_lbl = path / 'labels'
path_img = path / 'images'
codes = np.loadtxt(path / 'codes.txt', dtype=str)
get_y_fn = lambda x: path_lbl / f'{x.stem}_P{x.suffix}'
dataset = (SegmentationItemList.from_folder(path_img)
.split_by_fname_file('../valid.txt')
.label_from_func(get_y_fn, classes=codes)
.transform(get_transforms(), size=imgsize, tfm_y=True)
.databunch(bs=batch_size, num_workers=0)
.normalize(imagenet_stats))
return dataset
def camvid_tiny(batch_size,imgsize=(360,480),**kwargs):
path = url2path(URLs.CAMVID_TINY)
path_lbl = path / 'labels'
path_img = path / 'images'
codes = np.loadtxt(path / 'codes.txt', dtype=str)
get_y_fn = lambda x: path_lbl / f'{x.stem}_P{x.suffix}'
dataset = (SegmentationItemList.from_folder(path_img)
.split_by_fname_file('../valid.txt')
.label_from_func(get_y_fn, classes=codes)
.transform(get_transforms(), size=imgsize, tfm_y=True)
.databunch(bs=batch_size, num_workers=0)
.normalize(imagenet_stats))
return dataset
<file_sep>/data/cityscapes.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
<file_sep>/data/pascal.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
import torch
from torch.utils import data
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data.distributed import DistributedSampler
__all__ = ['pascal_2007', 'pascal_2012']
pascal_stat = ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
def pascal_2007(batch_size=16, imgsize=300, **kwargs):
# path = untar_data(URLs.PASCAL_2007)
path = url2path(URLs.PASCAL_2007)
train_images, train_lbl_bbox = get_annotations(path / 'train.json')
val_images, val_lbl_bbox = get_annotations(path / 'valid.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path / 'train')
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(pascal_stat))
return data
def pascal_2012(batch_size=16, imgsize=300, **kwargs):
# path = untar_data(URLs.PASCAL_2012)
path = url2path(URLs.PASCAL_2012)
train_images, train_lbl_bbox = get_annotations(path / 'train.json')
val_images, val_lbl_bbox = get_annotations(path / 'valid.json')
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path / 'train')
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(pascal_stat))
return data
<file_sep>/data/biwihead.py
from pathlib import Path
import copy
import numpy as np
from fastai.vision import *
from fastai.metrics import *
def biwihead(batch_size,imgsize=(120,160), **kwargs):
path = url2path(URLs.BIWI_HEAD_POSE)
cal = np.genfromtxt(path / '01' / 'rgb.cal', skip_footer=6)
def img2txt_name(f): return path / f'{str(f)[:-7]}pose.txt'
def convert_biwi(coords):
c1 = coords[0] * cal[0][0] / coords[2] + cal[0][2]
c2 = coords[1] * cal[1][1] / coords[2] + cal[1][2]
return tensor([c2, c1])
def get_ctr(f):
ctr = np.genfromtxt(img2txt_name(f), skip_header=3)
return convert_biwi(ctr)
def get_ip(img, pts): return ImagePoints(FlowField(img.size, pts), scale=True)
dataset = (PointsItemList.from_folder(path)
.split_by_valid_func(lambda o: o.parent.name == '13')
.label_from_func(get_ctr)
.transform(get_transforms(), tfm_y=True, size=imgsize) # default : 1
.databunch(bs=batch_size, num_workers=0).normalize(imagenet_stats)
)
return dataset
<file_sep>/run_train.sh
#!/bin/zsh
#
gradient jobs create \
--name "cifar10" \
--container "paperspace/fastai:1.0-CUDA9.2-base-3.0-v1.0.6" \
--machineType "P5000" \
--command "train_fastai.py ./configs/cifar10.py"
<file_sep>/data/widerperson.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.datasets import *
from fastai.metrics import *
import collections
__all__ = ['widerperson']
wider_stat = ([0.483, 0.454, 0.404], [1,1,1])
categories = ['pedestrians','riders','partially-visible persons','ignore regions','crowd']
def get_annotations_wider_txt(fname, prefix=None):
id2images, id2bboxes, id2cats = {}, collections.defaultdict(list), collections.defaultdict(list)
img_id = 0
categories = [{"id": 1, "name": 'pedestrians'},{"id": 2, "name": 'riders'},
{"id": 3, "name": 'partial-visible-person'},{"id":4, "name": 'crowd'},
{"id": 5, "name": 'ignore-region'}
]
with open(str(fname), 'r') as f:
classes = {}
for o in categories:
classes[o['id']] = o['name']
while True:
image_file = f.readline()
if not image_file:
break
image_file = image_file.replace('\n','')
image = {}
image['id'] = img_id
img_id +=1
image['file_name'] = image_file+'.jpg'
with open(str(Path(fname).parent) + '/Annotations/' + image_file+'.jpg.txt','r') as bbox_annotation_f:
nBBox = bbox_annotation_f.readline()
i = 0
while i < int(nBBox):
id, x1, y1, x2, y2 = [int(i) for i in bbox_annotation_f.readline().split()]
if (x2-x1) > 0 and (y2-y1) > 0:
id2bboxes[image['id']].append([y1, x1, y2, x2])
id2cats[image['id']].append(classes[id])
i = i + 1
id2images[image['id']] = ifnone(prefix, '') + image['file_name']
ids = list(id2images.keys())
return [id2images[k] for k in ids], [[id2bboxes[k], id2cats[k]] for k in ids]
def widerperson(batch_size=32, imgsize=256, **kwargs):
wider_path = Path('/datasets/widerperson/')
train_images, train_lbl_bbox = get_annotations_wider_txt(str(wider_path / 'train.txt'))
val_images, val_lbl_bbox = get_annotations_wider_txt(str(wider_path / 'val.txt'))
# test_images, test_lbl_bbox = get_annotations_wider_txt(str(wider_path / 'test.txt'))
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
# import shutil
# for img in train_images:
# shutil.copy(str(wider_path/'Images'/img),str(wider_path / 'train'/ img))
# for img in val_images:
# shutil.copy(str(wider_path/'Images'/img),str(wider_path / 'train'/ img))
# print("All copied")
# exit()
data = (ObjectItemList.from_folder(wider_path / 'train')
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(wider_stat))
return data
<file_sep>/README.md
# play_pytorch
Pytorch Trial with Paper, Kaggle, Computer Vision Applications
## Getting Started
## Results
## Demo
## Library used
- [Pytorch Demo Application] (https://github.com/pytorch/android-demo-app)
- [Fast.ai - The fastai deep learning library, plus lessons and tutorials] (https://github.com/fastai/fastai)
- [brevitas] (https://github.com/Xilinx/brevitas)
- [mmcv] (https://github.com/open-mmlab/mmcv)
- [imgclsmob - pytorchcv] (https://github.com/osmr/imgclsmob/tree/master/pytorch)
- [pytorch-cifar] (https://github.com/kuangliu/pytorch-cifar) => modified and integrated forked version of imgclsmob
- [fastai_extensions] (https://github.com/oguiza/fastai_extensions)
- [TorchRay] (https://github.com/facebookresearch/TorchRay.git)
- [FastAI V1.0 Course modified] (https://github.com/jav0927/course-v3)
<file_sep>/configs/config.py
total_epochs = 30
total_bs = 128
img_size = 240
log_level = 'INFO'
load_from = None
resume_from = None
dataset_type = 'openimages_v4'
model = dict(
type='seresnet20_cifar10',
pretrained=False
)
work_dir = './work_dirs/' + dataset_type + '_' + model['type']
loss = "CrossEntropyLoss"
metric = ["accuracy","error_rate"]
# optimizer = dict(type='SGD',lr=1e-1, momentum=0.9, weight_decay=1e-2)
optimizer = dict(type='AdamW',lr=3e-3, betas=(0.9,0.99), eps=1e-8, weight_decay=0.4)
lr_config = dict(policy='fit',iter=total_epochs,warmup_ratio=0.1)
# lr_config = dict(policy='cosine',iter=total_epochs,warmup_ratio=0.1)
# lr_config = dict(policy='cyclic',iter=total_epochs,warmup_ratio=0.1,div_factor=25,pct_start=0.8)
<file_sep>/data/imagenet.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
import torch
from torch.utils import data
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data.distributed import DistributedSampler
def imagenet(batch_size=32,imgsize=224, **kwargs):
path = Path('/datasets/imagenet')
dataset = ImageDataBunch.from_folder(path,valid='val',ds_tfms=get_transforms(),bs=batch_size,size=imgsize).normalize(imagenet_stats)
return dataset
def imagenet64(batch_size=128,imgsize=64, **kwargs):
path = Path('/datasets/imagenet64')
dataset = ImageDataBunch.from_folder(path,valid='val',ds_tfms=get_transforms(),bs=batch_size,size=imgsize).normalize(imagenet_stats)
return dataset
<file_sep>/data/__init__.py
from .mnist import *
from .biwihead import *
from .cifar import *
from .cinic import *
from .pascal import *
from .coco import *
from .object365 import *
from .caltech import *
from .camvid import *
from .cat_dog import *
from .imagenet import *
from .widerface import *
from .widerperson import *
from .lsun import *
from .food import *
from .oxford import *
from .stanford import *
from .cityscapes import *
from .CrowdHuman import *
from .openimages_v4 import *
<file_sep>/data/food.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def food101(batch_size=256, imgsize=224, **kwargs):
# path = untar_data(URLs.FOOD)
path = url2path(URLs.FOOD)
dataset = (ImageDataBunch.from_folder(path,valid_pct=0.2,test='test',ds_tfms=get_transforms(),size=imgsize,bs=batch_size,**kwargs).normalize(imagenet_stats))
return dataset
def fruits360(batch_size=256, imgsize=224, **kwargs):
path = Path('/datasets/fruits-360/')
dataset = (ImageDataBunch.from_folder(path,train='Training',valid_pct=0.2,test='Test',ds_tfms=get_transforms(),size=imgsize,bs=batch_size,**kwargs).normalize(imagenet_stats))
return dataset
# refer tohttps://github.com/marcusklasson/GroceryStoreDataset
def save_grocery_txt_to_csv(path, prefix=None):
categories = [
"Golden - Delicious","Granny - Smith","Pink - Lady","Red - Delicious",
"Royal - Gala","Avocado","Banana","Kiwi","Lemon","Lime","Mango","Cantaloupe",
"Galia - Melon","Honeydew - Melon","Watermelon","Nectarine","Orange","Papaya",
"Passion - Fruit","Peach","Anjou","Conference","Kaiser","Pineapple",
"Plum","Pomegranate","Red - Grapefruit","Satsumas","Bravo - Apple - Juice",
"Bravo - Orange - Juice","God - Morgon - Apple - Juice",
"God - Morgon - Orange - Juice","God - Morgon - Orange - Red - Grapefruit - Juice",
"God - Morgon - Red - Grapefruit - Juice","Tropicana - Apple - Juice",
"Tropicana - Golden - Grapefruit","Tropicana - Juice - Smooth","Tropicana - Mandarin - Morning",
"Arla - Ecological - Medium - Fat - Milk","Arla - Lactose - Medium - Fat - Milk",
"Arla - Medium - Fat - Milk","Arla - Standard - Milk",
"Garant - Ecological - Medium - Fat - Milk","Garant - Ecological - Standard - Milk",
"Oatly - Natural - Oatghurt","Oatly - Oat - Milk",
"Arla - Ecological - Sour - Cream","Arla - Sour - Cream","Arla - Sour - Milk",
"Alpro - Blueberry - Soyghurt","Alpro - Vanilla - Soyghurt",
"Alpro - Fresh - Soy - Milk","Alpro - Shelf - Soy - Milk",
"Arla - Mild - Vanilla - Yoghurt","Arla - Natural - Mild - Low - Fat - Yoghurt",
"Arla - Natural - Yoghurt","Valio - Vanilla - Yoghurt",
"Yoggi - Strawberry - Yoghurt","Yoggi - Vanilla - Yoghurt",
"Asparagus","Aubergine","Cabbage","Carrots","Cucumber","Garlic","Ginger",
"Leek","Brown - Cap - Mushroom","Yellow - Onion",
"Green - Bell - Pepper","Orange - Bell - Pepper",
"Red - Bell - Pepper","Yellow - Bell - Pepper","Floury - Potato",
"Solid - Potato","Sweet - Potato","Red - Beet","Beef - Tomato",
"Regular - Tomato","Vine - Tomato","Zucchini"
]
with open(str(path / 'train.csv'), 'w') as out_file:
with open(str(path / 'train.txt'), 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(out_file)
writer.writerows(lines)
with open(str(path / 'val.txt'), 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(out_file)
writer.writerows(lines)
with open(str(path / 'test.txt'), 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(out_file)
writer.writerows(lines)
def grocerystore(batch_size=256, imgsize=224, **kwargs):
# Image File Name Conflict
path = Path('/datasets/GroceryStoreDataset/dataset/')
save_grocery_txt_to_csv(path)
dataset = ImageDataBunch.from_csv(path,csv_labels='train.csv',label_delim=',',valid_pct=0.2,ds_tfms=get_transforms(),size=imgsize,bs=batch_size).normalize(imagenet_stats)
return dataset
<file_sep>/utils/optimizers.py
import torch.optim as optim
import math
import torch
from functools import partial
__all__ = ['get_optimizer']
def get_optimizer(config):
if config['type'].lower()=="sgd":
optimizer = partial(optim.SGD,momentum=config['momentum'])
elif config['type'].lower() == "adamw":
optimizer = partial(optim.AdamW, betas=config['betas'],eps=config['eps'])
else:
print("Error : Not Supported Type of Optimizer", config['type'],"Not Im,plemented Yet")
exit()
return optimizer
<file_sep>/data/cinic.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def cinic10(data_root=Path('/datasets'),batch_size=512,imgsize=32, **kwargs):
path = data_root / 'cinic10/'
dataset = (ImageDataBunch.from_folder(path)
.split_by_folder()
.label_from_folder()
.add_test_folder('test')
.transform(tfms=get_transforms(), size=imgsize)
.databunch(bs=batch_size, **kwargs)
.normalize(cifar_stats))
return dataset
<file_sep>/data/cat_dog.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def cat_dog(batch_size,imgsize=224,**kwargs):
# path = untar_data(URLs.DOGS)
path = url2path(URLs.DOGS)
dataset = (ImageDataBunch.from_folder(path,ds_tfms=get_transforms(),size=imgsize,valid_pct=0.2,bs=batch_size,**kwargs).normalize(imagenet_stats))
return dataset
<file_sep>/data/CrowdHuman.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
import json
import numpy as np
def get_annotations_odgt(fname, prefix=None):
"Open a COCO style json in `fname` and returns the lists of filenames (with maybe `prefix`) and labelled bboxes."
id2images, id2bboxes, id2cats = {}, collections.defaultdict(list), collections.defaultdict(list)
with open(fname, 'r+') as f:
datalist = f.readlines()
img_id = 0
for i in np.arange(len(datalist)):
adata = json.loads(datalist[i])
gtboxes = adata['gtboxes']
image = {}
image['id'] = img_id
img_id += 1
image['file_name'] = adata['ID'] + '.jpg'
for gtbox in gtboxes:
if gtbox['tag'] == 'person':
# Currently use only visible bbox
# bbox = gtbox['fbox']
# bbox[2] = bbox[2] + bbox[0]
# bbox[3] = bbox[3] + bbox[1]
# id2bboxes[image['id']].append(bbox)
# id2cats[image['id']].append('person')
# should consider mask and head occlusion etc
bbox = gtbox['vbox'] # x, y, w, h
bbox[2] = bbox[2] + bbox[0] # x1 + w
bbox[3] = bbox[3] + bbox[1] # y1 + h
id2bboxes[image['id']].append([bbox[1],bbox[0],bbox[3],bbox[2]]) # y1, x1, y2, x2
id2cats[image['id']].append('person')
hbox = gtbox['hbox']
hbox[2] = hbox[2] + hbox[0]
hbox[3] = hbox[3] + hbox[1]
id2bboxes[image['id']].append([hbox[1],hbox[0],hbox[3],hbox[2]]) # y1, x1, y2, x2
id2cats[image['id']].append('head')
elif gtbox['tag'] == 'mask':
pass
else:
print("??")
id2images[image['id']] = ifnone(prefix, '') + image['file_name']
ids = list(id2images.keys())
return [id2images[k] for k in ids], [[id2bboxes[k], id2cats[k]] for k in ids]
def crowdhuman(batch_size=8, imgsize=300, **kwargs):
path = Path('/datasets/CrowdHuman')
# using jq, json command line parser
train_images, train_lbl_bbox = get_annotations_odgt(str(path / 'annotation_train.odgt'))
val_images, val_lbl_bbox = get_annotations_odgt(str(path / 'annotation_val.odgt'))
images, lbl_bbox = train_images + val_images, train_lbl_bbox + val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o: img2bbox[o.name]
data = (ObjectItemList.from_folder(path / 'Images')
.split_by_files(val_images)
.label_from_func(get_y_func)
.transform(get_transforms(), tfm_y=True, size=imgsize)
.databunch(bs=batch_size, collate_fn=bb_pad_collate).normalize(imagenet_stats))
return data
<file_sep>/data/caltech.py
from pathlib import Path
from fastai.vision import *
from fastai.metrics import *
def caltech101(batch_size=512,imgsize=32, **kwargs):
# path = untar_data(URLs.CALTECH_101)
path = url2path(URLs.CALTECH_101)
# print(path)
path = path.parent.joinpath('101_ObjectCategories')
dataset = (ImageDataBunch.from_folder(path, valid_pct=0.2, ds_tfms=get_transforms(), bs=batch_size, size=imgsize).normalize(imagenet_stats))
return dataset
def CUB200_2011(batch_size=128,imgsize=224, **kwargs):
path = url2path(URLs.CUB_200_2011)
dataset = (ImageDataBunch.from_folder(path / 'images', valid_pct=0.2,ds_tfms=get_transforms(), size=imgsize,bs=batch_size, **kwargs).normalize(imagenet_stats))
return dataset
<file_sep>/data/oxford.py
from pathlib import Path
import copy
from fastai.vision import *
from fastai.metrics import *
def oxford_iiit_pet(batch_size,imgsize=224,**kwargs):
# path = untar_data(URLs.PETS)
path = url2path(URLs.PETS)
pat = r'/([^/]+)_\d+.jpg$'
fnames = get_image_files(path / 'images')
dataset = ImageDataBunch.from_name_re(path, fnames, pat, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)
return dataset
def get_annotations_from_txt(fname, prefix=None):
images = []
labels = []
with open(str(fname), 'r') as f:
while True:
line = f.readline()
if not line: break
img, lbl = line.replace('\n','').split(' ')
images.append(Path(img).name)
labels.append(lbl)
return images, labels
def oxford_102_flowers(batch_size,imgsize=224,**kwargs):
# path = untar_data(URLs.FLOWERS)
path = url2path(URLs.FLOWERS)
train_images, train_lbl = get_annotations_from_txt(path / 'train.txt')
val_images, val_lbl = get_annotations_from_txt(path / 'valid.txt')
test_images, test_lbl = get_annotations_from_txt(path / 'test.txt')
images, lbl = train_images + val_images, train_lbl + val_lbl
img2label = dict(zip(images, lbl))
get_y_func = lambda o: img2label[o.name]
fnames = get_image_files(path / 'jpg')
fnames_to_remove = [path / 'jpg' / img for img in test_images]
for fname in fnames_to_remove:
fnames.remove(fname)
dataset = (ImageDataBunch.from_name_func(path,fnames, get_y_func, valid_pct=0.2, ds_tfms=get_transforms(), size=imgsize, bs=batch_size)
# .add_test(test_images,tfms=([*rand_pad(10, imgsize), flip_lr(p=0.5)],[]),label=test_lbl)
.normalize(imagenet_stats))
return dataset
| e1f8c3af727dac32f5f93435123c45c620c79f9c | [
"Markdown",
"Python",
"Shell"
] | 31 | Python | ckddls1321/play_pytorch | 1f5b02eb5557e113e84b531021ab7cb9fa4ebf45 | 905b4487ef8c09dde9403bac32a8430295ebfb54 |
refs/heads/master | <file_sep>public class Voter
{
private int initialVote;
private int realignedVote;
private int precinct;
public Voter()
{
initialVote = 0;
realignedVote = 0;
precinct = 0;
}
public void setInitialVote(int vote)
{
initialVote = vote;
}
public void setRealignedVote(int vote)
{
realignedVote = vote;
}
public void setPrecinct(int precinct)
{
precinct = precinct;
}
public int getPrecinct()
{
return precinct;
}
public int getInitialVote()
{
return initialVote;
}
public int getRealignedVote()
{
return realignedVote;
}
}<file_sep>import java.util.*;
import java.util.Scanner;
import java.util.Random;
public class hangman
{
Scanner sc = new Scanner (System.in);// allows you to chose items on main menu
public static void homescreen()
{
Scanner sc = new Scanner (System.in);
System.out.println("\f");
System.out.println("Please resize the terminal window to ");
System.out.println("roughly 10cm by 15cm");
System.out.println("What is your name?");
String name = sc.nextLine();
System.out.println("\f");
String click = "0";
while (click != "1")
{
System.out.println("Hello " + name + " welcome to Hangman!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println ("Press 1 to START");
System.out.println (" ");
System.out.println("Press 2 for INSTRUCTIONS");
System.out.println (" ");
System.out.println("Press 3 for TWO PLAYER MODE");
click = sc.nextLine(); // what number on main menu is chosen
if (click.equals("1"))
{
System.out.println("\f");
game();//call game method to start game
}
else if (click.equals("2"))
{
System.out.println("\f");//clear screen
System.out.println("HOW TO PLAY");//print instructions
System.out.println(" ");
System.out.println("Enter any letter to guess and hit enter!");
System.out.println("A new piece will be added for each incorrect");
System.out.println("guess. You will lose on the 8th incorrect guess.");
System.out.println("If you want to guess the whole phrase type it");
System.out.println("with any spaces and punctuation included.");
System.out.println("If you guess the whole phrase and get it wrong");
System.out.println("You wont be penalized the first time.");
System.out.println("Good luck and have fun!!");
System.out.println(" ");
System.out.println("Press 4 to go back to MAIN MENU");
click = sc.nextLine(); // take input to go back to menu
}
else if(click.equals("3"))
{
System.out.println("\f");
System.out.println("Welcome to two player mode!");
int score1 = 0;
int score2 = 0;
int who = 2;
twoPlayer(score1, score2, who);
}
if (click.equals("4"))
System.out.println("\f");//clear screen go back to top of loop and print main menu again
else //if a mistake is made when typing it will take you back to main menu
//prevents program from crashing
{
System.out.println("\f");//clear screen and goes to top of loop so main menu is printed
}
}
}
public static void twoPlayer(int score1, int score2, int who)
{
Scanner sc = new Scanner(System.in);
System.out.println("\f");
System.out.println("What is player 1's name?");
String name1 = sc.nextLine();
System.out.println("What is player 2's name?");
String name2 = sc.nextLine();
if(who == 2) // these if statements change based on who's turn it is
{
System.out.println("Time for "+name1+" to pick a word for the game!");
}
else if(who == 1)
{
System.out.println("Time for "+name2+" to pick a word for the game!");
}
String wordGuess = sc.nextLine();
System.out.println("\f");
wordGuess = wordGuess.toUpperCase();
int word = 0;
for(int i = 0; i<wordGuess.length(); i++)
{
char n = wordGuess.charAt(i);
if(!((65<=n)&&(n<=90))) //these if statements make sure the word only uses accepted chars
{
if(!((97<=n)&&(n<=122)))
{
if(!(n=='!')||(n=='\'')||(n==',')||(n=='?'))
{
System.out.println("\f");
System.out.println("We can't use that word because you've inputted a character");
System.out.println("the game doesn't understand : (");
System.out.println("Please input another word");
wordGuess = sc.nextLine();
i = 0;
}
}
}
}
char [] phrase = new char[wordGuess.length()];
for(int i = 0; i<wordGuess.length(); i++) // creates an array of chars out of the given word
{
phrase[i] = wordGuess.charAt(i);
}
String dashWord = "";
for(int j = 0; j <wordGuess.length(); j++) //used to create the dashes that appear on screen
{
if(wordGuess.charAt(j)== ' ')
{
dashWord = dashWord+" ";
}
else if(wordGuess.charAt(j)== '!')
{
dashWord = dashWord+"!";
}
else if(wordGuess.charAt(j)== '\'')
{
dashWord = dashWord+"'";
}
else if(wordGuess.charAt(j)== ',')
{
dashWord = dashWord+",";
}
else if(wordGuess.charAt(j)== '?')
{
dashWord = dashWord+"?";
}
else
{
dashWord = dashWord+"_";
}
}
int longWordGuess = 0;
int countWrong = 0;
String previous = "";
int score = 8 - countWrong;
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println(" _____");// area where hangman will be drawn
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
guessValidTwo(name1, name2, score1, score2, who, phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
public static void guessValidTwo(String name1, String name2, int score1, int score2, int who,char[] phrase,String previous,String dashWord, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
String guess = sc.nextLine();
int guessLength = guess.length();
if (guessLength==2)//a letter guess is 1 char, and a word guess has 3 or more chars
{ //so here we ask for another entry if 2 chars are entered
System.out.println("Please input a different guess");
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
guessBeforeTwo(name1, name2, score1, score2, who, phrase,previous,dashWord, guess, wordGuess, longWordGuess, countWrong);
}
public static void guessBeforeTwo(String name1, String name2, int score1, int score2, int who, char[] phrase,String previous, String dashWord, String guess, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
char [] before = new char[previous.length()];
for(int j = 0; j<previous.length(); j++)
{
before[j] = previous.charAt(j); //make an array of the previously guessed chars
}
for(int i = 0; i<previous.length(); i++)
{
if(guess.length()==1)
{
if(before[i]==guess.charAt(0))//check if the guess has been guessed before
{
System.out.println("You have already guessed that letter. Please input another.");
guessValidTwo(name1, name2, score1, score2,who,phrase,previous,dashWord, wordGuess, longWordGuess, countWrong);
}
}
}
previous = previous+guess;//adds the current guess on to the string of previous guesses
twoPlayerCases(name1, name2, score1, score2, who, phrase,previous, guess, dashWord, wordGuess, longWordGuess, countWrong);
}
public static void twoPlayerCases(String name1, String name2, int score1, int score2, int who, char[] phrase, String previous, String guess,String dashWord, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
int wordLength = wordGuess.length();
int guessLength = guess.length();
guess = guess.toUpperCase();
char guess1 = guess.charAt(0);
int correct = 0;
if(guessLength == 1)
{
for(int i = 0; i<wordLength; i++)
{
if(phrase[i]==guess1)//if there is a match, this creates the new dashed word
{
dashWord = dashWord.substring(0,i)+guess+dashWord.substring(i+1, wordLength);
correct = 1000;//this is just used as a flag that there was a match
}
}
if(correct==0)//if the above if statement wasn't accessed, this is now accessed
{
countWrong = countWrong + 1;
}
}
else if(guess.length() != 1)//used for when the person tries to guess the whole word
{
if(guess.equals(wordGuess))
{
gameOver(wordGuess);
}
else
{
longWordGuess = longWordGuess + 1;
if(longWordGuess > 1)//after 1 strike, the full word guesses are added to the normal guesses
{
countWrong = countWrong + 1;
}
}
}
if(countWrong == 0)//from here on is all the different cases based on how many wrong answers
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println(" _____");// area where hangman will be drawn
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 1)
{
System.out.println("\f");
System.out.println("GUESS AGAIN!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 6 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 2)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 5 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 3)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 4 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 4)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 3 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 5)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 2 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 6)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 1 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | /");
System.out.println(" ___|___");
System.out.println(dashWord);
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who,name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 7)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 0 incorrect guesses left");
System.out.println(" _____");// draw hangman with new piece
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | / \\");
System.out.println(" ___|___");
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOverTwo(wordGuess, score1, score2, who, name1, name2);
}
guessValidTwo(name1, name2, score1, score2, who,phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 8)
{
int score = 8 - countWrong;
System.out.println("\f");// clear screen
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have "+ score + " incorrect guesses left");
System.out.println(" _____");// draw hangman wiht new piece
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | _/ \\_");
System.out.println(" ___|___");
System.out.println("GAME OVER :(");
System.out.println("The word was "+wordGuess+"!");
System.out.println(name1+"'s Score:"+score1);
System.out.println(name2+"'s Score:"+score2);
System.out.println("PRESS 4 TO RETURN TO MAIN MENU");
System.out.println("PRESS 3 TO PLAY AGAIN");
if(who==1)//these change the player who creates the word for the next round
{
who = 2;
}
else if(who ==2)
{
who = 1;
}
String click = sc.nextLine();
if (click.equals("4"))
{
homescreen();
}
else if(click.equals("3"))
{
twoPlayer(score1, score2, who);//the score is carried over into the next round
}
}
}
public static void gameOverTwo(String wordGuess, int score1, int score2, int who, String name1, String name2)
{
Scanner sc = new Scanner (System.in);
System.out.println("\f");
System.out.println("The word was "+wordGuess+"!");
if(who == 1)
{
System.out.println("Congrats! "+name1+ " Wins!");
score1 = score1+1;//adds to the score
who = 2;//switches the player who creates the word next round
}
else if(who == 2)
{
System.out.println("Congrats! "+name2+ " Wins!");
score2 = score2+1;
who = 1;
}
System.out.println("PRESS 4 TO RETURN TO MAIN MENU");
System.out.println("PRESS 3 TO PLAY AGAIN");
String click = sc.nextLine();
if (click.equals("4"))
{
homescreen();
}
else if(click.equals("3"))
{
twoPlayer(score1, score2, who);
}
}
public static void game()
{
wordBank();
}
public static void wordBank(){
Scanner sc = new Scanner (System.in);
String[] word = new String[50];
Random randy = new Random();
int x = randy.nextInt(50);
word[0] = "I'M SO TIRED";
word[1] = "HOW'S YOUR DAY GOING?";
word[2] = "DO YOUR HOMEWORK, RIGHT NOW";
word[3] = "DON'T BE MEAN";
word[4] = "HOW'S YOUR DAY SO FAR";
word[5] = "DON'T SKIP SCHOOL";
word[6] = "GRILLED CHEESE";
word[7] = "COMPUTER SCIENCE";
word[8] = "SUMMER VACATION";
word[9] = "NORTHERN SECONDARY";
word[10] = "I LOVE YOU!";
word[11] = "PLEASE, BE NICE";
word[12] = "GO TO SLEEP";
word[13] = "I WANT FOOD";
word[14] = "SUMMER IS SOON!";
word[15] = "SANDWICH";
word[16] = "HALLOWEEN!";
word[17] = "MONKEY!";
word[18] = "WEEKEND";
word[19] = "FRIDAY";
word[20] = "BAGEL";
word[21] = "COMPUTER";
word[22] = "HOLIDAY";
word[23] = "GOOGLE";
word[24] = "PUPPY";
word[25] = "SUNSHINE";
word[26] = "HOMEWORK";
word[27] = "TORONTO";
word[28] = "HANGMAN";
word[29] = "SNOWSTORM";
word[30] = "FLOWER";
word[31] = "CACTUS";
word[32] = "AUTUMN";
word[33] = "FOOTBALL";
word[34] = "BLUEJAY";
word[35] = "BASEBALL";
word[36] = "TELEVISION";
word[37] = "NETFLIX";
word[38] = "GOOGLE";
word[39] = "IPHONE";
word[40] = "DICTIONARY";
word[41] = "DINNER";
word[42] = "BANANA";
word[43] = "STRAWBERRY";
word[44] = "PIZZA";
word[45] = "BREAKFAST";
word[46] = "GRADUATION";
word[47] = "UNIVERSITY";
word[48] = "LEMONADE";
word[49] = "EYEBALL";
String wordGuess= word[x];//gets a randomly generated string from the string array
char [] phrase = new char[wordGuess.length()];//creates a char array of that string
//from here most of the methods are the same as in the two player version
for(int i = 0; i<wordGuess.length(); i++)
{
phrase[i] = wordGuess.charAt(i);
}
String dashWord = "";
for(int j = 0; j <wordGuess.length(); j++)
{
if(wordGuess.charAt(j)== ' ')
{
dashWord = dashWord+" ";
}
else if(wordGuess.charAt(j)== '!')
{
dashWord = dashWord+"!";
}
else if(wordGuess.charAt(j)== '\'')
{
dashWord = dashWord+"'";
}
else if(wordGuess.charAt(j)== ',')
{
dashWord = dashWord+",";
}
else if(wordGuess.charAt(j)== '?')
{
dashWord = dashWord+"?";
}
else
{
dashWord = dashWord+"_";
}
}
int longWordGuess = 0;
int countWrong = 0;
String previous = "";
int score = 8 - countWrong;
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println(" _____");// area where hangman will be drawn
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
public static void guessValid(char[] phrase,String previous,String dashWord, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
String guess = sc.nextLine();
int guessLength = guess.length();
if (guessLength==2)
{
System.out.println("Please input a different guess");
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
guessBefore(phrase,previous,dashWord, guess, wordGuess, longWordGuess, countWrong);
}
public static void guessBefore(char[] phrase,String previous, String dashWord, String guess, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
char [] before = new char[previous.length()];
for(int j = 0; j<previous.length(); j++)
{
before[j] = previous.charAt(j);
}
for(int i = 0; i<previous.length(); i++)
{
if(guess.length()==1)
{
if(before[i]==guess.charAt(0))
{
System.out.println("You have already guessed that letter. Please input another.");
guessValid(phrase,previous,dashWord, wordGuess, longWordGuess, countWrong);
}
}
}
previous = previous+guess;
cases(phrase,previous, guess, dashWord, wordGuess, longWordGuess, countWrong);
}
public static void cases(char[] phrase, String previous, String guess, String dashWord, String wordGuess, int longWordGuess, int countWrong)
{
Scanner sc = new Scanner (System.in);
int wordLength = wordGuess.length();
int guessLength = guess.length();
guess = guess.toUpperCase();
char guess1 = guess.charAt(0);
int correct = 0;
if(guessLength == 1)
{
for(int i = 0; i<wordLength; i++)
{
if(phrase[i]==guess1)
{
dashWord = dashWord.substring(0,i)+guess+dashWord.substring(i+1, wordLength);
correct = 1000;
}
}
if(correct==0)
{
countWrong = countWrong + 1;
}
}
else if(guess.length() != 1)
{
if(guess.equals(wordGuess))
{
gameOver(wordGuess);
}
else
{
longWordGuess = longWordGuess + 1;
if(longWordGuess > 1)
{
countWrong = countWrong + 1;
}
}
}
if(countWrong == 0)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println(" _____");// area where hangman will be drawn
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 1)
{
System.out.println("\f");
System.out.println("GUESS AGAIN!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 6 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 2)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 5 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 3)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 4 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 4)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 3 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 5)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 2 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 6)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 1 incorrect guesses left");
System.out.println(" _____");
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | /");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 7)
{
System.out.println("\f");
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have 0 incorrect guesses left");
System.out.println(" _____");// draw hangman with new piece
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | / \\");
System.out.println(" ___|___");
System.out.println(dashWord);
if(dashWord.equals(wordGuess))
{
gameOver(wordGuess);
}
guessValid(phrase,previous, dashWord, wordGuess, longWordGuess, countWrong);
}
if(countWrong == 8)
{
int score = 8 - countWrong;
System.out.println("\f");// clear screen
System.out.println("START GUESSING!");
System.out.println("\n\n\n\n\n");
System.out.println("You have "+ score + " incorrect guesses left");
System.out.println(" _____");// draw hangman wiht new piece
System.out.println(" | |");
System.out.println(" | o");
System.out.println(" | /|\\");
System.out.println(" | |");
System.out.println(" | _/ \\_");
System.out.println(" ___|___");
System.out.println("GAME OVER :(");
System.out.println("The word was "+wordGuess+"!");
System.out.println("PRESS 4 TO RETURN TO MAIN MENU");
String click = sc.nextLine();
if (click.equals("4"))
{
homescreen();
}
}
}
public static void gameOver(String wordGuess)
{
Scanner sc = new Scanner (System.in);
System.out.println("\f");
System.out.println("The word was "+wordGuess+"!");
System.out.println("Congrats! You Win!");
System.out.println("PRESS 4 TO RETURN TO MAIN MENU");
String click = sc.nextLine();
if (click.equals("4"))
{
homescreen();
}
}
}<file_sep>import java.io.*;
import java.util.*;
public class caucusSimulator
{
public static void simulator()
{
ArrayList<Voter> voters = new ArrayList<Voter>();
data(voters);
int sanders = 0;
int biden = 0;
int warren = 0;
int klobuchar = 0;
int yang = 0;
int buttigieg = 0;
for(int i = 1; i<999; i++)
{
Voter a = new Voter();
a = voters.get(i);
int vote = a.getRealignedVote();
if(vote==0)
{
sanders = sanders + 1;
}
else if(vote==1)
{
biden = biden +1;
}
else if(vote==2)
{
warren = warren +1;
}
else if(vote==3)
{
klobuchar = klobuchar +1;
}
else if(vote==4)
{
yang = yang +1;
}
else if(vote==5)
{
buttigieg = buttigieg +1;
}
}
System.out.println(sanders);
System.out.println(biden);
}
public static ArrayList<Voter> data(ArrayList<Voter> voters)
{
Random randy = new Random();
for(int i = 0; i<1000; i++)
{
Voter voter = new Voter();
int precinct = randy.nextInt(10);
int initialVote = randy.nextInt(6);
int realignedVote = randy.nextInt(6);
voter.setPrecinct(precinct);
voter.setInitialVote(initialVote);
voter.setRealignedVote(realignedVote);
voters.add(voter);
}
return voters;
}
} | f1a1cc29fb1d1f7cb4bdb837619f489e9590da1a | [
"Java"
] | 3 | Java | dibahey/projects | 00736ba1def0aa7db5fee6561258bd9eaf88f9cd | 66289d3a63eb82e59b2cdb3ae455d5a5bb786b36 |
refs/heads/master | <file_sep>// import React , {Component} from "react";
// import ReactDOM from "react-dom";
// import MUIDataTable from "mui-datatables";
// import FormControlLabel from "@material-ui/core/FormControlLabel";
// import Switch from "@material-ui/core/Switch";
// import Cities from "./cities";
// class MUI extends Component {
// render() {
// const columns = [
// {
// name: "Name",
// options: {
// filter: false
// }
// },
// {
// name: "Title",
// options: {
// filter: true
// }
// },
// {
// name: "Location",
// options: {
// filter: true,
// customBodyRender: (value, tableMeta, updateValue) => {
// return (
// <Cities
// value={value}
// index={tableMeta.columnIndex}
// change={event => updateValue(event)}
// />
// );
// }
// }
// },
// {
// name: "Age",
// options: {
// filter: false
// }
// },
// {
// name: "Salary",
// options: {
// filter: true,
// customBodyRender: (value, tableMeta, updateValue) => {
// const nf = new Intl.NumberFormat("en-US", {
// style: "currency",
// currency: "USD",
// minimumFractionDigits: 2,
// maximumFractionDigits: 2
// });
// return nf.format(value);
// }
// }
// },
// {
// name: "Active",
// options: {
// filter: true,
// customBodyRender: (value, tableMeta, updateValue) => {
// return (
// <FormControlLabel
// label={value ? "Yes" : "No"}
// value={value ? "Yes" : "No"}
// control={
// <Switch
// color="primary"
// checked={value}
// value={value ? "Yes" : "No"}
// />
// }
// onChange={event => {
// updateValue(event.target.value === "Yes" ? false : true);
// }}
// />
// );
// }
// }
// }
// ];
// const data = [
// ["<NAME>", "Business Analyst", "Los Angeles", 20, 77000, false],
// ["<NAME>", "Business Consultant", "Oklahoma City", 37, 135000, true],
// ["<NAME>", "Attorney", "Pittsburgh", 52, 420000, false],
// ["<NAME>", "Agency Legal Counsel", "Laredo", 30, 150000, true],
// ["<NAME>", "Industrial Analyst", "Austin", 31, 170000, false],
// ["<NAME>", "Business Analyst", "Norfolk", 22, 90000, true],
// ["<NAME>", "Business Consultant", "Chicago", 24, 133000, false],
// [
// "<NAME>",
// "Business Management Analyst",
// "New York",
// 50,
// 295000,
// true
// ],
// ["<NAME>", "Agency Legal Counsel", "Seattle", 28, 200000, false],
// ["<NAME>", "Commercial Specialist", "Long Beach", 65, 400000, true],
// ["<NAME>", "Industrial Analyst", "Hartford", 34, 110000, false],
// ["<NAME>", "Computer Scientist", "Newark", 60, 220000, true],
// ["<NAME>", "Corporate Counselor", "Cincinnati", 52, 180000, false],
// ["<NAME>", "Business Analyst", "Baltimore", 44, 99000, true],
// ["<NAME>", "Agency Legal Counsel", "Tampa", 37, 90000, false],
// ["<NAME>", "Commercial Specialist", "Miami", 39, 140000, true],
// ["<NAME>", "Attorney", "Tucson", 26, 330000, false],
// ["<NAME>", "Computer Scientist", "Memphis", 47, 250000, true],
// ["<NAME>", "Industrial Analyst", "Buffalo", 49, 190000, false],
// ["<NAME>", "Corporate Counselor", "Arlington", 44, 80000, true],
// [
// "<NAME>",
// "Business Process Consultant",
// "Scottsdale",
// 26,
// 45000,
// false
// ],
// ["<NAME>", "Computer Scientist", "San Francisco", 39, 142000, true]
// ];
// const options = {
// filter: true,
// filterType: "dropdown",
// responsive: "scroll"
// };
// return (
// <div className="content-wrapper">
// {/* Content Header (Page header) */}
// <section className="content-header">
// <h1>
// Advanced Table
// <small>Using MUI tables</small>
// </h1>
// <MUIDataTable
// title={"Employee list"}
// data={data}
// columns={columns}
// options={options}
// />
// </section>
// </div>
// );
// }
// }
// export default MUI
import React, { Component } from 'react'
import MaterialTable from 'material-table';
class MUI extends Component {
constructor(props) {
super(props)
this.state = {
columns: [
{ title: 'Name', field: 'name', },
{ title: 'Surname', field: 'surname' },
{ title: 'Birth Year', field: 'birthYear', type: 'numeric' },
{
title: 'Birth Place',
field: 'birthCity',
//lookup: { 34: 'Belgium', 63: 'Şandiageo'},
},
],
data: [
{ name: 'Mattew', surname: 'Georgia', birthYear: 1987, birthCity:'Europe' },
{ name: 'Andrea', surname: 'Buks', birthYear: 1980, birthCity:'Italy' },
{ name: 'Bill', surname: 'Kingsman', birthYear: 1967, birthCity:'France'},
{ name: 'Curt', surname: 'Falan', birthYear: 1969, birthCity:'Belgium' },
{ name: 'Darwin', surname: 'Kolt', birthYear: 1977, birthCity:'Spain' },
{ name: 'Falther', surname: 'Wings', birthYear: 1997, birthCity:'Germany' },
{ name: 'Holten', surname: 'Hops', birthYear: 1987, birthCity:'Uk'},
{ name: 'Kings', surname: 'Walts', birthYear: 1947, birthCity: 'Poland' },
{ name: 'Linda', surname: 'Hanns', birthYear: 1999, birthCity: 'England' },
{ name: 'Daniel', surname: 'Cliff', birthYear: 1937, birthCity:'NewYork'},
{ name: 'Sanderson', surname: 'Williams', birthYear: 1957, birthCity:'Amsterdam' },
{ name: 'Will', surname: 'Smith', birthYear: 1959, birthCity: 'London' },
{ name: 'Peterson', surname: 'Holts', birthYear: 1927, birthCity:"Italy" },
{
name: 'Zether',
surname: 'Fawn',
birthYear: 2000,
birthCity: 'Norway',
},
],
}
}
render() {
return (
<div className="content-wrapper">
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>MUI Tables</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">MUItables</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
<br/>
<MaterialTable
title="Tabular Data"
options={{filtering:true
}}
columns={this.state.columns}
data={this.state.data}
editable={{
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
this.setState((prevState) => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
if (oldData) {
this.setState((prevState) => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: (oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
this.setState((prevState) => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}}
/>
</section>
</div>
)
}
}
export default MUI;
<file_sep>import React from 'react'
import items from './sideData'
var LOGIN_IN = require('../Components/Server/login.json');
export default class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = {
login: LOGIN_IN,
login_in: LOGIN_IN["role"]
}
}
render() {
var login = this.state.login
var login_in = this.state.login_in
if (login.role.clientId === login.userData.clientId) {
var roledata = login_in.permissions.map((role) => {
if (role.privilege[1] === 1) {
return (
<li className="nav-item" >
<a href={role.redirectUrl} className="nav-link">
<i className="nav-icon fas fa-users"></i>
<p>{role.moduleDisplayName}</p>
</a>
</li>
)
}
})
}
const treeItem = items.map((item, name) => {
if ("nav-item has-treeview" === item.className) {
let list = [];
const loop = () => {
for (let i = 0; i < item.sub.length; i++) {
list.push(
<li className="nav-item">
<a href={item.sub[i].path} className="nav-link">
<i className="far fa-circle nav-icon"></i>
<p>{item.sub[i].label}</p>
</a>
</li>)
}
return list
}
return (
<li className="nav-item has-treeview" key={name}>
<a href="#" className="nav-link">
<i className={item.icon}></i>
<p> {item.label}
<i className="right fas fa-angle-left"></i>
</p>
</a>
<ul className="nav nav-treeview">
{loop()}
</ul>
</li>
)
}
else {
return (
<li className="nav-item" key={name}>
<a href={item.path} className="nav-link">
<i className={item.icon}></i>
<p> {item.label} </p>
</a>
</li>
)
}
})
return (
<aside className="main-sidebar sidebar-dark-primary elevation-4">
<a href="#" className="brand-link">
<img src={require("../images/datafoundry1.png")}
alt="DataFoundry Logo"
className="brand-image img-circle elevation-3" />
<span className="brand-text font-weight-light">DataFoundry</span>
</a>
<div className="sidebar">
<div className="user-panel mt-3 pb-3 mb-3 d-flex">
<div className="image">
<img src="../assets/dist/img/user2-160x160.jpg" className="img-circle elevation-2" alt="User Image" />
</div>
<div className="info">
<a href="#" className="d-block"><NAME></a>
</div>
</div>
<nav className="mt-2">
<ul className="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
{treeItem}
{roledata}
</ul>
</nav>
</div>
</aside>
)
}
}<file_sep>import React from 'react';
export default ( props ) => {
const {
loading,
showPrevLink,
showNextLink,
handlePrevClick,
handleNextClick,
} = props;
return (
<div className="nav-link-container"
style={{margin: "20px 0",
display: "flex",
justifyContent: "flex-end"
}}
>
<a
href="#"
className={
`nav-link
${ showPrevLink ? 'show' : 'hide'}
${ loading ? 'greyed-out' : ''
}`
}
onClick={ handlePrevClick }
style={{
color: "#555",
textDecoration: "none",
border: "1px solid #898989",
padding: "10px 20px",
marginRight: "10px"
}}
>
Prev
</a>
<a
href="#"
className={
`nav-link
${ showNextLink ? 'show' : 'hide'}
${ loading ? 'greyed-out' : '' }
`}
onClick={ handleNextClick }
style={{
color: "#555",
textDecoration: "none",
border: "1px solid #898989",
padding: "10px 20px",
marginRight: "10px"
}}
>
Next
</a>
</div>
)
}<file_sep>import React from 'react';
import {Redirect} from 'react-router-dom'
import SimpleReactValidator from './Components/Validations/simple-react-validator'
var LOGIN_INFO = require('./Components/Server/login.json');
class Login extends React.Component {
documentData;
constructor(props) {
super(props);
let documentData = JSON.parse(localStorage.getItem('Auth'));
this.state = {
emailId: "",
password: "",
loggedIn: documentData ? true : false
}
this.validator = new SimpleReactValidator();
this.emailId = this.emailId.bind(this);
this.password = this.password.bind(this);
this.login = this.login.bind(this);
}
emailId(event) {
this.setState({ emailId: event.target.value })
}
password(event) {
this.setState({ password: event.target.value })
}
login(event) {
if (this.validator.allValid()) {
alert('You submitted the form and stuff!');
} else {
this.validator.showMessages();
this.forceUpdate();
}
event.preventDefault();
const { emailId, password } = this.state;
if (emailId === LOGIN_INFO.userData.emailId && password === LOGIN_INFO.userData.clientId) {
localStorage.setItem('Auth', JSON.stringify(LOGIN_INFO['jwtToken']));
this.setState({
loggedIn: true
})
} else {
this.setState({
emailId: '',
password: ''
})
}
}
render() {
if (this.state.loggedIn) {
return <Redirect to="/dashboard" />
}
return (
<div className="material-login">
<div className="limiter">
<div className="container-login100">
<div className="wrap-login100">
<div className="login100-form-title" style={{ backgroundImage: 'url(assets/Login/bg-01.jpg)' }}>
<span className="login100-form-title-1">
Sign In
</span>
</div>
<form className="login100-form validate-form">
<div className="wrap-input100 validate-input m-b-26" data-validate="Username is required">
<span className="label-input100">Email</span>
<input className="input100" type="text" name="email" placeholder="Enter Email Id" onChange={this.emailId} />
<span className="focus-input100" />
{this.validator.message('email', this.state.email, 'required|email','text-danger')}
</div>
<div className="wrap-input100 validate-input m-b-18" data-validate="Password is required">
<span className="label-input100">Password</span>
<input className="input100" type="<PASSWORD>" name="pass" placeholder="Enter Password" onChange={this.password} />
<span className="focus-input100" />
{this.validator.message('password', this.state.password, 'required|min:4|max:10','text-danger')}
</div>
<div className="flex-sb-m w-full p-b-30">
<div className="contact100-form-checkbox">
<input className="input-checkbox100" id="ckb1" type="checkbox" name="remember-me" />
<label className="label-checkbox100" htmlFor="ckb1">
Remember me
</label>
</div>
<div className="forgot">
<a href="/#" className="txt1">
Forgot Password?
</a>
<div className="register">
<a href="/#" className="txt1">
Register a new membership
</a>
</div>
</div>
</div>
<div className="container-login100-form-btn">
<button className="login100-form-btn" type="submit" onClick={this.login}>
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
export default Login;
<file_sep>import React from 'react'
import SimpleReactValidator from './simple-react-validator';
export default class Form extends React.Component {
constructor(props) {
super(props)
this.state = {
userName: "",
phone: ""
}
this.validator = new SimpleReactValidator();
this.userName = this.userName.bind(this);
this.phone = this.phone.bind(this);
this.submitForm = this.submitForm.bind(this);
}
userName(event) {
this.setState({ userName: event.target.value })
}
phone(event) {
this.setState({ phone: event.target.value })
}
submitForm(event) {
event.preventDefault();
if (this.validator.allValid()) {
alert('You submitted the form and stuff!');
} else {
this.validator.showMessages();
this.forceUpdate();
}
}
render() {
return (
<div className="content-wrapper">
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>General Form</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="#">Home</a></li>
<li className="breadcrumb-item active">General Form</li>
</ol>
</div>
</div>
</div>
</section>
<section className="content">
<div className="container-fluid">
<div className="row">
<div className="col-md-6">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">Quick Example</h3>
</div>
<form role="form" >
<div className="card-body">
<div className="form-group">
<label >User Name</label>
<input type="text" className="form-control" onChange={this.userName} placeholder="Enter User Name" required />
{this.validator.message('Enter User name', this.state.userName, 'required|alpha_num', 'text-danger')}
</div>
<div className="form-group">
<label >Phone</label>
<input type="text" className="form-control" onChange={this.phone} placeholder="Enter Phone Number" required />
{this.validator.message('Enter Phone Number ', this.state.phone, 'required|phone|min:10|max:13', 'text-danger')}
</div>
<div className="form-group">
<label >File input</label>
<div className="input-group">
<div className="custom-file">
<input type="file" className="custom-file-input" />
<label className="custom-file-label" >Choose file</label>
</div>
<div className="input-group-append">
<span className="input-group-text" >Upload</span>
</div>
</div>
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" />
<label className="form-check-label" >Check me out</label>
</div>
</div>
<div className="card-footer">
<button type="submit" className="btn btn-primary" onClick={this.submitForm}>Submit</button>
</div>
</form>
</div></div></div></div></section></div>
)
}
}
<file_sep>import React, { Component } from 'react'
export class Sliders extends Component {
render() {
return (
<div>
{/* Content Wrapper. Contains page content */}
<div className="content-wrapper">
{/* Content Header (Page header) */}
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>Sliders</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">Sliders</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
{/* Main content */}
<section className="content">
<div className="container-fluid">
<div className="row">
<div className="col-12">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">Ion Slider</h3>
</div>
{/* /.card-header */}
<div className="card-body">
<div className="row margin">
<div className="col-sm-6">
<input id="range_1" type="text" name="range_1" defaultValue />
</div>
<div className="col-sm-6">
<input id="range_2" type="text" name="range_2" defaultValue="1000;100000" data-type="double" data-step={500} data-postfix=" €" data-from={30000} data-to={90000} data-hasgrid="true" />
</div>
</div>
<div className="row margin">
<div className="col-sm-6">
<input id="range_5" type="text" name="range_5" defaultValue />
</div>
<div className="col-sm-6">
<input id="range_6" type="text" name="range_6" defaultValue />
</div>
</div>
<div className="row margin">
<div className="col-sm-12">
<input id="range_4" type="text" name="range_4" defaultValue="10000;100000" />
</div>
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
{/* /.col */}
</div>
{/* /.row */}
<div className="row">
<div className="col-12">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">Bootstrap Slider</h3>
</div>
{/* /.card-header */}
<div className="card-body">
<div className="row margin">
<div className="col-sm-6">
<div className="slider-red">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-red input.slider</p>
<div className="slider-blue">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-blue input.slider</p>
<div className="slider-green">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-green input.slider</p>
<div className="slider-yellow">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-yellow input.slider</p>
<div className="slider-teal">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-teal input.slider</p>
<div className="slider-purple">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<p>.slider-purple input.slider</p>
</div>
<div className="col-sm-6 d-flex justify-content-center">
<div className="slider-red mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<div className="slider-blue mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<div className="slider-green mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<div className="slider-yellow mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<div className="slider-teal mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
<div className="slider-purple mx-3">
<input type="text" defaultValue className="slider form-control" data-slider-min={-200} data-slider-max={200} data-slider-step={5} data-slider-value="[-100,100]" data-slider-orientation="vertical" data-slider-selection="before" data-slider-tooltip="show" />
</div>
</div>
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
{/* /.col */}
</div>
{/* /.row */}
</div>{/* /.container-fluid */}
</section>
{/* /.content */}
</div>
{/* /.content-wrapper */}
</div>
)
}
}
export default Sliders
<file_sep>import React, { Component } from 'react';
import './rolemanagement.css';
var ROLE_MATRIX = require('../Server/rolematrix.json');
class Rolemanagement extends Component {
constructor(props){
super(props);
let role_matrix = JSON.parse(localStorage.getItem('role_matrix'));
if (role_matrix) {
this.state = {
role_matrix: role_matrix
}
} else {
localStorage.setItem('role_matrix', JSON.stringify(ROLE_MATRIX["data"]))
this.state = {
role_matrix: ROLE_MATRIX["data"]
}
}
console.log(this.state.role)
}
render() {
var that = this;
var permissions = function (permission, roleIndex, clientIndex) {
var handlepermission = function (e, perIndex, i) {
var role_matrix = that.state.role_matrix;
role_matrix[clientIndex]['roleList'][roleIndex]['permissions'][perIndex]['privilege'][i] = e.target.checked ? 1 : 0;
that.setState({ role_matrix });
localStorage.setItem('role_matrix', JSON.stringify(role_matrix));
}
return permission.map((per, i) => {
return (
// <div className="row">
// <div className="col-lg-4 permission">
// <lable>{per.moduleDisplayName}</lable>
// </div>
// <div className="col-lg-8">
// <div className="col-lg-2 permission"><input type="checkbox" checked={per.privilege[0] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 0) }} /><label>Create</label></div>
// <div className="col-lg-2 permission"><input type="checkbox" checked={per.privilege[1] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 1) }} /><label>Read</label></div>
// <div className="col-lg-2 permission"><input type="checkbox" checked={per.privilege[2] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 2) }} /><label>Update</label></div>
// <div className="col-lg-2 permission"><input type="checkbox" checked={per.privilege[3] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 3) }} /><label>Delete</label></div>
// </div>
// </div>
<tr >
<td>{per.moduleDisplayName}</td>
<td><input type="checkbox" checked={per.privilege[0] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 0) }} />Create</td>
<td><input type="checkbox" checked={per.privilege[1] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 1) }} />Read</td>
<td><input type="checkbox" checked={per.privilege[2] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 2) }} />Update</td>
<td><input type="checkbox" checked={per.privilege[3] == 0 ? false : true} onChange={(e) => { handlepermission(e, i, 3) }} />Delete</td>
</tr>
)
})
}
var rolList = function (rolelist, clientIndex) {
return rolelist.map((role, roleIndex) => {
return (
<div className="row">
<div className="col-lg-11">
<div className="card">
<div className="box-header with-border">
<div className="card-header" id="heading-1-1-1">
<h5 className="mb-0">
<a className="collapsed" role="button" data-toggle="collapse" href={"#collapse-1-1-"+ roleIndex} aria-expanded="false" aria-controls={"#collapse-1-1-"+ roleIndex}>
<i className="fa fa-user"></i> <label>{role.roleDisplayName}</label>
</a>
</h5>
</div>
</div>
<div id={"collapse-1-1-" + roleIndex} className="collapse" data-parent="#accordion-1-1" aria-labelledby="heading-1-1-1">
<div className="card-body">
<table className="table nowrap">
<tbody>
{permissions(role.permissions, roleIndex, clientIndex, that)}
</tbody>
</table>
<button type="submit" className="modifybtn">Modify</button>
</div>
</div>
</div>
</div>
<div className="col-lg-1">
<i className="fa fa-edit"></i>
</div>
</div>
)
})
}
var clients = this.state.role_matrix.map((client, clientIndex) => {
return (
<div className="box">
<div className="box-header with-border">
<div id="collapse-1" className="collapse show" data-parent="#accordion" aria-labelledby="heading-1">
<div className="card">
<div id="accordion-1">
<div className="card-header with-border">
<div className="card-header" id="heading-1-1">
<h5 className="mb-0">
<a className="collapsed" role="button" data-toggle="collapse" href={"#collapse-1-" + clientIndex} aria-expanded="false" aria-controls={"collapse-1-" + clientIndex}>
<i className="fa fa-users"></i><label>{client.clientName}</label>
</a>
</h5>
</div>
<div id={"collapse-1-" + clientIndex} className="collapse" data-parent="#accordion-1" aria-labelledby="heading-1-1">
<div className="card-body">
<div id="accordion-1-1">
<br />
{/* <div className="row">
<div className="col-lg-11"> */}
{rolList(client.roleList, clientIndex)}
{/* </div>
<div className="col-lg-1">
<i className="fa fa-edit"></i>
</div>
</div> */}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
})
return(
<div className="content-wrapper">
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>Rolemanagement Preview</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">Rolemanagement</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
<br/><br/>
{/* AddRole */}
<div className="addicon" >
<i className="fa fa-plus-circle fa-lg" data-toggle="modal" data-target="#addRole"></i>
</div>
{/* AddRole PopUp */}
<div className="modal fade" id="addRole" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title"> Add Role</h4>
<button type="button" className="close" data-dismiss="modal">×</button>
</div>
<div className="modal-body">
<div className="row">
<div className="col-lg-6">
<label> Name*</label>
<input type="text" placeholder="Enter Name"></input>
</div>
<div className="col-lg-6">
<label>Display Name*</label>
<input type="text" placeholder="Enter Display Name"></input>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<label>Client*</label>
<select placeholder="Enter Client">
<option>Select Module</option>
<option>123</option>
<option>456</option>
</select>
</div>
<div className="col-lg-6">
<label>Module*</label>
<select placeholder="Enter Module">
<option>Select Module</option>
<option>123</option>
<option>456</option>
</select>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-primary" >Save</button>
<button type="button" className="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
<div className="content">
{clients}
</div>
</div>
)
}
}
export default Rolemanagement;<file_sep>import React, { Component } from 'react'
export class ProjectAdd extends Component {
render() {
return (
<div>
{/* Content Wrapper. Contains page content */}
<div className="content-wrapper">
{/* Content Header (Page header) */}
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>Project Add</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">Project Add</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
{/* Main content */}
<section className="content">
<div className="row">
<div className="col-md-6">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">General</h3>
<div className="card-tools">
<button type="button" className="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i className="fas fa-minus" /></button>
</div>
</div>
<div className="card-body">
<div className="form-group">
<label htmlFor="inputName">Project Name</label>
<input type="text" id="inputName" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="inputDescription">Project Description</label>
<textarea id="inputDescription" className="form-control" rows={4} defaultValue={""} />
</div>
<div className="form-group">
<label htmlFor="inputStatus">Status</label>
<select className="form-control custom-select">
<option selected disabled>Select one</option>
<option>On Hold</option>
<option>Canceled</option>
<option>Success</option>
</select>
</div>
<div className="form-group">
<label htmlFor="inputClientCompany">Client Company</label>
<input type="text" id="inputClientCompany" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="inputProjectLeader">Project Leader</label>
<input type="text" id="inputProjectLeader" className="form-control" />
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
<div className="col-md-6">
<div className="card card-secondary">
<div className="card-header">
<h3 className="card-title">Budget</h3>
<div className="card-tools">
<button type="button" className="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i className="fas fa-minus" /></button>
</div>
</div>
<div className="card-body">
<div className="form-group">
<label htmlFor="inputEstimatedBudget">Estimated budget</label>
<input type="number" id="inputEstimatedBudget" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="inputSpentBudget">Total amount spent</label>
<input type="number" id="inputSpentBudget" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="inputEstimatedDuration">Estimated project duration</label>
<input type="number" id="inputEstimatedDuration" className="form-control" />
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
</div>
<div className="row">
<div className="col-12">
<a href="#" className="btn btn-secondary">Cancel</a>
<input type="submit" defaultValue="Create new Project" className="btn btn-success float-right" />
</div>
</div>
</section>
{/* /.content */}
</div>
{/* /.content-wrapper */}
</div>
)
}
}
export default ProjectAdd
<file_sep>import React, { Component } from 'react'
export class ProjectEdit extends Component {
render() {
return (
<div>
{/* Content Wrapper. Contains page content */}
<div className="content-wrapper">
{/* Content Header (Page header) */}
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>Project Edit</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">Project Edit</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
{/* Main content */}
<section className="content">
<div className="row">
<div className="col-md-6">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">General</h3>
<div className="card-tools">
<button type="button" className="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i className="fas fa-minus" /></button>
</div>
</div>
<div className="card-body">
<div className="form-group">
<label htmlFor="inputName">Project Name</label>
<input type="text" id="inputName" className="form-control" defaultValue="AdminLTE" />
</div>
<div className="form-group">
<label htmlFor="inputDescription">Project Description</label>
<textarea id="inputDescription" className="form-control" rows={4} defaultValue={"Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terr."} />
</div>
<div className="form-group">
<label htmlFor="inputStatus">Status</label>
<select className="form-control custom-select">
<option selected disabled>Select one</option>
<option>On Hold</option>
<option>Canceled</option>
<option selected>Success</option>
</select>
</div>
<div className="form-group">
<label htmlFor="inputClientCompany">Client Company</label>
<input type="text" id="inputClientCompany" className="form-control" defaultValue="Deveint Inc" />
</div>
<div className="form-group">
<label htmlFor="inputProjectLeader">Project Leader</label>
<input type="text" id="inputProjectLeader" className="form-control" defaultValue="<NAME>" />
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
<div className="col-md-6">
<div className="card card-secondary">
<div className="card-header">
<h3 className="card-title">Budget</h3>
<div className="card-tools">
<button type="button" className="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i className="fas fa-minus" /></button>
</div>
</div>
<div className="card-body">
<div className="form-group">
<label htmlFor="inputEstimatedBudget">Estimated budget</label>
<input type="number" id="inputEstimatedBudget" className="form-control" defaultValue={2300} step={1} />
</div>
<div className="form-group">
<label htmlFor="inputSpentBudget">Total amount spent</label>
<input type="number" id="inputSpentBudget" className="form-control" defaultValue={2000} step={1} />
</div>
<div className="form-group">
<label htmlFor="inputEstimatedDuration">Estimated project duration</label>
<input type="number" id="inputEstimatedDuration" className="form-control" defaultValue={20} step="0.1" />
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
<div className="card card-info">
<div className="card-header">
<h3 className="card-title">Files</h3>
<div className="card-tools">
<button type="button" className="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i className="fas fa-minus" /></button>
</div>
</div>
<div className="card-body p-0">
<table className="table">
<thead>
<tr>
<th>File Name</th>
<th>File Size</th>
<th />
</tr>
</thead>
<tbody>
<tr>
<td>Functional-requirements.docx</td>
<td>49.8005 kb</td>
<td className="text-right py-0 align-middle">
<div className="btn-group btn-group-sm">
<a href="#" className="btn btn-info"><i className="fas fa-eye" /></a>
<a href="#" className="btn btn-danger"><i className="fas fa-trash" /></a>
</div>
</td>
</tr><tr>
<td>UAT.pdf</td>
<td>28.4883 kb</td>
<td className="text-right py-0 align-middle">
<div className="btn-group btn-group-sm">
<a href="#" className="btn btn-info"><i className="fas fa-eye" /></a>
<a href="#" className="btn btn-danger"><i className="fas fa-trash" /></a>
</div>
</td>
</tr><tr>
<td>Email-from-flatbal.mln</td>
<td>57.9003 kb</td>
<td className="text-right py-0 align-middle">
<div className="btn-group btn-group-sm">
<a href="#" className="btn btn-info"><i className="fas fa-eye" /></a>
<a href="#" className="btn btn-danger"><i className="fas fa-trash" /></a>
</div>
</td>
</tr><tr>
<td>Logo.png</td>
<td>50.5190 kb</td>
<td className="text-right py-0 align-middle">
<div className="btn-group btn-group-sm">
<a href="#" className="btn btn-info"><i className="fas fa-eye" /></a>
<a href="#" className="btn btn-danger"><i className="fas fa-trash" /></a>
</div>
</td>
</tr><tr>
<td>Contract-10_12_2014.docx</td>
<td>44.9715 kb</td>
<td className="text-right py-0 align-middle">
<div className="btn-group btn-group-sm">
<a href="#" className="btn btn-info"><i className="fas fa-eye" /></a>
<a href="#" className="btn btn-danger"><i className="fas fa-trash" /></a>
</div>
</td>
</tr></tbody>
</table>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
</div>
<div className="row">
<div className="col-12">
<a href="#" className="btn btn-secondary">Cancel</a>
<input type="submit" defaultValue="Save Changes" className="btn btn-success float-right" />
</div>
</div>
</section>
{/* /.content */}
</div>
{/* /.content-wrapper */}
</div>
)
}
}
export default ProjectEdit
<file_sep>
const items = [
{
name: 'dashboard',
label: 'Dashboard',
icon: "nav-icon fas fa-tachometer-alt",
className: "nav-item has-treeview",
sub: [
{
name: 'dashboard',
label: 'Dashboard V1',
path: '/dashboard',
icon: "far fa-circle nav-icon"
},
{
name: 'dashboard',
label: 'Dashboard V2',
path: '/dashboard2',
icon: "far fa-circle nav-icon"
},
{
name: 'dashboard',
label: 'Dashboard V3',
path: '/dashboard3',
icon: "far fa-circle nav-icon"
}
]
},
{
name: 'widgets',
label: 'Widgets',
path: '/widgets',
icon: "nav-icon fas fa-th",
className: "nav-item"
},
{
name: 'search',
label: 'Search',
path: '/search',
icon: "nav-icon fas fa-th",
className: "nav-item"
},
{
name: 'charts',
label: 'Charts',
icon: "nav-icon fas fa-chart-pie",
className: "nav-item has-treeview",
sub: [
{
name: 'chartjs',
label: 'Chart Js',
path: '/chartjs',
icon: "far fa-circle nav-icon"
},
{
name: 'flot',
label: 'Flot',
path: '/flot',
icon: "far fa-circle nav-icon"
},
{
name: 'inline',
label: 'Inline',
path: '/inline',
icon: "far fa-circle nav-icon"
}
]
},
{
name: 'uielements',
label: 'UI Elements',
icon: "nav-icon fas fa-tree",
className: "nav-item has-treeview",
sub: [
{
name: 'general',
label: 'General',
path: '/general',
icon: "far fa-circle nav-icon"
},
{
name: 'icons',
label: 'Icons',
path: '/icons',
icon: "far fa-circle nav-icon"
},
{
name: 'buttons',
label: 'Buttons',
path: '/buttons',
icon: "far fa-circle nav-icon"
},
{
name: 'sliders',
label: 'Sliders',
path: '/sliders',
icon: "far fa-circle nav-icon"
},
{
name: 'modals',
label: 'Modals & Alerts',
path: '/modals',
icon: "far fa-circle nav-icon"
},
{
name: 'reactToaster',
label: 'React Toaster',
path: '/reactToaster',
icon: "far fa-circle nav-icon"
},
{
name: 'navtab',
label: 'Navbar & Tabs',
path: '/navtab',
icon: "far fa-circle nav-icon"
},
{
name: 'timeline',
label: 'Timeline',
path: '/timeline',
icon: "far fa-circle nav-icon"
},
{
name: 'ribbons',
label: 'Ribbons',
path: '/ribbons',
icon: "far fa-circle nav-icon"
}
]
},
{
name: 'forms',
label: 'Forms',
icon: "nav-icon fas fa-edit",
className: "nav-item has-treeview",
sub: [
{
name: 'generalform',
label: 'General form',
path: '/generalform',
icon: "far fa-circle nav-icon"
},
{
name: 'advancedelements',
label: 'Advanced elements',
path: '/advancedelements',
icon: "far fa-circle nav-icon"
},
{
name: 'editors',
label: 'Editors',
path: '/editors',
icon: "far fa-circle nav-icon"
},
{
name: 'validation',
label: 'Validation',
path: '/form',
icon: "far fa-circle nav-icon"
}
]
},
{
name: 'tables',
label: 'Tables',
icon: "nav-icon fas fa-table",
className: "nav-item has-treeview",
sub: [
{
name: 'simpletable',
label: 'Simple Tables',
path: '/simpletable',
icon: "far fa-circle nav-icon"
},
{
name: 'datatable',
label: 'Data Tables',
path: '/datatable',
icon: "far fa-circle nav-icon"
},
{
name: 'jsgrid',
label: 'js Grid',
path: '/jsgrid',
icon: "far fa-circle nav-icon"
},
{
name: 'mdb',
label: 'MUI',
path: '/mdb',
icon: "far fa-circle nav-icon"
},
{
name: 'reactbootstrap',
label: 'React Bootstrap Table',
path: '/reactbootstrap',
icon: "far fa-circle nav-icon"
},
{
name: 'reactTabulator',
label: 'React Tabulator',
path: '/reactTabulator',
icon: "far fa-circle nav-icon"
}
]
},
{
name: 'calendar',
label: 'Calendar',
path: '/calendar',
icon: "nav-icon fas fa-th",
className: "nav-item"
},
{
name: 'pages',
label: 'Pages',
icon: "nav-icon fas fa-table",
className: "nav-item has-treeview",
sub: [
{
name: 'projects',
label: 'Projects',
path: '/projects',
icon: "far fa-circle nav-icon"
},
{
name: 'projectadd',
label: 'Project Add',
path: '/projectadd',
icon: "far fa-circle nav-icon"
},
{
name: 'projectedit',
label: 'Project Edit',
path: '/projectedit',
icon: "far fa-circle nav-icon"
},
{
name: 'projectdetails',
label: 'Project Details',
path: '/projectdetails',
icon: "far fa-circle nav-icon"
},
{
name: 'contacts',
label: 'Contacts',
path: '/contacts',
icon: "far fa-circle nav-icon"
}
]
}
]
export default items<file_sep>import React,{Component} from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
class Alerts extends Component {
notifyA=()=> toast.success("Success Notification !",{
position: toast.POSITION.TOP_RIGHT
}, { autoClose: 4000 });
notifyB=()=> toast.info("Info Notification !", {
position: toast.POSITION.TOP_LEFT
},{ autoClose: 3000 });
notifyC=()=> toast.error("Error Notification !", {
position: toast.POSITION.TOP_CENTER
},{ autoClose: 2000 });
notifyD=()=> toast.warning("Warning Notification !", {
position: toast.POSITION.BOTTOM_RIGHT
},{ autoClose: 1000 });
render(){
return (
<div>
{/* Content Wrapper. Contains page content */}
<div className="content-wrapper">
{/* Content Header (Page header) */}
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>
React Toaster
</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active"> React Toaster</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
<div className="card card-success card-outline">
<div className="card-header">
<h3 className="card-title">
<i className="fas fa-edit" />
Toaster Examples
</h3>
</div>
<div className="card-body">
<div class="col-md-3">
<button type="button" onClick={this.notifyA} class="btn btn-block btn-success btn-lg">Launch Success Toast</button>
<ToastContainer />
</div>
<div class="col-md-3">
<button type="button" onClick={this.notifyB} class="btn btn-block btn-info btn-lg">Launch Info Toast</button>
<ToastContainer />
</div>
<div class="col-md-3">
<button type="button" onClick={this.notifyC} class="btn btn-block btn-danger btn-lg">Launch Danger Toast</button>
<ToastContainer />
</div>
<div class="col-md-3">
<button type="button" onClick={this.notifyD} class="btn btn-block btn-warning btn-lg">Launch Warning Toast</button>
<ToastContainer />
</div>
</div>
{/* /.card */}
</div>
</div>
</div>
);
}
}
export default Alerts<file_sep>import React, { Component } from 'react'
export class Ribbons extends Component {
render() {
return (
<div>
{/* Content Wrapper. Contains page content */}
<div className="content-wrapper">
{/* Content Header (Page header) */}
<section className="content-header">
<div className="container-fluid">
<div className="row mb-2">
<div className="col-sm-6">
<h1>Ribbons</h1>
</div>
<div className="col-sm-6">
<ol className="breadcrumb float-sm-right">
<li className="breadcrumb-item"><a href="/dashboard">Home</a></li>
<li className="breadcrumb-item active">Ribbons</li>
</ol>
</div>
</div>
</div>{/* /.container-fluid */}
</section>
{/* Main content */}
<section className="content">
<div className="container-fluid">
<div className="row">
<div className="col-12">
<div className="card card-primary">
<div className="card-header">
<h3 className="card-title">Ribbons</h3>
</div>
{/* /.card-header */}
<div className="card-body">
<div className="row">
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper">
<div className="ribbon bg-primary">
Ribbon
</div>
</div>
Ribbon Default <br />
<small>.ribbon-wrapper.ribbon-lg .ribbon</small>
</div>
</div>
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper ribbon-lg">
<div className="ribbon bg-info">
Ribbon Large
</div>
</div>
Ribbon Large <br />
<small>.ribbon-wrapper.ribbon-lg .ribbon</small>
</div>
</div>
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper ribbon-xl">
<div className="ribbon bg-secondary">
Ribbon Extra Large
</div>
</div>
Ribbon Extra Large <br />
<small>.ribbon-wrapper.ribbon-xl .ribbon</small>
</div>
</div>
</div>
<div className="row mt-4">
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper ribbon-lg">
<div className="ribbon bg-success text-lg">
Ribbon
</div>
</div>
Ribbon Large <br /> with Large Text <br />
<small>.ribbon-wrapper.ribbon-lg .ribbon.text-lg</small>
</div>
</div>
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper ribbon-xl">
<div className="ribbon bg-warning text-lg">
Ribbon
</div>
</div>
Ribbon Extra Large <br /> with Large Text <br />
<small>.ribbon-wrapper.ribbon-xl .ribbon.text-lg</small>
</div>
</div>
<div className="col-sm-4">
<div className="position-relative p-3 bg-gray" style={{height: 180}}>
<div className="ribbon-wrapper ribbon-xl">
<div className="ribbon bg-danger text-xl">
Ribbon
</div>
</div>
Ribbon Extra Large <br /> with Extra Large Text <br />
<small>.ribbon-wrapper.ribbon-xl .ribbon.text-xl</small>
</div>
</div>
</div>
</div>
{/* /.card-body */}
</div>
{/* /.card */}
</div>
{/* /.col */}
</div>
{/* /.row */}
</div>
{/* /.container-fluid */}
</section>
{/* /.content */}
</div>
{/* /.content-wrapper */}
</div>
)
}
}
export default Ribbons
| 3e95d0368dd023ab8173810d9e51198b1c1c38a8 | [
"JavaScript"
] | 12 | JavaScript | lalithaeti/AdminLTE3.0 | 69ed4e25e6581496b89a8b7cd38d813ed37f8a6d | 97e8af5935b74968bfcc887dfb35cc3b80675f4a |
refs/heads/master | <repo_name>fbfb6123/animals-app<file_sep>/README.md
# README
# ツール・ライブラリの名前
G.A.Reward
- G(Goal).A(Achievement).Reward
## 簡単な説明
自分で報酬を設定したうえで、達成に向けて頑張ったことや他人から褒められたことなどを投稿していくモチベーション向上を目的としたアプリ。
## 機能
- 報酬に紐付けられた頑張ったことをDBに保存
- 頑張ったことをより可視化するためにグラフを連携して表示。
## 開発環境
- Ruby 2.5.1
- Rails 5.0.7
- mysql 5.6.47
## 使い方
1. 自身で設定した報酬に対して、左下の入力フォームから頑張ったことを投稿。
- 投稿した内容が入力フォームの上段に表示される。
<img width="1431" alt="c42ecaeb66a8012d43cb019e6ca1dab3" src="https://user-images.githubusercontent.com/60612010/77875324-aeaf5180-728a-11ea-9935-68c36298740c.png">
2. マイページからこれまで設定した報酬一覧を表示して、報酬をクリックすると報酬に紐ついた頑張った事が表示されます。

## movere DB設計
## usersテーブル
|Column|Type|Options|
|------|----|-------|
|email|string|null: false|
|password|string|null: false|
|name|string|null: false|
### Association
- has_many :rewards
- has_many :comments
## rewardsテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false|
|user_id|integer|null: false, foreign_key: true|
### Association
- belongs_to :user
- has_many :comments
## messagesテーブル
|Column|Type|Options|
|------|----|-------|
|text|text|
|user_id|integer|null: false, foreign_key: true|
|reward_id|integer|null: false, foreign_key: true|
### Association
- belongs_to :user
- belongs_to :reward
<file_sep>/app/controllers/messages_controller.rb
class MessagesController < ApplicationController
before_action :set_reward
def index
@message = Message.new
# @reward = Reward.where(user_id: current_user.id)
# @messages = Message.where(user_id: current_user.id)
@messages = @reward.messages.includes(:user)
end
def show
@messages = @reward.messages.includes(:user)
end
def new
@message = Message.all
end
def create
@message = @reward.messages.new(message_params)
if @message.save
redirect_to reward_messages_path(@reward), notice: 'メッセージが送信されました'
else
@messages = @reward.messages.includes(:user)
render :index
end
end
def edit
end
private
def message_params
params.require(:message).permit(:content).merge(user_id: current_user.id)
end
def set_reward
@reward = Reward.find(params[:reward_id])
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
root "rewards#index"
#root "messages#index"
resources :users, only: [:edit, :update]
resources :rewards, only: [:index, :show, :new, :create, :edit, :update] do
resources :messages, only: [:index, :show, :new, :create, :edit, :update]
end
end<file_sep>/app/controllers/rewards_controller.rb
class RewardsController < ApplicationController
def index
@message = Message.new
@reward = Reward.where(user_id: current_user.id)
@rewards = Reward.where(reward_id: params[:reward_id])
@messages = Message.where(user_id: current_user.id)
end
def show
end
def new
@reward = Reward.new
@rewards = Reward.where(user_id: current_user.id)
end
def create
@reward = Reward.new(reward_params)
if @reward.save
redirect_to reward_messages_path(@reward), notice: 'グループを作成しました'
else
render :new
end
end
def edit
@reward = Reward.find(params[:id])
end
def update
@reward = Reward.find(params[:id])
if @reward.update(reward_params)
redirect_to root_path, notice: 'グループを更新しました'
else
render :edit
end
end
private
def reward_params
params.require(:reward).permit(:name, :user_id)
end
end
| 6bb0fb9140fbbe6ac0b5b230bd6ecda4e57134b9 | [
"Markdown",
"Ruby"
] | 4 | Markdown | fbfb6123/animals-app | 9e0ca9f03e823af93eb3dd71fffd60d4ef5c1128 | d2f651f7b52f3c19ca0332d5961131661627e7dd |
refs/heads/master | <repo_name>prologic/bitcask-bench<file_sep>/go.mod
module bitcask-bench
require (
cloud.google.com/go v0.44.3 // indirect
github.com/akrylysov/pogreb v0.0.0-20190204011455-cc74c6f0272e
github.com/coreos/bbolt v1.3.3 // indirect
github.com/coreos/etcd v3.3.15+incompatible // indirect
github.com/coreos/go-semver v0.3.0 // indirect
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect
github.com/dgraph-io/badger v1.6.2
github.com/etcd-io/bbolt v1.3.3
github.com/go-kit/kit v0.9.0 // indirect
github.com/gogo/protobuf v1.3.0 // indirect
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/google/pprof v0.0.0-20190723021845-34ac40c74b70 // indirect
github.com/gorilla/websocket v1.4.1 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.11.0 // indirect
github.com/hashicorp/golang-lru v0.5.3 // indirect
github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/pkg/profile v1.6.0
github.com/prologic/bitcask v0.3.10
github.com/prologic/msgbus v0.1.1 // indirect
github.com/prometheus/client_golang v1.1.0 // indirect
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 // indirect
github.com/prometheus/procfs v0.0.4 // indirect
github.com/rogpeppe/fastuuid v1.2.0 // indirect
github.com/rogpeppe/go-internal v1.3.1 // indirect
github.com/russross/blackfriday v2.0.0+incompatible // indirect
github.com/stretchr/objx v0.2.0 // indirect
github.com/syndtr/goleveldb v1.0.0
github.com/ugorji/go v1.1.7 // indirect
go.etcd.io/bbolt v1.3.3 // indirect
golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472 // indirect
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979 // indirect
golang.org/x/image v0.0.0-20190902063713-cb417be4ba39 // indirect
golang.org/x/mobile v0.0.0-20190830201351-c6da95954960 // indirect
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 // indirect
golang.org/x/sys v0.0.0-20190830142957-1e83adbbebd0 // indirect
golang.org/x/tools v0.0.0-20190830223141-573d9926052a // indirect
google.golang.org/api v0.9.0 // indirect
google.golang.org/appengine v1.6.2 // indirect
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 // indirect
google.golang.org/grpc v1.23.0 // indirect
gopkg.in/vmihailenco/msgpack.v2 v2.9.1 // indirect
honnef.co/go/tools v0.0.1-2019.2.2 // indirect
)
replace github.com/prologic/bitcask => /Users/prologic/Projects/bitcask
<file_sep>/engine.go
package main
import (
"errors"
"os"
"path/filepath"
)
type kvEngine interface {
Put(key []byte, value []byte) error
Get(key []byte) ([]byte, error)
Close() error
FileSize() (int64, error)
}
type engineCtr func(string) (kvEngine, error)
var engines = map[string]engineCtr{
"pogreb": newPogreb,
"goleveldb": newGolevelDB,
"bbolt": newBbolt,
"badger": newBadger,
"bitcask": newBitcask,
}
func getEngineCtr(name string) (engineCtr, error) {
if ctr, ok := engines[name]; ok {
return ctr, nil
}
return nil, errors.New("unknown engine")
}
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
<file_sep>/bbolt.go
package main
import (
"github.com/etcd-io/bbolt"
)
var boltBucketName = []byte("benchmark")
type bboltEngine struct {
db *bbolt.DB
path string
}
func newBbolt(path string) (kvEngine, error) {
db, err := bbolt.Open(path, 0600, nil)
if err != nil {
return nil, err
}
db.NoSync = true
db.Update(func(tx *bbolt.Tx) error {
_, err := tx.CreateBucket(boltBucketName)
return err
})
return &bboltEngine{db: db, path: path}, err
}
func (db *bboltEngine) Put(key []byte, value []byte) error {
return db.db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(boltBucketName)
return b.Put(key, value)
})
}
func (db *bboltEngine) Get(key []byte) ([]byte, error) {
var val []byte
err := db.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(boltBucketName)
val = b.Get(key)
return nil
})
return val, err
}
func (db *bboltEngine) Close() error {
return db.db.Close()
}
func (db *bboltEngine) FileSize() (int64, error) {
return dirSize(db.path)
}
<file_sep>/badger.go
package main
import (
"github.com/dgraph-io/badger"
)
func newBadger(path string) (kvEngine, error) {
opts := badger.DefaultOptions
opts.SyncWrites = false
opts.Dir = path
opts.ValueDir = path
db, err := badger.Open(opts)
return &badgerEngine{db: db, path: path}, err
}
type badgerEngine struct {
path string
db *badger.DB
}
func (db *badgerEngine) Put(key []byte, value []byte) error {
return db.db.Update(func(tx *badger.Txn) error {
return tx.Set(key, value)
})
}
func (db *badgerEngine) Get(key []byte) ([]byte, error) {
var val []byte
err := db.db.View(func(txn *badger.Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
v, err := item.ValueCopy(nil)
if err != nil {
return err
}
val = v
return nil
})
return val, err
}
func (db *badgerEngine) Close() error {
return db.db.Close()
}
func (db *badgerEngine) FileSize() (int64, error) {
return dirSize(db.path)
}
<file_sep>/pogreb.go
package main
import (
"github.com/akrylysov/pogreb"
"github.com/akrylysov/pogreb/fs"
)
func newPogreb(path string) (kvEngine, error) {
return pogreb.Open(path, &pogreb.Options{FileSystem: fs.OS})
}
<file_sep>/run.sh
#!/bin/sh
ENGINES="pogreb goleveldb bbolt badger bitcask"
GOROUTINES="1 10"
go build
for goroutines in ${GOROUTINES}; do
for engine in ${ENGINES}; do
echo "Benchmarking ${engine} with ${goroutines} threads ..."
./bitcask-bench -d ./tmp -c "${goroutines}" -e "${engine}"
done
done
<file_sep>/goleveldb.go
package main
import (
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
)
type goleveldbEngine struct {
db *leveldb.DB
path string
}
func newGolevelDB(path string) (kvEngine, error) {
opts := opt.Options{Compression: opt.NoCompression}
db, err := leveldb.OpenFile(path, &opts)
if err != nil {
return nil, err
}
err = db.CompactRange(util.Range{})
return &goleveldbEngine{db: db, path: path}, err
}
func (db *goleveldbEngine) Put(key []byte, value []byte) error {
return db.db.Put(key, value, nil)
}
func (db *goleveldbEngine) Get(key []byte) ([]byte, error) {
return db.db.Get(key, nil)
}
func (db *goleveldbEngine) Close() error {
return db.db.Close()
}
func (db *goleveldbEngine) FileSize() (int64, error) {
return dirSize(db.path)
}
<file_sep>/benchmark.go
package main
import (
"errors"
"fmt"
"math/rand"
"path"
"runtime"
"sync"
"time"
"github.com/akrylysov/pogreb"
)
func randKey(minL int, maxL int) string {
n := rand.Intn(maxL-minL+1) + minL
buf := make([]byte, n)
for i := 0; i < n; i++ {
buf[i] = byte(rand.Intn(25) + 65)
}
return string(buf)
}
func randValue(rnd *rand.Rand, src []byte, minS int, maxS int) []byte {
n := rnd.Intn(maxS-minS+1) + minS
return src[:n]
}
func forceGC() {
runtime.GC()
time.Sleep(time.Millisecond * 500)
}
func shuffle(a [][]byte) {
for i := len(a) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
}
func generateKeys(count int, minL int, maxL int) [][]byte {
keys := make([][]byte, 0, count)
seen := make(map[string]struct{}, count)
for len(keys) < count {
k := randKey(minL, maxL)
if _, ok := seen[k]; ok {
continue
}
seen[k] = struct{}{}
keys = append(keys, []byte(k))
}
return keys
}
func concurrentBatch(keys [][]byte, concurrency int, cb func(gid int, batch [][]byte) error) error {
wg := &sync.WaitGroup{}
batchSize := len(keys) / concurrency
wg.Add(concurrency)
var err error
for i := 0; i < concurrency; i++ {
batchStart := i * batchSize
batchEnd := (i + 1) * batchSize
if batchEnd > len(keys) {
batchEnd = len(keys)
}
go func(gid int, batch [][]byte) {
err = cb(gid, batch)
wg.Done()
}(i, keys[batchStart:batchEnd])
}
wg.Wait()
return err
}
func printStats(db *pogreb.DB) {
fmt.Printf("%+v\n", db.Metrics())
}
func showProgress(gid int, i int, total int) {
if i%50000 == 0 {
fmt.Printf("Goroutine %d. Processed %d from %d items...\n", gid, i, total)
}
}
func benchmark(engine string, dir string, numKeys int, minKS int, maxKS int, minVS int, maxVS int, concurrency int, progress bool) error {
ctr, err := getEngineCtr(engine)
if err != nil {
return err
}
dbpath := path.Join(dir, "bench_"+engine)
db, err := ctr(dbpath)
if err != nil {
return err
}
fmt.Printf("Number of keys: %d\n", numKeys)
fmt.Printf("Minimum key size: %d, maximum key size: %d\n", minKS, maxKS)
fmt.Printf("Minimum value size: %d, maximum value size: %d\n", minVS, maxVS)
fmt.Printf("Concurrency: %d\n", concurrency)
fmt.Printf("Running %s benchmark...\n", engine)
keys := generateKeys(numKeys, minKS, maxKS)
valSrc := make([]byte, maxVS)
if _, err := rand.Read(valSrc); err != nil {
return err
}
forceGC()
start := time.Now()
err = concurrentBatch(keys, concurrency, func(gid int, batch [][]byte) error {
rnd := rand.New(rand.NewSource(int64(rand.Uint64())))
for i, k := range batch {
if err := db.Put(k, randValue(rnd, valSrc, minVS, maxVS)); err != nil {
return err
}
if progress {
showProgress(gid, i, len(batch))
}
}
return nil
})
if err != nil {
return err
}
if err := db.Close(); err != nil {
return err
}
endsecs := time.Since(start).Seconds()
totalalsecs := endsecs
fmt.Printf("Put: %.3f sec, %d ops/sec\n", endsecs, int(float64(numKeys)/endsecs))
if pdb, ok := db.(*pogreb.DB); ok {
printStats(pdb)
}
shuffle(keys)
db, err = ctr(dbpath)
if err != nil {
return err
}
forceGC()
start = time.Now()
err = concurrentBatch(keys, concurrency, func(gid int, batch [][]byte) error {
for i, k := range batch {
v, err := db.Get(k)
if err != nil {
return err
}
if v == nil {
return errors.New("key doesn't exist")
}
if progress {
showProgress(gid, i, len(batch))
}
}
return nil
})
if err != nil {
return err
}
endsecs = time.Since(start).Seconds()
totalalsecs += endsecs
fmt.Printf("Get: %.3f sec, %d ops/sec\n", endsecs, int(float64(numKeys)/endsecs))
fmt.Printf("Put + Get time: %.3f sec\n", totalalsecs)
sz, err := db.FileSize()
if err != nil {
return err
}
fmt.Printf("File size: %s\n", byteSize(sz))
if pdb, ok := db.(*pogreb.DB); ok {
printStats(pdb)
}
return db.Close()
}
<file_sep>/bitcask.go
package main
import (
"github.com/prologic/bitcask"
)
type bitcaskEngine struct {
db *bitcask.Bitcask
path string
}
func newBitcask(path string) (kvEngine, error) {
db, err := bitcask.Open(path)
if err != nil {
return nil, err
}
return &bitcaskEngine{db: db, path: path}, err
}
func (db *bitcaskEngine) Put(key []byte, value []byte) error {
return db.db.Put(key, value)
}
func (db *bitcaskEngine) Get(key []byte) ([]byte, error) {
val, err := db.db.Get(key)
return val, err
}
func (db *bitcaskEngine) Close() error {
return db.db.Close()
}
func (db *bitcaskEngine) FileSize() (int64, error) {
return dirSize(db.path)
}
<file_sep>/main.go
package main
import (
"flag"
"fmt"
"os"
"github.com/pkg/profile"
)
var (
engine = flag.String("e", "bitcask", "database engine name. pogreb, goleveldb, bbolt, badger, or bitcask")
numKeys = flag.Int("n", 100000, "number of keys")
minKeySize = flag.Int("mink", 16, "minimum key size")
maxKeySize = flag.Int("maxk", 64, "maximum key size")
minValueSize = flag.Int("minv", 128, "minimum value size")
maxValueSize = flag.Int("maxv", 512, "maximum value size")
concurrency = flag.Int("c", 1, "number of concurrent goroutines")
dir = flag.String("d", "", "database directory")
progress = flag.Bool("p", false, "show progress")
profileMode = flag.String("profile", "", "enable profile. cpu, mem, block or mutex")
)
func main() {
flag.Parse()
if *dir == "" {
flag.Usage()
return
}
err := os.MkdirAll(*dir, 0755)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
switch *profileMode {
case "cpu":
defer profile.Start(profile.CPUProfile).Stop()
case "mem":
defer profile.Start(profile.MemProfile).Stop()
case "block":
defer profile.Start(profile.BlockProfile).Stop()
case "mutex":
defer profile.Start(profile.MutexProfile).Stop()
}
if err := benchmark(*engine, *dir, *numKeys, *minKeySize, *maxKeySize, *minValueSize, *maxValueSize, *concurrency, *progress); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
<file_sep>/README.md
# bitcask-bench
Fork of [akrylysov/pogreb-bench](https://github.com/akrylysov/pogreb-bench)
with support for Go11Modules + [prologic/bitcask](https://github.com/prologic/bitcask)
## Usage:
```#!bash
$ go get github.com/prologic/bitcask-bench
$ bitcask-bench -d ./tmp -e bitcask
```
## Benchmarks
Benchmark results on a Macbook 11" Dual core Intel Core i7 with 16GB RAM (~2015 model).
| Engine | Concurrency | Reads/s | Write/s |
| ------------- |:-------------:| --------:| -------:|
| pogreb | 1 | 1028574 | 22838 |
| goleveldb | 1 | 78180 | 78607 |
| bbolt | 1 | 340504 | 13836 |
| badger | 1 | 118662 | 28599 |
| bitcask | 1 | 441101 | 14686 |
| | | | |
| pogreb | 10 | 2011091 | 12805 |
| goleveldb | 10 | 194571 | 82431 |
| bbolt | 10 | 545263 | 7885 |
| badger | 10 | 316895 | 69107 |
| bitcask | 10 | 922374 | 11926 |
| 45d05685cd6fcf67800614976aa6137fa58e706c | [
"Go",
"Go Module",
"Markdown",
"Shell"
] | 11 | Go Module | prologic/bitcask-bench | 3436d9d62e66299ec8cbb7e8ffd0fa036b91d730 | e193cafcbacad6160f3d9a02f5842a6b2c7e24c6 |
refs/heads/master | <repo_name>walterieur/Module_2_2<file_sep>/process_2_2.R
#### load libraries ####
#install.packages("caret", dependencies = TRUE)
#install.packages("gdata", dependencies = TRUE)
#install.packages("pander", dependencies = TRUE)
#install.packages("doMC", dependencies = TRUE)
#install.packages("arules", dependencies = TRUE)
#install.packages("randomForest", dependencies = TRUE)
require(ggplot2)
require(caret)
require(gdata)
require(pander)
require(doMC)
registerDoMC(cores = 4) #make 4 cores avaiable to R
require(arules)
require(randomForest)
require(dplyr)
plotting <- TRUE
training_knn <- TRUE
training_dt <- FALSE
training_gb <- FALSE
training_rf <- FALSE
n_bins_age <- 6 # optimum for 6
n_bins_sal <- 5 # optimum for
n_bins_cre <- 5
#### INPUT ####
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/input")
survey_data <- read.csv("survey.csv", sep = ";", header = TRUE)
predicting_data <- read.csv("predicting.csv", sep = ";", header = TRUE)
summary(survey_data)
str(survey_data) # identify data types to change
#### plots ####
if(plotting){
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/output")
pdf("survey_plots.pdf")
hist(survey_data$brand)
hist(survey_data$salary)
hist(survey_data$age)
dev.off()
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/output")
pdf("predicting_plots.pdf")
hist(predicting_data$salary)
hist(predicting_data$age)
dev.off()
}
#### pre-process survey_data ####
##---------------------------------------------- adressing data type
survey_data$elevel <- as.factor(survey_data$elevel)
survey_data$car <- NULL #get rid of car data
survey_data$zipcode <- as.factor(survey_data$zipcode)
survey_data$brand <- factor(survey_data$brand, levels = c(0,1), labels = c("Acer", "Sony"))
##---------------------------------------------- discretize
survey_data$age <- discretize(survey_data$age, method = "interval", categories = n_bins_age, ordered = TRUE )
survey_data$salary <- discretize(survey_data$salary, method = "interval", categories = n_bins_sal, ordered = TRUE )
survey_data$credit <- discretize(survey_data$credit, method = "interval", categories = n_bins_cre, ordered = TRUE )
##---------------------------------------------- checking
sum(is.na(survey_data)) #check missing data
##--------------------------------------------- generate metrics
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/output")
write.csv(data.frame(summary(survey_data)), file = "survey_summary.csv")
write.csv(data.frame(capture.output(str(survey_data))), file = "survey_structure.csv")
write.csv(survey_data, file = "survey_preprocess.csv")
#### pre-process prediction_data ####
##---------------------------------------------- adressing data type
predicting_data$elevel <- as.factor(predicting_data$elevel)
predicting_data$car <- NULL #get rid of car data
predicting_data$zipcode <- as.factor(predicting_data$zipcode)
predicting_data$brand <- NULL
predicting_data$brand <- NA #brand: 0 -> NA
predicting_data$brand <- factor(predicting_data$brand, levels = c(0,1), labels = c("Acer", "Sony"))
##---------------------------------------------- discretize
predicting_data$age <- discretize(predicting_data$age, method = "interval", categories = n_bins_age, ordered = TRUE )#age 4 groups
predicting_data$salary <- discretize(predicting_data$salary, method = "interval", categories = n_bins_sal, ordered = TRUE )#salary 13 groups
predicting_data$credit <-discretize(predicting_data$credit, method = "interval", categories = n_bins_cre, ordered = TRUE )#credit 5 groups
##---------------------------------------------- checking
sum(is.na(predicting_data)) #check missing data
#### train and test ####
##---------------------------------------------- define train size
set.seed(123)
my_trainsize <- 0.75*seq_len(nrow(survey_data))
my_index <- createDataPartition(survey_data$brand, p = my_trainsize, list = FALSE)
survey_train <- survey_data[my_index, ]
survey_test <- survey_data[-my_index, ]
##---------------------------------------------- define cross-validation
my_ctrl <- trainControl(method = "cv",number = 5, classProbs = TRUE)
#### k-NN ####
if(training_knn){
set.seed(83)
my_knn_1 <- train(brand~ .-credit -zipcode -elevel , data = survey_train, method = "knn", metric = "Accuracy", trControl = my_ctrl, preProc = c("range"), tuneLength = 10)
my_knn_1
p_knn <- c(round(postResample(predict(my_knn_1,survey_test),survey_test$brand), digits = 3))
}
#### decision tree ####
if(training_dt){
set.seed(123)
my_dt_1 <- train(brand~ ., data = survey_train, method = "rpart", metric = "Accuracy", trControl = my_ctrl, tuneLength = 5)
my_dt_1
}
#### GBM ####
if(training_gb){
set.seed(123)
my_gb_1 <- train(brand~ ., data = survey_train, method = "gbm", metric = "Accuracy", trControl = my_ctrl, tuneLength = 5)
my_gb_1
}
#### RF ####
if(training_rf){
set.seed(123)
my_rf <- randomForest(brand~ ., data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p <- c(round(postResample(predict(my_rf,survey_test),survey_test$brand),digits = 2))
set.seed(123)
my_rf_1 <- randomForest(brand~ .-credit, data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p1 <- c(round(postResample(predict(my_rf_1,survey_test),survey_test$brand),digits = 2))
set.seed(123)
my_rf_2 <- randomForest(brand~ .-zipcode, data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p2 <- c(round(postResample(predict(my_rf_2,survey_test),survey_test$brand), digits = 2))
set.seed(123)
my_rf_3 <- randomForest(brand~ .-elevel, data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p3 <- c(round(postResample(predict(my_rf_3,survey_test),survey_test$brand),digits = 2))
set.seed(123)
my_rf_4 <- randomForest(brand~ .-age, data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p4 <- c(round(postResample(predict(my_rf_4,survey_test),survey_test$brand), digits = 2))
set.seed(123)
my_rf_5 <- randomForest(brand~ .-salary, data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p5 <- c(round(postResample(predict(my_rf_5,survey_test),survey_test$brand),digits = 2))
set.seed(123)
my_rf_6 <- randomForest(brand~ .-credit -zipcode -elevel , data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
p6 <- c(round(postResample(predict(my_rf_6,survey_test),survey_test$brand),digits = 2))
table_rf <- data.frame(rbind(p,p1,p2,p3,p4,p5,p6))
colnames(table_rf) <- c("Accuracy","Kappa")
rownames(table_rf) <- c("all","no credit","no zip","no elevel","no age", "no salary", "only age,salary")
table_rf
}else{
set.seed(7)
my_rf_opt <- randomForest(brand~ .-credit -zipcode -elevel , data = survey_train, trControl = my_ctrl, ntree=400, importance = TRUE,proximity =TRUE, tuneLength = 5)
my_rf_opt
p_rf <- c(round(postResample(predict(my_rf_opt,survey_test),survey_test$brand),digits = 3))
p_rf
table_comp <- data.frame(rbind(p_knn,p_rf))
colnames(table_comp) <- c("Accuracy","Kappa")
rownames(table_comp) <- c("kNN","RF")
}
#### prediction ####
my_prediction <- predict(my_knn_1,predicting_data)
summary(my_prediction)
my_prediction
#### Barplot + Error #####
confusionMatrix(my_knn_1)
x_1 <- data.frame(my_prediction)
colnames(x_1) <- c("Brand")
counts_1 <- as.data.frame(table(x_1$Brand))
my_cm <- confusionMatrix(my_knn_1)
my_cmt <- my_cm$table
my_cmt
#calc Errors
acer_error <- my_cmt[1,2]/(my_cmt[1,2]+my_cmt[1,1])
sony_error <- my_cmt[2,1]/(my_cmt[2,1]+my_cmt[2,2])
acer_error
sony_error
counts_1$Error <- c(acer_error, sony_error)
counts_1
names(counts_1)[1] <- "Brand"
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/output")
pdf("plots_technical.pdf")
ggplot(data = counts_1, aes(x = Brand, y = Freq)) + geom_bar(stat = "identity", width = 0.7, fill = "steelblue") +
theme_minimal() +
geom_errorbar(aes(ymin = Freq - Error*Freq, ymax = Freq + Error*Freq), width = 0.2)
dev.off()
#### Business Barplots ####
# create
predicting_reduced <- data.frame(predicting_data)
predicting_reduced$brand <- NULL
predicting_reduced$elevel <- NULL
predicting_reduced$zipcode <- NULL
predicting_reduced$credit <- NULL
predicting_reduced$brand <- my_prediction
str(predicting_reduced)
# Check group_by tutorial
x_2 <- group_by(predicting_reduced, brand, age)
str(x_2)
counts_2 <- summarize(x_2, freq = n())
counts_2
x_3 <- group_by(predicting_reduced, brand, salary)
x_3
counts_3 <- summarize(x_3, freq = n())
counts_3
setwd("/users/walterklaschka/desktop/Ubiqum/R_Data/Module_2_2/output")
pdf("plots_business.pdf")
ggplot() + geom_col(data = counts_3, aes(x = salary, y = freq, fill = brand))
ggplot() + geom_col(data = counts_3, aes(x = salary, y = freq, fill = brand)) +
scale_x_discrete(labels=c("[ 20000, 46000)" = "Low",
"[ 46000, 72000)" = "Low midrange",
"[ 72000, 98000)" = "Midrange",
"[ 98000,124000)" = "High Midrange",
"[124000,150000]" = "High"))
ggplot() + geom_col(data = counts_2, aes(x = age, y = freq, fill = brand))
dev.off()
#### SUMMARY ####
table_comp #comparison of performance metrics kNN vs. RF
| 53991c25ea896e9824f8eac6e538e3b78be92efd | [
"R"
] | 1 | R | walterieur/Module_2_2 | e29ea524c27b5a686137a5c54411798a8360385f | cc8687206e926130a9393a6f8aa793011f46f547 |
refs/heads/master | <repo_name>cran/OSMscale<file_sep>/R/earthDist.R
#' distance between lat-long coordinates
#'
#' Great-circle distance between points at lat-long coordinates.
#' (The shortest distance over the earth's surface).
#' The distance of all the entries is computed relative to the \code{i}th one.
#'
#' @return Vector with distance(s) in km (or units of \code{r}, if \code{r} is changed)
#' @author <NAME>, \email{<EMAIL>}, Aug 2016 + Jan 2017.
#' Angle formula from Diercke Weltatlas 1996, Page 245
#' @seealso \code{\link{degree}} for pre-formatting,
#' \url{http://www.movable-type.co.uk/scripts/latlong.html}
#' @keywords spatial
#' @importFrom berryFunctions getColumn almost.equal
#' @export
#' @examples
#' d <- read.table(header=TRUE, sep=",", text="
#' lat, long
#' 52.514687, 13.350012 # Berlin
#' 51.503162, -0.131082 # London
#' 35.685024, 139.753365") # Tokio
#' earthDist(lat, long, d) # from Berlin to L and T: 928 and 8922 km
#' earthDist(lat, long, d, i=2) # from London to B and T: 928 and 9562 km
#'
#' # slightly different with other formulas:
#' # install.packages("geosphere")
#' # geosphere::distHaversine(as.matrix(d[1,2:1]), as.matrix(d[2,2:1])) / 1000
#'
#'
#' # compare with UTM distance
#' set.seed(42)
#' d <- data.frame(lat=runif(100, 47,54), long=runif(100, 6, 15))
#' d2 <- projectPoints(d$lat, d$long)
#' d_utm <- berryFunctions::distance(d2$x[-1],d2$y[-1], d2$x[1],d2$y[1])/1000
#' d_earth <- earthDist(lat,long, d)[-1]
#' plot(d_utm, d_earth) # distances in km
#' hist(d_utm-d_earth) # UTM distance slightly larger than earth distance
#' plot(d_earth, d_utm-d_earth) # correlates with distance
#' berryFunctions::colPoints(d2$x[-1], d2$y[-1], d_utm-d_earth, add=FALSE)
#' points(d2$x[1],d2$y[1], pch=3, cex=2, lwd=2)
#'
#'
#' @param lat,long Latitude (North/South) and longitude (East/West) coordinates in decimal degrees
#' @param data Optional: data.frame with the columns \code{lat} and \code{long}
#' @param r radius of the earth. Could be given in miles. DEFAULT: 6371 (km)
#' @param i Integer: Index element against which all coordinate pairs
#' are computed. DEFAULT: 1
#'
earthDist <- function(
lat,
long,
data,
r=6371,
i=1L
)
{
# Input coordinates:
if(!missing(data)) # get lat and long from data.frame
{
lat <- getColumn(substitute(lat) , data)
long <- getColumn(substitute(long), data)
}
# coordinate control:
checkLL(lat, long)
# index control:
i <- as.integer(i[1])
# convert degree angles to radians
y1 <- lat[i]*pi/180
x1 <- long[i]*pi/180
y2 <- lat*pi/180
x2 <- long*pi/180
# angle preparation (numerical inaccuracies may lead to 1.0000000000000002):
cosinusangle <- sin(y1)*sin(y2) + cos(y1)*cos(y2)*cos(x1-x2)
cosinusangle <- replace(cosinusangle, cosinusangle>1, 1)
# angle between lines from earth center to coordinates:
angle <- acos( cosinusangle )
samepoint <- almost.equal(x2, x1) & almost.equal(y2, y1) # berryFunctions::almost.equal
angle[samepoint] <- 0 # again, to compensate numerical inaccuracies
# compute great-circle-distance:
r*angle
}
<file_sep>/R/proj.R
#' CRS of various PROJ.4 projections
#'
#' coordinate reference system (CRS) Object for several proj4 character strings.
#' \code{posm} and \code{pll} are taken directly from
#' \code{OpenStreetMap::\link[OpenStreetMap]{osm}} and
#' \code{\link[OpenStreetMap]{longlat}}.
#'
#' @name proj
#' @aliases posm pll putm
#'
#' @return \code{sp::\link[sp]{CRS}} objects for one of: \cr
#' - UTM projection with given zone\cr
#' - Open street map (and google) mercator projection\cr
#' - Latitude Longitude projection\cr
#' @author <NAME>, \email{<EMAIL>}, Aug 2016
#' @seealso \code{\link{projectPoints}}, \code{\link{degree}}
#' @keywords spatial
#' @importFrom sp CRS
#' @export
#' @examples
#' posm()
#' str(posm())
#' posm()@projargs
#' pll()
#' putm(5:14) # Germany
#' putm(zone=33) # Berlin
#'
#' @param long Vector of decimal longitude coordinates (East/West values).
#' Not needed of \code{zone} is given.
#' @param zone UTM (Universal Transverse Mercator) zone, see e.g. \url{https://upload.wikimedia.org/wikipedia/commons/e/ed/Utm-zones.jpg}.
#' DEFAULT: UTM zone at \link{mean} of \code{long}
#'
putm <- function
(
long,
zone=mean(long,na.rm=TRUE)%/%6+31
)
{
if(!missing(long)) checkLL(long=long, lat=0)
sp::CRS(paste0("+proj=utm +zone=",zone," +ellps=WGS84 +datum=WGS84"))
}
#' @export
#' @rdname proj
posm <- function() sp::CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs")
#' @export
#' @rdname proj
pll <- function() sp::CRS("+proj=longlat +datum=WGS84")
<file_sep>/README.md
### intro
`OSMscale` is an R package to easily handle and project lat-long coordinates,
download background maps and add a correct scale bar to 'OpenStreetMap' plots in any map projection.
There are some other spatially related miscellaneous functions as well.
### installation
`OSMscale` is available on CRAN: [](https://cran.r-project.org/package=OSMscale) [](http://www.r-pkg.org/services)
[](http://www.rdocumentation.org/packages/OSMscale)
It relies on [OpenStreetMap](http://blog.fellstat.com/?cat=15) to do the actual work,
thus `rgdal` and `rjava` must be available.
* **On Windows**: Check if Java is available.
There should be no errors when running ` install.packages("rJava") ; library(rJava) ` in R.
If necessary, install [Java](http://www.java.com/de/download/manual.jsp) in the same bit-version as R (eg 64bit).
The Java binary file must be on the [search path](http://www.java.com/en/download/help/path.xml),
which will normally happen automatically.
* **On Linux**: open a terminal (CTRL+ALT+T) and paste (CTRL+SHIFT+V) the following
line by line to install gdal and rJava:
```R
sudo apt update
sudo apt install libgdal-dev libproj-dev
sudo apt-get install r-cran-rjava
R
install.packages("rgdal")
library("rgdal"); library("rJava") # should not return errors
q("no") # to quit R
```
* Now actually install `OSMscale` from within R:
```R
install.packages("OSMscale")
library(OSMscale)
?OSMscale
# To update to the most recent development version:
berryFunctions::instGit("brry/berryFunctions")
berryFunctions::instGit("brry/OSMscale")
```
### basic usage
Assuming a data.frame with lat-long coordinates:
```R
d <- read.table(sep=",", header=TRUE, text=
"lat, long # could e.g. be copied from googleMaps, rightclick on What's here?
55.685143, 12.580008
52.514464, 13.350137
50.106452, 14.419989
48.847003, 2.337213
51.505364, -0.164752")
png("ExampleMap.png", width=4, height=3, units="in", res=150)
map <- pointsMap(lat, long, data=d, type="maptoolkit-topo", proj=putm(d$long), scale=FALSE)
scaleBar(map, abslen=500, y=0.8, cex=0.8)
lines(projectPoints(d$lat, d$long), col="blue", lwd=3)
points(projectPoints(52.386609, 4.877008, to=putm(zone=32)), cex=3, lwd=2, col="purple")
dev.off()
```

### trouble
If direct installation doesn't work, your R version might be too old.
In that case, an update is really recommendable: [r-project.org](https://www.r-project.org/).
If you can't update R, try installing from source (github) via `instGit` as mentioned above.
If that's not possible either, you might be able to `source` some functions from the
[package zip folder](https://github.com/brry/OSMscale/archive/master.zip)
```R
Vectorize(source)(dir("path/you/unzipped/to/OSMscale-master/R", full=T))
```
This creates all R functions as objects in your globalenv workspace (and overwrites existing objects of the same name!).
<file_sep>/R/maxEarthDist.R
#' maximum distance between set of points
#'
#' Maximum great-circle distance between points at lat-long coordinates.
#' This is not computationally efficient.
#' For large datasets, consider pages like \url{http://stackoverflow.com/a/16870359}.
#'
#' @return Single number
#' @author <NAME>, \email{<EMAIL>}, Jan 2017
#' @seealso \code{\link{earthDist}}
#' @keywords spatial
#' @export
#' @examples
#'
#' d <- read.table(header=TRUE, text="
#' x y
#' 9.19 45.73
#' 6.55 58.13
#' 7.71 71.44")
#'
#' plot(d, asp=1, pch=as.character(1:3))
#' earthDist(y,x,d, i=2)
#' earthDist(y,x,d, i=3)
#'
#' maxEarthDist(y,x,d)
#'
#' @param lat,long,data Coordinates for \code{\link{earthDist}}
#' @param r radius for \code{\link{earthDist}}
#'
maxEarthDist <- function(
lat,
long,
data,
r=6371
)
{
if(!missing(data)) # get lat and long from data.frame
{
lat <- getColumn(substitute(lat) , data)
long <- getColumn(substitute(long), data)
}
d <- sapply(seq_along(lat), function(i) earthDist(lat,long,r=r,i=i) )
max(d, na.rm=TRUE)
}
<file_sep>/tests/testthat.R
library(testthat)
library(OSMscale)
test_check("OSMscale")
| 0b59923950c179f7a8c3cf3d352b52d12ef65570 | [
"Markdown",
"R"
] | 5 | R | cran/OSMscale | c3335d3987eae9da9aa7e7f51468afda350b7795 | e11b4569046410d2df08ad0d17e8955962dcf858 |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Oct 20, 2021 at 09:28 AM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.3.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `emp`
--
-- --------------------------------------------------------
--
-- Table structure for table `employee`
--
CREATE TABLE `employee` (
`EmployeeId` int(11) NOT NULL,
`Name` varchar(255) DEFAULT NULL,
`Phone` varchar(23) DEFAULT NULL,
`Address` varchar(255) DEFAULT NULL,
`Deparment` varchar(255) DEFAULT NULL,
`Gender` varchar(255) DEFAULT NULL,
`Email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `employee`
--
INSERT INTO `employee` (`EmployeeId`, `Name`, `Phone`, `Address`, `Deparment`, `Gender`, `Email`) VALUES
(2, 'Ali', '2147483647', 'lahroe', 'bio', 'male', 'malik@jlaf'),
(4, 'Ali', '2147483647', 'lahore', 'male', 'bio', 'malik@aldjksf'),
(5, 'Ahmad', '2147483647', 'lahore', 'Bio', 'male', '<EMAIL>'),
(6, 'Khawar', '0303-1234567', 'House 99, Block-5, johar town, lahore', 'Bio', 'male', '<EMAIL>');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`UserId` int(11) NOT NULL,
`Name` varchar(255) DEFAULT NULL,
`Phone` bigint(13) DEFAULT NULL,
`Address` varchar(255) DEFAULT NULL,
`Gender` varchar(255) DEFAULT NULL,
`Email` varchar(255) DEFAULT NULL,
`UserPassword` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`UserId`, `Name`, `Phone`, `Address`, `Gender`, `Email`, `UserPassword`) VALUES
(10, '<NAME>', 3084957932, 'DHA PAHSE 8 , LAHORE', 'MALE', '<EMAIL>', 'C12345678'),
(11, 'Waqas', 3023456754, 'Ravi Road', 'MALE', '<EMAIL>', 'C0987654321');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `employee`
--
ALTER TABLE `employee`
ADD PRIMARY KEY (`EmployeeId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `employee`
MODIFY `EmployeeId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
// shows database errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
// allows everyone to access your rest-api
header("Access-Control-Allow-Headers: access");
// all header access is allowed
header("Access-Control-Allow-Methods: POST");
//header used to insert data
header("Content-Type: application/json");
// used to return json format
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// the names of the headers that we will be used
// include validations file
include "validation.php";
// include database class
include 'database.php';
class EMPLOYEE extends Database
{
function validate_emp_data($emp_name, $emp_phone, $emp_email)
{
$db = new DATABASE;
$conn = $db->build_connection();
// emp_id(auto_inc) / emp_name / phone // address // gender // email // dept
$vali = new Validate;
$check = false;
// check validity of name
$name = $vali->name_validate($emp_name);
// check validity of phone number
$phone = $vali->phone_validate($emp_phone);
// check validity of email
$email = $vali->email_validate($emp_email);
if($name == true && $phone == true && $email == true)
{
return 1;
}
else
{
return 0;
}
}
function add_emp_data($name, $phone, $address, $department, $gender, $email)
{
$db = new DATABASE;
$conn = $db->build_connection();
$sql = "INSERT into employee (Name, Phone, Address, Deparment, Gender, Email) VALUES
('{$name}', '{$phone}', '{$address}', '{$department}', '{$gender}', '{$email}')";
//$result = $conn->query($sql);
$result = mysqli_query($conn, $sql) or die('failed');
if($result)
{
echo "all ok";
return 1;
}
else
{
echo "something went wrong";
return 0;
}
}
}
//decode input request parameters and store them in an array.
$data = json_decode(file_get_contents("php://input"), true);
$name=$data["name"];
$phone=$data["phone"];
$address=$data["address"];
$department=$data["department"];
$gender=$data["gender"];
$email=$data["email"];
$emp = new EMPLOYEE;
$check = $emp->validate_emp_data($name, $phone, $email);
if($check == 1)
{
echo ("<br>"."Data Valid"."<br>");
$check1 = $emp->add_emp_data($name, $phone, $address, $department, $gender, $email);
echo ("<br>".$check1."<br>");
if($check1 == 1)
{
$display_message = array("Status_code"=>200,"Message"=>"Successfully Data Inserted!");
print_r(json_encode($display_message));
}
else if($check1 == 0)
{
$display_message = array("Status_code"=>200,"Message"=>"Data Not Inserted!");
print_r(json_encode($display_message));
}
}
<file_sep><?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:POST");
require "Database.php";
require "validation.php";
class SearchEmployeeApi {
// This fucntion will take php object , conver to json format and return json
function apiData($tableName,$name)
{
$data = json_decode(file_get_contents("php://input"), true);
$name = $data['Name'];
$db = new Database();
$employee = $db->searchEmployee($tableName,$name);
echo json_encode($employee);
}
}
$tableName = "employ";
$name = null;
$Search = new SearchEmployeeApi();
$Search->apiData($tableName,$name);
?><file_sep><?php
ini_set('display_errors' , 1); //The ini_set function will try to override the configuration found in PHP ini file.
ini_set('display_startup_errors', 1);// It is a directive which determine whether the error will be displayed to the user or will be remain hidden.
error_reporting(E_ALL);
header("Content-Type: Application/json"); //sends browser to inform him what the kind / format of a data he expects.
header("Access-Control-Allow-Origin: *"); //any auccess our given name website
header("Access-Control-Methods: post"); //response-type header. It is used to indicate which HTTP
header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Methods,Access-Control-Allow-Headers,Authorization,X-Requested-With');
include "validation.php";
require "Database.php";
class signup extends Database{
private $email;
private $name;
private $phone;
private $address;
private $password;
private $gender;
private $table_name;
private $data;
private $parameter;
// Function to get the information through the postman
function get_data(){
$data=json_decode(file_get_contents("php://input"),true); //decde input request parameters and store them in an array.
$name=$data["Name"];
$phone=$data["phone"];
$address=$data["address"];
$gender=$data["gender"];
$email=$data["email"];
$password=$data["<PASSWORD>"];
$parameter=array($name,$phone,$address,$gender,$email,$password); //store all data in array(parameter)
if($parameter[0]=="" || $parameter[1]=="" || $parameter[2]=="" || $parameter[4]=="" || $parameter[5]==""){
return false;}
else{ return $parameter; }
}
// Function to validate request input.
function validation($parameter){
$checked=true;
$objV = new Validate();
if(!$objV->name_validate($parameter[0])) { $checked=false; } // validating name
if(!$objV->phone_validate($parameter[1])) { $checked=false; } // validating phone
if(!$objV->email_validate($parameter[4])) { $checked=false; } // validating email
if(!$objV->password_validate($parameter[5])) { $checked=false; } // validating password
return $checked;
}
// function to insert data in data base after successful signup by the user
function insert_data($parameter){
if(self::search_employ_by_email("user",$parameter[4])) //checking whether user already exists or not
{
echo json_encode(array('Message'=>'User Already Exist With This Email','status'=>"409")); //status code 409 because user data added successfuly
}
else{
$table_name="user";
self::insert($table_name,$parameter); //insert data for new user
echo json_encode(array('Message'=>'SignUp Successfully :','status'=>"201")); //status code 201 because user data added successfuly
}
}
}
$objS = new signup(); //create object signup class
$gdata=$objS->get_data(); //function call and get array
if(!$objS->get_data()){ //check get_data return true or false
echo json_encode(array('Message'=>'Please Fill All the Fields :','status'=>"422")); //status code 422 because user not fill important field
}
else{
if($objS->validation($gdata)){
$objS->insert_data($gdata);
}
else{
echo json_encode(array('Message'=>'Please Enter valid Data :','status'=>"422")); //status code 422 because user enter invalid data
}
}
?><file_sep><?php
use DATABASE as GlobalDATABASE;
header("Access-Control-Allow-Origin: *");
// allows everyone to access your rest-api
header("Access-Control-Allow-Headers: access");
// all header access is allowed
header("Access-Control-Allow-Methods: POST");
//header used to insert data
header("Content-Type: application/json");
// used to return json format
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// the names of the headers that we will be used
// include database class
include 'database.php';
class ALL_EMPLOYEE extends Database
{
private $table_name = "employee"; // database user table_name
function display_all_employees()
{
$db = new DATABASE;
$conn = $db->build_connection();
$q2 = "select * from ".$this->table_name." ";
$result = $conn->query($q2);
$data = $result->fetch_all(MYSQLI_ASSOC);
$db->close_connection($conn);
return $data;
}
}
$emp = new ALL_EMPLOYEE;
$db = $emp->display_all_employees();
echo json_encode($db);
?><file_sep><?php
session_start(); //start session
header('Content-Type:application/json'); //Here we set header as json Format
include 'Database.php';
class forgetPassword extends Database {
public function check_email($semail) //email verification it exist or not
{
$conn= self::build_connection(); //connection building with database
$sql = "select * from user WHERE email='{$semail}'"; //check email exist in database or not
echo json_encode($sql);
$result = $conn->query($sql) or die("not working"); //sql query running
echo json_encode($result);
self::close_connection($result); //Close database Connection
if( $semail == "") //if empty request then show error
{
$msg = array("status"=>"204","message"=>"no content recieve"); //message in array form
echo json_encode($msg); //conversion in json form and printing on console
}
else if($result->num_rows > 0) //if value >0 then call inside functiom
{
self::send_email($semail);
}
else
{
$msg = array("status"=>"404","message"=>"result not found"); //if email not exist then show this
echo json_encode($msg);
}
}
public function send_email($remail) //here we genrate password and send to user email
{
$password = rand(1<PASSWORD>,<PASSWORD>); // Random number and set as password
$to_email = "<EMAIL>";
$subject = "email test via php";
$body = "hi,this is your seven digit password(one time pin)-{$password}";
$headers = "from: <EMAIL>";
if (mail($to_email, $subject, $body, $headers)) { //PHP mail Function Use For Sending mail
$msg = array("status"=>"200","message"=>"password send on '{$to_email}'");
echo json_encode($msg);
self::save_password_in_db($password,$remail); //call Function saving password in DATABASE
}
else
{
$msg = array("status"=>"500","message"=>"internal server error"); //Any Error occur
}
}
}
//Data get from user through Postmen
$data = json_decode(file_get_contents('php://input'),true); //Postman Input
$email = $data['email']; //Fecth email in variable
$_SESSION['email'] = $email; //Creating Session for Password_check page for checks
//Object and Function Call
$password = new forgetPassword(); // object initilization of class
$password->check_email($email); // call function through object
?>
<file_sep><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class Database{
public function build_connection(){ //build sql database connection
$conn = new mysqli("localhost","root","","employee");
if ($conn->connect_error){
echo "Database Connection Error";
}
else{
return $conn;
}
}
public function close_connection($conn){ //close database connection
$conn->close();
}
// This functioon is used to forget save password where email
public function save_password_in_db($password,$email) //here we set password in database
{
$conn = self::build_connection(); //connectivity with database
$sql = "update user set userPassword='{$password}' where Email='{$email}'"; // set password
$result = $conn->query($sql) or exit("sql query failed"); //Running Query
self::close_connection($conn); //connection close with database
}
// This function is used to select user from table with the specific email.
function search_employ_by_email($tableName,$email) // searching employee by email
{
$conn = self::build_connection();
$sql = "select * from ".$tableName ." WHERE email='{$email}'";
$result = $conn->query($sql);
self::close_connection($conn);
if($result->num_rows > 0){
return true;
}
else{
return false;
}
}
// This functioon is used to search employee with specific name.
function searchEmployee($tableName,$name){
$conn = self::build_connection();
$sql = "SELECT * FROM ".$tableName ." WHERE Name LIKE '%{$name}%'";
$result = $conn->query($sql) or die("SQL Query Failed.");
if(mysqli_num_rows($result) > 0 ){
$output = $result->fetch_all();
return $output;
}else{
return json_encode(array('No Search Found.'));
}
self::close_connection($conn);
}
// Function to insert user or Employee in database.
function insert($tableName,$perameter){
if ($tableName == "user"){
$innerPera = "Name,phone,address,gender,email,userPassword";
}else{
$innerPera = "Name,Phone,Address,Deparment,Gender,Email";
}
$S = implode("','",$perameter);
$data = "'".$S."'";
$conn = self::build_connection();
$sql = "insert into $tableName($innerPera) values($data)";
$conn->query($sql);
self::close_connection($conn);
}
}
?>
<file_sep>
# EMPLOYEE MANAGEMENT SYSTEM
The purpose of this project is to develop an management system where new user register it's employees.
## Documentation
The Documentation is avaliable at [click here](https://github.com/90-HAQ/Employee-Management/blob/main/SRS_Document.docx)
## Features
- User Sign up
- User Login
- Add Employee
- Search Employee
- Employee Listing
- Forget Password
## Installation
Install XAMPP.
Install Postman.
Open Xampp Control Panel and start [apache] and [mysql].
Download project from
github(github link)
OR follow gitbash commands
```bash
cd C:\\xampp\htdocs\
git clone https://github.com/90-HAQ/Employee-Management.git
```
extract files in C:\xampp\htdocs.
open link localhost/phpmyadmin.
click on new at side navbar.
give a database name as (emp) hit on create button.
after creating database name click on import.
browse the file in the directory [EmployeeManagement/emp.sql].
## Deployment
To deploy this project run
```bash
Operating System Server : Windows 10
```
## Built With
- PHP
- MYSQLI DATABASES
## Contribution
Contributions are always welcome and appreciated.
## Authors
- [@Khawar Shahzad](https://github.com/khawars282) - Search Employee / User Signup / Forget Password
- [@Hussain Ali](https://github.com/90-HAQ) - User login / Employee List / Add Employee
## Lesson Learned
How to create Rest API using PHP
## Feed Back
If you have any feedback, please reach out to us at <EMAIL>
## Support
For support, email at <EMAIL>
## API Testing
Login API / https://www.getpostman.com/collections/7fe75b69cfe0f0f5c689
Employee_List API / https://www.getpostman.com/collections/f984612a735016252c18
## Screenshots
Screenshot-1

Screenshot-2

Screenshot-3

Screenshot-4

Screenshot-5

Screenshot-6

Screenshot-7

Screenshot-8

Screenshot-9

| 105e6a2323f81c1ca5a5285d481eab628f9189ea | [
"Markdown",
"SQL",
"PHP"
] | 8 | SQL | 90-HAQ/Employee-Management | fe6c49152803ffbe5077dd7108c2819c28eac9b7 | a94d885d506bbf3262fbd488bb973979a38654e8 |
refs/heads/master | <file_sep>import Vue from 'vue'
import * as constants from '@/store/constants'
import * as types from './language_types'
const state = {
languages: []
}
const getters = {
languages: (state) => {
return state.languages
}
}
const mutations = {
setLanguages: (state, payload) => {
state.languages = payload
}
}
const actions = {
[types.FETCH_LANGUAGES] ({commit}) {
let url = constants.apiUrl + '/langs'
Vue.axios.get(url).then(function (response) {
if (response.data.status) {
commit('setLanguages', response.data.result)
}
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Vue from 'vue'
import * as constants from '../../constants'
import * as types from './teams_types'
const state = {
teams: [],
showTeamSelection: false,
showTeamSettings: false,
oaTeam: null
}
const getters = {
teams: (state) => {
return state.teams
},
showTeamSettings: (state) => {
return state.showTeamSettings
},
showTeamSelection: (state) => {
return state.showTeamSelection
},
oaTeam: (state) => {
return state.oaTeam
}
}
const mutations = {
setTeams: (state, payload) => {
console.log('teams.js :: setTeams :: state: ', state)
state.teams = payload
},
showTeamSelection: (state) => {
state.showTeamSelection = true
},
hideTeamSelection: (state) => {
state.showTeamSelection = false
},
showTeamSettings: (state) => {
state.showTeamSettings = true
},
hideTeamSettings: (state) => {
state.showTeamSettings = false
},
setOATeam: (state, payload) => {
state.oaTeam = payload
}
}
const actions = {
async [types.UPDATE_TEAMS] ({commit}, payload) {
let url = constants.apiUrl + '/teams'
let data = {
teams: payload
}
Vue.axios.post(url, data)
},
[types.FETCH_APP_TEAMS] ({commit}, payload) {
return new Promise((resolve, reject) => {
let query = payload
let page = Math.floor(query.offset / query.limit)
let url = constants.apiUrl + '/teams'
let config = {
params: {
...query,
page: page
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
} else {
reject(new Error('error'))
}
}, function (error) {
reject(error)
})
})
},
async [types.FETCH_TEAMS] ({rootGetters, state, commit, dispatch}) {
console.log('action(FETCH_TEAMS)')
let url = constants.oaApiUrl + '/t/teams?include=currency'
let config = {}
await Vue.axios.get(url, config).then(response => {
if (response.data.status) {
dispatch('UPDATE_TEAMS', response.data.result)
console.log('FETCH_TEAMS :: response.data.result : ', response.data.result)
commit('setTeams', response.data.result)
console.log('fetch teams :: teams: ', response.data.result)
}
})
},
async [types.FETCH_TEAM] ({rootGetters, state, commit}) {
console.log('action(FETCH_TEAM)')
let url = constants.oaApiUrl + '/t/teams/' + rootGetters.teamId
await Vue.axios.get(url).then(response => {
if (response.data.status) {
console.log('FETCH_TEAMS :: response.data.result : ', response.data.result)
commit('setOATeam', response.data.result)
console.log('fetch teams :: teams: ', response.data.result)
}
})
},
async [types.FETCH_TEAM_INFO] ({rootGetters, state, commit}) {
console.log('action(FETCH_TEAM_INFO)')
let url = constants.oaApiUrl + '/t/teams?include=currency'
await Vue.axios.get(url).then(response => {
if (response.data.status) {
console.log('FETCH_TEAMS :: response.data.result : ', response.data.result)
commit('setTeams', response.data.result)
console.log('fetch teams :: teams: ', response.data.result)
}
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Vue from 'vue'
import * as constants from '../../constants'
import * as types from './employees_types'
const state = {
selectedEmployeeIds: [],
employees: [],
groups: []
}
const getters = {
employees: state => {
return state.employees
},
selectedEmployeeIds: state => {
return state.selectedEmployeeIds
},
isAllEmployeesSelected: state => {
let result = true
for (var i = 0; i < state.employees.length; i++) {
if (state.selectedEmployeeIds.indexOf(state.employees[i].id) === -1) {
result = false
break
}
}
return result
}
// employeesOfSelectedGroup: state => (group, search) => {
// let employees = []
// if (group === null || group.id === 0) {
// employees = state.employees
// } else {
// employees = group.employees
// }
// if (search.length >= 3) {
// employees = employees.filter(employee => {
// return employee.displayName.toLowerCase().indexOf(search.toLowerCase()) >= 0
// })
// }
// return employees
//
// }
}
const mutations = {
isAllSelected: (state) => {
let result = true
let employee
for (var i = 0; i < state.employees.length; i++) {
employee = state.employees[i]
if (state.selectedEmployeeIds.indexOf(employee.id) === -1) {
result = false
break
}
}
return result
},
clearSelection: (state) => {
state.selectedEmployeeIds = []
}
}
const actions = {
async [types.CLEAR_EMPLOYEE_SELECTION] ({commit}) {
commit('clearSelection')
},
async [types.SELECT_ALL_EMPLOYEES] ({state}) {
let result = []
for (var i = 0; i < state.employees.length; i++) {
result.push(state.employees[i].id)
}
return result
},
async [types.FETCH_EMPLOYEES] ({rootGetters, state, commit, dispatch, getters}) {
let url = constants.oaApiUrl + '/user/employees'
let config = rootGetters.oaApiHeaderConfig
config['params'] = {
state: 'active',
include: 'groups,workingGroups,permissions',
teamId: rootGetters.user.oa_last_team_id
}
await Vue.axios.get(url, config).then(response => {
if (response.data.status) {
commit('setEmployees', response.data.result)
console.log('FETCH_EMPLOYEES: employees: ', response.data.result)
}
})
},
async [types.SELECT_EMPLOYEE] ({commit}, payload) {
commit('selectEmployee', payload)
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>export const FETCH_IR56B_INCOMES = 'FETCH_IR56B_INCOMES'
export const FETCH_IR56F_INCOMES = 'FETCH_IR56F_INCOMES'
// export const UPDATE_INCOME_PARTICULARS = 'UPDATE_INCOME_PARTICULARS'
// export const UPDATE_INCOME_PARTICULAR_PAYTYPES = 'UPDATE_INCOME_PARTICULAR_PAYTYPE'
<file_sep>export default {
items: [
{
name: 'general.dashboard',
url: '/dashboard',
icon: 'icon-speedometer',
badge: {
variant: 'primary',
text: 'NEW'
}
},
{
name: 'tax.ird_forms_management',
url: '/ird_forms',
icon: 'fa fa-file-text',
authRole: 'Payroll Management'
},
{
name: 'tax.apply_for_computerized_form_approval',
url: '/apply_for_approval',
icon: 'fa fa-file-text',
authRole: 'Payroll Management'
},
{
name: 'tax.salary_tax_records',
url: '/my_ird_forms',
icon: 'fa fa-file-text'
}
// {
// name: 'tax.notification_to_ird',
// url: '/ird_forms_xxx',
// icon: 'fa fa-file-text',
// children: [
// {
// name: 'tax.employee_commencement',
// url: '/employee_commencement',
// icon: 'fa fa-file-text'
// },
// {
// name: 'tax.employee_termination',
// url: '/employee_termination',
// icon: 'fa fa-file-text'
// },
// {
// name: 'tax.employee_departure_from_hk',
// url: '/employee_departure',
// icon: 'fa fa-file-text'
// },
// {
// name: 'tax.employee_salary',
// url: '/employee_salary',
// icon: 'fa fa-file-text'
// }
// ]
// },
// {
// name: 'tax.tax_forms',
// url: '/tax_forms',
// icon: 'fa fa-file-text',
// badge: {}
// },
// {
// name: 'mpf.mpf_management',
// url: '/mpf_management',
// icon: 'fa fa-dollar',
// badge: {}
// }
// ,
// {
// title: true,
// name: 'UI elements'
// },
// {
// name: 'Custom',
// url: '/custom',
// icon: 'icon-settings',
// children: [
// {
// name: 'Drag Drop Tree',
// url: '/custom/dragdrop_tree',
// icon: 'icon-share'
// },
// {
// name: 'Draggable Tree',
// url: '/custom/draggable_tree',
// icon: 'icon-share'
// },
// {
// name: 'Vue Drag Tree',
// url: '/custom/vue_drag_tree',
// icon: 'icon-share'
// },
// {
// name: 'Sortable Tree',
// url: '/custom/sortable_tree',
// icon: 'icon-share'
// },
// {
// name: 'Vue Draggable',
// url: '/custom/vue_draggable',
// icon: 'icon-share'
// },
// {
// name: 'Vue2 DataTable',
// url: '/custom/vue2_datatable',
// icon: 'icon-share'
// }
// ]
// },
// {
// name: 'Bootstrap',
// url: '/bootstrap',
// icon: 'icon-settings',
// children: [
// {
// name: 'Alerts',
// url: '/bootstrap/alerts',
// icon: 'icon-link'
// },
// {
// name: 'Badge',
// url: '/bootstrap/badge',
// icon: 'icon-link'
// },
// {
// name: 'Breadcrumb',
// url: '/bootstrap/breadcrumb',
// icon: 'icon-link'
// },
// {
// name: 'Buttons',
// url: '/bootstrap/buttons',
// icon: 'icon-link'
// },
// {
// name: 'Button Group',
// url: '/bootstrap/button_group',
// icon: 'icon-link'
// },
// {
// name: 'Button Toolbar',
// url: '/bootstrap/button_toolbar',
// icon: 'icon-link'
// },
// {
// name: 'Carousel',
// url: '/bootstrap/carousel',
// icon: 'icon-link'
// },
// {
// name: 'Collapse',
// url: '/bootstrap/collapse',
// icon: 'icon-link'
// },
// {
// name: 'Dropdown',
// url: '/bootstrap/dropdown',
// icon: 'icon-link'
// },
// {
// name: 'Forms',
// url: '/bootstrap/forms',
// icon: 'icon-link'
// },
// {
// name: 'InputGroups',
// url: '/bootstrap/inputgroup',
// icon: 'icon-link'
// },
// {
// name: 'Jumbotron',
// url: '/bootstrap/jumbotron',
// icon: 'icon-link'
// },
// {
// name: 'ListGroup',
// url: '/bootstrap/listgroup',
// icon: 'icon-link'
// },
// {
// name: 'Modal',
// url: '/bootstrap/modal',
// icon: 'icon-link'
// }
//
// ]
// },
// {
// name: 'Vue Plugins',
// url: '/vueplugins',
// icon: 'icon-puzzle',
// children: [
// {
// name: 'VToolTip',
// url: '/vueplugins/vtooltip',
// icon: 'icon-puzzle'
// }
// ]
// },
// {
// name: 'Components',
// url: '/components',
// icon: 'icon-puzzle',
// children: [
// // {
// // name: 'Alerts',
// // url: '/components/alerts',
// // icon: 'icon-puzzle'
// // },
// {
// name: 'Buttons',
// url: '/components/buttons',
// icon: 'icon-puzzle'
// },
//
// {
// name: 'Social Buttons',
// url: '/components/social-buttons',
// icon: 'icon-puzzle'
// },
// {
// name: 'Cards',
// url: '/components/cards',
// icon: 'icon-puzzle'
// },
// {
// name: 'Forms',
// url: '/components/forms',
// icon: 'icon-puzzle'
// },
// {
// name: 'Modals',
// url: '/components/modals',
// icon: 'icon-puzzle'
// },
// {
// name: 'Switches',
// url: '/components/switches',
// icon: 'icon-puzzle'
// },
// {
// name: 'Tables',
// url: '/components/tables',
// icon: 'icon-puzzle'
// }
// ]
// },
// {
// name: 'Icons',
// url: '/icons',
// icon: 'icon-star',
// children: [
// {
// name: 'Font Awesome',
// url: '/icons/font-awesome',
// icon: 'icon-star'
// },
// {
// name: 'Simple Line Icons',
// url: '/icons/simple-line-icons',
// icon: 'icon-star'
// }
// ]
// },
// {
// name: 'Widgets',
// url: '/widgets',
// icon: 'icon-calculator',
// badge: {
// variant: 'danger',
// text: 'NEW'
// }
// },
// {
// name: 'Charts',
// url: '/charts',
// icon: 'icon-pie-chart'
// },
// {
// divider: true
// },
// {
// title: true,
// name: 'Extras'
// },
// {
// name: 'Pages',
// url: '/pages',
// icon: 'icon-star',
// children: [
// {
// name: 'Product Menu',
// url: '/main_panel/product_menu',
// icon: 'icon-menu'
// },
// {
// name: 'Login',
// url: '/pages/login',
// icon: 'icon-star'
// },
// {
// name: 'Register',
// url: '/pages/register',
// icon: 'icon-star'
// },
// {
// name: 'Error 404',
// url: '/pages/404',
// icon: 'icon-star'
// },
// {
// name: 'Error 500',
// url: '/pages/500',
// icon: 'icon-star'
// }
// ]
// }
]
}
<file_sep>import Vue from 'vue'
import * as constants from '../../constants'
import * as types from './payrolls_types'
const state = {
payrolls: []
}
const getters = {
payrolls: (state) => {
return state.payrolls
}
}
const mutations = {
setPayrolls: (state, payrolls) => {
state.payrolls = payrolls
}
}
const actions = {
async [types.FETCH_PAYROLLS] ({rootGetters, commit}) {
let teamId = rootGetters.teamId
if (teamId) {
let url = constants.oaApiUrl + '/admin/payrolls'
let config = {
...rootGetters.oaApiHeaderConfig,
params: {
teamId: teamId
}
}
await Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
console.log('FETCH_PAYROLLS :: result: ', response.data.result)
commit('setPayrolls', response.data.result)
}
})
}
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Vue from 'vue'
import * as constants from '../../constants'
import * as types from './payTypes_types'
const state = {
payTypes: []
}
const getters = {
payTypes: (state) => {
return state.payTypes
}
}
const mutations = {
setPayTypes: (state, payload) => {
state.payTypes = payload
}
}
const actions = {
async [types.FETCH_PAY_TYPES] ({rootGetters, commit}) {
return new Promise((resolve, reject) => {
let url = constants.oaApiUrl + '/admin/pay_types'
let teamId = rootGetters.teamId
console.log('FETCH_PAY_TYPES :; teamId = ' + teamId)
if (teamId && teamId !== '') {
let config = {
params: {
teamId: teamId
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
commit('setPayTypes', response.data.result)
resolve(response.data.result)
}
})
} else {
resolve([])
}
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Opt from './td-Opt.vue'
import Employees from './td-Employee.vue'
import Status from './td-Status.vue'
import CommonHeader from './td-CommonHeader.vue'
import FormType from './td-FormType.vue'
import Published from './td-Published.vue'
export default {
Opt,
Employees,
Status,
CommonHeader,
FormType,
Published
}
<file_sep>export const FETCH_TEAMS = 'FETCH_TEAMS'
export const FETCH_TEAM = 'FETCH_TEAM'
export const SET_TEAMS = 'SET_TEAMS'
export const FETCH_TEAM_INFO = 'FETCH_TEAM_INFO'
export const UPDATE_TEAMS = 'UPDATE_TEAMS'
export const FETCH_APP_TEAMS = 'FETCH_APP_TEAMS'
<file_sep>import Vue from 'vue'
import * as constants from '@/store/constants'
import * as types from './formRecord_types'
const state = {
}
const getters = {
}
const mutations = {
}
const actions = {
[types.FETCH_FORM_RECORD]: ({rootGetters, commit}, payload) => {
let query = payload
let page = Math.floor(query.offset / query.limit)
return new Promise((resolve, reject) => {
let url = constants.apiUrl + '/forms'
let config = {
...rootGetters.apiHeaderConfig,
params: {
...query,
page: page
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
},
[types.REMOVE_FORM_RECORD]: ({rootGetters, commit}, payload) => {
let formId = payload
return new Promise((resolve, reject) => {
let url = constants.apiUrl + '/forms/' + formId
Vue.axios.delete(url).then(function (response) {
if (response.data.status) {
resolve(true)
} else {
reject(new Error('server error'))
}
}, function (error) {
reject(error)
})
})
},
[types.SAVE_FORM_RECORD]: ({rootGetters, commit}, payload) => {
let form = payload
return new Promise((resolve, reject) => {
let url = constants.apiUrl + '/forms'
let data = form
let config = rootGetters.apiHeaderConfig
Vue.axios.post(url, data, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
},
[types.UPDATE_FORM_RECORD]: ({rootGetters, commit}, payload) => {
let form = payload
return new Promise((resolve, reject) => {
console.log('SAVE_EMPLOYEE_COMMENCEMENT :: payload: ', payload)
let url = constants.apiUrl + '/forms/' + form.id
let data = form
let config = rootGetters.apiHeaderConfig
Vue.axios.put(url, data, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Vue from 'vue'
import * as constants from '@/store/constants'
import * as types from './commencements_types'
// import * as helpers from '@/helpers'
const state = {
commencementForms: []
}
const getters = {
commencementForms: (state) => {
return state.commencementForms
}
// ,
// BLANK_COMMENCEMENT_FORM: () => {
// return {
// id: 0,
// form_no: '',
// form_date: helpers.getToday(),
// status: 'pending',
// subject: '',
//
// }
// }
}
const mutations = {
}
const actions = {
[types.FETCH_EMPLOYEE_COMMENCEMENTS]: ({rootGetters, commit}, payload) => {
let query = payload
let page = Math.floor(query.offset / query.limit)
return new Promise((resolve, reject) => {
console.log('FETCH_EMPLOYEE_COMMENCEMENTS :: payload: ', payload)
let url = constants.apiUrl + '/employee_commencements'
let config = {
...rootGetters.apiHeaderConfig,
params: {
...query,
page: page
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
},
[types.SAVE_EMPLOYEE_COMMENCEMENT]: ({rootGetters, commit}, payload) => {
let form = payload
return new Promise((resolve, reject) => {
console.log('SAVE_EMPLOYEE_COMMENCEMENT :: payload: ', payload)
let url = constants.apiUrl + '/employee_commencements'
let data = form
let config = rootGetters.apiHeaderConfig
Vue.axios.post(url, data, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
},
[types.UPDATE_EMPLOYEE_COMMENCEMENT]: ({rootGetters, commit}, payload) => {
let form = payload
return new Promise((resolve, reject) => {
console.log('SAVE_EMPLOYEE_COMMENCEMENT :: payload: ', payload)
let url = constants.apiUrl + '/employee_commencements/' + form.id
let data = form
let config = rootGetters.apiHeaderConfig
Vue.axios.put(url, data, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>export const FETCH_FORM_RECORD = 'FETCH_FORM_RECORD'
export const SAVE_FORM_RECORD = 'SAVE_FORM_RECORD'
export const UPDATE_FORM_RECORD = 'UPDATE_FORM_RECORD'
export const REMOVE_FORM_RECORD = 'REMOVE_FORM_RECORD'
<file_sep>export default {
items: [
{
titleTag: 'general.account',
menuItems: [
{icon: 'fa-users', popup: 'teamSelection', titleTag: 'team.company_team'},
{icon: 'fa-address-card', link: '/profile', titleTag: 'general.profile'},
// {icon: 'fa-gear', popup: 'teamSettings', titleTag: 'team.team_settings'},
{icon: 'fa-lock', command: 'logout', titleTag: 'login.logout'}
// {icon: 'fa-bell-o', link: '/pages/login', title: 'Updates', badgeClass: 'badge-info', badgeNo: 42},
// {icon: 'fa-envelope-o', title: 'Messages', badgeClass: 'badge-success', badgeNo: 42},
// {icon: 'fa-tasks', title: 'Tasks', badgeClass: 'badge-danger', badgeNo: 42},
// {icon: 'fa-comments', title: 'Comments', badgeClass: 'badge-warning', badgeNo: 42}
]
}
// {
// sectionTitle: 'Settings',
// menuItems: [
// {icon: 'fa-user', title: 'Profile'},
// {icon: 'fa-wrench', title: 'Settings'},
// {icon: 'fa-usd', title: 'Payments'},
// {icon: 'fa-file', title: 'Projects'}
// ]
// },
// {
// sectionTitle: 'System',
// menuItems: [
// // {icon: 'fa-shield', title: 'Lock Account'},
// {icon: 'fa-lock', command: 'logout', title: 'Logout'}
// ]
// }
]
}
<file_sep>export const GET_MEETINGS = 'GET_MEETINGS'
export const SET_MEETINGS = 'SET_MEETINGS'
export const DELETE_MEETING = 'DELETE_MEETING'
export const SET_TEMP_MEETING = 'SET_TEMP_MEETING'
export const SET_TEMP_MEETING_STARTED_AT = 'SET_TEMP_MEETING_STARTED_AT'
export const SET_TEMP_MEETING_ENDED_AT = 'SET_TEMP_MEETING_ENDED_AT'
export const STORE_MEETING = 'CREATE_MEETING'
export const UPDATE_MEETING = 'UPDATE_MEETING'
<file_sep>export const AUTH_REQUEST = 'AUTH_REQUEST'
export const AUTH_REQUEST_OA = 'AUTH_REQUEST_OA'
export const AUTH_SUCCESS = 'AUTH_SUCCESS'
export const AUTH_ERROR = 'AUTH_ERROR'
export const USER_REQUEST = 'USER_REQUEST'
export const AUTH_LOGOUT = 'AUTH_LOGOUT'
<file_sep>//
// vue-tree
// added:
// babel-plugin-syntax-jsx
// babel-plugin-transform-vue-jsx
// babel-helper-vue-jsx-merge-props
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import $ from 'jquery'
import Vue from 'vue'
import * as constants from '@/store/constants'
// import VueRouter from 'vue-router'
import VueMq from 'vue-mq'
import Vue2TouchEvents from 'vue2-touch-events'
import VeeValidate from 'vee-validate'
import 'vue-tree-halower/dist/halower-tree.min.css'
import {VTree} from 'vue-tree-halower'
// import LiquorTree from 'liquor-tree'
// import datePicker from 'vue-bootstrap-datetimepicker'
// import 'eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css'
// import 'eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker-standalone.css'
import VModal from 'vue-js-modal'
import VueDraggable from 'vue-draggable'
import VuejsDialog from 'vuejs-dialog'
import Datatable from 'vue2-datatable-component'
import axios from 'axios'
import VueAxios from 'vue-axios'
import Moment from 'vue-moment'
import VueCookie from 'vue-cookie'
import VueCookies from 'vue-cookies'
import longpress from 'vue-long-press-directive'
import VueSlimScroll from 'vue-slimscroll'
// import customLocale from 'vue2-datatable-component/locale/custom'
// import VueDraggableTree from 'vue-draggable-tree'
// import VueDragTree from 'vue-drag-tree'
import SortableTree from 'vue-sortable-tree'
import { store } from './store/store'
import 'bootstrap'
import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'
// import {Carousel} from 'bootstrap-vue/es/components'
import App from './App'
// import Spinner from './Spinner'
// import router from './router'
import router from './router'
import VTooltip from 'v-tooltip'
// import jQuery from 'jquery'
//
import 'font-awesome/scss/font-awesome.scss'
import 'simple-line-icons/scss/simple-line-icons.scss'
// import 'bootstrap/dist/css/bootstrap.css'
// import 'bootstrap-vue/dist/bootstrap-vue.css'
// window.jQuery = jQuery
// window.$ = jQuery
import i18n from '@/lang/lang.js'
import vSelect from 'vue-select'
window.$ = $
window.jQuery = $
Vue.use(VeeValidate)
Vue.use(VueMq, {
breakpoints: {
mobile: 450,
tablet: 900,
laptop: 1250,
desktop: Infinity
}
})
Vue.use(Vue2TouchEvents, {
disableClick: true,
touchClass: '',
tapTolerance: 10,
swipeTolerance: 30,
longTapTimeInterval: 400
})
Vue.use(VModal, {dynamic: true})
Vue.use(VuejsDialog)
Vue.use(BootstrapVue)
Vue.use(Moment)
Vue.use(VueCookie)
Vue.use(VueCookies)
Vue.use(longpress, {duration: 1000})
Vue.use(VueSlimScroll)
// Vue.use(datePicker)
// Vue.directive('tooltip', VTooltip)
Vue.use(VTooltip)
// Vue.use(LiquorTree)
Vue.use(VueDraggable)
Vue.use(VueAxios, axios)
Vue.use(Datatable)
// Vue.use(Datatable, {customLocale})
Vue.use(VTree)
// Vue.use(VSelectTree)
// Vue.use(Carousel)
// Vue.component('vue-drag-tree', VueDragTree)
Vue.component(SortableTree.name, SortableTree)
Vue.config.productionTip = false
Vue.mixin({
methods: {
formatCurrency: (number) => number.toFixed(2)
}
})
Vue.use(vSelect)
Vue.axios.interceptors.request.use(function (config) {
console.log('axios :: interceptors :: url = ' + config.url + ' headers: ', config.headers)
// alert(JSON.stringify(config))
// console.log('axios.interceptors: config: ', JSON.stringify(config))
// console.log('axios :: store.getters.apiHeaderConfig: ',
// store.getters.apiHeaderConfig)
// console.log('axios :: constants: ', constants)
// console.log('axios :: config.url = ' + config.url)
let promiseConfig = null
if (config.url.indexOf(constants.apiUrl) === 0) {
// console.log('axios :: is app api')
// using app api
// if (config.url.indexOf('oa_token') >= 0) {
// console.log('axios :: store.getters: ', store.getters)
// }
config.headers = store.getters.apiHeaderConfig.headers
// console.log('axios :: using apiUrl')
promiseConfig = Promise.resolve(config)
} else if (config.url.indexOf(constants.oaApiUrl) === 0) {
// console.log('axios :: is oa api')
// using oa api
// Check if oaAuth header applied
if (config.headers['Authorization']) {
promiseConfig = Promise.resolve(config)
} else {
promiseConfig = new Promise((resolve, reject) => {
// console.log('axios (url=' + config.url + ') : ready to refreshOAToken')
store.dispatch('refreshOAToken').then(function (response) {
// console.log('axios :: refreshOAToken : response: ', response)
let headerConfig = {
'Authorization': response.oaTokenType + ' ' + response.oaAccessToken,
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
}
// .getters.oaApiHeaderConfig
// if (headerConfig === null) {
// console.log('axios (oa): url = ' + config.url + ': headerConfig is null')
// reject(config)
// } else {
// console.log('axios (oa): url = ' + config.url + ': headerConfig ok')
config.headers = headerConfig
// console.log('axios :: config.headers: ', config.headers)
resolve(config)
// }
}, function (error) {
alert('refreshOAToken error')
// console.log('axios :: error: ', error)
reject(error)
})
})
}
// if (config.url.indexOf('employees') >= 0) {
// promiseConfig = store.dispatch('refreshOAToken').then(function () {
// config.headers = store.getters.oaApiHeaderConfig.headers
// promiseConfig = Promise.resolve(config)
// Promise.resolve(config)
// })
// } else {
// let headerConfig = store.getters.oaApiHeaderConfig
// if (headerConfig === null) {
// promiseConfig = Promise.reject(config)
// } else {
// config.headers = headerConfig.headers
// promiseConfig = Promise.resolve(config)
// }
// }
// console.log('axios :: using oaApiUrl')
} else {
promiseConfig = config
}
return promiseConfig
})
Vue.filter('formatSize', function (size) {
if (size > 1024 * 1024 * 1024 * 1024) {
return (size / 1024 / 1024 / 1024 / 1024).toFixed(2) + ' TB'
} else if (size > 1024 * 1024 * 1024) {
return (size / 1024 / 1024 / 1024).toFixed(2) + ' GB'
} else if (size > 1024 * 1024) {
return (size / 1024 / 1024).toFixed(2) + ' MB'
} else if (size > 1024) {
return (size / 1024).toFixed(2) + ' KB'
}
return size.toString() + ' B'
})
// Object.defineProperty(Vue.prototype, '$formatter', new Intl.NumberFormat('en-US', {
// style: 'currency',
// currency: 'USD',
// minimumFractionDigits: 2
// }))
/* eslint-disable no-new */
// router.beforeEnter = (to, from, next) => {
// alert('beforeEnter')
// if (to.name !== 'general.login') {
// console.log('beforeEnter this: ', this.app)
// } else {
// next()
// }
// }
// Vue.use(VueRouter)
//
// let router = new VueRouter({
// mode: 'history',
// linkActiveClass: 'open active',
// beforeEach: (to, from, next) => {
// alert('beforeach')
// },
// scrollBehavior: () => ({y: 0}),
// routes: [{
// beforeEnter: (to, from, next) => {
// if (to.name !== 'general.login') {
// console.log('beforeEnter this.app: ', this.app)
// next()
// } else {
// next()
// }
// },
// ...routes
// }]
// })
// let checkToken = () => {
// let token = getCookieToken()
// alert('token = ' + token)
// return true
// }
// export const spinner = new Vue({
// el: '#spinner',
// components: {
// Spinner
// },
// mounted () {
// alert('x')
// }
// })
Vue.mixin({
methods: {
i18nForDatatable: (srcTxt) => {
this.t('database.' + srcTxt)
}
}
})
const myMixin = {
methods: {
getCurrentFiscalYear () {
return 2017
}
}
}
export const app = new Vue({
el: '#app',
router,
store,
i18n,
mixins: [myMixin],
template: '<App/>',
mounted () {
// after current component is mounted
//
// i.e.
// Fue.vue is mounted before
//
},
beforeCreate: function () {
console.log('main.js beforeCreate')
},
// created: function () {
// let token = getCookieToken()
// console.log('main.js created :: token = ' + token)
// },
components: {
App
}
// ,
// methods: {
// checkToken: function () {
// alert('checkToken')
// return true
// }
// }
})
console.log('main.js :: app: ', app)
window['vue'] = app
window.store = store
<file_sep>export const GET_MEETING_ROOMS = 'GET_MEETING_ROOMS'
export const SET_MEETING_ROOMS = 'SET_MEETING_ROOMS'
export const CREATE_MEETING_ROOM = 'CREATE_MEETING_ROOM'
export const UPDATE_MEETING_ROOM = 'UPDATE_MEETING_ROOM'
export const SELECT_ROOM = 'SELECT_ROOM'
<file_sep>import Vue from 'vue'
import * as constants from '@/store/constants'
import * as types from './irdForms_types'
const state = {
irdFormTypes: []
}
const getters = {
irdFormTypes: (state) => {
return state.irdFormTypes
}
}
const mutations = {
setIrdFormTypes: (state, payload) => {
state.irdFormTypes = payload
}
}
const actions = {
[types.FETCH_IRD_FORM_TYPES] ({rootGetters, commit}) {
return new Promise((resolve, reject) => {
let url = constants.apiUrl + '/ird_form_types'
let config = rootGetters.apiHeaderConfig
Vue.axios.get(url, config).then(response => {
if (response.data.status) {
commit('setIrdFormTypes', response.data.result)
resolve(response.data.result)
}
}).then((error) => reject(error))
})
},
[types.FETCH_IRD_FORMS] ({rootGetters, commit}, payload) {
return new Promise((resolve, reject) => {
let query = payload
let page = Math.floor(query.offset / query.limit)
let url = constants.apiUrl + '/ird_forms'
let config = {
...rootGetters.apiHeaderConfig,
params: {
...query,
page: page
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
// commit('setIrdForms', response.data.result)
} else {
reject(new Error('error'))
}
}, function (error) {
reject(error)
})
})
},
[types.FETCH_FORMS] ({rootGetters, commit}, payload) {
let query = payload
let page = Math.floor(query.offset / query.limit)
return new Promise((resolve, reject) => {
let url = constants.apiUrl + '/forms'
let config = {
// ...rootGetters.apiHeaderConfig,
params: {
...query,
page: page
}
}
Vue.axios.get(url, config).then(function (response) {
if (response.data.status) {
resolve(response.data.result)
}
})
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>// GROUPS
export const FETCH_OA_GROUPS = 'FETCH_OA_GROUPS'
export const CLEAR_GROUP_SELECTION = 'CLEAR_GROUP_SELECTION'
export const SELECT_GROUP = 'SELECT_GROUP'
export const CLEAR_GROUP_EMPLOYEE_SELECTION = 'CLEAR_GROUP_EMPLOYEE_SELECTION'
export const SELECT_ALL_GROUP_EMPLOYEES = 'SELECT_ALL_GROUP_EMPLOYEES'
// EMPLOYEES
export const FETCH_EMPLOYEES = 'FETCH_EMPLOYEES'
export const SELECT_EMPLOYEE = 'SELECT_EMPLOYEE'
export const SELECT_ALL_EMPLOYEES = 'SELECT_ALL_EMPLOYEES'
export const CLEAR_EMPLOYEE_SELECTION = 'CLEAR_EMPLOYEE_SELECTION'
export const TOGGLE_EMPLOYEE_SELECTION = 'TOGGLE_EMPLOYEE_SELECTION'
export const TOGGLE_TO_EMPLOYEE = 'TOGGLE_TO_EMPLOYEE'
export const SET_ACTIVE_EMPLOYEE_ID = 'SET_ACTIVE_EMPLOYEE_ID'
export const SET_HOVERING_EMPLOYEE_ID_ACTIVE = 'SET_HOVERING_EMPLOYEE_ID_ACTIVE'
<file_sep>export const FETCH_SELF = 'FETCH_SELF'
export const SET_DB_TEAM = 'SET_DB_TEAM'
<file_sep>import Logo from './TdLogo'
import Opt from './TdOpt'
export default {
Logo,
Opt
}
<file_sep>import AppAside from './Aside2.vue'
import AppAsideSettings from './AsideSettings.vue'
import Breadcrumb from './Breadcrumb.vue'
import Callout from './Callout.vue'
import AppFooter from './Footer.vue'
import AppHeader from './Header.vue'
import AppSidebar from './Sidebar.vue'
// import AppSidebar2 from './Sidebar2.vue'
import Switch from './Switch.vue'
import MyDropdownItem from './MyDropdownItem.vue'
export {
AppAside,
AppAsideSettings,
Breadcrumb,
Callout,
AppFooter,
AppHeader,
AppSidebar,
// AppSidebar2,
Switch,
MyDropdownItem
}
<file_sep>// import {app} from '@/main'
import Vue from 'vue'
import VueRouter from 'vue-router'
import { store } from '@/store/store'
// import Cookie from 'cookie'
// import Cookies from 'js-cookie'
// Containers
import Full from '@/containers/Full'
// Views
// import Dashboard from '@/views/Dashboard'
import OADashboard from '@/views/oa/dashboard/Dashboard'
import OAProfile from '@/views/oa/profile/Profile'
// import Charts from '@/views/Charts'
import Widgets from '@/views/Widgets'
// View: /Auth
// import Login from '@/pages/login'
// import Register from '@/pages/register'
// View: /bootstrapcdn
import Alerts from '@/views/bootstrap/Alerts'
// import Alerts from '@/views/bootstrap/Alerts'
import Badge from '@/views/bootstrap/Badge'
import Breadcrumb from '@/views/bootstrap/Breadcrumb'
import BootstrapButtons from '@/views/bootstrap/Buttons'
import BootstrapButtonGroup from '@/views/bootstrap/ButtonGroup'
import BootstrapButtonToolbar from '@/views/bootstrap/ButtonToolbar'
import Carousel from '@/views/bootstrap/Carousel'
import Collapse from '@/views/bootstrap/Collapse'
import Dropdown from '@/views/bootstrap/Dropdown'
import BootstrapForms from '@/views/bootstrap/Forms'
import InputGroup from '@/views/bootstrap/InputGroup'
import Jumbotron from '@/views/bootstrap/Jumbotron'
import ListGroup from '@/views/bootstrap/ListGroup'
import Modal from '@/views/bootstrap/Modal'
// Application Modules
import AppContainer from '@/containers/AppContainer'
import ProductList from '@/views/products/ProductList'
import AttributeList from '@/views/attributes/AttributeList'
import BundleList from '@/views/bundles/BundleList'
import MenuSectionList from '@/views/menuSections/MenuSectionList'
import VToolTip from '@/views/vueplugins/VToolTip'
// OA - Meetings
import MeetingRoomBookingList from '@/views/oa/meetingRoomBookings/MeetingRoomBookingList'
import MeetingList from '@/views/oa/meetings/MeetingList'
import MeetingRoomList from '@/views/oa/meetingRooms/MeetingRoomList'
import FileManager from '@/views/oa/fileManager/FileManager'
// View: /Components
import Buttons from '@/views/components/Buttons'
import SocialButtons from '@/views/components/SocialButtons'
import Cards from '@/views/components/Cards'
import Forms from '@/views/components/Forms'
import Modals from '@/views/components/Modals'
import Switches from '@/views/components/Switches'
import Tables from '@/views/components/Tables'
// Views - Custom
// Views - DragDropTree
import DragDropTree from '@/views/custom/DragDropTree'
import DraggableTree from '@/views/custom/DraggableTree'
import VueDragTree from '@/views/custom/VueDragTree'
import SortableTree from '@/views/custom/SortableTree'
import VueDraggable from '@/views/custom/VueDraggable'
import Vue2DataTable from '@/views/custom/Vue2DataTable'
// Views - Icons
import FontAwesome from '@/views/icons/FontAwesome'
import SimpleLineIcons from '@/views/icons/SimpleLineIcons'
// Views - pages
import Page404 from '@/views/pages/Page404'
import Page500 from '@/views/pages/Page500'
import Login from '@/views/pages/Login'
import Register from '@/views/pages/Register'
// Main Panel
// import ProductMenu from '@/views/MainPanel/ProductMenu'
// Views - header Pages
import HeaderPage1 from '@/views/headerPages/HeaderPage1'
import HeaderPage2 from '@/views/headerPages/HeaderPage2'
import HeaderPage3 from '@/views/headerPages/HeaderPage3'
// OA
import MpfManagement from '@/views/oa/mpfManagement/MpfManagement'
// import TaxForms from '@/views/oa/taxForms/TaxForms'
import TeamSelection from '@/views/oa/teamSelection/TeamSelection'
import EmployeeCommencement from '@/views/oa/irdForms/employeeCommencement/EmployeeCommencement'
import EmployeeTermination from '@/views/oa/irdForms/employeeTermination/EmployeeTermination'
import EmployeeDeparture from '@/views/oa/irdForms/employeeDeparture/EmployeeDeparture'
import EmployeeSalary from '@/views/oa/irdForms/employeeSalary/EmployeeSalary'
import IrdForms from '@/views/oa/irdForms/IrdForms'
import ApplyForIrdApproval from '@/views/oa/applyForIrdApproval/ApplyForIrdApproval'
import IrdFormSetup from '@/views/oa/irdFormSetup/IrdFormSetup'
import MyIrdForms from '@/views/oa/myIrdForms/MyIrdForms'
// Supervisor Modules
import SuperDashboard from '@/views/oaAdmin/superDashboard/SuperDashboard'
import IrdFormManager from '@/views/oaAdmin/irdFormManager/IrdFormManager'
import TeamManager from '@/views/oaAdmin/teamManager/TeamManager'
// import jQuery from 'jquery'
// window.jQuery = jQuery
// window.$ = jQuery
Vue.use(VueRouter)
// let getCookieToken = () => {
// const cookieStr = process.browser ? document.cookie : this.app.context.req.headers.cookie
// const cookies = Cookie.parse(cookieStr || '') || {}
// return cookies['ccmsToken']
// }
// let checkToken = () => {
// let token = getCookieToken()
// alert('token = ' + token)
// return true
// }
//
const adminModules = [
'/ird_forms', '/ird_forms/setup'
]
// const checkRole = (roles, targetRole) => {
// let result = false
// for (var i = 0; i < roles.length; i++) {
// if (roles[i].name === targetRole) {
// result = true
// break
// }
// }
// return result
// }
const ifAuthenticated = (to, from, next) => {
if (store.getters.languageOptions.length === 0) {
store.dispatch('FETCH_LANGUAGES')
}
if (store.getters.user) {
console.log('ifAuthenticated :: user is defined.')
if (store.getters.isAuthenticated) {
console.log('ifAuthenticated :: is Authenicated')
if (adminModules.indexOf(to.path) >= 0) {
console.log('ifAuthenticated :: modules requires checking')
let isPayrollAdmin = store.getters.isPayrollAdmin
let isOwner = store.getters.isOwner
if (isPayrollAdmin || isOwner) {
next()
} else {
next('/login')
}
// let roles = store.getters.roles
// if (checkRole(roles, 'Payroll Management')) {
// next()
// } else {
// next('/my_ird_forms')
// }
} else {
next()
}
}
} else {
console.log('ifAuthenticated :: user is undefined')
store.dispatch('CHECK_TOKEN', {
callback: function (status) {
let isSupervisor = store.getters.isSupervisor
console.log('CHECK_TOKEN :: callback :: status = ' + (status ? 'yes' : ' no') + ', isSupervisor: ' + (isSupervisor ? 'yes' : 'no'))
if (status) {
if (isSupervisor) {
next()
} else {
store.dispatch('FETCH_OA_USER_EMPLOYEE', 'x').then(function (oaEmployee) {
if (adminModules.indexOf(to.path) >= 0) {
let roles = store.getters.roles
console.log('router/index.js/roles: ', roles)
let isPayrollAdmin = store.getters.isPayrollAdmin
let isOwner = store.getters.isOwner
if (isPayrollAdmin || isOwner) {
next()
} else {
next('/login')
}
// if (checkRole(roles, 'Payroll Management')) {
// next()
// } else {
// console.log('ifAuthenticated :; next(my_ird_forms)')
// next('/my_ird_forms')
// }
// store.dispatch('FETCH_OA_PERMISSIONS').then((roles) => {
// console.log('FETCH OA PERMISSIONS: roles: ', roles)
// if (checkRole(roles, 'Payroll Management')) {
// next()
// } else {
// next('/my_ird_forms')
// }
// })
} else {
next()
}
})
}
} else {
next('/login')
}
}
})
// next('/login')
}
// if (false && store.getters.isAuthenticated) {
// store.dispatch('CHECK_TOKEN', {
// callback: function (status) {
// if (status) {
// if (adminModules.indexOf(to.path) >= 0) {
// let roles = store.getters.roles
// console.log('router/index.js/roles: ', roles)
// if (checkRole(roles, 'Payroll Management')) {
// next()
// } else {
// next('/my_ird_forms')
// }
// // store.dispatch('FETCH_OA_PERMISSIONS').then((roles) => {
// // console.log('FETCH OA PERMISSIONS: roles: ', roles)
// // if (checkRole(roles, 'Payroll Management')) {
// // next()
// // } else {
// // next('/my_ird_forms')
// // }
// // })
// }
// } else {
// next('/login')
// }
// }
// })
// //
// // alert('isAuthenticated is true')
// // next()
// // return
// } else {
// next('/login')
// }
}
// const withPrefix = (prefix, routes) =>
// routes.map((route) => {
// route.path = prefix + route.path
// return route
// })
export default new VueRouter({
mode: 'history',
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
redirect: '/ird_forms',
// beforeEnter: (to, from, next) => {
// alert('beforeEach')
// console.log('app: ', app)
// },
name: 'general.home',
component: Full,
beforeEnter: ifAuthenticated,
// beforeEnter: (from, to, next) => {
// if (checkToken()) {
// next()
// } else {
// next(false)
// }
// },
children: [
// *******************
// Supervisor
// *******************
{
path: '/super_dashboard',
name: 'super.super_dashboard',
component: SuperDashboard
},
{
path: '/ird_form_manager',
name: 'tax.tax_form_manager',
component: IrdFormManager
},
{
path: '/team_manager',
name: 'team.team_manager',
component: TeamManager
},
{
path: '/ird_form_setup',
name: 'tax.ird_form_setup',
component: IrdFormSetup
},
// ********************
// General User
// ********************
{
path: 'profile',
name: 'general.profile',
component: OAProfile
},
{
path: 'dashboard',
name: 'general.dashboard',
component: OADashboard
},
{
path: 'mpf_management',
name: 'mpf.mpf_management',
component: MpfManagement
},
{
path: 'ird_forms',
name: 'tax.ird_forms_management',
component: IrdForms,
children: [
{
path: 'setupx',
name: 'tax.setup'
}
]
},
{
path: 'apply_for_approval',
name: 'tax.apply_for_computerized_form_approval',
component: ApplyForIrdApproval
},
{
path: 'my_ird_forms',
name: 'tax.salary_tax_records',
component: MyIrdForms
// ,
// beforeEnter: ifAuthenticated
},
{
path: 'employee_commencement',
name: 'tax.employee_commencement',
component: EmployeeCommencement
},
{
path: 'employee_termination',
name: 'tax.employee_termination',
component: EmployeeTermination
},
{
path: 'employee_departure',
name: 'tax.employee_departure_from_hk',
component: EmployeeDeparture
},
{
path: 'employee_salary',
name: 'tax.employee_salary',
component: EmployeeSalary
},
// {
// path: 'tax_forms',
// name: 'tax.tax_forms',
// component: TaxForms,
// beforeEnter: ifAuthenticated
// },
{
path: '/app',
redirect: '/app/products',
name: 'Products',
component: AppContainer,
children: [
{
path: 'meeting_rooms',
name: 'Meeting Rooms',
component: MeetingRoomList
},
{
path: 'meeting_room_bookings',
name: 'Meeting Room Bookings',
component: MeetingRoomBookingList
},
{
path: 'meetings',
name: 'Meetings',
component: MeetingList
},
{
path: 'products',
name: '食品列表',
component: ProductList
},
{
path: 'attributes',
name: '選項列表',
component: AttributeList
},
{
path: 'bundles',
name: '套餐列表',
component: BundleList
},
{
path: 'menu_sections',
name: '菜品分類列表',
component: MenuSectionList
}
]
},
{
path: 'folders/:folderId?/:folderName?',
name: 'file.file_manager',
component: FileManager
},
// {
// path: 'charts',
// name: 'Charts',
// component: Charts
// },
{
path: 'widgets',
name: 'Widgets',
component: Widgets
},
{
path: 'auth',
name: 'Auth',
component: {
render (c) { return c('router-view') }
},
children: [
// {
// path: 'login',
// name: 'BootstrapLogin',
// component: Login
// },
{
path: 'register',
name: 'BootstrapRegister',
component: Register
}
]
},
{
path: 'pages/header_page1',
name: 'HeaderPage1',
component: HeaderPage1
},
{
path: 'pages/header_page2',
name: 'HeaderPage2',
component: HeaderPage2
},
{
path: 'pages/header_page3',
name: 'HeaderPage3',
component: HeaderPage3
},
{
path: 'custom',
redirect: '/custom/draggable_tree',
name: 'Custom',
component: {
render (c) {
return c('router-view')
}
},
children: [
{
path: 'dragdrop_tree',
name: 'Tree',
component: DragDropTree
},
{
path: 'draggable_tree',
name: 'Draggable Tree',
component: DraggableTree
},
{
path: 'vue_drag_tree',
name: 'Vue Drag Tree',
component: VueDragTree
},
{
path: 'sortable_tree',
name: 'Sortable Tree',
component: SortableTree
},
{
path: 'vue_draggable',
name: 'VueDraggable',
component: VueDraggable
},
{
path: 'vue2_datatable',
name: 'Vue2DataTable',
component: Vue2DataTable
}
]
},
{
path: 'bootstrap',
redirect: '/bootstrap/alerts',
name: 'Bootstrap',
component: {
render (c) {
return c('router-view')
}
},
children: [
{
path: 'alerts',
name: 'Alerts',
component: Alerts
},
{
path: 'badge',
name: 'Badges',
component: Badge
},
{
path: 'breadcrumb',
name: 'Breadcrumb',
component: Breadcrumb
},
{
path: 'buttons',
name: 'BootstrapButtons',
component: BootstrapButtons
},
{
path: 'button_group',
name: 'Button Group',
component: BootstrapButtonGroup
},
{
path: 'button_toolbar',
name: 'Button Toolbar',
component: BootstrapButtonToolbar
},
{
path: 'carousel',
name: 'Carousel',
component: Carousel
},
{
path: 'collapse',
name: 'Collapse',
component: Collapse
},
{
path: 'dropdown',
name: 'Dropdown',
component: Dropdown
},
{
path: 'forms',
name: 'BootstrapForms',
component: BootstrapForms
},
{
path: 'inputgroup',
name: 'InputGroup',
component: InputGroup
},
{
path: 'jumbotron',
name: 'Jumbotron',
component: Jumbotron
},
{
path: 'listgroup',
name: 'ListGroup',
component: ListGroup
},
{
path: 'modal',
name: 'Modal',
component: Modal
}
]
},
{
path: 'vueplugins',
redirect: '/vueplugins/vtooltip',
name: 'VuePlugins',
component: {
render (c) {
return c('router-view')
}
},
children: [
{
path: 'vtooltip',
name: 'VToolTip',
component: VToolTip
}
]
},
{
path: 'components',
redirect: '/components/buttons',
name: 'Components',
component: {
render (c) {
return c('router-view')
}
},
children: [
{
path: 'buttons',
name: 'Buttons',
component: Buttons
},
{
path: 'social-buttons',
name: 'Social Buttons',
component: SocialButtons
},
{
path: 'cards',
name: 'Cards',
component: Cards
},
{
path: 'forms',
name: 'Forms',
component: Forms
},
{
path: 'modals',
name: 'Modals',
component: Modals
},
{
path: 'switches',
name: 'Switches',
component: Switches
},
{
path: 'tables',
name: 'Tables',
component: Tables
}
]
},
{
path: 'icons',
redirect: '/icons/font-awesome',
name: 'Icons',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'font-awesome',
name: 'Font Awesome',
component: FontAwesome
},
{
path: 'simple-line-icons',
name: 'Simple Line Icons',
component: SimpleLineIcons
}
]
}
]
},
{
path: '/main_panel',
redirect: '/main_panel/product_menu',
name: 'Main Panel',
component: {
render (c) { return c('router-view') }
}
// ,
// children: [
// {
// path: 'product_menu',
// name: 'Menu',
// component: ProductMenu
// }
// ]
},
{
path: '/team_selection',
name: 'team.team_selection',
component: TeamSelection
},
{
path: '/login',
name: 'Login',
beforeEnter: function (to, from, next) {
console.log('Logon beforeEnter')
next()
},
component: Login
},
{
path: '/pages',
redirect: '/pages/p404',
name: 'Pages',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: '404',
name: 'Page404',
component: Page404
},
{
path: '500',
name: 'Page500',
component: Page500
},
// {
// path: 'login',
// name: 'PagesLogin',
// component: Login
// },
{
path: 'register',
name: 'Register',
component: Register
}
]
},
{
path: '*',
redirect: '/'
}
]
})
<file_sep>import * as types from './fileManager_types'
import * as constants from '../../constants'
import axios from 'axios'
// import moment from 'moment'
const state = {
currentFolder: null,
selectedDocumentIds: [],
selectedFolderIds: [],
userAllFolders: {
personalFolders: [],
publicFolders: [],
sharedFolders: []
},
fileItemList: [],
lastSelectedIndex: -1
}
function getFileItemIndex (fileItem) {
let result = -1
for (var i = 0; i < state.fileItemList.length; i++) {
let item = state.fileItemList[i]
if (item.data.id === fileItem.data.id && item.type === fileItem.type) {
result = i
break
}
}
return result
}
// function getFileIndex (itemList, type, id) {
// console.log('getFileIndex: itemList: ', itemList)
// console.log('getFileIndex: type = ' + type)
// console.log('getFileIndex: id = ' + id)
// let result = -1
// for (var i = 0; i < itemList.length; i++) {
// let item = itemList[i]
// if (item.data.id === id && item.type === type) {
// result = i
// break
// }
// }
// return result
// }
//
function fileItemSelected (index) {
let fileItem = state.fileItemList[index]
console.log('fileItemSelected(' + index + ') :; fileItem.data.id = ' + fileItem.data.id)
let result = false
let i
if (fileItem.type === 'folder') {
i = state.selectedFolderIds.indexOf(fileItem.data.id)
console.log('fileItemSelected :: folder index=' + i)
result = i >= 0
} else {
i = state.selectedDocumentIds.indexOf(fileItem.data.id)
console.log('fileItemSelected :: document index=' + i)
result = i >= 0
}
return result
}
function allSelected (startIndex, endIndex) {
let result = true
for (var i = startIndex; i <= endIndex; i++) {
if (!fileItemSelected(i)) {
result = false
break
}
}
return result
}
function isSelected (fileItem) {
let result = false
let i = 0
if (fileItem.type === 'folder') {
for (i = 0; i < state.selectedFolderIds.length; i++) {
if (state.selectedFolderIds[i] === fileItem.data.id) {
result = true
break
}
}
} else {
for (i = 0; i < state.selectedDocumentIds.length; i++) {
if (state.selectedDocumentIds[i] === fileItem.data.id) {
result = true
break
}
}
}
return result
}
const getters = {
currentFolder: (state) => {
return state.currentFolder
},
selectedDocumentIds: (state) => {
return state.selectedDocumentIds
},
personalFolders: (state) => {
return state.userAllFolders.personalFolders
},
selectedFolderIds: (state) => {
return state.selectedFolderIds
},
haveFileSelected: (state) => {
return state.selectedDocumentIds.length + state.selectedFolderIds.length > 0
},
selectionCount: (state) => {
return state.selectedDocumentIds.length + state.selectedFolderIds.length
},
userAllFolders: (state) => {
return state.userAllFolders
},
fileItemList: (state) => {
return state.fileItemList
},
lastSelectedFileItem: (state) => {
return state.lastSelectedIndex >= 0 ? state.fileItemList[state.lastSelectedIndex] : null
},
lastSelectedIndex: (state) => {
return state.lastSelectedIndex
},
allSelected: (state) => {
return state.fileItemList.length === (state.selectedDocumentIds.length + state.selectedFolderIds.length)
}
}
const mutations = {
setCurrentFolder: (state, payload) => {
console.log('mutations :: setCurrentFolder :: payload: ', payload)
state.currentFolder = payload
// for (var i = 0; i < state.currentFolder.documents.length; i++) {
// state.currentFolder.documents[i].selected = false
// }
state.selectedDocumentIds = []
state.selectedFolderIds = []
state.fileItemList = []
let i
for (i = 0; i < payload.children.length; i++) {
state.fileItemList.push({
type: 'folder',
data: payload.children[i]
})
}
for (i = 0; i < payload.documents.length; i++) {
state.fileItemList.push({
type: 'document',
data: payload.documents[i]
})
}
console.log('currentFolder:', state.currentFolder)
console.log('fileItemList: ', state.fileItemList)
},
toggleDocumentSelection: (state, payload) => {
let document = payload
let index = state.selectedDocumentIds.indexOf(document.id)
if (index >= 0) {
state.selectedDocumentIds.splice(index, 1)
} else {
state.selectedDocumentIds.push(document.id)
}
},
toggleFolderSelection: (state, payload) => {
let folder = payload
let index = state.selectedFolderIds.indexOf(folder.id)
if (index >= 0) {
state.selectedFolderIds.splice(index, 1)
} else {
state.selectedFolderIds.push(folder.id)
}
},
toggleFileItemSelection: (state, payload) => {
let fileItem = payload.fileItem
let i
if (fileItem.type === 'folder') {
// if not selected, set lastSelected
i = state.selectedFolderIds.indexOf(fileItem.data.id)
if (i === -1) {
state.selectedFolderIds.push(fileItem.data.id)
state.lastSelectedIndex = getFileItemIndex(fileItem)
} else {
state.selectedFolderIds.splice(i, 1)
}
} else {
i = state.selectedDocumentIds.indexOf(fileItem.data.id)
if (i === -1) {
state.selectedDocumentIds.push(fileItem.data.id)
state.lastSelectedIndex = getFileItemIndex(fileItem)
} else {
state.selectedDocumentIds.splice(i, 1)
}
}
// let fileItem = payload.fileItem
// let data = fileItem.data
// if (fileItem.type === 'folder') {
// dispatch(types.TOGGLE_FOLDER_SELECTION, data).then(function () {
// commit('setLastSelectedFileItem', {fileType: 'folder', id: data.id})
// })
// } else {
// dispatch(types.TOGGLE_DOCUMENT_SELECTION, data).then(function () {
// commit('setLastSelectedFileItem', {fileType: 'document', id: data.id})
// })
// }
},
selectAllDocuments: (state, payload) => {
console.log('selectAllDocuments')
state.selectedDocumentIds = state.currentFolder.documents.map(function (document) {
return document.id
})
console.log('state.selectedDocumentIds: ', state.selectedDocumentIds)
},
selectAllFolders: (state, payload) => {
console.log('selectAllFolders')
state.selectedFolderIds = state.currentFolder.children.map(function (folder) {
return folder.id
})
console.log('state.selectedFolderIds: ', state.selectedFolderIds)
},
clearDocumentSelection: (state) => {
state.selectedDocumentIds = []
},
clearFolderSelection: (state) => {
state.selectedFolderIds = []
},
updateFolderName: (state, payload) => {
payload.folder.name = payload.name
},
updateDocumentName: (state, payload) => {
payload.document.filename = payload.name
},
setUserAllFolders: (state, payload) => {
state.userAllFolders = payload
},
setLastSelectedFileItem: (state, payload) => {
let fileItem = payload.fileItem
for (var i = 0; i < state.fileItemList.length; i++) {
let loopFileItem = state.fileItemList[i]
if (loopFileItem.type === fileItem.type && loopFileItem.data.id === fileItem.data.id) {
state.lastSelectedIndex = i
break
}
}
},
setSelection: (state, payload) => {
console.log('setSelection startIndex=' + payload.startIndex)
console.log('setSelection endIndex=' + payload.endIndex)
for (var i = payload.startIndex; i <= payload.endIndex; i++) {
let fileItem = state.fileItemList[i]
let index
if (fileItem.type === 'folder') {
index = state.selectedFolderIds.indexOf(fileItem.data.id)
if (index === -1) {
state.selectedFolderIds.push(fileItem.data.id)
}
} else {
index = state.selectedDocumentIds.indexOf(fileItem.data.id)
if (index === -1) {
state.selectedDocumentIds.push(fileItem.data.id)
}
}
}
},
clearSelection: (state, payload) => {
console.log('clearSelection startIndex=' + payload.startIndex)
console.log('clearSelection endIndex=' + payload.endIndex)
for (var i = payload.startIndex; i <= payload.endIndex; i++) {
let fileItem = state.fileItemList[i]
let index
if (fileItem.type === 'folder') {
index = state.selectedFolderIds.indexOf(fileItem.data.id)
console.log('clearSelection :: folder #' + fileItem.data.id + ', index = ' + index)
if (index >= 0) {
state.selectedFolderIds.splice(index, 1)
console.log('clearSelection :: after removal: ' + state.selectedFolderIds)
}
} else {
index = state.selectedDocumentIds.indexOf(fileItem.data.id)
console.log('clearSelection :: document #' + fileItem.data.id + ', index = ' + index)
if (index >= 0) {
state.selectedDocumentIds.splice(index, 1)
}
}
}
},
clearLastSelection: (state) => {
state.lastSelectedIndex = -1
}
}
const actions = {
async [types.REFRESH_FOLDER] ({state, commit, dispatch}) {
let apiUrl = constants.apiUrl + '/folders/' + state.currentFolder.id
console.log('REFRESH_FOLDER :: apiUrl = ' + apiUrl)
await axios.get(apiUrl).then(function (response) {
console.log('actions :: REFRESH_FOLDER => call mutations :: setCurrentFolder')
commit('setCurrentFolder', response.data)
})
},
async [types.SET_CURRENT_FOLDER_BY_TYPE] ({commit}, payload) {
let folderType = payload.folderName
let folderName = payload.subFolderName
let apiUrl = constants.apiUrl + '/folders'
let data = {
type: folderType
}
if (folderName) {
data.folderName = folderName
}
await axios.get(apiUrl, {params: data}).then(function (response) {
commit('setCurrentFolder', response.data)
})
},
async [types.SET_CURRENT_FOLDER] ({commit}, payload) {
let folderId = payload
if (typeof folderId === 'undefined') {
folderId = 0
}
let apiUrl = constants.apiUrl + '/folders/' + folderId
await axios.get(apiUrl).then(function (response) {
commit('setCurrentFolder', response.data)
})
},
async [types.TOGGLE_DOCUMENT_SELECTION] ({commit}, payload) {
await commit('toggleDocumentSelection', payload)
},
async [types.TOGGLE_FOLDER_SELECTION] ({commit}, payload) {
await commit('toggleFolderSelection', payload)
},
async [types.TOGGLE_FILE_ITEM_SELECTION] ({commit, dispatch}, payload) {
await commit('toggleFileItemSelection', payload)
},
async [types.CLEAR_LAST_SELECTION] ({commit}, payload) {
commit('clearLastSelection')
},
async [types.EXTEND_FILE_ITEM_SELECTION] ({state, dispatch, commit}, payload) {
console.log('EXTEND_FILE_ITEM_SELECTION :: lastSelectedIndex = ' + state.lastSelectedIndex)
let fileItem = payload.fileItem
let type = fileItem.type
let id = fileItem.data.id
// valid only lastSelected point exists.
// if no last selected point
if (state.lastSelectedIndex === -1) {
if (isSelected(fileItem)) {
await commit('setLastSelectedFileItem', {fileItem: fileItem})
} else {
await commit('toggleFileItemSelection', payload)
}
return
}
console.log('EXTEND_FILE_ITEM_SELECTION :: type = ' + type)
console.log('EXTEND_FILE_ITEM_SELECTION :: fileId = ' + id)
console.log('EXTEND_FILE_ITEM_SELECTION :: fileItemlist: ', state.fileItemList)
let fileIndex = getFileItemIndex(fileItem)
console.log('EXTEND_FILE_ITEM_SELECTION :: lastSelectedIndex = ' + state.lastSelectedIndex)
let startIndex
let endIndex
if (fileIndex < state.lastSelectedIndex) {
startIndex = fileIndex
endIndex = state.lastSelectedIndex - 1
} else if (fileIndex > state.lastSelectedIndex) {
startIndex = state.lastSelectedIndex + 1
endIndex = fileIndex
} else {
dispatch(types.TOGGLE_FILE_ITEM_SELECTION, {fileIndex: fileIndex})
return
}
if (allSelected(startIndex, endIndex)) {
console.log('allSelected : true (startIndex=' + startIndex + ', endIndex=' + endIndex + ')')
commit('clearSelection', {startIndex: startIndex, endIndex: endIndex})
} else {
console.log('allSelected : false (startIndex=' + startIndex + ', endIndex=' + endIndex + ')')
commit('setSelection', {startIndex: startIndex, endIndex: endIndex})
}
// if (fileType === 'folder') {
// if (state.lastSelectedFileItem.fileType === 'folder') {
// let lastFolderIndex = folderIndex(state.currentFolder.children, state.lastSelectedFileItem.id)
// let currFolderIndex = folderIndex(state.currentFolder.children, fileItem.id)
// if (currFolderIndex < lastFolderIndex) {
// startIndex = currFolderIndex
// endIndex = lastFolderIndex - 1
// for (var i = startIndex; i <= endIndex; i++) {
// commit('setToggleFolderSelection', state.currentFolder.children[i])
// }
// } else if (lastFolderIndex < currFolderIndex) {
// startIndex = lastFolderIndex + 1
// endIndex = currFolderIndex
// for (var i = startIndex; i <= endIndex; i++) {
// commit('setToggleFolderSelection', state.currentFolder.children[i])
// }
// }
// } else {
// for (var i = 0; i < state.currentFolder.documents.length; i++) {
// if (state.selectedDocumentIds.indexOf(state.currentFolder.documents[i].id) >= 0) {
//
// }
// }
// }
// dispatch(types.TOGGLE_FOLDER_SELECTION, fileItem)
// } else {
// dispatch(types.TOGGLE_DOCUMENT_SELECTION, fileItem)
// }
},
async [types.SELECT_ALL_FILES] ({state, commit, dispatch}, payload) {
console.log('fileManager.js :: SELECT_ALL_FILES')
await commit('selectAllDocuments')
await commit('selectAllFolders')
},
async [types.CLEAR_ALL_FILES] ({state, commit, dispatch}, payload) {
await commit('clearDocumentSelection')
await commit('clearFolderSelection')
},
async [types.DELETE_FOLDER] ({state, commit, dispatch}, payload) {
console.log('actions :: DELETE_FOLDER :: payload: ', payload)
let folderId = payload
let apiUrl = constants.apiUrl + '/folders/' + folderId
await axios.delete(apiUrl).then(function (response) {
console.log('actions :: DELETE_FOLDER => actions :: REFRESH_FOLDER')
dispatch(types.REFRESH_FOLDER)
// dispatch('SET_CURRENT_FOLDER', state.currentFolder.id)
})
},
async [types.DELETE_DOCUMENT] ({state, commit, dispatch}, payload) {
console.log('actions :: DELETE_DOCUMENT :: payload: ', payload)
let documentId = payload
let apiUrl = constants.apiUrl + '/documents/' + documentId
await axios.delete(apiUrl).then(function (response) {
dispatch(types.REFRESH_FOLDER)
// dispatch('SET_CURRENT_FOLDER', state.currentFolder.id)
})
},
async [types.DELETE_SELECTED] ({state, commit, dispatch}, payload) {
console.log('actions :: DELETE_SELECTED :: payload: ', payload)
let promises = []
promises.push(
axios.post(
constants.apiUrl + '/documents',
{
command: 'DELETE',
ids: state.selectedDocumentIds
}
)
)
promises.push(
axios.post(
constants.apiUrl + '/folders',
{
command: 'DELETE',
ids: state.selectedFolderIds
}
)
)
await Promise.all(promises).then(function () {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.NEW_FOLDER] ({state, commit, dispatch}, payload) {
let apiUrl = constants.apiUrl + '/folders'
let data = {
command: 'NEW',
parent_folder_id: state.currentFolder.id
}
await axios.post(apiUrl, data).then(function (response) {}).then(function () {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.UPDATE_DOCUMENT_NAME] ({state, commit, dispatch}, payload) {
let document = payload.document
let apiUrl = constants.apiUrl + '/documents/' + document.id
let data = {
command: 'UPDATE_DOCUMENT_NAME',
name: payload.name
}
await axios.post(apiUrl, data).then(function (response) {}).then(function () {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.UPDATE_FOLDER_NAME] ({state, commit, dispatch}, payload) {
commit('updateFolderName', payload)
let folder = payload.folder
let apiUrl = constants.apiUrl + '/folders/' + folder.id
let data = {
command: 'UPDATE_FOLDER_NAME',
name: payload.name
}
await axios.put(apiUrl, data).then(function (response) {}).then(function () {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.GET_USER_ALL_FOLDERS] ({commit}, payload) {
let userId = payload
let apiUrl = constants.apiUrl + '/folders'
let data = {
user_id: userId,
type: 'all'
}
await axios.get(apiUrl, {params: data}).then(function (response) {
commit('setUserAllFolders', response.data)
})
},
async [types.PROCESS_SELECTION] ({dispatch, state}, payload) {
let command = payload.command
let targetFolderId = payload.targetFolderId
let apiUrl = constants.apiUrl + '/folders'
let data = {
command: command,
targetFolderId: targetFolderId,
documentIds: state.selectedDocumentIds.join(','),
folderIds: state.selectedFolderIds.join(',')
}
await axios.post(apiUrl, data).then(function (response) {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.PROCESS_FILE_ITEM] ({dispatch}, payload) {
let command = payload.command
let apiUrl = constants.apiUrl + '/folders'
let data = {}
switch (command) {
case 'RENAME':
data = {
command: command,
fileType: payload.fileType,
fileItemId: payload.fileItem.id,
newName: payload.newName
}
break
default:
let targetFolderId = payload.targetFolderId
let documentIds = []
let folderIds = []
if (payload.fileType === 'folder') {
folderIds = [payload.fileItem.id]
} else {
documentIds = [payload.fileItem.id]
}
data = {
command: command,
targetFolderId: targetFolderId,
documentIds: documentIds.join(','),
folderIds: folderIds.join(',')
}
}
await axios.post(apiUrl, data).then(function (response) {
dispatch(types.REFRESH_FOLDER)
})
},
async [types.FETCH_FOLDER] ({dispatch}, payload) {
if (payload.folderId) {
await dispatch('SET_CURRENT_FOLDER', payload.folderId)
} else {
let folderName = payload.folderName
if (isNaN(folderName)) {
// if not number, i.e. folderName
dispatch('SET_CURRENT_FOLDER_BY_TYPE', payload)
} else {
let folderId = folderName
await dispatch('SET_CURRENT_FOLDER', folderId)
}
}
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>export default {
items: [
// { caption: 'Page 1', link: '/pages/header_page1' },
// { caption: 'Page 2', link: '/pages/header_page2' },
// { caption: 'Page 3', link: '/pages/header_page3' }
]
}
<file_sep>export const FETCH_IRD_FORM_TYPES = 'FETCH_IRD_FORM_TYPES'
export const FETCH_FORMS = 'FETCH_FORMS'
export const FETCH_IRD_FORMS = 'FETCH_IRD_FORMS'
<file_sep>// import Vue from 'vue'
// import * as constants from '@/store/constants'
// import * as types from './terminations_types'
const state = {
terminationForms: []
}
const getters = {
terminationForms: (state) => {
return state.terminationForms
}
}
const mutations = {
}
const actions = {
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>// import Vue from 'vue'
// import * as constants from '@/store/constants'
// import * as types from './salaries_types'
const state = {
salaryForms: []
}
const getters = {
salaryForms: (state) => {
return state.salaryForms
}
}
const mutations = {
}
const actions = {
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import FormType from './TdFormType'
import Version from './TdVersion'
import Opt from './TdOpt'
export default {
FormType,
Version,
Opt
}
<file_sep>import * as types from './equipments_types'
import * as constants from '../../constants'
import axios from 'axios'
const state = {
equipments: []
}
const getters = {
equipments: state => {
return state.equipments
},
scanner: state => {
let result = null
for (var i = 0; i < state.equipments.length; i++) {
if (state.equipments[i].name === 'scanner') {
result = state.equipments[i]
break
}
}
return result
}
}
const mutations = {
setEquipments (state, payload) {
state.equipments = payload
},
holdScanner (state, payload) {
let scanner = payload.scanner
let user = payload.user
scanner.occupied_by = user.id
scanner.occupied_by_user = user
},
releaseScanner (state, payload) {
let scanner = payload.scanner
scanner.occupied_by = 0
scanner.occupied_by_user = null
}
}
const actions = {
async [types.GET_EQUIPMENTS] ({rootGetters, state, commit, dispatch}) {
let apiUrl = constants.apiUrl + '/equipments'
let config = rootGetters.apiHeaderConfig
await axios.get(apiUrl, config).then(function (response) {
commit('setEquipments', response.data)
})
},
async [types.HOLD_SCANNER] ({state, commit, dispatch, getters}, user) {
let apiUrl = constants.apiUrl + '/equipments/' + getters.scanner.id
await axios.put(apiUrl, {occupied_by: user.id}).then(function (response) {
commit('holdScanner', {scanner: getters.scanner, user: user})
})
},
async [types.RELEASE_SCANNER] ({state, commit, dispatch, getters}) {
let apiUrl = constants.apiUrl + '/equipments/' + getters.scanner.id
await axios.put(apiUrl, {occupied_by: 0}).then(function (response) {
commit('releaseScanner', {scanner: getters.scanner})
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Vue from 'vue'
import * as constants from '../../constants'
import * as types from './user_types'
const state = {
profile: null,
activeTeam: null
}
const getters = {
profile: (state) => {
return state.profile
},
activeTeam: (state) => {
return state.activeTeam
},
activeTeamId: (state) => {
console.log('user.js :: getters.activeItemId')
return state.activeTeam ? state.activeTeam.id : 0
}
}
const mutations = {
setActiveTeam: (state, payload) => {
state.activeTeam = payload
},
setProfile: (state, payload) => {
state.profile = payload
}
}
const actions = {
// async [types.UPDATE_DB_USER] ({commit}, payload) {
// let url = constants.oaApiUrl + '/t/users/self'
// let headerConfig = rootGetters.oaApiHeaderConfig
// await Vue.axios.get(url, headerConfig).then(response => {
// if (response.data.status) {
// dispatch('UPDATE_DB_USER', response.data.result)
// commit('setProfile', response.data.result)
// }
// })
// }
[types.FETCH_SELF] ({rootDispatch, rootGetters, state, commit, dispatch}, payload) {
console.log('action(FETCH_SELF)')
let vm = this
let url = constants.oaApiUrl + '/t/users/self'
let config = {}
if (payload && payload['oaAuth']) {
config['headers'] = vm.oaAuth2Headers(payload['oaAuth'])
}
// let teamId = rootGetters.teamId
// let url = constants.oaApiUrl + '/user/employees/self'
// let config = {
// params: {
// include: 'groups',
// teamId: teamId
// }
// }
return new Promise((resolve, reject) => {
Vue.axios.get(url, config).then(response => {
if (response.data.status) {
// let employeeId = response.data.result.groups[0].groupEmployee.employeeId
// dispatch('UPDATE_EMPLOYEE_ID', employeeId)
// commit('setEmployeeId', employeeId)
commit('setProfile', response.data.result)
resolve(response.data.result)
} else {
reject(response.data)
}
}).catch((error) => {
reject(error)
})
})
}
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>import Pusher from 'pusher-js' // import Pusher
import * as constants from '@/store/constants.json'
const getToday = () => {
var dateObj = new Date()
var month = dateObj.getUTCMonth() + 1
var day = dateObj.getUTCDate()
var year = dateObj.getUTCFullYear()
let monthStr = month < 10 ? '0' + month.toString() : month.toString()
let dayStr = day < 10 ? '0' + day.toString() : day.toString()
let yearStr = year.toString()
return yearStr + '-' + monthStr + '-' + dayStr
}
const subscribe = (vm, teamId, channelHandlers) => {
if (vm.pusherSubscribed) {
vm.unSubscribe()
}
// alert('subscribe PUSHER_APP_KEY = ' + constants.PUSHER_CLUSTER)
// alert('teamId = ' + teamId)
if (teamId) {
vm.pusher = new Pusher(constants.PUSHER_APP_KEY, {cluster: constants.PUSHER_CLUSTER})
console.log('helpers: subscribe: created pusher')
vm.pusher.subscribe('team_' + teamId)
for (var i = 0; i < channelHandlers.length; i++) {
let channelHandler = channelHandlers[i]
console.log('helpers: subscribe: added channel: ' + channelHandler.channel)
vm.pusher.bind(channelHandler.channel, data => channelHandler.handler(data))
}
vm.pusherSubscribed = true
}
}
const unSubscribe = (vm) => {
if (vm.pusher) {
vm.pusher.disconnect()
}
}
export default {
getToday,
subscribe,
unSubscribe
}
<file_sep>// import * as types from './dialogs_types'
// import * as constants from '../../constants'
//
const state = {
modalTitle: '',
modalVisible: false,
modalMessage: '',
modalComponent: null
}
const getters = {
modalTitle (state) {
return state.modalTitle
},
modalVisible (state) {
return state.modalVisible
},
modalMessage (state) {
return state.modalMessage
}
}
const mutations = {
showModal (state, payload) {
console.log('showModal :: payload:', payload)
state.modalTitle = payload.title
state.modalVisible = true
state.modalMessage = payload.message
},
hideModal (state) {
state.modalVisible = false
}
}
const actions = {
}
export default {
state,
getters,
mutations,
actions
}
<file_sep>export const FETCH_PAYROLLS = 'FETCH_PAYROLLS'
<file_sep>import TdPrice from './td-price.vue'
export default {
TdPrice
}
<file_sep>import tdAction from './tdAction.vue'
import tdStatus from './tdStatus.vue'
export default {
tdAction,
tdStatus
}
<file_sep>export const TOGGLE_DOCUMENT_SELECTION = 'TOGGLE_DOCUMENT_SELECTION'
export const TOGGLE_FOLDER_SELECTION = 'TOGGLE_FOLDER_SELECTION'
export const TOGGLE_FILE_ITEM_SELECTION = 'TOGGLE_FILE_ITEM_SELECTION'
export const SELECT_ALL_FILES = 'SELECT_ALL_FILES'
export const CLEAR_ALL_FILES = 'CLEAR_ALL_FILES'
export const DELETE_SELECTED = 'DELETE_SELECTED'
export const UPDATE_DOCUMENT_NAME = 'UPDATE_DOCUMENT_NAME'
export const UPDATE_FOLDER_NAME = 'UPDATE_FOLDER_NAME'
export const EXTEND_FILE_ITEM_SELECTION = 'EXTEND_FILE_ITEM_SELECTION'
export const CLEAR_LAST_SELECTION = 'CLEAR_LAST_SELECTION'
export const SET_CURRENT_FOLDER = 'SET_CURRENT_FOLDER'
export const SET_CURRENT_FOLDER_BY_TYPE = 'SET_CURRENT_FOLDER_BY_TYPE'
export const NEW_FOLDER = 'NEW_FOLDER'
export const DELETE_DOCUMENT = 'DELETE_DOCUMENT'
export const DELETE_FOLDER = 'DELETE_FOLDER'
export const COPY_SELECTED = 'COPY_SELECTED'
export const MOVE_SELECTED = 'MOVE_SELECTED'
export const REFRESH_FOLDER = 'REFRESH_FOLDER'
export const PROCESS_SELECTION = 'PROCESS_SELECTION'
export const PROCESS_FILE_ITEM = 'PROCESS_FILE_ITEM'
export const FETCH_FOLDER = 'FETCH_FOLDER'
export const GET_USER_ALL_FOLDERS = 'GET_USER_ALL_FOLDERS'
<file_sep>export const SET_ACTIVE_MENU = 'SET_ACTIVE_MENU'
export const REPOSITION_CATEGORY = 'REPOSITION_CATEGORY'
export const MOVE_PRODUCT_CATEGORY = 'MOVE_PRODUCT_CATEGORY'
export const CLEAR_COOKIE_TOKEN = 'CLEAR_COOKIE_TOKEN'
export const SET_USER = 'SET_USER'
export const SET_TOKEN = 'SET_TOKEN'
export const REMOVE_COOKIE_TOKEN = 'REMOVE_COOKIE_TOKEN'
export const SET_OAAUTH = 'SET_OAAUTH'
// set memory active team
export const SET_ACTIVE_TEAM = 'SET_ACTIVE_TEAM'
export const SET_DB_TEAM = 'SET_DB_TEAM'
export const FETCH_USER = 'FETCH_USER'
export const FETCH_TEAM_SETTINGS = 'FETCH_TEAM_SETTINGS'
export const GET_PUBLIC_FOLDERS = 'GET_PUBLIC_FOLDERS'
export const SET_LANG = 'SET_LANG'
export const FETCH_AVAILABLE_FISCAL_YEARS = 'FETCH_AVAILABLE_FISCAL_YEARS'
export const CHECK_TOKEN = 'CHECK_TOKEN'
export const FETCH_USER_BY_TOKEN = 'FETCH_USER_BY_TOKEN'
// Language
export const FETCH_LANGUAGES = 'FETCH_LANGUAGES'
export const UPDATE_USER_LANGUAGE = 'UPDATE_USER_LANGUAGE'
<file_sep>import * as types from './meetingRoomBookings_types'
import * as constants from '../../constants'
import axios from 'axios'
import moment from 'moment'
const state = {
meetingRoomBookings: [],
loadingMeetingRoomBookings: true,
workingBooking: null,
bookingTemplate: {
id: 0,
applicant_id: 0,
applicant_name: '',
meeting_room_id: 0,
meeting_room: null,
meeting_room_name: '',
started_at: null,
ended_at: null,
status: 'new',
remark: '',
processingBooking: true
}
}
const getters = {
meetingRoomBookings: (state) => {
return state.meetingRoomBookings
},
workingBooking: (state) => {
return state.workingBooking
},
bookingTemplate: (state) => {
return state.bookingTemplate
},
processingBooking: (state) => {
return state.processingBooking
}
}
const getBooking = (bookings, bookingId) => {
let result = null
for (var i = 0; i < bookings.length; i++) {
if (bookings[i].id === bookingId) {
result = bookings[i]
break
}
}
return result
}
const getHumanReadableTime = (moment) => {
let hour = moment.get('hour')
let minute = moment.get('minute')
let ampm = 'am'
if (hour >= 12) {
ampm = 'pm'
}
let result = hour > 12 ? hour - 12 : hour
if (minute > 0) {
result += ':' + (minute < 10 ? '0' + minute : minute)
}
result += ampm
return result
}
const getTimeSlotRange = (startMoment, endMoment) => {
let startTime = getHumanReadableTime(startMoment)
let endTime = getHumanReadableTime(endMoment)
return startTime + ' - ' + endTime
}
const mutations = {
// updateMeetingRooms (state, payload) {
// state.meetingRooms = payload
// console.log('updateMeetingRooms :: meetingRooms: ', state.meetingRooms)
// },
changeLoadingMeetingRoomsState (state, loading) {
state.loadingMeetingRooms = loading
},
createMeetingRoom (state, payload) {
},
updateMeetingRoom (state, payload) {
},
setMeetingRoomBookings (state, payload) {
state.meetingRoomBookings = payload
console.log('Store :: meetingRoomBookings :: setMeetingRoomBookings')
for (var i = 0; i < state.meetingRoomBookings.length; i++) {
var bookingStartMoment = moment(state.meetingRoomBookings[i].started_at)
var bookingEndMoment = moment(state.meetingRoomBookings[i].ended_at)
var bookingStartMomentClone = bookingStartMoment.clone()
var weekStart = bookingStartMomentClone.startOf('week')
state.meetingRoomBookings[i].weekday = Math.floor(bookingStartMoment.diff(weekStart, 'day'))
state.meetingRoomBookings[i].quarter = bookingStartMoment.format('HH:mm')
state.meetingRoomBookings[i].range = getTimeSlotRange(bookingStartMoment, bookingEndMoment)
state.meetingRoomBookings[i].startMoment = bookingStartMoment
state.meetingRoomBookings[i].endMoment = bookingEndMoment
}
},
removeBooking (state, bookingId) {
console.log('meetingRoomBooking.js :: removeBooking :: bookingId = ' + bookingId)
for (var i = 0; i < state.meetingRoomBookings.length; i++) {
if (state.meetingRoomBookings[i].id === bookingId) {
state.meetingRoomBookings.splice(i, 1)
}
}
},
appendBooking (state, booking) {
let existingBooking = getBooking(state.meetingRoomBookings, booking.id)
if (!existingBooking) {
state.meetingRoomBookins.push(booking)
}
},
updateBooking (state, booking) {
/* payload
id
applicant_id
status
meeting_room_id
meeting_room
started_at
ended_at
remark
*/
console.log('meetingRoomBooking :: updateBooking: booking.id=(' + booking.id + ') booking:', booking)
let found = false
for (var i = 0; i < state.meetingRoomBookings.length; i++) {
console.log('meetingRoomBooking i=' + i)
if (state.meetingRoomBookings[i].id === booking.id) {
console.log('meetingRoomBooking :: found')
state.meetingRoomBookings[i].status = 'pending'
state.meetingRoomBookings[i].meeting_room_id = booking.meeting_room_id
state.meetingRoomBookings[i].meeting_room = booking.meeting_room
state.meetingRoomBookings[i].meeting_room_name = booking.meeting_room.name
state.meetingRoomBookings[i].started_at = booking.started_at
state.meetingRoomBookings[i].ended_at = booking.ended_at
state.meetingRoomBookings[i].remark = booking.remark
found = true
}
}
if (!found) {
state.meetingRoomBookings.push(booking)
}
},
updateWorkingBooking (state, booking) {
if (state.workingBooking === null) {
state.workingBooking = booking
} else {
state.workingBooking.id = booking.id
state.workingBooking.status = booking.status
state.workingBooking.meeting_room_id = booking.meeting_room_id
state.workingBooking.meeting_room = booking.meeting_room
state.workingBooking.meeting_room_name = booking.meeting_room_name
state.workingBooking.started_at = booking.started_at
state.workingBooking.ended_at = booking.ended_at
state.workingBooking.remark = booking.remark
}
},
setProcessingStatus (state, yesNo) {
console.log('*** setProcessingStatus = ' + (yesNo ? 'yes' : 'no'))
if (!yesNo) {
return
}
state.processingBooking = true
}
}
const actions = {
async [types.GET_MEETING_ROOM_BOOKINGS] ({commit, dispatch}, payload) {
let apiUrl = constants.apiUrl
commit('setProcessingStatus', true)
await axios.get(apiUrl + '/meeting_room_bookings').then(function (response) {
commit('setProcessingStatus', false)
commit('setMeetingRoomBookings', response.data)
if (payload) {
if (typeof payload.callback === 'function') {
payload.callback(response.data)
}
}
})
},
async [types.REMOVE_BOOKING] ({commit, dispatch, state}, payload) {
let bookingId = payload
commit('removeBooking', bookingId)
},
async [types.APPEND_BOOKING] ({commit, dispatch, state}, payload) {
commit('appendBooking', payload)
},
async [types.GET_DAY_BOOKINGS] ({commit, dispatch, state}, payload) {
return new Promise((resolve, reject) => {
let requestedDayMoment = payload
let ymmdd = requestedDayMoment.format('Y-MM-DD')
// console.log('GET_DAY_BOOKINGS requestedDayMoment :: ymmdd: ' + ymmdd)
// console.log('GET_DAY_BOOKINGS state.meetingRoomBookings.length = ' + state.meetingRoomBookings.length)
let result = []
for (var i = 0; i < state.meetingRoomBookings.length; i++) {
// console.log('#' + i + ': meetingRoomBookings[i]: ', state.meetingRoomBookings[i])
// console.log('#' + i + ': started_at=' + state.meetingRoomBookings[i].started_at)
// console.log('#' + i + ': subsstr(0,8): ' + state.meetingRoomBookings[i].started_at.substr(0, 10)) // let moment = Vue.moment(state.meetingRoomBookings.started_at)
if (state.meetingRoomBookings[i].started_at.substr(0, 10) === ymmdd) {
// console.log('#' + i + ': push')
result.push(state.meetingRoomBookings[i])
}
}
resolve(result)
})
},
async [types.SET_BOOKING] ({commit, dispatch, state}, payload) {
commit('updateBooking', payload)
},
async [types.SET_WORKING_BOOKING] ({commit, dispatch, state}, payload) {
commit('updateWorkingBooking', payload)
},
// DB Processing
async [types.SAVE_BOOKING] ({commit, dispatch, state}, payload) {
let booking = payload
let apiUrl = constants.apiUrl + '/meeting_room_bookings'
commit('setProcessingStatus', true)
await axios.post(apiUrl, {booking: booking}).then(function (response) {
commit('setProcessingStatus', false)
dispatch(types.GET_MEETING_ROOM_BOOKINGS)
})
},
async [types.UPDATE_BOOKING] ({commit, dispatch, state}, payload) {
let booking = payload
let apiUrl = constants.apiUrl + '/meeting_room_bookings/' + booking.id
commit('setProcessingStatus', true)
await axios.put(apiUrl, {booking: booking}).then(function (response) {
commit('setProcessingStatus', false)
dispatch(types.GET_MEETING_ROOM_BOOKINGS)
})
},
async [types.DELETE_BOOKING] ({commit, dispatch, state}, payload) {
commit('setProcessingStatus', true)
let bookingId = payload
let apiUrl = constants.apiUrl + '/meeting_room_bookings/' + bookingId
await axios.delete(apiUrl).then(function (response) {
commit('setProcessingStatus', false)
dispatch(types.GET_MEETING_ROOM_BOOKINGS)
})
}
}
export default {
state,
getters,
actions,
mutations
}
| 00e7387deddca644103c4d0fb2ad9ebf2a189071 | [
"JavaScript"
] | 39 | JavaScript | laputafish/oa_mpf | c7bc4cc2eda957f5711438d13b01a483ae04cc7f | 55c93c4ef3e064677cad10a56b7bf6c7bca77b1b |
refs/heads/master | <file_sep>package com.astoma.ccsf.drawingGui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* @author A.Stoma Dec 17, 2016
*/
public class DrawingPanel extends JPanel {
private JRadioButton blueMarker, redMarker, greenMarker, eraserButton;
private JButton clearButton;
private JPanel buttonsPanel;
private ButtonGroup group;
private Marker marker;
private boolean markerIsOn = false;
private boolean resetIsClicked = false;
// constructor
public DrawingPanel() {
marker = new Marker();
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setBackground(Color.LIGHT_GRAY);
this.addMouseListener(new MouseAdapter() {
// count number of clicks to determine marker on/off
int clickCount = 0;
public void mouseClicked(MouseEvent e) {
clickCount += e.getClickCount();
if (clickCount % 2 == 1) {
markerIsOn = true;
} else {
markerIsOn = false;
}
}
});
this.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
if (markerIsOn) {
moveMarker(e.getX(), e.getY());
}
}
});
// create radio buttons (Marker color)
blueMarker = new JRadioButton("Blue", true);
blueMarker.setForeground(Color.BLUE);
redMarker = new JRadioButton("Red");
redMarker.setForeground(Color.RED);
greenMarker = new JRadioButton("Green");
greenMarker.setForeground(Color.GREEN);
eraserButton = new JRadioButton("Eraser");
eraserButton.setBackground(Color.LIGHT_GRAY);
clearButton = new JButton();
this.add(clearButton);
clearButton.setText("Clear");
clearButton.addActionListener(new ButtonListener());
// add action listeners
blueMarker.addActionListener(new ButtonListener());
redMarker.addActionListener(new ButtonListener());
greenMarker.addActionListener(new ButtonListener());
eraserButton.addActionListener(new ButtonListener());
group = new ButtonGroup();
group.add(blueMarker);
group.add(redMarker);
group.add(greenMarker);
group.add(eraserButton);
// create panel containing buttons
buttonsPanel = new JPanel();
buttonsPanel.setSize(230, 20);
buttonsPanel.setBackground(Color.WHITE);
buttonsPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
this.add(buttonsPanel);
buttonsPanel.add(blueMarker);
buttonsPanel.add(redMarker);
buttonsPanel.add(greenMarker);
buttonsPanel.add(eraserButton);
buttonsPanel.add(clearButton);
}
private void moveMarker(int x, int y) {
// current marker state
final int CURR_X = marker.getX();
final int CURR_Y = marker.getY();
final int OFFSET = 0;
if ((CURR_X != x) || (CURR_Y != y)) {
marker.setX(x);
marker.setY(y);
repaint(marker.getX(), marker.getY(), marker.getW() + OFFSET,
marker.getH() + OFFSET);
}
}
// put drawing code inside paintComponenet method
public void paintComponent(Graphics pen) {
super.paintComponent(pen);
Graphics2D g2 = (Graphics2D) pen;
if(resetIsClicked == false){
g2.setColor(marker.getMarkerColor());
g2.drawOval(marker.getX(), marker.getY(), marker.getW(), marker.getH());
g2.fillOval(marker.getX(), marker.getY(), marker.getW(), marker.getH());
}else{
marker.setX(0);
marker.setY(0);
repaint();
resetIsClicked = false;
}
}
public class Marker {
private int markerX = 0;
private int markerY = 0;
private int markerW = 3;
private int markerH = 3;
private Color markerColor = Color.BLUE;
public int getX() {
return markerX;
}
public void setX(int x) {
this.markerX = x;
}
public int getY() {
return markerY;
}
public void setY(int y) {
this.markerY = y;
}
public int getW() {
return markerW;
}
public void setW(int w) {
this.markerW = w;
}
public int getH() {
return markerH;
}
public void setH(int h) {
this.markerH = h;
}
public Color getMarkerColor() {
return this.markerColor;
}
public void setMarkerColor(Color color) {
this.markerColor = color;
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == clearButton) {
resetIsClicked = true;
}
if (redMarker.isSelected()) {
marker.setMarkerColor(Color.RED);
} else if (blueMarker.isSelected()) {
marker.setMarkerColor(Color.BLUE);
} else if (greenMarker.isSelected()) {
marker.setMarkerColor(Color.GREEN);
} else if (eraserButton.isSelected()){
marker.setMarkerColor(Color.LIGHT_GRAY);
}
}
}
}<file_sep>package com.astoma.ccsf.drawingGui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawingPanelDriver {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JPanel panel = new DrawingPanel();
JFrame frame = new JFrame("Drawing Board");
frame.setSize(400, 400);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
| fc719097c77f66ac7df7da21c7d59f80c9af4034 | [
"Java"
] | 2 | Java | sky2day/Project_Drawing | bd683946c2f751b2182e6cfdba0bb1dd4a5912ad | 97eea69d7461570c0d7584bc5dba6331e724cd9d |
refs/heads/master | <repo_name>itggot-Lowe-Blank/standard-biblioteket<file_sep>/lib/sum.rb
# Public: Takes an array of integers as inputs and gives the sum of all numbers as output.
#
# array - any Array.
# array2 - any Array.
#
# Examples
#
# concat([1,2,3],[1,2,3])
# # => 12
#
# Returns the sum.
def sum(array,array2)
output = 0
while array2.length > 0
array << array2.delete_at(0)
end
while array.length > 0
output += array.delete_at(0)
end
return output
end
p sum([1,2,3],[1,2,3])<file_sep>/lib/is_negative.rb
# Public: Checks if number is negative.
#
# number - The Integer to check if even.
#
# Examples
#
# is_negative(-4)
# # => true
#
# Returns the answer
def is_negative(number)
return number < 0
end<file_sep>/lib/power.rb
# Public: Takes two numbers as inputs and gives the power as output, with first input as base and others as an exponent
#
# base - The Integer base.
# exp - The Integer exponent.
#
# Examples
#
# power(3,2)
# # => 9
#
# Returns the value.
def power(base,exp)
return base ** exp
end<file_sep>/lib/sum_to.rb
# Public: Takes a number as input and gives the sum of all numbers from 0 to the number as output.
#
# number - The Integer.
#
# Examples
#
# sum_to(3)
# # => 6
#
# Returns the value.
def sum_to(number)
i = number
output = number
while i > 0
output += number-1
number-=1
i-=1
end
return output
end<file_sep>/lib/first_of.rb
# Public: Takes an Array as input and gives the first element in the array as output.
#
# array - any Array
#
# Examples
#
# array(["hej",2,5,"oj"])
# # => "hej"
#
# Returns the first value in the array.
def first_of(array)
return array[0]
end<file_sep>/lib/is_odd.rb
# Public: Checks if number is odd.
#
# number - The Integer to check if odd.
#
# Examples
#
# is_even(5)
# # => true
#
# Returns the answer
def is_odd(number)
return number % 2 != 0
end<file_sep>/lib/previous_number.rb
# Public: Returns the previous integer.
#
# number - The Integer to check the previous Integer.
#
# Examples
#
# next_number(4)
# # => 3
#
# Returns the previous integer.
def previous_number(number)
return number - 1
end<file_sep>/lib/is_even.rb
# Public: Checks if number is even.
#
# number - The Integer to check if even.
#
# Examples
#
# is_even(4)
# # => true
#
# Returns the answer
def is_even(number)
return number % 2 == 0
end<file_sep>/lib/min_of_two.rb
# Public: Compares two numbers and returns the smallest.
#
# numb - The Integer to compare.
# num2 - The second Integer to compare.
#
# Examples
#
# min_of_two(4,5)
# # => 4
#
# Returns the smallest number
def min_of_two(num, num2)
if num < num2
return num
end
return num2
end<file_sep>/lib/average.rb
# Public: Takes an array of integers as inputs and gives the average of all integer.
#
# array - any Array.
#
# Examples
#
# concat([1,2,3,1,2,3)
# # => 2
#
# Returns the average.
def average(array)
output = 0
i=0
while i < array.length
output += array[i]
i += 1
end
return output/array.length.to_f
end<file_sep>/lib/square.rb
# Public: Returns the squared value of a number.
#
# number - The Integer to square.
#
# Examples
#
# cube(4)
# # => 16
#
# Returns the squared value.
def square(number)
return number ** 2
end<file_sep>/lib/min_of_four.rb
# Public: Checks the smallest value of four integers.
#
# min - The Integer with lowest value, also guessed as the first number.
# num2 - The Integer to compare with.
# num3 - The Integer to compare with.
# num4 - The Integer to compare with.
#
# Examples
#
# min_of_four(4,1,5,-1)
# # => -1
#
# Returns the smallest value of three integers.
def min_of_three(min,num2,num3,num4)
if min > num2
min = num2
end
if min > num3
min = num3
end
if min > num4
min = num4
end
return min
end<file_sep>/lib/concat.rb
# Public: Takes two arrays as input and provides a new array as output, where both arrays are added togheter.
#
# array - any Array.
# array2 - any Array.
#
# Examples
#
# concat([1,2,3],[4,5,6,7])
# # => [1,2,3,4,5,6,7]
#
# Returns the new array.
def concat(array,array2)
while array2.length > 0
array << array2.delete_at(0)
end
return array
end<file_sep>/lib/max_of_four.rb
# Public: Checks the largest of two numbers.
#
# min - The Integer with largest value, also guessed as the first number.
# num2 - The Integer to compare with.
# num3 - The Integer to compare with.
# num4 - The Integer to compare with.
#
# Examples
#
# max_of_four(4,1,5,6)
# # => 6
#
# Returns the largest integer.
def max_of_four(max,num2, num3,num4)
if max < num2
max = num2
end
if max < num3
max = num3
end
if max < num4
max = num4
end
return max
end<file_sep>/lib/factorial.rb
# Public: Takes a number as input and gives the product of all 1-digit numbers as output.
#
# number - The Integer.
#
# Examples
#
# factorial(3)
# # => 6
#
# Returns the value.
def factorial(number)
i = number
output = number
if number == 0
return 1
end
while i > 1
output *= number-1
number-=1
i-=1
end
return output
end<file_sep>/lib/max_of_two.rb
# Public: Checks the largest of two numbers.
#
# max - The Integer with largest value, also guessed as the first number.
# num2 - The Integer to compare with.
#
# Examples
#
# max_of_two(4,1)
# # => 4
#
# Returns the largest integer.
def max_of_two(max,num2)
if max < num2
max = num2
end
return max
end<file_sep>/lib/min_of_three.rb
# Public:Checks the smallest value of three integers.
#
# min - The Integer with lowest value, also guessed as the first number.
# num2 - The Integer to compare with.
# num3 - The Integer to compare with.
#
# Examples
#
# min_of_three(4,1,5)
# # => 1
#
# Returns the smallest value of three integers.
def min_of_three(min,num2,num3)
if min > num2
min = num2
end
if min > num3
min = num3
end
return min
end<file_sep>/lib/between.rb
# Public: Checks if chosen number is between two other numbers.
#
# num - The Integer that is checked.
# num1 - The Integer to compare num with.
# num2 - The second Integer to compare num with.
#
# Examples
#
# between_strict(4, 2, 4)
# # => true
#
# Returns true or false.
def between(num1,num2,num3)
return num1 <= num2 && num2 <= num3
end<file_sep>/lib/append.rb
# Public: Takes an array and an integer as input and provides a new array as output, where the integer is added at the end of the array.
#
# array - any Array
# num - any Integer or string.
#
# Examples
#
# append([1,2,3],4)
# # => [1,2,3,4]
#
# Returns the new array.
def append(array,num)
output = array
output << num
return output
end<file_sep>/lib/between_strict.rb
# Public: Checks if chosen number is between two other numbers. Two or more of the same number is not allowed.
#
# num - The Integer that is checked.
# num1 - The Integer to compare num with.
# num2 - The second Integer to compare num with.
#
# Examples
#
# between_strict(4, 2, 5)
# # => true
#
# between_strict(4,2,4)
# # => false
#
# Returns true or false.
def between_strict(num,num1,num2)
return num1 < num && num < num2
end<file_sep>/lib/max_of_three.rb
# Public: Checks the largest of two numbers.
#
# min - The Integer with largest value, also guessed as the first number.
# num2 - The Integer to compare with.
# num3 - The Integer to compare with.
#
# Examples
#
# max_of_three(4,1,5)
# # => 5
#
# Returns the largest integer.
def max_of_three(max,num2, num3)
if max < num2
max = num2
end
if max < num3
max = num3
end
return max
end<file_sep>/lib/cube.rb
# Public: Returns the cubed value of a number.
#
# number - The Integer to be cubed.
#
# Examples
#
# cube(4)
# # => 64
#
# Returns the cube value.
def cube(number)
return number ** 3
end<file_sep>/lib/prepend.rb
# Public: Takes an array and an integer as input and provides a new array as output, where the integer is added at the beginning ofthe array.
#
# array - any Array.
# array2 - any Array.
#
# Examples
#
# concat([1,2,3],3)
# # => [3,1,2,3]
#
# Returns the new array.
def prepend(array,array2)
array2 = [array2]
while array.length > 0
array2 << array.delete_at(0)
end
return array2
end
p prepend([1,2,3],4)<file_sep>/lib/next_number.rb
# Public: Returns the following integer.
#
# number - The Integer to check next following Integer.
#
# Examples
#
# next_number(4)
# # => 5
#
# Returns the following integer.
def next_number(number)
return number + 1
end<file_sep>/lib/absolute.rb
# Public: Returns the absolute value of number.
#
# number - The Integer to convert to absolute value.
#
# Examples
#
# absolute(-19)
# # => 19
#
# Returns the absolute value.
def absolute(number)
if number < 0
return number*-1
end
return number
end<file_sep>/lib/last_of.rb
# Public: Takes an Array as input and gives the last element in the array as output.
#
# array - any Array
#
# Examples
#
# array(["hej",2,5,"oj"])
# # => "oj"
#
# Returns the first value in the array.
def last_of(array)
return array[-1]
end | 0890aabf1f526a05e26cdfd2c0d4b0c71995450a | [
"Ruby"
] | 26 | Ruby | itggot-Lowe-Blank/standard-biblioteket | fc6d908aefafc75fad9f614c53d3ee66900578ca | eaeab082a23ab97c2e1490bae625c11a1fcf533a |
refs/heads/master | <repo_name>Mandor99/waste-time-in-javascript<file_sep>/pure.js
var test = document.querySelector('.test');
function multiStyles(ele, styles){
for( var css in styles ){
ele.style[css] = styles[css];
}
}
// function slideUp( ele, duration = 500 ){
// // var elem = document.querySelector('.'+ele);
// multiStyles(ele,{
// 'transition' : `all ${duration}ms ease-in-out`,
// 'height' : '0px'
// });
// }
// test.onclick =()=>slideUp(test);
// test.onclick = function(){
// slideUp(this, 2000);
// };
class uiLib{
constructor(selector){
this.selector=selector;
// this.ele = document.querySelector(selector);
// let slidedHeight = this.selector.height;
}
slideUp(){
multiStyles(this.selector,{
'transition' : `all 500ms ease-in-out`,
'height' : '0px'
});
}
// slideDown(){
// multiStyles(this.selector,{
// 'transition': `all 500ms ease-in-out`,
// 'height':`${slidedHeight}`
// });
// }
}
// function uiLib(ele){
// this.element=document.querySelector(ele);
// this.log = function(){
// this
// }
// }
function $(selector){
return new uiLib(selector);
}
console.log($(test));
test.onclick=function(){$(this).slideUp();};
// test.addEventListener('click', slideUp(test));
// function javaScriptUi(selector){
// this.slideUp = function(){
// // multiStyles(selector, {
// // 'transtion':`all ${duration} ease-in-out`,
// // 'height': '0px'
// // });
// selector.setAttribute('style', 'transition: all 400ms ease-in-out;height:0');
// };
// }
multiStyles(test, {
'width':'500px',
'height': '300px',
'margin': 'auto',
'background-color': '#f00',
// 'transition':'all 2s ease-in-out'
});
// var t = new javaScriptUi(test);
// t.onclick = () => this.slideUp();
console.log(document.querySelector('.lists')); // the dom element
console.log(document.querySelectorAll('.list')); // nodeList
console.log(document.getElementsByClassName('list')); //htmlCollection
console.log(document.getElementsByTagName('li')); //htmlCollection
let t0 = document.querySelector('.lists');
let t1 = document.querySelectorAll('.list');
let t2 = document.getElementsByClassName('list');
let t1Arr = [...t1]; // array
let t2Arr = [...t2]; // array
let chain1 = document.querySelector('.list .class1 .class2 div'); //work good
let chain2 = document.getElementsByClassName('list1 class1 class2'); //don't work good
// let chain3 = document.getElementsByClassName('list1')[0].getElementsByClassName('class1')[0].getElementsByClassName('class2')[0]; //error
let chain4 = document.getElementById('test-lists').getElementsByClassName('list1')[0]; //don't work good
console.log(chain4);
for(let i = 0; i<t1.length; i++){
console.log('jj');
}
console.log(t1[1].textContent);
// console.log(t1.protoType + 'querySelectorAll');
// let tt = t1Arr.reduce((a, b) => a+b);
// console.log(tt);
// console.log(t1Arr);
t1.forEach((e,i) => console.log(`this ${e.textContent} is ${i}`)); //convert nodeList into array and loop it
t2Arr.forEach((e,i) => console.log(`this ${e.textContent} is ${i}`)); //DON'T convert htmlCollection into array but i must convert it to array to loop it
t1Arr.map((e, i) => console.log(`this ${e.textContent} is ${i}`));
//correct ==> as query* is static not live node as itrate on it is possible with the regular loop or forEach() as the length is known
let ul = document.querySelectorAll('ul')[0],
li = ul.querySelectorAll('li');
for (let index = 0; index < li.length; index++) {
ul.appendChild(document.createElement('li'));
}
// wrong ==> as GE* ==> live node as the length is unknown
// let uls = document.getElementsByTagName('ul')[0],
// lis = ul.getElementsByTagName('li');
// for (let index = 0; index < lis.length; index++) {
// uls.appendChild(document.createElement('li'));
// }
//also correct as it an array
let uls = document.getElementsByTagName('ul')[0],
lis = ul.getElementsByTagName('li');
let = liArr = [...lis];
for (let index = 0; liArr < lis.length; index++) {
uls.appendChild(document.createElement('li'));
}
let sty0 = t1[2].innerText;
let sty1 = t1[3].textContent;
let tt0 = document.querySelector('.test');
let tt1 = document.querySelector('.test1');
tt0.innerText = sty0; // save the style
tt1.innerText = sty1; // don't save the style
tt1.style.color = 'red'; // but i can reset it
t1[2].onclick = () => alert('1 is not worked'); // not work as the element has the same event on it
t1[2].onclick = () => alert('2 is worked'); //it override the first event on the same element and it is run only
t1[2].addEventListener('click', ()=>alert('3 is worked')); //will work
t1[2].addEventListener('click', ()=>alert('4 is worked')); // also will work and not override the last bervious
| 82838a369d65efa4403a253b005954043de78287 | [
"JavaScript"
] | 1 | JavaScript | Mandor99/waste-time-in-javascript | 8c0be1f6d74a4c0c86b9bfcf2d0f7d29657fc0e5 | d636332a44978a031afba9667ac214b294915016 |
refs/heads/master | <repo_name>aemoe/golff-pool<file_sep>/README.md
# golff-pool
<file_sep>/migrations/2_deploy_token.js
// ++++++++++++++++ Define Contracts ++++++++++++++++
//Token First
const GOF = artifacts.require("./GOF.sol");
// ++++++++++++++++ Main Migration ++++++++++++++++
const migration = async (deployer, network, accounts) => {
await Promise.all([
deployToken(deployer, network),
]);
};
module.exports = migration;
// ++++++++++++++++ Deploy Functions ++++++++++++++++
async function deployToken(deployer, network) {
await deployer.deploy(GOF);
} | ea7b2f757ab68bafd6d9c518ddb182129b887128 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | aemoe/golff-pool | d7373baba1fc2b6eaf0fcfbb5903faafb3caf57d | 44c57266a82e3b16c40a9140b37331100658ef29 |
refs/heads/master | <file_sep>[{
id: '34324dfea',
name: 'Ryan',
room: 'Cool Room'
}]
class Users {
constructor() {
this.users = [];
}
addUser(id, name, room) {
var user = {id, name, room};
this.users.push(user);
return user;
}
removeUser(id) {
var user = this.users.filter(function(user) {
return user.id === id;
})[0];
if (user) {
this.users = this.users.filter(function(user) {
return user.id !== id;
});
}
return user;
}
getUser(id) {
return this.users.filter(function(user) {
return user.id === id;
})[0];
}
getUserList(room) {
var users = this.users.filter(function(user) {
return user.room === room;
});
var namesArray = users.map(function(user) {
return user.name;
});
return namesArray;
}
}
module.exports = {Users};
//class Person {
// constructor(name, age) {
// this.name = name;
// this.age = age;
// }
// getUserDescription() {
// return this.name + ' is ' + this.age + ' year(s) old.'
// }
//}
//
//var user = new Person('Ryan', 26);
//
//var description = user.getUserDescription();
//console.log(description);<file_sep>var expect = require('expect');
var {makeMessage, makeLocationMessage} = require('./message');
describe('makeMessage', function() {
it('should create correct message object', function() {
var from = 'Ryan';
var text = 'Hello';
var message = makeMessage(from, text);
expect(message.createdAt).toBeA('number');
expect(message).toInclude({
from: from,
text: text
});
});
});
describe('makeLocationMessage', function() {
it('should create correct location object', function() {
var from = 'Betty';
var latitude = 25.5;
var longitude = 22.2;
var url = 'https://www.google.com/maps?q=25.5,22.2';
var message = makeLocationMessage(from, latitude, longitude);
expect(message.createdAt).toBeA('number');
expect(message).toInclude({
from: from,
url: url
});
});
}); | d1c8069704725a16722fca44f39a335e455f994d | [
"JavaScript"
] | 2 | JavaScript | gomteng218/socketio-chat-app | 4d541c8d751981fc06f29803ec603bfe35d412d0 | 928cfe11dd641812e9607dc1a51fbce5854bf244 |
refs/heads/master | <repo_name>AtlasAerospace/EridaCopter_Android<file_sep>/app/jni/jmavlink.cpp
#include "include_v1.0/ardupilotmega/version.h"
#include "include_v1.0/mavlink_types.h"
#include "include_v1.0/ardupilotmega/mavlink.h"
#include <string.h>
#include <jni.h>
//#include <android/log.h>
// Declare each of the known java classes
#include "classDeclarations.h"
jclass interface_class;
// Declare each of the parser functions.
// These convert from a MAVLink C message to the java equivalent.
#include "parseFunctions.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_MAVLink_MAVLink
* Method: init
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_MAVLink_MAVLink_init(JNIEnv * env, jclass){
// Load each of the known classes. Saves having to do it each and every time.
#include "classLoader.h"
// Also prepare the interface class
interface_class = env->FindClass( "com/MAVLink/Messages/IMAVLinkMessage");
}
/*
* Class: com_MAVLink_MAVLink
* Method: receivedByte
* Signature: (B)Lcom/bvcode/MAVLink/IMAVLinkMessage;
*/
JNIEXPORT jobject JNICALL Java_com_MAVLink_MAVLink_receivedByte(JNIEnv * env, jclass objNotUsed, jbyte b){
mavlink_message_t message;
mavlink_status_t status;
unsigned char data = b;
unsigned int decodeState = mavlink_parse_char(0 /*link->getId()*/, (uint8_t)(data), &message, &status);
if( decodeState == 1){
jobject result;
//__android_log_print(ANDROID_LOG_DEBUG, "TEST", "Received Msg: %d", message.msgid );
switch(message.msgid){
// Switch to the correct receive unpack function (defined in parseFunctions.h)
#include "switchReceive.h"
default:
result = NULL;
}
return result;
}
return NULL;
}
/*
* Class: com_MAVLink_MAVLink
* Method: createMessage
* Signature: (Lcom/bvcode/MAVLink/IMAVLinkMessage;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_com_MAVLink_MAVLink_createMessage(JNIEnv * env, jclass objNotUsed, jobject obj){
bool parsed = false;
mavlink_message_t msg;
int messageType = env->GetIntField (obj, env->GetFieldID(interface_class, "messageType", "I"));
switch(messageType){
#include "packSelection.h"
}
//---------------------------------------------------------------
// Off it goes.
if(parsed){
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
// Write message into buffer, prepending start sign
int len = mavlink_msg_to_send_buffer(buffer, &msg);
// Lets send it onto Java.
jbyteArray jb = env->NewByteArray(len);
// Get the elements (you probably have to fetch the length of the array as well
jbyte* data = env->GetByteArrayElements(jb, NULL);
for(int i = 0; i < len; i++)
data[i] = buffer[i];
// Don't forget to release it
env->ReleaseByteArrayElements(jb, data, 0);
return (jb);
}
return NULL;
}
#ifdef __cplusplus
}
#endif
<file_sep>/app/src/main/java/com/atlas/aerospace/framework/MAVLink.java
package com.atlas.aerospace.framework;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.MAVLink.MAVLinkPacket;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.Parser;
import com.MAVLink.common.msg_command_ack;
import com.MAVLink.common.msg_command_long;
import com.MAVLink.common.msg_global_position_int;
import com.MAVLink.common.msg_gps_raw_int;
import com.MAVLink.common.msg_gps_status;
import com.MAVLink.common.msg_heartbeat;
import com.MAVLink.common.msg_message_interval;
import com.MAVLink.common.msg_mission_ack;
import com.MAVLink.common.msg_mission_count;
import com.MAVLink.common.msg_mission_item;
import com.MAVLink.common.msg_mission_item_reached;
import com.MAVLink.common.msg_mission_request;
import com.MAVLink.common.msg_request_data_stream;
import com.MAVLink.common.msg_set_mode;
import com.MAVLink.common.msg_statustext;
import com.MAVLink.common.msg_sys_status;
import com.MAVLink.enums.MAV_CMD;
import com.MAVLink.enums.MAV_FRAME;
import com.MAVLink.enums.MAV_MISSION_RESULT;
import com.MAVLink.enums.MAV_MODE_FLAG;
import com.MAVLink.enums.MAV_RESULT;
import com.atlas.aerospace.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by killro on 15/02/16.
*/
public class MAVLink {
private ScheduledExecutorService heartbeatExecutor;
private OutputStream out;
private BufferedInputStream in;
private Drone drone;
private boolean first = true;
private Thread listenerThread;
private Interfaces.OnDroneListener droneCallback;
private Runnable armRetryRunnable = new Runnable() {
public void run() {
armDisarm(true);
Looper.myLooper().quit();
}
};
private final Runnable heartbeatRunnable = new Runnable() {
@Override
public void run() {
if(!drone.connected)
return;
msg_heartbeat sMsg = new msg_heartbeat(); {
sMsg.sysid = 0;
sMsg.compid = 0;
sMsg.type = drone.type;
sMsg.autopilot = drone.autopilot;
sMsg.base_mode = drone.baseMode;
sMsg.custom_mode = drone.customMode;
sMsg.system_status = drone.systemStatus;
}
sendToMAVLink(sMsg.pack());
}
};
public MAVLink(OutputStream out, BufferedInputStream in, Drone drone) {
this.out = out;
this.in = in;
this.drone = drone;
this.droneCallback = drone.droneListener;
listenerThread = new Thread(new SocketListenerThread()); // TODO: implement onDestroy method
listenerThread.start();
}
public void setMode(int customMode) {
msg_set_mode msg = new msg_set_mode();
msg.target_system = 0;
msg.base_mode = 1;
msg.custom_mode = customMode;
sendToMAVLink(msg.pack());
}
public void armDisarm(boolean arm) {
msg_command_long disarmMsg = new msg_command_long(); {
disarmMsg.target_system = 0;
disarmMsg.target_component = 0;
disarmMsg.command = MAV_CMD.MAV_CMD_COMPONENT_ARM_DISARM;
disarmMsg.param1 = arm ? 1 : 0;
disarmMsg.param2 = 0;
disarmMsg.param3 = 0;
disarmMsg.param4 = 0;
disarmMsg.param5 = 0;
disarmMsg.param6 = 0;
disarmMsg.param7 = 0;
disarmMsg.confirmation = 0;
}
sendToMAVLink(disarmMsg.pack());
}
public void sendMissionCount(int count) {
msg_mission_count missionCount = new msg_mission_count();
missionCount.target_system = 0;
missionCount.target_component = 0;
missionCount.count = count;
sendToMAVLink(missionCount.pack());
}
private void sendToMAVLink(MAVLinkPacket mavLinkPacket) {
final byte[] packet = mavLinkPacket.encodePacket();
final Runnable sendToMAVLinkRunnable = new Runnable() {
@Override
public void run() {
try {
out.write(packet);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(sendToMAVLinkRunnable).start();
}
public int getCommand(Interfaces.CommandTypes command) {
int mavLinkCommand = 0;
if(command == Interfaces.CommandTypes.WAYPOINT)
mavLinkCommand = MAV_CMD.MAV_CMD_NAV_WAYPOINT;
else if(command == Interfaces.CommandTypes.RTL)
mavLinkCommand = MAV_CMD.MAV_CMD_NAV_RETURN_TO_LAUNCH;
else if(command == Interfaces.CommandTypes.TAKEOFF)
mavLinkCommand = MAV_CMD.MAV_CMD_NAV_TAKEOFF;
return mavLinkCommand;
}
private void onMAVLinkDataReceived(final Parser parser, int bufferSize, byte[] buffer) {
for (int i = 0; i < bufferSize; i++) {
MAVLinkPacket receivedPacket = parser.mavlink_parse_char(buffer[i] & 0x00ff);
if (receivedPacket != null) {
final MAVLinkMessage msg = receivedPacket.unpack();
switch (msg.msgid) {
case msg_heartbeat.MAVLINK_MSG_ID_HEARTBEAT: {
msg_heartbeat hb = (msg_heartbeat) msg;
Log.d("copter", hb.toString());
if (first) {
drone.type = hb.type;
drone.autopilot = hb.autopilot;
drone.protocolVersion = hb.mavlink_version;
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
heartbeatExecutor.scheduleWithFixedDelay(heartbeatRunnable, 0, 1, TimeUnit.SECONDS);
first = false;
msg_request_data_stream req1 = new msg_request_data_stream();
req1.sysid = 0;
req1.compid = 0;
req1.req_message_rate = 1;
req1.req_stream_id = 0;
req1.start_stop = 1;
req1.target_system = 0;
req1.target_component = 0;
sendToMAVLink(req1.pack());
setMode(0);
droneCallback.onDroneEvent(Interfaces.DroneEventsType.FIRST_HEARTBEAT);
}
drone.baseMode = hb.base_mode;
drone.customMode = hb.custom_mode;
drone.systemStatus = hb.system_status;
if((drone.baseMode & MAV_MODE_FLAG.MAV_MODE_FLAG_SAFETY_ARMED) != 0) {
if(!drone.armed) {
drone.armed = true;
droneCallback.onDroneEvent(Interfaces.DroneEventsType.ARMED);
}
} else if(drone.armed) {
drone.armed = false;
}
break;
}
case msg_command_ack.MAVLINK_MSG_ID_COMMAND_ACK: {
final msg_command_ack commandAck = (msg_command_ack) msg;
Log.d("copter", commandAck.toString());
if(commandAck.command == MAV_CMD.MAV_CMD_COMPONENT_ARM_DISARM && commandAck.result == MAV_RESULT.MAV_RESULT_FAILED) {
if (Looper.myLooper() == null) {
Looper.prepare();
}
new android.os.Handler().postDelayed(armRetryRunnable, 1000);
Looper.loop();
}
/*if (commandAck.result == MAV_RESULT.MAV_RESULT_ACCEPTED && !copter.armed) {
copter.armed = true;
}*/
break;
}
case msg_mission_ack.MAVLINK_MSG_ID_MISSION_ACK: {
msg_mission_ack missionAck = (msg_mission_ack) msg;
if(missionAck.type == MAV_MISSION_RESULT.MAV_MISSION_ACCEPTED) {
msg_command_long missionStartMsg = new msg_command_long(); {
missionStartMsg.target_system = 0;
missionStartMsg.target_component = 0;
missionStartMsg.command = MAV_CMD.MAV_CMD_MISSION_START;
missionStartMsg.param1 = 0; // here
missionStartMsg.param2 = drone.getMissionCount();
missionStartMsg.param3 = 0;
missionStartMsg.param4 = 0;
missionStartMsg.param5 = 0;
missionStartMsg.param6 = 0;
missionStartMsg.param7 = 0;
missionStartMsg.confirmation = 0;
}
Log.d("copter", missionStartMsg.toString());
sendToMAVLink(missionStartMsg.pack());
}
break;
}
case msg_mission_request.MAVLINK_MSG_ID_MISSION_REQUEST: {
msg_mission_request missionRequest = (msg_mission_request) msg;
msg_mission_item mavMsg = new msg_mission_item();
mavMsg.target_component = 0;
mavMsg.target_system = 0;
mavMsg.frame = MAV_FRAME.MAV_FRAME_GLOBAL_RELATIVE_ALT;
mavMsg.current = 0;
mavMsg.param1 = 0;
mavMsg.param2 = 0;
mavMsg.param3 = 0;
mavMsg.param4 = 0;
mavMsg.autocontinue = 1;
HashMap<String, Object> missionData = drone.getMission(missionRequest.seq);
mavMsg.command = getCommand((Interfaces.CommandTypes) missionData.get("command"));
mavMsg.seq = missionRequest.seq;
mavMsg.z = (Float) missionData.get("z");
mavMsg.x = (Float) missionData.get("x");
mavMsg.y = (Float) missionData.get("y");
sendToMAVLink(mavMsg.pack());
break;
}
case msg_mission_item_reached.MAVLINK_MSG_ID_MISSION_ITEM_REACHED: {
if(msg instanceof msg_mission_item_reached) {
msg_mission_item_reached missionItemReached = (msg_mission_item_reached) msg;
Log.d("copter", "Hiya Mission number " + Integer.toString(missionItemReached.seq) + " finished");
} else if(msg instanceof msg_mission_request) {
msg_mission_request missionItemReached = (msg_mission_request) msg;
Log.d("copter", "Mission number " + Integer.toString(missionItemReached.seq) + " finished");
}
break;
}
case msg_global_position_int.MAVLINK_MSG_ID_GLOBAL_POSITION_INT: {
final msg_global_position_int globalPositionInt = (msg_global_position_int) msg;
double lat = (double) (globalPositionInt.lat / 10000000.0);
double lon = (double) (globalPositionInt.lon / 10000000.0);
if(lat != drone.lat || lon != drone.lon) {
drone.lat = lat;
drone.lon = lon;
droneCallback.onDroneEvent(Interfaces.DroneEventsType.LOCATION_UPDATED);
}
if(globalPositionInt.relative_alt >= 0 && globalPositionInt.relative_alt != drone.altitude) {
drone.altitude = globalPositionInt.relative_alt;
droneCallback.onDroneEvent(Interfaces.DroneEventsType.ALTITUDE_UPDATED);
}
break;
}
case msg_gps_raw_int.MAVLINK_MSG_ID_GPS_RAW_INT: {
final msg_gps_raw_int gpsRawInt = (msg_gps_raw_int) msg;
if(gpsRawInt.satellites_visible != drone.satellitesCount) {
drone.satellitesCount = gpsRawInt.satellites_visible;
droneCallback.onDroneEvent(Interfaces.DroneEventsType.SATELLITES_COUNT_UPDATED);
}
break;
}
case msg_sys_status.MAVLINK_MSG_ID_SYS_STATUS: {
final msg_sys_status sysStatus = (msg_sys_status) msg;
int batteryRemaining = (int) sysStatus.battery_remaining;
float batteryVoltage = sysStatus.voltage_battery / 1000;
if(batteryRemaining == -1)
batteryRemaining = 100;
if(batteryRemaining != drone.batteryRemainingPercentage || batteryVoltage != drone.batteryVoltage) {
drone.batteryRemainingPercentage = batteryRemaining;
drone.batteryVoltage = batteryVoltage;
droneCallback.onDroneEvent(Interfaces.DroneEventsType.BATTERY_UPDATED);
}
break;
}
case msg_statustext.MAVLINK_MSG_ID_STATUSTEXT: {
msg_statustext statusText = (msg_statustext) msg;
// Log.d("copter", "Statustext: " + statusText.toString());
break;
}
default: {
//Log.d("copter", "Msg with id " + Integer.toString(msg.msgid) + " received");
}
/* default: {
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(currentContext, Integer.toString(msg.msgid), Toast.LENGTH_SHORT).show();
}
});
}*/
}
}
}
}
public class SocketListenerThread implements Runnable {
public void run() {
final Parser parser = new Parser();
parser.stats.mavlinkResetStats();
final byte[] readBuffer = new byte[263];
while (!Thread.currentThread().isInterrupted()) {
try {
int bufferSize = in.read(readBuffer);
if (bufferSize < 1) {
continue;
}
onMAVLinkDataReceived(parser, bufferSize, readBuffer);
} catch (IOException e) {
drone.connected = false;
}
}
}
}
}
<file_sep>/app/jni/classLoader.h
heartbeat_class= env->FindClass( "com/MAVLink/Messages/common/msg_heartbeat");
sys_status_class= env->FindClass( "com/MAVLink/Messages/common/msg_sys_status");
system_time_class= env->FindClass( "com/MAVLink/Messages/common/msg_system_time");
ping_class= env->FindClass( "com/MAVLink/Messages/common/msg_ping");
change_operator_control_class= env->FindClass( "com/MAVLink/Messages/common/msg_change_operator_control");
change_operator_control_ack_class= env->FindClass( "com/MAVLink/Messages/common/msg_change_operator_control_ack");
auth_key_class= env->FindClass( "com/MAVLink/Messages/common/msg_auth_key");
set_mode_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_mode");
param_request_read_class= env->FindClass( "com/MAVLink/Messages/common/msg_param_request_read");
param_request_list_class= env->FindClass( "com/MAVLink/Messages/common/msg_param_request_list");
param_value_class= env->FindClass( "com/MAVLink/Messages/common/msg_param_value");
param_set_class= env->FindClass( "com/MAVLink/Messages/common/msg_param_set");
gps_raw_int_class= env->FindClass( "com/MAVLink/Messages/common/msg_gps_raw_int");
gps_status_class= env->FindClass( "com/MAVLink/Messages/common/msg_gps_status");
scaled_imu_class= env->FindClass( "com/MAVLink/Messages/common/msg_scaled_imu");
raw_imu_class= env->FindClass( "com/MAVLink/Messages/common/msg_raw_imu");
raw_pressure_class= env->FindClass( "com/MAVLink/Messages/common/msg_raw_pressure");
scaled_pressure_class= env->FindClass( "com/MAVLink/Messages/common/msg_scaled_pressure");
attitude_class= env->FindClass( "com/MAVLink/Messages/common/msg_attitude");
//attitude_quaternion_class= env->FindClass( "com/MAVLink/Messages/common/msg_attitude_quaternion");
//local_position_ned_class= env->FindClass( "com/MAVLink/Messages/common/msg_local_position_ned");
global_position_int_class= env->FindClass( "com/MAVLink/Messages/common/msg_global_position_int");
rc_channels_scaled_class= env->FindClass( "com/MAVLink/Messages/common/msg_rc_channels_scaled");
rc_channels_raw_class= env->FindClass( "com/MAVLink/Messages/common/msg_rc_channels_raw");
servo_output_raw_class= env->FindClass( "com/MAVLink/Messages/common/msg_servo_output_raw");
//mission_request_partial_list_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_request_partial_list");
//mission_write_partial_list_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_write_partial_list");
mission_item_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint");
mission_request_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_request");
mission_set_current_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_set_current");
mission_current_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_current");
mission_request_list_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_request_list");
mission_count_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_count");
mission_clear_all_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_clear_all");
//mission_item_reached_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_item_reached");
mission_ack_class= env->FindClass( "com/MAVLink/Messages/common/msg_waypoint_ack");
//set_gps_global_origin_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_gps_global_origin");
//gps_global_origin_class= env->FindClass( "com/MAVLink/Messages/common/msg_gps_global_origin");
//set_local_position_setpoint_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_local_position_setpoint");
local_position_setpoint_class= env->FindClass( "com/MAVLink/Messages/common/msg_local_position_setpoint");
//global_position_setpoint_int_class= env->FindClass( "com/MAVLink/Messages/common/msg_global_position_setpoint_int");
//set_global_position_setpoint_int_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_global_position_setpoint_int");
safety_set_allowed_area_class= env->FindClass( "com/MAVLink/Messages/common/msg_safety_set_allowed_area");
safety_allowed_area_class= env->FindClass( "com/MAVLink/Messages/common/msg_safety_allowed_area");
set_roll_pitch_yaw_thrust_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_roll_pitch_yaw_thrust");
set_roll_pitch_yaw_speed_thrust_class= env->FindClass( "com/MAVLink/Messages/common/msg_set_roll_pitch_yaw_speed_thrust");
roll_pitch_yaw_thrust_setpoint_class= env->FindClass( "com/MAVLink/Messages/common/msg_roll_pitch_yaw_thrust_setpoint");
roll_pitch_yaw_speed_thrust_setpoint_class= env->FindClass( "com/MAVLink/Messages/common/msg_roll_pitch_yaw_speed_thrust_setpoint");
nav_controller_output_class= env->FindClass( "com/MAVLink/Messages/common/msg_nav_controller_output");
state_correction_class= env->FindClass( "com/MAVLink/Messages/common/msg_state_correction");
request_data_stream_class= env->FindClass( "com/MAVLink/Messages/common/msg_request_data_stream");
//data_stream_class= env->FindClass( "com/MAVLink/Messages/common/msg_data_stream");
manual_control_class= env->FindClass( "com/MAVLink/Messages/common/msg_manual_control");
rc_channels_override_class= env->FindClass( "com/MAVLink/Messages/common/msg_rc_channels_override");
vfr_hud_class= env->FindClass( "com/MAVLink/Messages/common/msg_vfr_hud");
command_long_class= env->FindClass( "com/MAVLink/Messages/common/msg_command_long");
command_ack_class= env->FindClass( "com/MAVLink/Messages/common/msg_command_ack");
hil_state_class= env->FindClass( "com/MAVLink/Messages/common/msg_hil_state");
hil_controls_class= env->FindClass( "com/MAVLink/Messages/common/msg_hil_controls");
//hil_rc_inputs_raw_class= env->FindClass( "com/MAVLink/Messages/common/msg_hil_rc_inputs_raw");
optical_flow_class= env->FindClass( "com/MAVLink/Messages/common/msg_optical_flow");
//global_vision_position_estimate_class= env->FindClass( "com/MAVLink/Messages/common/msg_global_vision_position_estimate");
//vision_position_estimate_class= env->FindClass( "com/MAVLink/Messages/common/msg_vision_position_estimate");
//vision_speed_estimate_class= env->FindClass( "com/MAVLink/Messages/common/msg_vision_speed_estimate");
//vicon_position_estimate_class= env->FindClass( "com/MAVLink/Messages/common/msg_vicon_position_estimate");
//memory_vect_class= env->FindClass( "com/MAVLink/Messages/common/msg_memory_vect");
debug_vect_class= env->FindClass( "com/MAVLink/Messages/common/msg_debug_vect");
named_value_float_class= env->FindClass( "com/MAVLink/Messages/common/msg_named_value_float");
named_value_int_class= env->FindClass( "com/MAVLink/Messages/common/msg_named_value_int");
statustext_class= env->FindClass( "com/MAVLink/Messages/common/msg_statustext");
debug_class= env->FindClass( "com/MAVLink/Messages/common/msg_debug");
//extended_message_class= env->FindClass( "com/MAVLink/Messages/common/msg_extended_message");
sensor_offsets_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_sensor_offsets");
set_mag_offsets_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_set_mag_offsets");
meminfo_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_meminfo");
ap_adc_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_ap_adc");
digicam_configure_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_digicam_configure");
digicam_control_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_digicam_control");
mount_configure_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_mount_configure");
mount_control_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_mount_control");
mount_status_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_mount_status");
//fence_point_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_fence_point");
//fence_fetch_point_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_fence_fetch_point");
//fence_status_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_fence_status");
//ahrs_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_ahrs");
//simstate_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_simstate");
//hwstatus_class= env->FindClass( "com/MAVLink/Messages/ardupilotmega/msg_hwstatus");
<file_sep>/app/jni/packSelection.h
case MAVLINK_MSG_ID_HEARTBEAT:
pack_msg_heartbeat(env, heartbeat_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SYS_STATUS:
pack_msg_sys_status(env, sys_status_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SYSTEM_TIME:
pack_msg_system_time(env, system_time_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_PING:
pack_msg_ping(env, ping_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL:
pack_msg_change_operator_control(env, change_operator_control_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK:
pack_msg_change_operator_control_ack(env, change_operator_control_ack_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_AUTH_KEY:
pack_msg_auth_key(env, auth_key_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_MODE:
pack_msg_set_mode(env, set_mode_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
pack_msg_param_request_read(env, param_request_read_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
pack_msg_param_request_list(env, param_request_list_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_PARAM_VALUE:
pack_msg_param_value(env, param_value_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_PARAM_SET:
pack_msg_param_set(env, param_set_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GPS_RAW_INT:
pack_msg_gps_raw_int(env, gps_raw_int_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GPS_STATUS:
pack_msg_gps_status(env, gps_status_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SCALED_IMU:
pack_msg_scaled_imu(env, scaled_imu_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_RAW_IMU:
pack_msg_raw_imu(env, raw_imu_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_RAW_PRESSURE:
pack_msg_raw_pressure(env, raw_pressure_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SCALED_PRESSURE:
pack_msg_scaled_pressure(env, scaled_pressure_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_ATTITUDE:
pack_msg_attitude(env, attitude_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_ATTITUDE_QUATERNION:
pack_msg_attitude_quaternion(env, attitude_quaternion_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_LOCAL_POSITION_NED:
pack_msg_local_position_ned(env, local_position_ned_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
pack_msg_global_position_int(env, global_position_int_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_RC_CHANNELS_SCALED:
pack_msg_rc_channels_scaled(env, rc_channels_scaled_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_RC_CHANNELS_RAW:
pack_msg_rc_channels_raw(env, rc_channels_raw_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SERVO_OUTPUT_RAW:
pack_msg_servo_output_raw(env, servo_output_raw_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST:
pack_msg_mission_request_partial_list(env, mission_request_partial_list_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST:
pack_msg_mission_write_partial_list(env, mission_write_partial_list_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_ITEM:
pack_msg_mission_item(env, mission_item_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_REQUEST:
pack_msg_mission_request(env, mission_request_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
pack_msg_mission_set_current(env, mission_set_current_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_CURRENT:
pack_msg_mission_current(env, mission_current_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
pack_msg_mission_request_list(env, mission_request_list_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_COUNT:
pack_msg_mission_count(env, mission_count_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
pack_msg_mission_clear_all(env, mission_clear_all_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_ITEM_REACHED:
pack_msg_mission_item_reached(env, mission_item_reached_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MISSION_ACK:
pack_msg_mission_ack(env, mission_ack_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
pack_msg_set_gps_global_origin(env, set_gps_global_origin_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN:
pack_msg_gps_global_origin(env, gps_global_origin_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_LOCAL_POSITION_SETPOINT:
pack_msg_set_local_position_setpoint(env, set_local_position_setpoint_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT:
pack_msg_local_position_setpoint(env, local_position_setpoint_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GLOBAL_POSITION_SETPOINT_INT:
pack_msg_global_position_setpoint_int(env, global_position_setpoint_int_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_GLOBAL_POSITION_SETPOINT_INT:
pack_msg_set_global_position_setpoint_int(env, set_global_position_setpoint_int_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA:
pack_msg_safety_set_allowed_area(env, safety_set_allowed_area_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA:
pack_msg_safety_allowed_area(env, safety_allowed_area_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_THRUST:
pack_msg_set_roll_pitch_yaw_thrust(env, set_roll_pitch_yaw_thrust_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_SPEED_THRUST:
pack_msg_set_roll_pitch_yaw_speed_thrust(env, set_roll_pitch_yaw_speed_thrust_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT:
pack_msg_roll_pitch_yaw_thrust_setpoint(env, roll_pitch_yaw_thrust_setpoint_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT:
pack_msg_roll_pitch_yaw_speed_thrust_setpoint(env, roll_pitch_yaw_speed_thrust_setpoint_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT:
pack_msg_nav_controller_output(env, nav_controller_output_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_STATE_CORRECTION:
pack_msg_state_correction(env, state_correction_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_REQUEST_DATA_STREAM:
pack_msg_request_data_stream(env, request_data_stream_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_DATA_STREAM:
pack_msg_data_stream(env, data_stream_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MANUAL_CONTROL:
pack_msg_manual_control(env, manual_control_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
pack_msg_rc_channels_override(env, rc_channels_override_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_VFR_HUD:
pack_msg_vfr_hud(env, vfr_hud_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_COMMAND_LONG:
pack_msg_command_long(env, command_long_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_COMMAND_ACK:
pack_msg_command_ack(env, command_ack_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_HIL_STATE:
pack_msg_hil_state(env, hil_state_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_HIL_CONTROLS:
pack_msg_hil_controls(env, hil_controls_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW:
pack_msg_hil_rc_inputs_raw(env, hil_rc_inputs_raw_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_OPTICAL_FLOW:
pack_msg_optical_flow(env, optical_flow_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE:
pack_msg_global_vision_position_estimate(env, global_vision_position_estimate_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE:
pack_msg_vision_position_estimate(env, vision_position_estimate_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE:
pack_msg_vision_speed_estimate(env, vision_speed_estimate_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE:
pack_msg_vicon_position_estimate(env, vicon_position_estimate_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MEMORY_VECT:
pack_msg_memory_vect(env, memory_vect_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_DEBUG_VECT:
pack_msg_debug_vect(env, debug_vect_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_NAMED_VALUE_FLOAT:
pack_msg_named_value_float(env, named_value_float_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_NAMED_VALUE_INT:
pack_msg_named_value_int(env, named_value_int_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_STATUSTEXT:
pack_msg_statustext(env, statustext_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_DEBUG:
pack_msg_debug(env, debug_class, obj, msg);
parsed=true;
break;
// case MAVLINK_MSG_ID_EXTENDED_MESSAGE:
// pack_msg_extended_message(env, extended_message_class, obj, msg);
// parsed=true;
// break;
case MAVLINK_MSG_ID_SENSOR_OFFSETS:
pack_msg_sensor_offsets(env, sensor_offsets_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SET_MAG_OFFSETS:
pack_msg_set_mag_offsets(env, set_mag_offsets_class, obj, msg);
parsed=true;
break;
// case MAVLINK_MSG_ID_MEMINFO:
// pack_msg_meminfo(env, meminfo_class, obj, msg);
// parsed=true;
// break;
case MAVLINK_MSG_ID_AP_ADC:
pack_msg_ap_adc(env, ap_adc_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_DIGICAM_CONFIGURE:
pack_msg_digicam_configure(env, digicam_configure_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_DIGICAM_CONTROL:
pack_msg_digicam_control(env, digicam_control_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MOUNT_CONFIGURE:
pack_msg_mount_configure(env, mount_configure_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MOUNT_CONTROL:
pack_msg_mount_control(env, mount_control_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_MOUNT_STATUS:
pack_msg_mount_status(env, mount_status_class, obj, msg);
parsed=true;
break;
/*
case MAVLINK_MSG_ID_FENCE_POINT:
pack_msg_fence_point(env, fence_point_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_FENCE_FETCH_POINT:
pack_msg_fence_fetch_point(env, fence_fetch_point_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_FENCE_STATUS:
pack_msg_fence_status(env, fence_status_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_AHRS:
pack_msg_ahrs(env, ahrs_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_SIMSTATE:
pack_msg_simstate(env, simstate_class, obj, msg);
parsed=true;
break;
case MAVLINK_MSG_ID_HWSTATUS:
pack_msg_hwstatus(env, hwstatus_class, obj, msg);
parsed=true;
break;*/
<file_sep>/app/jni/switchReceive.h
case MAVLINK_MSG_ID_HEARTBEAT:
result = unpack_msg_heartbeat(env, message);
break;
case MAVLINK_MSG_ID_SYS_STATUS:
result = unpack_msg_sys_status(env, message);
break;
case MAVLINK_MSG_ID_SYSTEM_TIME:
result = unpack_msg_system_time(env, message);
break;
case MAVLINK_MSG_ID_PING:
result = unpack_msg_ping(env, message);
break;
case MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL:
result = unpack_msg_change_operator_control(env, message);
break;
case MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK:
result = unpack_msg_change_operator_control_ack(env, message);
break;
case MAVLINK_MSG_ID_AUTH_KEY:
result = unpack_msg_auth_key(env, message);
break;
case MAVLINK_MSG_ID_SET_MODE:
result = unpack_msg_set_mode(env, message);
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
result = unpack_msg_param_request_read(env, message);
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
result = unpack_msg_param_request_list(env, message);
break;
case MAVLINK_MSG_ID_PARAM_VALUE:
result = unpack_msg_param_value(env, message);
break;
case MAVLINK_MSG_ID_PARAM_SET:
result = unpack_msg_param_set(env, message);
break;
case MAVLINK_MSG_ID_GPS_RAW_INT:
result = unpack_msg_gps_raw_int(env, message);
break;
case MAVLINK_MSG_ID_GPS_STATUS:
result = unpack_msg_gps_status(env, message);
break;
case MAVLINK_MSG_ID_SCALED_IMU:
result = unpack_msg_scaled_imu(env, message);
break;
case MAVLINK_MSG_ID_RAW_IMU:
result = unpack_msg_raw_imu(env, message);
break;
case MAVLINK_MSG_ID_RAW_PRESSURE:
result = unpack_msg_raw_pressure(env, message);
break;
case MAVLINK_MSG_ID_SCALED_PRESSURE:
result = unpack_msg_scaled_pressure(env, message);
break;
case MAVLINK_MSG_ID_ATTITUDE:
result = unpack_msg_attitude(env, message);
break;
case MAVLINK_MSG_ID_ATTITUDE_QUATERNION:
result = unpack_msg_attitude_quaternion(env, message);
break;
case MAVLINK_MSG_ID_LOCAL_POSITION_NED:
result = unpack_msg_local_position_ned(env, message);
break;
case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
result = unpack_msg_global_position_int(env, message);
break;
case MAVLINK_MSG_ID_RC_CHANNELS_SCALED:
result = unpack_msg_rc_channels_scaled(env, message);
break;
case MAVLINK_MSG_ID_RC_CHANNELS_RAW:
result = unpack_msg_rc_channels_raw(env, message);
break;
case MAVLINK_MSG_ID_SERVO_OUTPUT_RAW:
result = unpack_msg_servo_output_raw(env, message);
break;
case MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST:
result = unpack_msg_mission_request_partial_list(env, message);
break;
case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST:
result = unpack_msg_mission_write_partial_list(env, message);
break;
case MAVLINK_MSG_ID_MISSION_ITEM:
result = unpack_msg_mission_item(env, message);
break;
case MAVLINK_MSG_ID_MISSION_REQUEST:
result = unpack_msg_mission_request(env, message);
break;
case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
result = unpack_msg_mission_set_current(env, message);
break;
/*
case MAVLINK_MSG_ID_MISSION_CURRENT:
result = unpack_msg_mission_current(env, message);
break;
*/
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
result = unpack_msg_mission_request_list(env, message);
break;
case MAVLINK_MSG_ID_MISSION_COUNT:
result = unpack_msg_mission_count(env, message);
break;
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
result = unpack_msg_mission_clear_all(env, message);
break;
case MAVLINK_MSG_ID_MISSION_ITEM_REACHED:
result = unpack_msg_mission_item_reached(env, message);
break;
case MAVLINK_MSG_ID_MISSION_ACK:
result = unpack_msg_mission_ack(env, message);
break;
case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
result = unpack_msg_set_gps_global_origin(env, message);
break;
case MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN:
result = unpack_msg_gps_global_origin(env, message);
break;
case MAVLINK_MSG_ID_SET_LOCAL_POSITION_SETPOINT:
result = unpack_msg_set_local_position_setpoint(env, message);
break;
case MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT:
result = unpack_msg_local_position_setpoint(env, message);
break;
case MAVLINK_MSG_ID_GLOBAL_POSITION_SETPOINT_INT:
result = unpack_msg_global_position_setpoint_int(env, message);
break;
case MAVLINK_MSG_ID_SET_GLOBAL_POSITION_SETPOINT_INT:
result = unpack_msg_set_global_position_setpoint_int(env, message);
break;
case MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA:
result = unpack_msg_safety_set_allowed_area(env, message);
break;
case MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA:
result = unpack_msg_safety_allowed_area(env, message);
break;
case MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_THRUST:
result = unpack_msg_set_roll_pitch_yaw_thrust(env, message);
break;
case MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_SPEED_THRUST:
result = unpack_msg_set_roll_pitch_yaw_speed_thrust(env, message);
break;
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT:
result = unpack_msg_roll_pitch_yaw_thrust_setpoint(env, message);
break;
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT:
result = unpack_msg_roll_pitch_yaw_speed_thrust_setpoint(env, message);
break;
case MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT:
result = unpack_msg_nav_controller_output(env, message);
break;
case MAVLINK_MSG_ID_STATE_CORRECTION:
result = unpack_msg_state_correction(env, message);
break;
case MAVLINK_MSG_ID_REQUEST_DATA_STREAM:
result = unpack_msg_request_data_stream(env, message);
break;
case MAVLINK_MSG_ID_DATA_STREAM:
result = unpack_msg_data_stream(env, message);
break;
case MAVLINK_MSG_ID_MANUAL_CONTROL:
result = unpack_msg_manual_control(env, message);
break;
case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
result = unpack_msg_rc_channels_override(env, message);
break;
case MAVLINK_MSG_ID_VFR_HUD:
result = unpack_msg_vfr_hud(env, message);
break;
case MAVLINK_MSG_ID_COMMAND_LONG:
result = unpack_msg_command_long(env, message);
break;
case MAVLINK_MSG_ID_COMMAND_ACK:
result = unpack_msg_command_ack(env, message);
break;
case MAVLINK_MSG_ID_HIL_STATE:
result = unpack_msg_hil_state(env, message);
break;
case MAVLINK_MSG_ID_HIL_CONTROLS:
result = unpack_msg_hil_controls(env, message);
break;
case MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW:
result = unpack_msg_hil_rc_inputs_raw(env, message);
break;
case MAVLINK_MSG_ID_OPTICAL_FLOW:
result = unpack_msg_optical_flow(env, message);
break;
case MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE:
result = unpack_msg_global_vision_position_estimate(env, message);
break;
case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE:
result = unpack_msg_vision_position_estimate(env, message);
break;
case MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE:
result = unpack_msg_vision_speed_estimate(env, message);
break;
case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE:
result = unpack_msg_vicon_position_estimate(env, message);
break;
case MAVLINK_MSG_ID_MEMORY_VECT:
result = unpack_msg_memory_vect(env, message);
break;
case MAVLINK_MSG_ID_DEBUG_VECT:
result = unpack_msg_debug_vect(env, message);
break;
case MAVLINK_MSG_ID_NAMED_VALUE_FLOAT:
result = unpack_msg_named_value_float(env, message);
break;
case MAVLINK_MSG_ID_NAMED_VALUE_INT:
result = unpack_msg_named_value_int(env, message);
break;
case MAVLINK_MSG_ID_STATUSTEXT:
result = unpack_msg_statustext(env, message);
break;
case MAVLINK_MSG_ID_DEBUG:
result = unpack_msg_debug(env, message);
break;
// case MAVLINK_MSG_ID_EXTENDED_MESSAGE:
// result = unpack_msg_extended_message(env, message);
// break;
case MAVLINK_MSG_ID_SENSOR_OFFSETS:
result = unpack_msg_sensor_offsets(env, message);
break;
case MAVLINK_MSG_ID_SET_MAG_OFFSETS:
result = unpack_msg_set_mag_offsets(env, message);
break;
// case MAVLINK_MSG_ID_MEMINFO:
// result = unpack_msg_meminfo(env, message);
// break;
case MAVLINK_MSG_ID_AP_ADC:
result = unpack_msg_ap_adc(env, message);
break;
case MAVLINK_MSG_ID_DIGICAM_CONFIGURE:
result = unpack_msg_digicam_configure(env, message);
break;
case MAVLINK_MSG_ID_DIGICAM_CONTROL:
result = unpack_msg_digicam_control(env, message);
break;
case MAVLINK_MSG_ID_MOUNT_CONFIGURE:
result = unpack_msg_mount_configure(env, message);
break;
case MAVLINK_MSG_ID_MOUNT_CONTROL:
result = unpack_msg_mount_control(env, message);
break;
case MAVLINK_MSG_ID_MOUNT_STATUS:
result = unpack_msg_mount_status(env, message);
break;
/*
case MAVLINK_MSG_ID_FENCE_POINT:
result = unpack_msg_fence_point(env, message);
break;
case MAVLINK_MSG_ID_FENCE_FETCH_POINT:
result = unpack_msg_fence_fetch_point(env, message);
break;
case MAVLINK_MSG_ID_FENCE_STATUS:
result = unpack_msg_fence_status(env, message);
break;
case MAVLINK_MSG_ID_AHRS:
result = unpack_msg_ahrs(env, message);
break;
case MAVLINK_MSG_ID_SIMSTATE:
result = unpack_msg_simstate(env, message);
break;
case MAVLINK_MSG_ID_HWSTATUS:
result = unpack_msg_hwstatus(env, message);
break;*/
<file_sep>/app/jni/classDeclarations.h
jclass heartbeat_class;
jclass sys_status_class;
jclass system_time_class;
jclass ping_class;
jclass change_operator_control_class;
jclass change_operator_control_ack_class;
jclass auth_key_class;
jclass set_mode_class;
jclass param_request_read_class;
jclass param_request_list_class;
jclass param_value_class;
jclass param_set_class;
jclass gps_raw_int_class;
jclass gps_status_class;
jclass scaled_imu_class;
jclass raw_imu_class;
jclass raw_pressure_class;
jclass scaled_pressure_class;
jclass attitude_class;
jclass attitude_quaternion_class;
jclass local_position_ned_class;
jclass global_position_int_class;
jclass rc_channels_scaled_class;
jclass rc_channels_raw_class;
jclass servo_output_raw_class;
jclass mission_request_partial_list_class;
jclass mission_write_partial_list_class;
jclass mission_item_class;
jclass mission_request_class;
jclass mission_set_current_class;
jclass mission_current_class;
jclass mission_request_list_class;
jclass mission_count_class;
jclass mission_clear_all_class;
jclass mission_item_reached_class;
jclass mission_ack_class;
jclass set_gps_global_origin_class;
jclass gps_global_origin_class;
jclass set_local_position_setpoint_class;
jclass local_position_setpoint_class;
jclass global_position_setpoint_int_class;
jclass set_global_position_setpoint_int_class;
jclass safety_set_allowed_area_class;
jclass safety_allowed_area_class;
jclass set_roll_pitch_yaw_thrust_class;
jclass set_roll_pitch_yaw_speed_thrust_class;
jclass roll_pitch_yaw_thrust_setpoint_class;
jclass roll_pitch_yaw_speed_thrust_setpoint_class;
jclass nav_controller_output_class;
jclass state_correction_class;
jclass request_data_stream_class;
jclass data_stream_class;
jclass manual_control_class;
jclass rc_channels_override_class;
jclass vfr_hud_class;
jclass command_long_class;
jclass command_ack_class;
jclass hil_state_class;
jclass hil_controls_class;
jclass hil_rc_inputs_raw_class;
jclass optical_flow_class;
jclass global_vision_position_estimate_class;
jclass vision_position_estimate_class;
jclass vision_speed_estimate_class;
jclass vicon_position_estimate_class;
jclass memory_vect_class;
jclass debug_vect_class;
jclass named_value_float_class;
jclass named_value_int_class;
jclass statustext_class;
jclass debug_class;
jclass extended_message_class;
jclass sensor_offsets_class;
jclass set_mag_offsets_class;
jclass meminfo_class;
jclass ap_adc_class;
jclass digicam_configure_class;
jclass digicam_control_class;
jclass mount_configure_class;
jclass mount_control_class;
jclass mount_status_class;
jclass fence_point_class;
jclass fence_fetch_point_class;
jclass fence_status_class;
jclass ahrs_class;
jclass simstate_class;
jclass hwstatus_class;
<file_sep>/app/src/main/java/com/atlas/aerospace/app/MainActivity.java
package com.atlas.aerospace.app;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.MAVLink.enums.MAV_CMD;
import com.atlas.aerospace.R;
import com.atlas.aerospace.framework.Drone;
import com.atlas.aerospace.framework.Interfaces;
import com.atlas.aerospace.framework.Mission;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Calendar;
import java.util.List;
/**
* Created by killro on 15/02/16.
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private String copterIp = "192.168.0.192";
private int copterPort = 5760;
//private String copterIp = "192.168.0.99";
//private int copterPort = 6789;
private Drone drone;
private GoogleMap map = null;
private LocationManager mLocationManager;
private Marker copterMarker = null, userMarker = null;
public Interfaces.OnDroneListener droneListener = new Interfaces.OnDroneListener() {
@Override
public void onDroneEvent(Interfaces.DroneEventsType eventType) {
if (eventType == Interfaces.DroneEventsType.CONNECTED) {
} else if (eventType == Interfaces.DroneEventsType.FIRST_HEARTBEAT) {
Mission mission = new Mission();
mission.add(56.97852312f, 24.21056271f, 20);
mission.add(56.97869998f, 24.21020329f, 20);
drone.startMission(mission);
} else if(eventType == Interfaces.DroneEventsType.LOCATION_UPDATED) {
if(map != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (copterMarker == null) {
copterMarker = map.addMarker(new MarkerOptions()
.position(new LatLng(drone.lat, drone.lon))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.quadcopter)));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(copterMarker.getPosition(), 18));
} else {
copterMarker.setPosition(new LatLng(drone.lat, drone.lon));
}
}
});
}
} else if(eventType == Interfaces.DroneEventsType.ALTITUDE_UPDATED) {
runOnUiThread(new Runnable() {
@Override
public void run() {
double altitude = round(drone.altitude / 1000, 1);
String altitudeStr;
if(altitude == (int) altitude)
altitudeStr = Integer.toString((int) altitude);
else
altitudeStr = Double.toString(altitude);
((TextView) findViewById(R.id.altitude)).setText(altitudeStr);
}
});
} else if(eventType == Interfaces.DroneEventsType.SATELLITES_COUNT_UPDATED) {
runOnUiThread(new Runnable() {
@Override
public void run() {
((TextView) findViewById(R.id.satellitesCount)).setText(Integer.toString(drone.satellitesCount));
}
});
} else if(eventType == Interfaces.DroneEventsType.BATTERY_UPDATED) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String batteryVoltageStr;
if(drone.batteryVoltage == (int) drone.batteryVoltage)
batteryVoltageStr = Integer.toString((int) drone.batteryVoltage);
else
batteryVoltageStr = Float.toString(drone.batteryVoltage);
((TextView) findViewById(R.id.batteryPercentage)).setText(Integer.toString(drone.batteryRemainingPercentage));
((TextView) findViewById(R.id.voltage)).setText(batteryVoltageStr);
}
});
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drone = new Drone(droneListener);
drone.connect(copterIp, copterPort);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
Log.d("location", "let's use recent location");
processUserGpsLocation(location);
}// else {
Log.d("location", "let's request updates");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
//}
MapFragment mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int state = wifi.getWifiState();
if (state == WifiManager.WIFI_STATE_ENABLED) {
List<ScanResult> results = wifi.getScanResults();
for (ScanResult result : results) {
if (result.BSSID.equals(wifi.getConnectionInfo().getBSSID())) {
int level = WifiManager.calculateSignalLevel(wifi.getConnectionInfo().getRssi(),
10);
int percentage = (int) ((level / 10.0) * 100);
((TextView) findViewById(R.id.signalStrength)).setText(Integer.toString(percentage));
}
}
}
}
}, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
((ImageView) findViewById(R.id.gpsTarget)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (copterMarker != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(copterMarker.getPosition(), 18));
}
}
});
}
public double round(double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
private void processUserGpsLocation(Location location) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.d("copter", "we've got a problem...");
return;
}
Log.d("copter", "Coordinates received LAT: " + Double.toString(location.getLatitude()) + " LON: " + Double.toString(location.getLongitude()));
LatLng userMarkerLoc = new LatLng(location.getLatitude(), location.getLongitude());
if(userMarker == null) {
userMarker = map.addMarker(new MarkerOptions()
.position(userMarkerLoc)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_marker)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 18));
} else {
userMarker.setPosition(userMarkerLoc);
}
//mLocationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
processUserGpsLocation(location);
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
<file_sep>/app/jni/parseFunctions.h
uint8_t system_id = 255;
uint8_t component_id = 0;
jobject unpack_msg_heartbeat(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_heartbeat_t inp;
mavlink_msg_heartbeat_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(heartbeat_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(heartbeat_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(heartbeat_class, "custom_mode", "J");
env->SetLongField (result, fid, (long) inp.custom_mode);
fid = env->GetFieldID(heartbeat_class, "type", "I");
env->SetIntField (result, fid, (int) inp.type);
fid = env->GetFieldID(heartbeat_class, "autopilot", "I");
env->SetIntField (result, fid, (int) inp.autopilot);
fid = env->GetFieldID(heartbeat_class, "base_mode", "I");
env->SetIntField (result, fid, (int) inp.base_mode);
fid = env->GetFieldID(heartbeat_class, "system_status", "I");
env->SetIntField (result, fid, (int) inp.system_status);
fid = env->GetFieldID(heartbeat_class, "mavlink_version", "I");
env->SetIntField (result, fid, (int) inp.mavlink_version);
fid = env->GetFieldID(heartbeat_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(heartbeat_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_heartbeat(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t custom_mode = (uint32_t)env->GetLongField (obj, env->GetFieldID(heartbeat_class, "custom_mode", "J"));
uint8_t type = (uint8_t)env->GetIntField (obj, env->GetFieldID(heartbeat_class, "type", "I"));
uint8_t autopilot = (uint8_t)env->GetIntField (obj, env->GetFieldID(heartbeat_class, "autopilot", "I"));
uint8_t base_mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(heartbeat_class, "base_mode", "I"));
uint8_t system_status = (uint8_t)env->GetIntField (obj, env->GetFieldID(heartbeat_class, "system_status", "I"));
uint8_t mavlink_version = (uint8_t)env->GetIntField (obj, env->GetFieldID(heartbeat_class, "mavlink_version", "I"));
mavlink_msg_heartbeat_pack(system_id, component_id, &msg,type, autopilot, base_mode, custom_mode, system_status);
}
jobject unpack_msg_sys_status(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_sys_status_t inp;
mavlink_msg_sys_status_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(sys_status_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(sys_status_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(sys_status_class, "onboard_control_sensors_present", "J");
env->SetLongField (result, fid, (long) inp.onboard_control_sensors_present);
fid = env->GetFieldID(sys_status_class, "onboard_control_sensors_enabled", "J");
env->SetLongField (result, fid, (long) inp.onboard_control_sensors_enabled);
fid = env->GetFieldID(sys_status_class, "onboard_control_sensors_health", "J");
env->SetLongField (result, fid, (long) inp.onboard_control_sensors_health);
fid = env->GetFieldID(sys_status_class, "load", "I");
env->SetIntField (result, fid, (int) inp.load);
fid = env->GetFieldID(sys_status_class, "voltage_battery", "I");
env->SetIntField (result, fid, (int) inp.voltage_battery);
fid = env->GetFieldID(sys_status_class, "current_battery", "I");
env->SetIntField (result, fid, (int) inp.current_battery);
fid = env->GetFieldID(sys_status_class, "drop_rate_comm", "I");
env->SetIntField (result, fid, (int) inp.drop_rate_comm);
fid = env->GetFieldID(sys_status_class, "errors_comm", "I");
env->SetIntField (result, fid, (int) inp.errors_comm);
fid = env->GetFieldID(sys_status_class, "errors_count1", "I");
env->SetIntField (result, fid, (int) inp.errors_count1);
fid = env->GetFieldID(sys_status_class, "errors_count2", "I");
env->SetIntField (result, fid, (int) inp.errors_count2);
fid = env->GetFieldID(sys_status_class, "errors_count3", "I");
env->SetIntField (result, fid, (int) inp.errors_count3);
fid = env->GetFieldID(sys_status_class, "errors_count4", "I");
env->SetIntField (result, fid, (int) inp.errors_count4);
fid = env->GetFieldID(sys_status_class, "battery_remaining", "I");
env->SetIntField (result, fid, (int) inp.battery_remaining);
fid = env->GetFieldID(sys_status_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(sys_status_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_sys_status(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t onboard_control_sensors_present = (uint32_t)env->GetLongField (obj, env->GetFieldID(sys_status_class, "onboard_control_sensors_present", "J"));
uint32_t onboard_control_sensors_enabled = (uint32_t)env->GetLongField (obj, env->GetFieldID(sys_status_class, "onboard_control_sensors_enabled", "J"));
uint32_t onboard_control_sensors_health = (uint32_t)env->GetLongField (obj, env->GetFieldID(sys_status_class, "onboard_control_sensors_health", "J"));
uint16_t load = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "load", "I"));
uint16_t voltage_battery = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "voltage_battery", "I"));
int16_t current_battery = (int16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "current_battery", "I"));
uint16_t drop_rate_comm = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "drop_rate_comm", "I"));
uint16_t errors_comm = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "errors_comm", "I"));
uint16_t errors_count1 = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "errors_count1", "I"));
uint16_t errors_count2 = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "errors_count2", "I"));
uint16_t errors_count3 = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "errors_count3", "I"));
uint16_t errors_count4 = (uint16_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "errors_count4", "I"));
int8_t battery_remaining = (int8_t)env->GetIntField (obj, env->GetFieldID(sys_status_class, "battery_remaining", "I"));
mavlink_msg_sys_status_pack(system_id, component_id, &msg,onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4);
}
jobject unpack_msg_system_time(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_system_time_t inp;
mavlink_msg_system_time_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(system_time_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(system_time_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(system_time_class, "time_unix_usec", "J");
env->SetLongField (result, fid, (long) inp.time_unix_usec);
fid = env->GetFieldID(system_time_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(system_time_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(system_time_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_system_time(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_unix_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(system_time_class, "time_unix_usec", "J"));
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(system_time_class, "time_boot_ms", "J"));
mavlink_msg_system_time_pack(system_id, component_id, &msg,time_unix_usec, time_boot_ms);
}
jobject unpack_msg_ping(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_ping_t inp;
mavlink_msg_ping_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(ping_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(ping_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(ping_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(ping_class, "seq", "J");
env->SetLongField (result, fid, (long) inp.seq);
fid = env->GetFieldID(ping_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(ping_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(ping_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(ping_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_ping(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(ping_class, "time_usec", "J"));
uint32_t seq = (uint32_t)env->GetLongField (obj, env->GetFieldID(ping_class, "seq", "J"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(ping_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(ping_class, "target_component", "I"));
mavlink_msg_ping_pack(system_id, component_id, &msg,time_usec, seq, target_system, target_component);
}
jobject unpack_msg_change_operator_control(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_change_operator_control_t inp;
mavlink_msg_change_operator_control_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(change_operator_control_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(change_operator_control_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(change_operator_control_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(change_operator_control_class, "control_request", "I");
env->SetIntField (result, fid, (int) inp.control_request);
fid = env->GetFieldID(change_operator_control_class, "version", "I");
env->SetIntField (result, fid, (int) inp.version);
{
fid = env->GetFieldID(change_operator_control_class, "passkey", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 25; i++)
data[i] = inp.passkey[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(change_operator_control_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(change_operator_control_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_change_operator_control(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_class, "target_system", "I"));
uint8_t control_request = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_class, "control_request", "I"));
uint8_t version = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_class, "version", "I"));
char passkey[25];
{
jfieldID fid;
fid = env->GetFieldID(change_operator_control_class, "passkey", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 25; i++)
passkey[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_change_operator_control_pack(system_id, component_id, &msg,target_system, control_request, version, passkey);
}
jobject unpack_msg_change_operator_control_ack(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_change_operator_control_ack_t inp;
mavlink_msg_change_operator_control_ack_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(change_operator_control_ack_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(change_operator_control_ack_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(change_operator_control_ack_class, "gcs_system_id", "I");
env->SetIntField (result, fid, (int) inp.gcs_system_id);
fid = env->GetFieldID(change_operator_control_ack_class, "control_request", "I");
env->SetIntField (result, fid, (int) inp.control_request);
fid = env->GetFieldID(change_operator_control_ack_class, "ack", "I");
env->SetIntField (result, fid, (int) inp.ack);
fid = env->GetFieldID(change_operator_control_ack_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(change_operator_control_ack_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_change_operator_control_ack(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t gcs_system_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_ack_class, "gcs_system_id", "I"));
uint8_t control_request = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_ack_class, "control_request", "I"));
uint8_t ack = (uint8_t)env->GetIntField (obj, env->GetFieldID(change_operator_control_ack_class, "ack", "I"));
mavlink_msg_change_operator_control_ack_pack(system_id, component_id, &msg,gcs_system_id, control_request, ack);
}
jobject unpack_msg_auth_key(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_auth_key_t inp;
mavlink_msg_auth_key_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(auth_key_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(auth_key_class, cid);
//Set values
jfieldID fid;
{
fid = env->GetFieldID(auth_key_class, "key", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 32; i++)
data[i] = inp.key[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(auth_key_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(auth_key_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_auth_key(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
char key[32];
{
jfieldID fid;
fid = env->GetFieldID(auth_key_class, "key", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 32; i++)
key[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_auth_key_pack(system_id, component_id, &msg,key);
}
jobject unpack_msg_set_mode(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_mode_t inp;
mavlink_msg_set_mode_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_mode_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_mode_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_mode_class, "custom_mode", "J");
env->SetLongField (result, fid, (long) inp.custom_mode);
fid = env->GetFieldID(set_mode_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_mode_class, "base_mode", "I");
env->SetIntField (result, fid, (int) inp.base_mode);
fid = env->GetFieldID(set_mode_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_mode_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_mode(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t custom_mode = (uint32_t)env->GetLongField (obj, env->GetFieldID(set_mode_class, "custom_mode", "J"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_mode_class, "target_system", "I"));
uint8_t base_mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_mode_class, "base_mode", "I"));
mavlink_msg_set_mode_pack(system_id, component_id, &msg,target_system, base_mode, custom_mode);
}
jobject unpack_msg_param_request_read(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_param_request_read_t inp;
mavlink_msg_param_request_read_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(param_request_read_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(param_request_read_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(param_request_read_class, "param_index", "I");
env->SetIntField (result, fid, (int) inp.param_index);
fid = env->GetFieldID(param_request_read_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(param_request_read_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
{
fid = env->GetFieldID(param_request_read_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 16; i++)
data[i] = inp.param_id[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(param_request_read_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(param_request_read_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_param_request_read(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int16_t param_index = (int16_t)env->GetIntField (obj, env->GetFieldID(param_request_read_class, "param_index", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_request_read_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_request_read_class, "target_component", "I"));
char param_id[16];
{
jfieldID fid;
fid = env->GetFieldID(param_request_read_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 16; i++)
param_id[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_param_request_read_pack(system_id, component_id, &msg,target_system, target_component, param_id, param_index);
}
jobject unpack_msg_param_request_list(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_param_request_list_t inp;
mavlink_msg_param_request_list_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(param_request_list_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(param_request_list_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(param_request_list_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(param_request_list_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(param_request_list_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(param_request_list_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_param_request_list(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_request_list_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_request_list_class, "target_component", "I"));
mavlink_msg_param_request_list_pack(system_id, component_id, &msg,target_system, target_component);
}
jobject unpack_msg_param_value(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_param_value_t inp;
mavlink_msg_param_value_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(param_value_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(param_value_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(param_value_class, "param_value", "F");
env->SetFloatField (result, fid, (float)inp.param_value);
fid = env->GetFieldID(param_value_class, "param_count", "I");
env->SetIntField (result, fid, (int) inp.param_count);
fid = env->GetFieldID(param_value_class, "param_index", "I");
env->SetIntField (result, fid, (int) inp.param_index);
{
fid = env->GetFieldID(param_value_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 16; i++)
data[i] = inp.param_id[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(param_value_class, "param_type", "I");
env->SetIntField (result, fid, (int) inp.param_type);
fid = env->GetFieldID(param_value_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(param_value_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_param_value(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float param_value = (float)env->GetFloatField (obj, env->GetFieldID(param_value_class, "param_value", "F"));
uint16_t param_count = (uint16_t)env->GetIntField (obj, env->GetFieldID(param_value_class, "param_count", "I"));
uint16_t param_index = (uint16_t)env->GetIntField (obj, env->GetFieldID(param_value_class, "param_index", "I"));
char param_id[16];
{
jfieldID fid;
fid = env->GetFieldID(param_value_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 16; i++)
param_id[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
uint8_t param_type = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_value_class, "param_type", "I"));
mavlink_msg_param_value_pack(system_id, component_id, &msg,param_id, param_value, param_type, param_count, param_index);
}
jobject unpack_msg_param_set(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_param_set_t inp;
mavlink_msg_param_set_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(param_set_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(param_set_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(param_set_class, "param_value", "F");
env->SetFloatField (result, fid, (float)inp.param_value);
fid = env->GetFieldID(param_set_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(param_set_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
{
fid = env->GetFieldID(param_set_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 16; i++)
data[i] = inp.param_id[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(param_set_class, "param_type", "I");
env->SetIntField (result, fid, (int) inp.param_type);
fid = env->GetFieldID(param_set_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(param_set_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_param_set(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float param_value = (float)env->GetFloatField (obj, env->GetFieldID(param_set_class, "param_value", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_set_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_set_class, "target_component", "I"));
char param_id[16] = {0};
{
jfieldID fid;
fid = env->GetFieldID(param_set_class, "param_id", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
jsize len = (env)->GetArrayLength(charArr);
for(int i = 0; i < len; i++)
param_id[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
uint8_t param_type = (uint8_t)env->GetIntField (obj, env->GetFieldID(param_set_class, "param_type", "I"));
mavlink_msg_param_set_pack(system_id, component_id, &msg,target_system, target_component, param_id, param_value, param_type);
}
jobject unpack_msg_gps_raw_int(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_gps_raw_int_t inp;
mavlink_msg_gps_raw_int_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(gps_raw_int_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(gps_raw_int_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(gps_raw_int_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(gps_raw_int_class, "lat", "J");
env->SetLongField (result, fid, (long) inp.lat);
fid = env->GetFieldID(gps_raw_int_class, "lon", "J");
env->SetLongField (result, fid, (long) inp.lon);
fid = env->GetFieldID(gps_raw_int_class, "alt", "J");
env->SetLongField (result, fid, (long) inp.alt);
fid = env->GetFieldID(gps_raw_int_class, "eph", "I");
env->SetIntField (result, fid, (int) inp.eph);
fid = env->GetFieldID(gps_raw_int_class, "epv", "I");
env->SetIntField (result, fid, (int) inp.epv);
fid = env->GetFieldID(gps_raw_int_class, "vel", "I");
env->SetIntField (result, fid, (int) inp.vel);
fid = env->GetFieldID(gps_raw_int_class, "cog", "I");
env->SetIntField (result, fid, (int) inp.cog);
fid = env->GetFieldID(gps_raw_int_class, "fix_type", "I");
env->SetIntField (result, fid, (int) inp.fix_type);
fid = env->GetFieldID(gps_raw_int_class, "satellites_visible", "I");
env->SetIntField (result, fid, (int) inp.satellites_visible);
fid = env->GetFieldID(gps_raw_int_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(gps_raw_int_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_gps_raw_int(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(gps_raw_int_class, "time_usec", "J"));
int32_t lat = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_raw_int_class, "lat", "J"));
int32_t lon = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_raw_int_class, "lon", "J"));
int32_t alt = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_raw_int_class, "alt", "J"));
uint16_t eph = (uint16_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "eph", "I"));
uint16_t epv = (uint16_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "epv", "I"));
uint16_t vel = (uint16_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "vel", "I"));
uint16_t cog = (uint16_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "cog", "I"));
uint8_t fix_type = (uint8_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "fix_type", "I"));
uint8_t satellites_visible = (uint8_t)env->GetIntField (obj, env->GetFieldID(gps_raw_int_class, "satellites_visible", "I"));
mavlink_msg_gps_raw_int_pack(system_id, component_id, &msg,time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible);
}
jobject unpack_msg_gps_status(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_gps_status_t inp;
mavlink_msg_gps_status_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(gps_status_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(gps_status_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(gps_status_class, "satellites_visible", "I");
env->SetIntField (result, fid, (int) inp.satellites_visible);
{
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_prn", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
data[i] = inp.satellite_prn[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
{
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_used", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
data[i] = inp.satellite_used[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
{
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_elevation", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
data[i] = inp.satellite_elevation[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
{
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_azimuth", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
data[i] = inp.satellite_azimuth[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
{
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_snr", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
data[i] = inp.satellite_snr[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
fid = env->GetFieldID(gps_status_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(gps_status_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_gps_status(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t satellites_visible = (uint8_t)env->GetIntField (obj, env->GetFieldID(gps_status_class, "satellites_visible", "I"));
uint8_t satellite_prn[20];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_prn", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
satellite_prn[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
uint8_t satellite_used[20];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_used", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
satellite_used[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
uint8_t satellite_elevation[20];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_elevation", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
satellite_elevation[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
uint8_t satellite_azimuth[20];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_azimuth", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
satellite_azimuth[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
uint8_t satellite_snr[20];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(gps_status_class, "satellite_snr", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 20; i++)
satellite_snr[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
mavlink_msg_gps_status_pack(system_id, component_id, &msg,satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr);
}
jobject unpack_msg_scaled_imu(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_scaled_imu_t inp;
mavlink_msg_scaled_imu_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(scaled_imu_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(scaled_imu_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(scaled_imu_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(scaled_imu_class, "xacc", "I");
env->SetIntField (result, fid, (int) inp.xacc);
fid = env->GetFieldID(scaled_imu_class, "yacc", "I");
env->SetIntField (result, fid, (int) inp.yacc);
fid = env->GetFieldID(scaled_imu_class, "zacc", "I");
env->SetIntField (result, fid, (int) inp.zacc);
fid = env->GetFieldID(scaled_imu_class, "xgyro", "I");
env->SetIntField (result, fid, (int) inp.xgyro);
fid = env->GetFieldID(scaled_imu_class, "ygyro", "I");
env->SetIntField (result, fid, (int) inp.ygyro);
fid = env->GetFieldID(scaled_imu_class, "zgyro", "I");
env->SetIntField (result, fid, (int) inp.zgyro);
fid = env->GetFieldID(scaled_imu_class, "xmag", "I");
env->SetIntField (result, fid, (int) inp.xmag);
fid = env->GetFieldID(scaled_imu_class, "ymag", "I");
env->SetIntField (result, fid, (int) inp.ymag);
fid = env->GetFieldID(scaled_imu_class, "zmag", "I");
env->SetIntField (result, fid, (int) inp.zmag);
fid = env->GetFieldID(scaled_imu_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(scaled_imu_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_scaled_imu(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(scaled_imu_class, "time_boot_ms", "J"));
int16_t xacc = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "xacc", "I"));
int16_t yacc = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "yacc", "I"));
int16_t zacc = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "zacc", "I"));
int16_t xgyro = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "xgyro", "I"));
int16_t ygyro = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "ygyro", "I"));
int16_t zgyro = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "zgyro", "I"));
int16_t xmag = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "xmag", "I"));
int16_t ymag = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "ymag", "I"));
int16_t zmag = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_imu_class, "zmag", "I"));
mavlink_msg_scaled_imu_pack(system_id, component_id, &msg,time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag);
}
jobject unpack_msg_raw_imu(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_raw_imu_t inp;
mavlink_msg_raw_imu_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(raw_imu_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(raw_imu_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(raw_imu_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(raw_imu_class, "xacc", "I");
env->SetIntField (result, fid, (int) inp.xacc);
fid = env->GetFieldID(raw_imu_class, "yacc", "I");
env->SetIntField (result, fid, (int) inp.yacc);
fid = env->GetFieldID(raw_imu_class, "zacc", "I");
env->SetIntField (result, fid, (int) inp.zacc);
fid = env->GetFieldID(raw_imu_class, "xgyro", "I");
env->SetIntField (result, fid, (int) inp.xgyro);
fid = env->GetFieldID(raw_imu_class, "ygyro", "I");
env->SetIntField (result, fid, (int) inp.ygyro);
fid = env->GetFieldID(raw_imu_class, "zgyro", "I");
env->SetIntField (result, fid, (int) inp.zgyro);
fid = env->GetFieldID(raw_imu_class, "xmag", "I");
env->SetIntField (result, fid, (int) inp.xmag);
fid = env->GetFieldID(raw_imu_class, "ymag", "I");
env->SetIntField (result, fid, (int) inp.ymag);
fid = env->GetFieldID(raw_imu_class, "zmag", "I");
env->SetIntField (result, fid, (int) inp.zmag);
fid = env->GetFieldID(raw_imu_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(raw_imu_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_raw_imu(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(raw_imu_class, "time_usec", "J"));
int16_t xacc = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "xacc", "I"));
int16_t yacc = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "yacc", "I"));
int16_t zacc = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "zacc", "I"));
int16_t xgyro = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "xgyro", "I"));
int16_t ygyro = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "ygyro", "I"));
int16_t zgyro = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "zgyro", "I"));
int16_t xmag = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "xmag", "I"));
int16_t ymag = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "ymag", "I"));
int16_t zmag = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_imu_class, "zmag", "I"));
mavlink_msg_raw_imu_pack(system_id, component_id, &msg,time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag);
}
jobject unpack_msg_raw_pressure(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_raw_pressure_t inp;
mavlink_msg_raw_pressure_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(raw_pressure_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(raw_pressure_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(raw_pressure_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(raw_pressure_class, "press_abs", "I");
env->SetIntField (result, fid, (int) inp.press_abs);
fid = env->GetFieldID(raw_pressure_class, "press_diff1", "I");
env->SetIntField (result, fid, (int) inp.press_diff1);
fid = env->GetFieldID(raw_pressure_class, "press_diff2", "I");
env->SetIntField (result, fid, (int) inp.press_diff2);
fid = env->GetFieldID(raw_pressure_class, "temperature", "I");
env->SetIntField (result, fid, (int) inp.temperature);
fid = env->GetFieldID(raw_pressure_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(raw_pressure_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_raw_pressure(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(raw_pressure_class, "time_usec", "J"));
int16_t press_abs = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_pressure_class, "press_abs", "I"));
int16_t press_diff1 = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_pressure_class, "press_diff1", "I"));
int16_t press_diff2 = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_pressure_class, "press_diff2", "I"));
int16_t temperature = (int16_t)env->GetIntField (obj, env->GetFieldID(raw_pressure_class, "temperature", "I"));
mavlink_msg_raw_pressure_pack(system_id, component_id, &msg,time_usec, press_abs, press_diff1, press_diff2, temperature);
}
jobject unpack_msg_scaled_pressure(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_scaled_pressure_t inp;
mavlink_msg_scaled_pressure_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(scaled_pressure_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(scaled_pressure_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(scaled_pressure_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(scaled_pressure_class, "press_abs", "F");
env->SetFloatField (result, fid, (float)inp.press_abs);
fid = env->GetFieldID(scaled_pressure_class, "press_diff", "F");
env->SetFloatField (result, fid, (float)inp.press_diff);
fid = env->GetFieldID(scaled_pressure_class, "temperature", "I");
env->SetIntField (result, fid, (int) inp.temperature);
fid = env->GetFieldID(scaled_pressure_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(scaled_pressure_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_scaled_pressure(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(scaled_pressure_class, "time_boot_ms", "J"));
float press_abs = (float)env->GetFloatField (obj, env->GetFieldID(scaled_pressure_class, "press_abs", "F"));
float press_diff = (float)env->GetFloatField (obj, env->GetFieldID(scaled_pressure_class, "press_diff", "F"));
int16_t temperature = (int16_t)env->GetIntField (obj, env->GetFieldID(scaled_pressure_class, "temperature", "I"));
mavlink_msg_scaled_pressure_pack(system_id, component_id, &msg,time_boot_ms, press_abs, press_diff, temperature);
}
jobject unpack_msg_attitude(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_attitude_t inp;
mavlink_msg_attitude_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(attitude_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(attitude_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(attitude_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(attitude_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(attitude_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(attitude_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(attitude_class, "rollspeed", "F");
env->SetFloatField (result, fid, (float)inp.rollspeed);
fid = env->GetFieldID(attitude_class, "pitchspeed", "F");
env->SetFloatField (result, fid, (float)inp.pitchspeed);
fid = env->GetFieldID(attitude_class, "yawspeed", "F");
env->SetFloatField (result, fid, (float)inp.yawspeed);
fid = env->GetFieldID(attitude_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(attitude_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_attitude(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(attitude_class, "time_boot_ms", "J"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "yaw", "F"));
float rollspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "rollspeed", "F"));
float pitchspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "pitchspeed", "F"));
float yawspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_class, "yawspeed", "F"));
mavlink_msg_attitude_pack(system_id, component_id, &msg,time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed);
}
jobject unpack_msg_attitude_quaternion(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_attitude_quaternion_t inp;
mavlink_msg_attitude_quaternion_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(attitude_quaternion_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(attitude_quaternion_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(attitude_quaternion_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(attitude_quaternion_class, "q1", "F");
env->SetFloatField (result, fid, (float)inp.q1);
fid = env->GetFieldID(attitude_quaternion_class, "q2", "F");
env->SetFloatField (result, fid, (float)inp.q2);
fid = env->GetFieldID(attitude_quaternion_class, "q3", "F");
env->SetFloatField (result, fid, (float)inp.q3);
fid = env->GetFieldID(attitude_quaternion_class, "q4", "F");
env->SetFloatField (result, fid, (float)inp.q4);
fid = env->GetFieldID(attitude_quaternion_class, "rollspeed", "F");
env->SetFloatField (result, fid, (float)inp.rollspeed);
fid = env->GetFieldID(attitude_quaternion_class, "pitchspeed", "F");
env->SetFloatField (result, fid, (float)inp.pitchspeed);
fid = env->GetFieldID(attitude_quaternion_class, "yawspeed", "F");
env->SetFloatField (result, fid, (float)inp.yawspeed);
fid = env->GetFieldID(attitude_quaternion_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(attitude_quaternion_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_attitude_quaternion(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(attitude_quaternion_class, "time_boot_ms", "J"));
float q1 = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "q1", "F"));
float q2 = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "q2", "F"));
float q3 = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "q3", "F"));
float q4 = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "q4", "F"));
float rollspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "rollspeed", "F"));
float pitchspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "pitchspeed", "F"));
float yawspeed = (float)env->GetFloatField (obj, env->GetFieldID(attitude_quaternion_class, "yawspeed", "F"));
mavlink_msg_attitude_quaternion_pack(system_id, component_id, &msg,time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed);
}
jobject unpack_msg_local_position_ned(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_local_position_ned_t inp;
mavlink_msg_local_position_ned_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(local_position_ned_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(local_position_ned_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(local_position_ned_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(local_position_ned_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(local_position_ned_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(local_position_ned_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(local_position_ned_class, "vx", "F");
env->SetFloatField (result, fid, (float)inp.vx);
fid = env->GetFieldID(local_position_ned_class, "vy", "F");
env->SetFloatField (result, fid, (float)inp.vy);
fid = env->GetFieldID(local_position_ned_class, "vz", "F");
env->SetFloatField (result, fid, (float)inp.vz);
fid = env->GetFieldID(local_position_ned_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(local_position_ned_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_local_position_ned(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(local_position_ned_class, "time_boot_ms", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "z", "F"));
float vx = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "vx", "F"));
float vy = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "vy", "F"));
float vz = (float)env->GetFloatField (obj, env->GetFieldID(local_position_ned_class, "vz", "F"));
mavlink_msg_local_position_ned_pack(system_id, component_id, &msg,time_boot_ms, x, y, z, vx, vy, vz);
}
jobject unpack_msg_global_position_int(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_global_position_int_t inp;
mavlink_msg_global_position_int_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(global_position_int_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(global_position_int_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(global_position_int_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(global_position_int_class, "lat", "J");
env->SetLongField (result, fid, (long) inp.lat);
fid = env->GetFieldID(global_position_int_class, "lon", "J");
env->SetLongField (result, fid, (long) inp.lon);
fid = env->GetFieldID(global_position_int_class, "alt", "J");
env->SetLongField (result, fid, (long) inp.alt);
fid = env->GetFieldID(global_position_int_class, "relative_alt", "J");
env->SetLongField (result, fid, (long) inp.relative_alt);
fid = env->GetFieldID(global_position_int_class, "vx", "I");
env->SetIntField (result, fid, (int) inp.vx);
fid = env->GetFieldID(global_position_int_class, "vy", "I");
env->SetIntField (result, fid, (int) inp.vy);
fid = env->GetFieldID(global_position_int_class, "vz", "I");
env->SetIntField (result, fid, (int) inp.vz);
fid = env->GetFieldID(global_position_int_class, "hdg", "I");
env->SetIntField (result, fid, (int) inp.hdg);
fid = env->GetFieldID(global_position_int_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(global_position_int_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_global_position_int(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(global_position_int_class, "time_boot_ms", "J"));
int32_t lat = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_int_class, "lat", "J"));
int32_t lon = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_int_class, "lon", "J"));
int32_t alt = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_int_class, "alt", "J"));
int32_t relative_alt = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_int_class, "relative_alt", "J"));
int16_t vx = (int16_t)env->GetIntField (obj, env->GetFieldID(global_position_int_class, "vx", "I"));
int16_t vy = (int16_t)env->GetIntField (obj, env->GetFieldID(global_position_int_class, "vy", "I"));
int16_t vz = (int16_t)env->GetIntField (obj, env->GetFieldID(global_position_int_class, "vz", "I"));
uint16_t hdg = (uint16_t)env->GetIntField (obj, env->GetFieldID(global_position_int_class, "hdg", "I"));
mavlink_msg_global_position_int_pack(system_id, component_id, &msg,time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg);
}
jobject unpack_msg_rc_channels_scaled(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_rc_channels_scaled_t inp;
mavlink_msg_rc_channels_scaled_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(rc_channels_scaled_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(rc_channels_scaled_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(rc_channels_scaled_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(rc_channels_scaled_class, "chan1_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan1_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan2_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan2_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan3_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan3_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan4_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan4_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan5_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan5_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan6_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan6_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan7_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan7_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "chan8_scaled", "I");
env->SetIntField (result, fid, (int) inp.chan8_scaled);
fid = env->GetFieldID(rc_channels_scaled_class, "port", "I");
env->SetIntField (result, fid, (int) inp.port);
fid = env->GetFieldID(rc_channels_scaled_class, "rssi", "I");
env->SetIntField (result, fid, (int) inp.rssi);
fid = env->GetFieldID(rc_channels_scaled_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(rc_channels_scaled_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_rc_channels_scaled(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(rc_channels_scaled_class, "time_boot_ms", "J"));
int16_t chan1_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan1_scaled", "I"));
int16_t chan2_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan2_scaled", "I"));
int16_t chan3_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan3_scaled", "I"));
int16_t chan4_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan4_scaled", "I"));
int16_t chan5_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan5_scaled", "I"));
int16_t chan6_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan6_scaled", "I"));
int16_t chan7_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan7_scaled", "I"));
int16_t chan8_scaled = (int16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "chan8_scaled", "I"));
uint8_t port = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "port", "I"));
uint8_t rssi = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_scaled_class, "rssi", "I"));
mavlink_msg_rc_channels_scaled_pack(system_id, component_id, &msg,time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi);
}
jobject unpack_msg_rc_channels_raw(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_rc_channels_raw_t inp;
mavlink_msg_rc_channels_raw_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(rc_channels_raw_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(rc_channels_raw_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(rc_channels_raw_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(rc_channels_raw_class, "chan1_raw", "I");
env->SetIntField (result, fid, (int) inp.chan1_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan2_raw", "I");
env->SetIntField (result, fid, (int) inp.chan2_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan3_raw", "I");
env->SetIntField (result, fid, (int) inp.chan3_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan4_raw", "I");
env->SetIntField (result, fid, (int) inp.chan4_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan5_raw", "I");
env->SetIntField (result, fid, (int) inp.chan5_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan6_raw", "I");
env->SetIntField (result, fid, (int) inp.chan6_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan7_raw", "I");
env->SetIntField (result, fid, (int) inp.chan7_raw);
fid = env->GetFieldID(rc_channels_raw_class, "chan8_raw", "I");
env->SetIntField (result, fid, (int) inp.chan8_raw);
fid = env->GetFieldID(rc_channels_raw_class, "port", "I");
env->SetIntField (result, fid, (int) inp.port);
fid = env->GetFieldID(rc_channels_raw_class, "rssi", "I");
env->SetIntField (result, fid, (int) inp.rssi);
fid = env->GetFieldID(rc_channels_raw_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(rc_channels_raw_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_rc_channels_raw(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(rc_channels_raw_class, "time_boot_ms", "J"));
uint16_t chan1_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan1_raw", "I"));
uint16_t chan2_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan2_raw", "I"));
uint16_t chan3_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan3_raw", "I"));
uint16_t chan4_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan4_raw", "I"));
uint16_t chan5_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan5_raw", "I"));
uint16_t chan6_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan6_raw", "I"));
uint16_t chan7_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan7_raw", "I"));
uint16_t chan8_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "chan8_raw", "I"));
uint8_t port = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "port", "I"));
uint8_t rssi = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_raw_class, "rssi", "I"));
mavlink_msg_rc_channels_raw_pack(system_id, component_id, &msg,time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi);
}
jobject unpack_msg_servo_output_raw(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_servo_output_raw_t inp;
mavlink_msg_servo_output_raw_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(servo_output_raw_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(servo_output_raw_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(servo_output_raw_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(servo_output_raw_class, "servo1_raw", "I");
env->SetIntField (result, fid, (int) inp.servo1_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo2_raw", "I");
env->SetIntField (result, fid, (int) inp.servo2_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo3_raw", "I");
env->SetIntField (result, fid, (int) inp.servo3_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo4_raw", "I");
env->SetIntField (result, fid, (int) inp.servo4_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo5_raw", "I");
env->SetIntField (result, fid, (int) inp.servo5_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo6_raw", "I");
env->SetIntField (result, fid, (int) inp.servo6_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo7_raw", "I");
env->SetIntField (result, fid, (int) inp.servo7_raw);
fid = env->GetFieldID(servo_output_raw_class, "servo8_raw", "I");
env->SetIntField (result, fid, (int) inp.servo8_raw);
fid = env->GetFieldID(servo_output_raw_class, "port", "I");
env->SetIntField (result, fid, (int) inp.port);
fid = env->GetFieldID(servo_output_raw_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(servo_output_raw_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_servo_output_raw(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_usec = (uint32_t)env->GetLongField (obj, env->GetFieldID(servo_output_raw_class, "time_usec", "J"));
uint16_t servo1_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo1_raw", "I"));
uint16_t servo2_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo2_raw", "I"));
uint16_t servo3_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo3_raw", "I"));
uint16_t servo4_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo4_raw", "I"));
uint16_t servo5_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo5_raw", "I"));
uint16_t servo6_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo6_raw", "I"));
uint16_t servo7_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo7_raw", "I"));
uint16_t servo8_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "servo8_raw", "I"));
uint8_t port = (uint8_t)env->GetIntField (obj, env->GetFieldID(servo_output_raw_class, "port", "I"));
mavlink_msg_servo_output_raw_pack(system_id, component_id, &msg,time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw);
}
jobject unpack_msg_mission_request_partial_list(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_request_partial_list_t inp;
mavlink_msg_mission_request_partial_list_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_request_partial_list_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_request_partial_list_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_request_partial_list_class, "start_index", "I");
env->SetIntField (result, fid, (int) inp.start_index);
fid = env->GetFieldID(mission_request_partial_list_class, "end_index", "I");
env->SetIntField (result, fid, (int) inp.end_index);
fid = env->GetFieldID(mission_request_partial_list_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_request_partial_list_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_request_partial_list_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_request_partial_list_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_request_partial_list(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int16_t start_index = (int16_t)env->GetIntField (obj, env->GetFieldID(mission_request_partial_list_class, "start_index", "I"));
int16_t end_index = (int16_t)env->GetIntField (obj, env->GetFieldID(mission_request_partial_list_class, "end_index", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_partial_list_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_partial_list_class, "target_component", "I"));
mavlink_msg_mission_request_partial_list_pack(system_id, component_id, &msg,target_system, target_component, start_index, end_index);
}
jobject unpack_msg_mission_write_partial_list(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_write_partial_list_t inp;
mavlink_msg_mission_write_partial_list_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_write_partial_list_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_write_partial_list_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_write_partial_list_class, "start_index", "I");
env->SetIntField (result, fid, (int) inp.start_index);
fid = env->GetFieldID(mission_write_partial_list_class, "end_index", "I");
env->SetIntField (result, fid, (int) inp.end_index);
fid = env->GetFieldID(mission_write_partial_list_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_write_partial_list_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_write_partial_list_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_write_partial_list_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_write_partial_list(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int16_t start_index = (int16_t)env->GetIntField (obj, env->GetFieldID(mission_write_partial_list_class, "start_index", "I"));
int16_t end_index = (int16_t)env->GetIntField (obj, env->GetFieldID(mission_write_partial_list_class, "end_index", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_write_partial_list_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_write_partial_list_class, "target_component", "I"));
mavlink_msg_mission_write_partial_list_pack(system_id, component_id, &msg,target_system, target_component, start_index, end_index);
}
jobject unpack_msg_mission_item(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_item_t inp;
mavlink_msg_mission_item_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_item_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_item_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_item_class, "param1", "F");
env->SetFloatField (result, fid, (float)inp.param1);
fid = env->GetFieldID(mission_item_class, "param2", "F");
env->SetFloatField (result, fid, (float)inp.param2);
fid = env->GetFieldID(mission_item_class, "param3", "F");
env->SetFloatField (result, fid, (float)inp.param3);
fid = env->GetFieldID(mission_item_class, "param4", "F");
env->SetFloatField (result, fid, (float)inp.param4);
fid = env->GetFieldID(mission_item_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(mission_item_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(mission_item_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(mission_item_class, "seq", "I");
env->SetIntField (result, fid, (int) inp.seq);
fid = env->GetFieldID(mission_item_class, "command", "I");
env->SetIntField (result, fid, (int) inp.command);
fid = env->GetFieldID(mission_item_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_item_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_item_class, "frame", "I");
env->SetIntField (result, fid, (int) inp.frame);
fid = env->GetFieldID(mission_item_class, "current", "I");
env->SetIntField (result, fid, (int) inp.current);
fid = env->GetFieldID(mission_item_class, "autocontinue", "I");
env->SetIntField (result, fid, (int) inp.autocontinue);
fid = env->GetFieldID(mission_item_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_item_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_item(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float param1 = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "param1", "F"));
float param2 = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "param2", "F"));
float param3 = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "param3", "F"));
float param4 = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "param4", "F"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(mission_item_class, "z", "F"));
uint16_t seq = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "seq", "I"));
uint16_t command = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "command", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "target_component", "I"));
uint8_t frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "frame", "I"));
uint8_t current = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "current", "I"));
uint8_t autocontinue = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_item_class, "autocontinue", "I"));
mavlink_msg_mission_item_pack(system_id, component_id, &msg,target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z);
}
jobject unpack_msg_mission_request(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_request_t inp;
mavlink_msg_mission_request_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_request_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_request_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_request_class, "seq", "I");
env->SetIntField (result, fid, (int) inp.seq);
fid = env->GetFieldID(mission_request_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_request_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_request_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_request_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_request(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t seq = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_request_class, "seq", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_class, "target_component", "I"));
mavlink_msg_mission_request_pack(system_id, component_id, &msg,target_system, target_component, seq);
}
jobject unpack_msg_mission_set_current(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_set_current_t inp;
mavlink_msg_mission_set_current_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_set_current_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_set_current_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_set_current_class, "seq", "I");
env->SetIntField (result, fid, (int) inp.seq);
fid = env->GetFieldID(mission_set_current_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_set_current_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_set_current_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_set_current_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_set_current(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t seq = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_set_current_class, "seq", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_set_current_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_set_current_class, "target_component", "I"));
mavlink_msg_mission_set_current_pack(system_id, component_id, &msg,target_system, target_component, seq);
}
jobject unpack_msg_mission_current(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_current_t inp;
mavlink_msg_mission_current_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_current_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_current_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_current_class, "seq", "I");
env->SetIntField (result, fid, (int) inp.seq);
fid = env->GetFieldID(mission_current_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_current_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_current(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t seq = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_current_class, "seq", "I"));
mavlink_msg_mission_current_pack(system_id, component_id, &msg,seq);
}
jobject unpack_msg_mission_request_list(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_request_list_t inp;
mavlink_msg_mission_request_list_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_request_list_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_request_list_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_request_list_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_request_list_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_request_list_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_request_list_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_request_list(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_list_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_request_list_class, "target_component", "I"));
mavlink_msg_mission_request_list_pack(system_id, component_id, &msg,target_system, target_component);
}
jobject unpack_msg_mission_count(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_count_t inp;
mavlink_msg_mission_count_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_count_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_count_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_count_class, "count", "I");
env->SetIntField (result, fid, (int) inp.count);
fid = env->GetFieldID(mission_count_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_count_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_count_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_count_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_count(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t count = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_count_class, "count", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_count_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_count_class, "target_component", "I"));
mavlink_msg_mission_count_pack(system_id, component_id, &msg,target_system, target_component, count);
}
jobject unpack_msg_mission_clear_all(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_clear_all_t inp;
mavlink_msg_mission_clear_all_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_clear_all_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_clear_all_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_clear_all_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_clear_all_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_clear_all_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_clear_all_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_clear_all(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_clear_all_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_clear_all_class, "target_component", "I"));
mavlink_msg_mission_clear_all_pack(system_id, component_id, &msg,target_system, target_component);
}
jobject unpack_msg_mission_item_reached(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_item_reached_t inp;
mavlink_msg_mission_item_reached_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_item_reached_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_item_reached_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_item_reached_class, "seq", "I");
env->SetIntField (result, fid, (int) inp.seq);
fid = env->GetFieldID(mission_item_reached_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_item_reached_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_item_reached(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t seq = (uint16_t)env->GetIntField (obj, env->GetFieldID(mission_item_reached_class, "seq", "I"));
mavlink_msg_mission_item_reached_pack(system_id, component_id, &msg,seq);
}
jobject unpack_msg_mission_ack(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mission_ack_t inp;
mavlink_msg_mission_ack_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mission_ack_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mission_ack_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mission_ack_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mission_ack_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mission_ack_class, "type", "I");
env->SetIntField (result, fid, (int) inp.type);
fid = env->GetFieldID(mission_ack_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mission_ack_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mission_ack(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_ack_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_ack_class, "target_component", "I"));
uint8_t type = (uint8_t)env->GetIntField (obj, env->GetFieldID(mission_ack_class, "type", "I"));
mavlink_msg_mission_ack_pack(system_id, component_id, &msg,target_system, target_component, type);
}
jobject unpack_msg_set_gps_global_origin(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_gps_global_origin_t inp;
mavlink_msg_set_gps_global_origin_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_gps_global_origin_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_gps_global_origin_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_gps_global_origin_class, "latitude", "J");
env->SetLongField (result, fid, (long) inp.latitude);
fid = env->GetFieldID(set_gps_global_origin_class, "longitude", "J");
env->SetLongField (result, fid, (long) inp.longitude);
fid = env->GetFieldID(set_gps_global_origin_class, "altitude", "J");
env->SetLongField (result, fid, (long) inp.altitude);
fid = env->GetFieldID(set_gps_global_origin_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_gps_global_origin_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_gps_global_origin_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_gps_global_origin(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t latitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_gps_global_origin_class, "latitude", "J"));
int32_t longitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_gps_global_origin_class, "longitude", "J"));
int32_t altitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_gps_global_origin_class, "altitude", "J"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_gps_global_origin_class, "target_system", "I"));
mavlink_msg_set_gps_global_origin_pack(system_id, component_id, &msg,target_system, latitude, longitude, altitude);
}
jobject unpack_msg_gps_global_origin(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_gps_global_origin_t inp;
mavlink_msg_gps_global_origin_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(gps_global_origin_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(gps_global_origin_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(gps_global_origin_class, "latitude", "J");
env->SetLongField (result, fid, (long) inp.latitude);
fid = env->GetFieldID(gps_global_origin_class, "longitude", "J");
env->SetLongField (result, fid, (long) inp.longitude);
fid = env->GetFieldID(gps_global_origin_class, "altitude", "J");
env->SetLongField (result, fid, (long) inp.altitude);
fid = env->GetFieldID(gps_global_origin_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(gps_global_origin_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_gps_global_origin(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t latitude = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_global_origin_class, "latitude", "J"));
int32_t longitude = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_global_origin_class, "longitude", "J"));
int32_t altitude = (int32_t)env->GetLongField (obj, env->GetFieldID(gps_global_origin_class, "altitude", "J"));
mavlink_msg_gps_global_origin_pack(system_id, component_id, &msg,latitude, longitude, altitude);
}
jobject unpack_msg_set_local_position_setpoint(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_local_position_setpoint_t inp;
mavlink_msg_set_local_position_setpoint_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_local_position_setpoint_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_local_position_setpoint_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_local_position_setpoint_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(set_local_position_setpoint_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(set_local_position_setpoint_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(set_local_position_setpoint_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(set_local_position_setpoint_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_local_position_setpoint_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(set_local_position_setpoint_class, "coordinate_frame", "I");
env->SetIntField (result, fid, (int) inp.coordinate_frame);
fid = env->GetFieldID(set_local_position_setpoint_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_local_position_setpoint_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_local_position_setpoint(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float x = (float)env->GetFloatField (obj, env->GetFieldID(set_local_position_setpoint_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(set_local_position_setpoint_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(set_local_position_setpoint_class, "z", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(set_local_position_setpoint_class, "yaw", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_local_position_setpoint_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_local_position_setpoint_class, "target_component", "I"));
uint8_t coordinate_frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_local_position_setpoint_class, "coordinate_frame", "I"));
mavlink_msg_set_local_position_setpoint_pack(system_id, component_id, &msg,target_system, target_component, coordinate_frame, x, y, z, yaw);
}
jobject unpack_msg_local_position_setpoint(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_local_position_setpoint_t inp;
mavlink_msg_local_position_setpoint_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(local_position_setpoint_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(local_position_setpoint_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(local_position_setpoint_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(local_position_setpoint_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(local_position_setpoint_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(local_position_setpoint_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(local_position_setpoint_class, "coordinate_frame", "I");
env->SetIntField (result, fid, (int) inp.coordinate_frame);
fid = env->GetFieldID(local_position_setpoint_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(local_position_setpoint_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_local_position_setpoint(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float x = (float)env->GetFloatField (obj, env->GetFieldID(local_position_setpoint_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(local_position_setpoint_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(local_position_setpoint_class, "z", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(local_position_setpoint_class, "yaw", "F"));
uint8_t coordinate_frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(local_position_setpoint_class, "coordinate_frame", "I"));
mavlink_msg_local_position_setpoint_pack(system_id, component_id, &msg,coordinate_frame, x, y, z, yaw);
}
jobject unpack_msg_global_position_setpoint_int(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_global_position_setpoint_int_t inp;
mavlink_msg_global_position_setpoint_int_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(global_position_setpoint_int_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(global_position_setpoint_int_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(global_position_setpoint_int_class, "latitude", "J");
env->SetLongField (result, fid, (long) inp.latitude);
fid = env->GetFieldID(global_position_setpoint_int_class, "longitude", "J");
env->SetLongField (result, fid, (long) inp.longitude);
fid = env->GetFieldID(global_position_setpoint_int_class, "altitude", "J");
env->SetLongField (result, fid, (long) inp.altitude);
fid = env->GetFieldID(global_position_setpoint_int_class, "yaw", "I");
env->SetIntField (result, fid, (int) inp.yaw);
fid = env->GetFieldID(global_position_setpoint_int_class, "coordinate_frame", "I");
env->SetIntField (result, fid, (int) inp.coordinate_frame);
fid = env->GetFieldID(global_position_setpoint_int_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(global_position_setpoint_int_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_global_position_setpoint_int(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t latitude = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_setpoint_int_class, "latitude", "J"));
int32_t longitude = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_setpoint_int_class, "longitude", "J"));
int32_t altitude = (int32_t)env->GetLongField (obj, env->GetFieldID(global_position_setpoint_int_class, "altitude", "J"));
int16_t yaw = (int16_t)env->GetIntField (obj, env->GetFieldID(global_position_setpoint_int_class, "yaw", "I"));
uint8_t coordinate_frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(global_position_setpoint_int_class, "coordinate_frame", "I"));
mavlink_msg_global_position_setpoint_int_pack(system_id, component_id, &msg,coordinate_frame, latitude, longitude, altitude, yaw);
}
jobject unpack_msg_set_global_position_setpoint_int(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_global_position_setpoint_int_t inp;
mavlink_msg_set_global_position_setpoint_int_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_global_position_setpoint_int_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_global_position_setpoint_int_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_global_position_setpoint_int_class, "latitude", "J");
env->SetLongField (result, fid, (long) inp.latitude);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "longitude", "J");
env->SetLongField (result, fid, (long) inp.longitude);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "altitude", "J");
env->SetLongField (result, fid, (long) inp.altitude);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "yaw", "I");
env->SetIntField (result, fid, (int) inp.yaw);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "coordinate_frame", "I");
env->SetIntField (result, fid, (int) inp.coordinate_frame);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_global_position_setpoint_int_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_global_position_setpoint_int(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t latitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_global_position_setpoint_int_class, "latitude", "J"));
int32_t longitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_global_position_setpoint_int_class, "longitude", "J"));
int32_t altitude = (int32_t)env->GetLongField (obj, env->GetFieldID(set_global_position_setpoint_int_class, "altitude", "J"));
int16_t yaw = (int16_t)env->GetIntField (obj, env->GetFieldID(set_global_position_setpoint_int_class, "yaw", "I"));
uint8_t coordinate_frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_global_position_setpoint_int_class, "coordinate_frame", "I"));
mavlink_msg_set_global_position_setpoint_int_pack(system_id, component_id, &msg,coordinate_frame, latitude, longitude, altitude, yaw);
}
jobject unpack_msg_safety_set_allowed_area(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_safety_set_allowed_area_t inp;
mavlink_msg_safety_set_allowed_area_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(safety_set_allowed_area_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(safety_set_allowed_area_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(safety_set_allowed_area_class, "p1x", "F");
env->SetFloatField (result, fid, (float)inp.p1x);
fid = env->GetFieldID(safety_set_allowed_area_class, "p1y", "F");
env->SetFloatField (result, fid, (float)inp.p1y);
fid = env->GetFieldID(safety_set_allowed_area_class, "p1z", "F");
env->SetFloatField (result, fid, (float)inp.p1z);
fid = env->GetFieldID(safety_set_allowed_area_class, "p2x", "F");
env->SetFloatField (result, fid, (float)inp.p2x);
fid = env->GetFieldID(safety_set_allowed_area_class, "p2y", "F");
env->SetFloatField (result, fid, (float)inp.p2y);
fid = env->GetFieldID(safety_set_allowed_area_class, "p2z", "F");
env->SetFloatField (result, fid, (float)inp.p2z);
fid = env->GetFieldID(safety_set_allowed_area_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(safety_set_allowed_area_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(safety_set_allowed_area_class, "frame", "I");
env->SetIntField (result, fid, (int) inp.frame);
fid = env->GetFieldID(safety_set_allowed_area_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(safety_set_allowed_area_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_safety_set_allowed_area(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float p1x = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p1x", "F"));
float p1y = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p1y", "F"));
float p1z = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p1z", "F"));
float p2x = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p2x", "F"));
float p2y = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p2y", "F"));
float p2z = (float)env->GetFloatField (obj, env->GetFieldID(safety_set_allowed_area_class, "p2z", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(safety_set_allowed_area_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(safety_set_allowed_area_class, "target_component", "I"));
uint8_t frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(safety_set_allowed_area_class, "frame", "I"));
mavlink_msg_safety_set_allowed_area_pack(system_id, component_id, &msg,target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z);
}
jobject unpack_msg_safety_allowed_area(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_safety_allowed_area_t inp;
mavlink_msg_safety_allowed_area_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(safety_allowed_area_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(safety_allowed_area_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(safety_allowed_area_class, "p1x", "F");
env->SetFloatField (result, fid, (float)inp.p1x);
fid = env->GetFieldID(safety_allowed_area_class, "p1y", "F");
env->SetFloatField (result, fid, (float)inp.p1y);
fid = env->GetFieldID(safety_allowed_area_class, "p1z", "F");
env->SetFloatField (result, fid, (float)inp.p1z);
fid = env->GetFieldID(safety_allowed_area_class, "p2x", "F");
env->SetFloatField (result, fid, (float)inp.p2x);
fid = env->GetFieldID(safety_allowed_area_class, "p2y", "F");
env->SetFloatField (result, fid, (float)inp.p2y);
fid = env->GetFieldID(safety_allowed_area_class, "p2z", "F");
env->SetFloatField (result, fid, (float)inp.p2z);
fid = env->GetFieldID(safety_allowed_area_class, "frame", "I");
env->SetIntField (result, fid, (int) inp.frame);
fid = env->GetFieldID(safety_allowed_area_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(safety_allowed_area_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_safety_allowed_area(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float p1x = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p1x", "F"));
float p1y = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p1y", "F"));
float p1z = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p1z", "F"));
float p2x = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p2x", "F"));
float p2y = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p2y", "F"));
float p2z = (float)env->GetFloatField (obj, env->GetFieldID(safety_allowed_area_class, "p2z", "F"));
uint8_t frame = (uint8_t)env->GetIntField (obj, env->GetFieldID(safety_allowed_area_class, "frame", "I"));
mavlink_msg_safety_allowed_area_pack(system_id, component_id, &msg,frame, p1x, p1y, p1z, p2x, p2y, p2z);
}
jobject unpack_msg_set_roll_pitch_yaw_thrust(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_roll_pitch_yaw_thrust_t inp;
mavlink_msg_set_roll_pitch_yaw_thrust_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_roll_pitch_yaw_thrust_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_roll_pitch_yaw_thrust_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "thrust", "F");
env->SetFloatField (result, fid, (float)inp.thrust);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_roll_pitch_yaw_thrust_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_roll_pitch_yaw_thrust(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float roll = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "yaw", "F"));
float thrust = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "thrust", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_roll_pitch_yaw_thrust_class, "target_component", "I"));
mavlink_msg_set_roll_pitch_yaw_thrust_pack(system_id, component_id, &msg,target_system, target_component, roll, pitch, yaw, thrust);
}
jobject unpack_msg_set_roll_pitch_yaw_speed_thrust(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_roll_pitch_yaw_speed_thrust_t inp;
mavlink_msg_set_roll_pitch_yaw_speed_thrust_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_roll_pitch_yaw_speed_thrust_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_roll_pitch_yaw_speed_thrust_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "roll_speed", "F");
env->SetFloatField (result, fid, (float)inp.roll_speed);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "pitch_speed", "F");
env->SetFloatField (result, fid, (float)inp.pitch_speed);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "yaw_speed", "F");
env->SetFloatField (result, fid, (float)inp.yaw_speed);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "thrust", "F");
env->SetFloatField (result, fid, (float)inp.thrust);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_roll_pitch_yaw_speed_thrust(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float roll_speed = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "roll_speed", "F"));
float pitch_speed = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "pitch_speed", "F"));
float yaw_speed = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "yaw_speed", "F"));
float thrust = (float)env->GetFloatField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "thrust", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_roll_pitch_yaw_speed_thrust_class, "target_component", "I"));
mavlink_msg_set_roll_pitch_yaw_speed_thrust_pack(system_id, component_id, &msg,target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust);
}
jobject unpack_msg_roll_pitch_yaw_thrust_setpoint(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_roll_pitch_yaw_thrust_setpoint_t inp;
mavlink_msg_roll_pitch_yaw_thrust_setpoint_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(roll_pitch_yaw_thrust_setpoint_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(roll_pitch_yaw_thrust_setpoint_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "thrust", "F");
env->SetFloatField (result, fid, (float)inp.thrust);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_roll_pitch_yaw_thrust_setpoint(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "time_boot_ms", "J"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "yaw", "F"));
float thrust = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_thrust_setpoint_class, "thrust", "F"));
mavlink_msg_roll_pitch_yaw_thrust_setpoint_pack(system_id, component_id, &msg,time_boot_ms, roll, pitch, yaw, thrust);
}
jobject unpack_msg_roll_pitch_yaw_speed_thrust_setpoint(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_roll_pitch_yaw_speed_thrust_setpoint_t inp;
mavlink_msg_roll_pitch_yaw_speed_thrust_setpoint_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(roll_pitch_yaw_speed_thrust_setpoint_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(roll_pitch_yaw_speed_thrust_setpoint_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "roll_speed", "F");
env->SetFloatField (result, fid, (float)inp.roll_speed);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "pitch_speed", "F");
env->SetFloatField (result, fid, (float)inp.pitch_speed);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "yaw_speed", "F");
env->SetFloatField (result, fid, (float)inp.yaw_speed);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "thrust", "F");
env->SetFloatField (result, fid, (float)inp.thrust);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_roll_pitch_yaw_speed_thrust_setpoint(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "time_boot_ms", "J"));
float roll_speed = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "roll_speed", "F"));
float pitch_speed = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "pitch_speed", "F"));
float yaw_speed = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "yaw_speed", "F"));
float thrust = (float)env->GetFloatField (obj, env->GetFieldID(roll_pitch_yaw_speed_thrust_setpoint_class, "thrust", "F"));
mavlink_msg_roll_pitch_yaw_speed_thrust_setpoint_pack(system_id, component_id, &msg,time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust);
}
jobject unpack_msg_nav_controller_output(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_nav_controller_output_t inp;
mavlink_msg_nav_controller_output_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(nav_controller_output_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(nav_controller_output_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(nav_controller_output_class, "nav_roll", "F");
env->SetFloatField (result, fid, (float)inp.nav_roll);
fid = env->GetFieldID(nav_controller_output_class, "nav_pitch", "F");
env->SetFloatField (result, fid, (float)inp.nav_pitch);
fid = env->GetFieldID(nav_controller_output_class, "alt_error", "F");
env->SetFloatField (result, fid, (float)inp.alt_error);
fid = env->GetFieldID(nav_controller_output_class, "aspd_error", "F");
env->SetFloatField (result, fid, (float)inp.aspd_error);
fid = env->GetFieldID(nav_controller_output_class, "xtrack_error", "F");
env->SetFloatField (result, fid, (float)inp.xtrack_error);
fid = env->GetFieldID(nav_controller_output_class, "nav_bearing", "I");
env->SetIntField (result, fid, (int) inp.nav_bearing);
fid = env->GetFieldID(nav_controller_output_class, "target_bearing", "I");
env->SetIntField (result, fid, (int) inp.target_bearing);
fid = env->GetFieldID(nav_controller_output_class, "wp_dist", "I");
env->SetIntField (result, fid, (int) inp.wp_dist);
fid = env->GetFieldID(nav_controller_output_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(nav_controller_output_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_nav_controller_output(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float nav_roll = (float)env->GetFloatField (obj, env->GetFieldID(nav_controller_output_class, "nav_roll", "F"));
float nav_pitch = (float)env->GetFloatField (obj, env->GetFieldID(nav_controller_output_class, "nav_pitch", "F"));
float alt_error = (float)env->GetFloatField (obj, env->GetFieldID(nav_controller_output_class, "alt_error", "F"));
float aspd_error = (float)env->GetFloatField (obj, env->GetFieldID(nav_controller_output_class, "aspd_error", "F"));
float xtrack_error = (float)env->GetFloatField (obj, env->GetFieldID(nav_controller_output_class, "xtrack_error", "F"));
int16_t nav_bearing = (int16_t)env->GetIntField (obj, env->GetFieldID(nav_controller_output_class, "nav_bearing", "I"));
int16_t target_bearing = (int16_t)env->GetIntField (obj, env->GetFieldID(nav_controller_output_class, "target_bearing", "I"));
uint16_t wp_dist = (uint16_t)env->GetIntField (obj, env->GetFieldID(nav_controller_output_class, "wp_dist", "I"));
mavlink_msg_nav_controller_output_pack(system_id, component_id, &msg,nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error);
}
jobject unpack_msg_state_correction(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_state_correction_t inp;
mavlink_msg_state_correction_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(state_correction_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(state_correction_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(state_correction_class, "xErr", "F");
env->SetFloatField (result, fid, (float)inp.xErr);
fid = env->GetFieldID(state_correction_class, "yErr", "F");
env->SetFloatField (result, fid, (float)inp.yErr);
fid = env->GetFieldID(state_correction_class, "zErr", "F");
env->SetFloatField (result, fid, (float)inp.zErr);
fid = env->GetFieldID(state_correction_class, "rollErr", "F");
env->SetFloatField (result, fid, (float)inp.rollErr);
fid = env->GetFieldID(state_correction_class, "pitchErr", "F");
env->SetFloatField (result, fid, (float)inp.pitchErr);
fid = env->GetFieldID(state_correction_class, "yawErr", "F");
env->SetFloatField (result, fid, (float)inp.yawErr);
fid = env->GetFieldID(state_correction_class, "vxErr", "F");
env->SetFloatField (result, fid, (float)inp.vxErr);
fid = env->GetFieldID(state_correction_class, "vyErr", "F");
env->SetFloatField (result, fid, (float)inp.vyErr);
fid = env->GetFieldID(state_correction_class, "vzErr", "F");
env->SetFloatField (result, fid, (float)inp.vzErr);
fid = env->GetFieldID(state_correction_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(state_correction_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_state_correction(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float xErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "xErr", "F"));
float yErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "yErr", "F"));
float zErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "zErr", "F"));
float rollErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "rollErr", "F"));
float pitchErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "pitchErr", "F"));
float yawErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "yawErr", "F"));
float vxErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "vxErr", "F"));
float vyErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "vyErr", "F"));
float vzErr = (float)env->GetFloatField (obj, env->GetFieldID(state_correction_class, "vzErr", "F"));
mavlink_msg_state_correction_pack(system_id, component_id, &msg,xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr);
}
jobject unpack_msg_request_data_stream(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_request_data_stream_t inp;
mavlink_msg_request_data_stream_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(request_data_stream_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(request_data_stream_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(request_data_stream_class, "req_message_rate", "I");
env->SetIntField (result, fid, (int) inp.req_message_rate);
fid = env->GetFieldID(request_data_stream_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(request_data_stream_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(request_data_stream_class, "req_stream_id", "I");
env->SetIntField (result, fid, (int) inp.req_stream_id);
fid = env->GetFieldID(request_data_stream_class, "start_stop", "I");
env->SetIntField (result, fid, (int) inp.start_stop);
fid = env->GetFieldID(request_data_stream_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(request_data_stream_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_request_data_stream(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t req_message_rate = (uint16_t)env->GetIntField (obj, env->GetFieldID(request_data_stream_class, "req_message_rate", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(request_data_stream_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(request_data_stream_class, "target_component", "I"));
uint8_t req_stream_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(request_data_stream_class, "req_stream_id", "I"));
uint8_t start_stop = (uint8_t)env->GetIntField (obj, env->GetFieldID(request_data_stream_class, "start_stop", "I"));
mavlink_msg_request_data_stream_pack(system_id, component_id, &msg,target_system, target_component, req_stream_id, req_message_rate, start_stop);
}
jobject unpack_msg_data_stream(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_data_stream_t inp;
mavlink_msg_data_stream_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(data_stream_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(data_stream_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(data_stream_class, "message_rate", "I");
env->SetIntField (result, fid, (int) inp.message_rate);
fid = env->GetFieldID(data_stream_class, "stream_id", "I");
env->SetIntField (result, fid, (int) inp.stream_id);
fid = env->GetFieldID(data_stream_class, "on_off", "I");
env->SetIntField (result, fid, (int) inp.on_off);
fid = env->GetFieldID(data_stream_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(data_stream_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_data_stream(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t message_rate = (uint16_t)env->GetIntField (obj, env->GetFieldID(data_stream_class, "message_rate", "I"));
uint8_t stream_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(data_stream_class, "stream_id", "I"));
uint8_t on_off = (uint8_t)env->GetIntField (obj, env->GetFieldID(data_stream_class, "on_off", "I"));
mavlink_msg_data_stream_pack(system_id, component_id, &msg,stream_id, message_rate, on_off);
}
jobject unpack_msg_manual_control(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_manual_control_t inp;
mavlink_msg_manual_control_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(manual_control_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(manual_control_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(manual_control_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(manual_control_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(manual_control_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(manual_control_class, "thrust", "F");
env->SetFloatField (result, fid, (float)inp.thrust);
fid = env->GetFieldID(manual_control_class, "target", "I");
env->SetIntField (result, fid, (int) inp.target);
fid = env->GetFieldID(manual_control_class, "roll_manual", "I");
env->SetIntField (result, fid, (int) inp.roll_manual);
fid = env->GetFieldID(manual_control_class, "pitch_manual", "I");
env->SetIntField (result, fid, (int) inp.pitch_manual);
fid = env->GetFieldID(manual_control_class, "yaw_manual", "I");
env->SetIntField (result, fid, (int) inp.yaw_manual);
fid = env->GetFieldID(manual_control_class, "thrust_manual", "I");
env->SetIntField (result, fid, (int) inp.thrust_manual);
fid = env->GetFieldID(manual_control_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(manual_control_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_manual_control(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float roll = (float)env->GetFloatField (obj, env->GetFieldID(manual_control_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(manual_control_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(manual_control_class, "yaw", "F"));
float thrust = (float)env->GetFloatField (obj, env->GetFieldID(manual_control_class, "thrust", "F"));
uint8_t target = (uint8_t)env->GetIntField (obj, env->GetFieldID(manual_control_class, "target", "I"));
uint8_t roll_manual = (uint8_t)env->GetIntField (obj, env->GetFieldID(manual_control_class, "roll_manual", "I"));
uint8_t pitch_manual = (uint8_t)env->GetIntField (obj, env->GetFieldID(manual_control_class, "pitch_manual", "I"));
uint8_t yaw_manual = (uint8_t)env->GetIntField (obj, env->GetFieldID(manual_control_class, "yaw_manual", "I"));
uint8_t thrust_manual = (uint8_t)env->GetIntField (obj, env->GetFieldID(manual_control_class, "thrust_manual", "I"));
mavlink_msg_manual_control_pack(system_id, component_id, &msg,target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual);
}
jobject unpack_msg_rc_channels_override(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_rc_channels_override_t inp;
mavlink_msg_rc_channels_override_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(rc_channels_override_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(rc_channels_override_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(rc_channels_override_class, "chan1_raw", "I");
env->SetIntField (result, fid, (int) inp.chan1_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan2_raw", "I");
env->SetIntField (result, fid, (int) inp.chan2_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan3_raw", "I");
env->SetIntField (result, fid, (int) inp.chan3_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan4_raw", "I");
env->SetIntField (result, fid, (int) inp.chan4_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan5_raw", "I");
env->SetIntField (result, fid, (int) inp.chan5_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan6_raw", "I");
env->SetIntField (result, fid, (int) inp.chan6_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan7_raw", "I");
env->SetIntField (result, fid, (int) inp.chan7_raw);
fid = env->GetFieldID(rc_channels_override_class, "chan8_raw", "I");
env->SetIntField (result, fid, (int) inp.chan8_raw);
fid = env->GetFieldID(rc_channels_override_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(rc_channels_override_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(rc_channels_override_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(rc_channels_override_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_rc_channels_override(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t chan1_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan1_raw", "I"));
uint16_t chan2_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan2_raw", "I"));
uint16_t chan3_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan3_raw", "I"));
uint16_t chan4_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan4_raw", "I"));
uint16_t chan5_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan5_raw", "I"));
uint16_t chan6_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan6_raw", "I"));
uint16_t chan7_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan7_raw", "I"));
uint16_t chan8_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "chan8_raw", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(rc_channels_override_class, "target_component", "I"));
mavlink_msg_rc_channels_override_pack(system_id, component_id, &msg,target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw);
}
jobject unpack_msg_vfr_hud(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_vfr_hud_t inp;
mavlink_msg_vfr_hud_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(vfr_hud_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(vfr_hud_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(vfr_hud_class, "airspeed", "F");
env->SetFloatField (result, fid, (float)inp.airspeed);
fid = env->GetFieldID(vfr_hud_class, "groundspeed", "F");
env->SetFloatField (result, fid, (float)inp.groundspeed);
fid = env->GetFieldID(vfr_hud_class, "alt", "F");
env->SetFloatField (result, fid, (float)inp.alt);
fid = env->GetFieldID(vfr_hud_class, "climb", "F");
env->SetFloatField (result, fid, (float)inp.climb);
fid = env->GetFieldID(vfr_hud_class, "heading", "I");
env->SetIntField (result, fid, (int) inp.heading);
fid = env->GetFieldID(vfr_hud_class, "throttle", "I");
env->SetIntField (result, fid, (int) inp.throttle);
fid = env->GetFieldID(vfr_hud_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(vfr_hud_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_vfr_hud(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float airspeed = (float)env->GetFloatField (obj, env->GetFieldID(vfr_hud_class, "airspeed", "F"));
float groundspeed = (float)env->GetFloatField (obj, env->GetFieldID(vfr_hud_class, "groundspeed", "F"));
float alt = (float)env->GetFloatField (obj, env->GetFieldID(vfr_hud_class, "alt", "F"));
float climb = (float)env->GetFloatField (obj, env->GetFieldID(vfr_hud_class, "climb", "F"));
int16_t heading = (int16_t)env->GetIntField (obj, env->GetFieldID(vfr_hud_class, "heading", "I"));
uint16_t throttle = (uint16_t)env->GetIntField (obj, env->GetFieldID(vfr_hud_class, "throttle", "I"));
mavlink_msg_vfr_hud_pack(system_id, component_id, &msg,airspeed, groundspeed, heading, throttle, alt, climb);
}
jobject unpack_msg_command_long(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_command_long_t inp;
mavlink_msg_command_long_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(command_long_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(command_long_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(command_long_class, "param1", "F");
env->SetFloatField (result, fid, (float)inp.param1);
fid = env->GetFieldID(command_long_class, "param2", "F");
env->SetFloatField (result, fid, (float)inp.param2);
fid = env->GetFieldID(command_long_class, "param3", "F");
env->SetFloatField (result, fid, (float)inp.param3);
fid = env->GetFieldID(command_long_class, "param4", "F");
env->SetFloatField (result, fid, (float)inp.param4);
fid = env->GetFieldID(command_long_class, "param5", "F");
env->SetFloatField (result, fid, (float)inp.param5);
fid = env->GetFieldID(command_long_class, "param6", "F");
env->SetFloatField (result, fid, (float)inp.param6);
fid = env->GetFieldID(command_long_class, "param7", "F");
env->SetFloatField (result, fid, (float)inp.param7);
fid = env->GetFieldID(command_long_class, "command", "I");
env->SetIntField (result, fid, (int) inp.command);
fid = env->GetFieldID(command_long_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(command_long_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(command_long_class, "confirmation", "I");
env->SetIntField (result, fid, (int) inp.confirmation);
fid = env->GetFieldID(command_long_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(command_long_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_command_long(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float param1 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param1", "F"));
float param2 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param2", "F"));
float param3 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param3", "F"));
float param4 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param4", "F"));
float param5 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param5", "F"));
float param6 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param6", "F"));
float param7 = (float)env->GetFloatField (obj, env->GetFieldID(command_long_class, "param7", "F"));
uint16_t command = (uint16_t)env->GetIntField (obj, env->GetFieldID(command_long_class, "command", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(command_long_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(command_long_class, "target_component", "I"));
uint8_t confirmation = (uint8_t)env->GetIntField (obj, env->GetFieldID(command_long_class, "confirmation", "I"));
mavlink_msg_command_long_pack(system_id, component_id, &msg,target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7);
}
jobject unpack_msg_command_ack(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_command_ack_t inp;
mavlink_msg_command_ack_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(command_ack_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(command_ack_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(command_ack_class, "command", "I");
env->SetIntField (result, fid, (int) inp.command);
fid = env->GetFieldID(command_ack_class, "result", "I");
env->SetIntField (result, fid, (int) inp.result);
fid = env->GetFieldID(command_ack_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(command_ack_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_command_ack(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t command = (uint16_t)env->GetIntField (obj, env->GetFieldID(command_ack_class, "command", "I"));
uint8_t result = (uint8_t)env->GetIntField (obj, env->GetFieldID(command_ack_class, "result", "I"));
mavlink_msg_command_ack_pack(system_id, component_id, &msg,command, result);
}
jobject unpack_msg_hil_state(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_hil_state_t inp;
mavlink_msg_hil_state_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(hil_state_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(hil_state_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(hil_state_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(hil_state_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(hil_state_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(hil_state_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(hil_state_class, "rollspeed", "F");
env->SetFloatField (result, fid, (float)inp.rollspeed);
fid = env->GetFieldID(hil_state_class, "pitchspeed", "F");
env->SetFloatField (result, fid, (float)inp.pitchspeed);
fid = env->GetFieldID(hil_state_class, "yawspeed", "F");
env->SetFloatField (result, fid, (float)inp.yawspeed);
fid = env->GetFieldID(hil_state_class, "lat", "J");
env->SetLongField (result, fid, (long) inp.lat);
fid = env->GetFieldID(hil_state_class, "lon", "J");
env->SetLongField (result, fid, (long) inp.lon);
fid = env->GetFieldID(hil_state_class, "alt", "J");
env->SetLongField (result, fid, (long) inp.alt);
fid = env->GetFieldID(hil_state_class, "vx", "I");
env->SetIntField (result, fid, (int) inp.vx);
fid = env->GetFieldID(hil_state_class, "vy", "I");
env->SetIntField (result, fid, (int) inp.vy);
fid = env->GetFieldID(hil_state_class, "vz", "I");
env->SetIntField (result, fid, (int) inp.vz);
fid = env->GetFieldID(hil_state_class, "xacc", "I");
env->SetIntField (result, fid, (int) inp.xacc);
fid = env->GetFieldID(hil_state_class, "yacc", "I");
env->SetIntField (result, fid, (int) inp.yacc);
fid = env->GetFieldID(hil_state_class, "zacc", "I");
env->SetIntField (result, fid, (int) inp.zacc);
fid = env->GetFieldID(hil_state_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(hil_state_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_hil_state(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(hil_state_class, "time_usec", "J"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "yaw", "F"));
float rollspeed = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "rollspeed", "F"));
float pitchspeed = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "pitchspeed", "F"));
float yawspeed = (float)env->GetFloatField (obj, env->GetFieldID(hil_state_class, "yawspeed", "F"));
int32_t lat = (int32_t)env->GetLongField (obj, env->GetFieldID(hil_state_class, "lat", "J"));
int32_t lon = (int32_t)env->GetLongField (obj, env->GetFieldID(hil_state_class, "lon", "J"));
int32_t alt = (int32_t)env->GetLongField (obj, env->GetFieldID(hil_state_class, "alt", "J"));
int16_t vx = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "vx", "I"));
int16_t vy = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "vy", "I"));
int16_t vz = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "vz", "I"));
int16_t xacc = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "xacc", "I"));
int16_t yacc = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "yacc", "I"));
int16_t zacc = (int16_t)env->GetIntField (obj, env->GetFieldID(hil_state_class, "zacc", "I"));
mavlink_msg_hil_state_pack(system_id, component_id, &msg,time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc);
}
jobject unpack_msg_hil_controls(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_hil_controls_t inp;
mavlink_msg_hil_controls_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(hil_controls_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(hil_controls_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(hil_controls_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(hil_controls_class, "roll_ailerons", "F");
env->SetFloatField (result, fid, (float)inp.roll_ailerons);
fid = env->GetFieldID(hil_controls_class, "pitch_elevator", "F");
env->SetFloatField (result, fid, (float)inp.pitch_elevator);
fid = env->GetFieldID(hil_controls_class, "yaw_rudder", "F");
env->SetFloatField (result, fid, (float)inp.yaw_rudder);
fid = env->GetFieldID(hil_controls_class, "throttle", "F");
env->SetFloatField (result, fid, (float)inp.throttle);
fid = env->GetFieldID(hil_controls_class, "aux1", "F");
env->SetFloatField (result, fid, (float)inp.aux1);
fid = env->GetFieldID(hil_controls_class, "aux2", "F");
env->SetFloatField (result, fid, (float)inp.aux2);
fid = env->GetFieldID(hil_controls_class, "aux3", "F");
env->SetFloatField (result, fid, (float)inp.aux3);
fid = env->GetFieldID(hil_controls_class, "aux4", "F");
env->SetFloatField (result, fid, (float)inp.aux4);
fid = env->GetFieldID(hil_controls_class, "mode", "I");
env->SetIntField (result, fid, (int) inp.mode);
fid = env->GetFieldID(hil_controls_class, "nav_mode", "I");
env->SetIntField (result, fid, (int) inp.nav_mode);
fid = env->GetFieldID(hil_controls_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(hil_controls_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_hil_controls(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(hil_controls_class, "time_usec", "J"));
float roll_ailerons = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "roll_ailerons", "F"));
float pitch_elevator = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "pitch_elevator", "F"));
float yaw_rudder = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "yaw_rudder", "F"));
float throttle = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "throttle", "F"));
float aux1 = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "aux1", "F"));
float aux2 = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "aux2", "F"));
float aux3 = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "aux3", "F"));
float aux4 = (float)env->GetFloatField (obj, env->GetFieldID(hil_controls_class, "aux4", "F"));
uint8_t mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(hil_controls_class, "mode", "I"));
uint8_t nav_mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(hil_controls_class, "nav_mode", "I"));
mavlink_msg_hil_controls_pack(system_id, component_id, &msg,time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode);
}
jobject unpack_msg_hil_rc_inputs_raw(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_hil_rc_inputs_raw_t inp;
mavlink_msg_hil_rc_inputs_raw_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(hil_rc_inputs_raw_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(hil_rc_inputs_raw_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(hil_rc_inputs_raw_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan1_raw", "I");
env->SetIntField (result, fid, (int) inp.chan1_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan2_raw", "I");
env->SetIntField (result, fid, (int) inp.chan2_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan3_raw", "I");
env->SetIntField (result, fid, (int) inp.chan3_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan4_raw", "I");
env->SetIntField (result, fid, (int) inp.chan4_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan5_raw", "I");
env->SetIntField (result, fid, (int) inp.chan5_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan6_raw", "I");
env->SetIntField (result, fid, (int) inp.chan6_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan7_raw", "I");
env->SetIntField (result, fid, (int) inp.chan7_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan8_raw", "I");
env->SetIntField (result, fid, (int) inp.chan8_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan9_raw", "I");
env->SetIntField (result, fid, (int) inp.chan9_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan10_raw", "I");
env->SetIntField (result, fid, (int) inp.chan10_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan11_raw", "I");
env->SetIntField (result, fid, (int) inp.chan11_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "chan12_raw", "I");
env->SetIntField (result, fid, (int) inp.chan12_raw);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "rssi", "I");
env->SetIntField (result, fid, (int) inp.rssi);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(hil_rc_inputs_raw_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_hil_rc_inputs_raw(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "time_usec", "J"));
uint16_t chan1_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan1_raw", "I"));
uint16_t chan2_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan2_raw", "I"));
uint16_t chan3_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan3_raw", "I"));
uint16_t chan4_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan4_raw", "I"));
uint16_t chan5_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan5_raw", "I"));
uint16_t chan6_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan6_raw", "I"));
uint16_t chan7_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan7_raw", "I"));
uint16_t chan8_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan8_raw", "I"));
uint16_t chan9_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan9_raw", "I"));
uint16_t chan10_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan10_raw", "I"));
uint16_t chan11_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan11_raw", "I"));
uint16_t chan12_raw = (uint16_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "chan12_raw", "I"));
uint8_t rssi = (uint8_t)env->GetIntField (obj, env->GetFieldID(hil_rc_inputs_raw_class, "rssi", "I"));
mavlink_msg_hil_rc_inputs_raw_pack(system_id, component_id, &msg,time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi);
}
jobject unpack_msg_optical_flow(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_optical_flow_t inp;
mavlink_msg_optical_flow_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(optical_flow_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(optical_flow_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(optical_flow_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(optical_flow_class, "ground_distance", "F");
env->SetFloatField (result, fid, (float)inp.ground_distance);
fid = env->GetFieldID(optical_flow_class, "flow_x", "I");
env->SetIntField (result, fid, (int) inp.flow_x);
fid = env->GetFieldID(optical_flow_class, "flow_y", "I");
env->SetIntField (result, fid, (int) inp.flow_y);
fid = env->GetFieldID(optical_flow_class, "sensor_id", "I");
env->SetIntField (result, fid, (int) inp.sensor_id);
fid = env->GetFieldID(optical_flow_class, "quality", "I");
env->SetIntField (result, fid, (int) inp.quality);
fid = env->GetFieldID(optical_flow_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(optical_flow_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_optical_flow(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(optical_flow_class, "time_usec", "J"));
float ground_distance = (float)env->GetFloatField (obj, env->GetFieldID(optical_flow_class, "ground_distance", "F"));
int16_t flow_x = (int16_t)env->GetIntField (obj, env->GetFieldID(optical_flow_class, "flow_x", "I"));
int16_t flow_y = (int16_t)env->GetIntField (obj, env->GetFieldID(optical_flow_class, "flow_y", "I"));
uint8_t sensor_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(optical_flow_class, "sensor_id", "I"));
uint8_t quality = (uint8_t)env->GetIntField (obj, env->GetFieldID(optical_flow_class, "quality", "I"));
//mavlink_msg_optical_flow_pack(system_id, component_id, &msg,time_usec, sensor_id, flow_x, flow_y, quality, ground_distance);
}
jobject unpack_msg_global_vision_position_estimate(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_global_vision_position_estimate_t inp;
mavlink_msg_global_vision_position_estimate_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(global_vision_position_estimate_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(global_vision_position_estimate_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(global_vision_position_estimate_class, "usec", "J");
env->SetLongField (result, fid, (long) inp.usec);
fid = env->GetFieldID(global_vision_position_estimate_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(global_vision_position_estimate_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(global_vision_position_estimate_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(global_vision_position_estimate_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(global_vision_position_estimate_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(global_vision_position_estimate_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(global_vision_position_estimate_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(global_vision_position_estimate_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_global_vision_position_estimate(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(global_vision_position_estimate_class, "usec", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "z", "F"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(global_vision_position_estimate_class, "yaw", "F"));
mavlink_msg_global_vision_position_estimate_pack(system_id, component_id, &msg,usec, x, y, z, roll, pitch, yaw);
}
jobject unpack_msg_vision_position_estimate(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_vision_position_estimate_t inp;
mavlink_msg_vision_position_estimate_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(vision_position_estimate_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(vision_position_estimate_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(vision_position_estimate_class, "usec", "J");
env->SetLongField (result, fid, (long) inp.usec);
fid = env->GetFieldID(vision_position_estimate_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(vision_position_estimate_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(vision_position_estimate_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(vision_position_estimate_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(vision_position_estimate_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(vision_position_estimate_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(vision_position_estimate_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(vision_position_estimate_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_vision_position_estimate(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(vision_position_estimate_class, "usec", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "z", "F"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(vision_position_estimate_class, "yaw", "F"));
mavlink_msg_vision_position_estimate_pack(system_id, component_id, &msg,usec, x, y, z, roll, pitch, yaw);
}
jobject unpack_msg_vision_speed_estimate(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_vision_speed_estimate_t inp;
mavlink_msg_vision_speed_estimate_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(vision_speed_estimate_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(vision_speed_estimate_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(vision_speed_estimate_class, "usec", "J");
env->SetLongField (result, fid, (long) inp.usec);
fid = env->GetFieldID(vision_speed_estimate_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(vision_speed_estimate_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(vision_speed_estimate_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(vision_speed_estimate_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(vision_speed_estimate_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_vision_speed_estimate(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(vision_speed_estimate_class, "usec", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(vision_speed_estimate_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(vision_speed_estimate_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(vision_speed_estimate_class, "z", "F"));
mavlink_msg_vision_speed_estimate_pack(system_id, component_id, &msg,usec, x, y, z);
}
jobject unpack_msg_vicon_position_estimate(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_vicon_position_estimate_t inp;
mavlink_msg_vicon_position_estimate_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(vicon_position_estimate_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(vicon_position_estimate_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(vicon_position_estimate_class, "usec", "J");
env->SetLongField (result, fid, (long) inp.usec);
fid = env->GetFieldID(vicon_position_estimate_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(vicon_position_estimate_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(vicon_position_estimate_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
fid = env->GetFieldID(vicon_position_estimate_class, "roll", "F");
env->SetFloatField (result, fid, (float)inp.roll);
fid = env->GetFieldID(vicon_position_estimate_class, "pitch", "F");
env->SetFloatField (result, fid, (float)inp.pitch);
fid = env->GetFieldID(vicon_position_estimate_class, "yaw", "F");
env->SetFloatField (result, fid, (float)inp.yaw);
fid = env->GetFieldID(vicon_position_estimate_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(vicon_position_estimate_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_vicon_position_estimate(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(vicon_position_estimate_class, "usec", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "z", "F"));
float roll = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "roll", "F"));
float pitch = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "pitch", "F"));
float yaw = (float)env->GetFloatField (obj, env->GetFieldID(vicon_position_estimate_class, "yaw", "F"));
mavlink_msg_vicon_position_estimate_pack(system_id, component_id, &msg,usec, x, y, z, roll, pitch, yaw);
}
jobject unpack_msg_memory_vect(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_memory_vect_t inp;
mavlink_msg_memory_vect_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(memory_vect_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(memory_vect_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(memory_vect_class, "address", "I");
env->SetIntField (result, fid, (int) inp.address);
fid = env->GetFieldID(memory_vect_class, "ver", "I");
env->SetIntField (result, fid, (int) inp.ver);
fid = env->GetFieldID(memory_vect_class, "type", "I");
env->SetIntField (result, fid, (int) inp.type);
{
// Lets send it onto Java.
fid = env->GetFieldID(memory_vect_class, "value", "[I");
jintArray intArr = (jintArray) env->GetObjectField(result, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 32; i++)
data[i] = inp.value[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
fid = env->GetFieldID(memory_vect_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(memory_vect_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_memory_vect(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t address = (uint16_t)env->GetIntField (obj, env->GetFieldID(memory_vect_class, "address", "I"));
uint8_t ver = (uint8_t)env->GetIntField (obj, env->GetFieldID(memory_vect_class, "ver", "I"));
uint8_t type = (uint8_t)env->GetIntField (obj, env->GetFieldID(memory_vect_class, "type", "I"));
int8_t value[32];
{
jfieldID fid;
// Lets send it onto Java.
fid = env->GetFieldID(memory_vect_class, "value", "[I");
jintArray intArr = (jintArray) env->GetObjectField(obj, fid);
jint* data = env->GetIntArrayElements(intArr, NULL);
for(int i = 0; i < 32; i++)
value[i] = data[i];
//Don't forget to release it
env->ReleaseIntArrayElements(intArr, data, 0);
}
mavlink_msg_memory_vect_pack(system_id, component_id, &msg,address, ver, type, value);
}
jobject unpack_msg_debug_vect(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_debug_vect_t inp;
mavlink_msg_debug_vect_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(debug_vect_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(debug_vect_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(debug_vect_class, "time_usec", "J");
env->SetLongField (result, fid, (long) inp.time_usec);
fid = env->GetFieldID(debug_vect_class, "x", "F");
env->SetFloatField (result, fid, (float)inp.x);
fid = env->GetFieldID(debug_vect_class, "y", "F");
env->SetFloatField (result, fid, (float)inp.y);
fid = env->GetFieldID(debug_vect_class, "z", "F");
env->SetFloatField (result, fid, (float)inp.z);
{
fid = env->GetFieldID(debug_vect_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
data[i] = inp.name[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(debug_vect_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(debug_vect_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_debug_vect(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint64_t time_usec = (uint64_t)env->GetLongField (obj, env->GetFieldID(debug_vect_class, "time_usec", "J"));
float x = (float)env->GetFloatField (obj, env->GetFieldID(debug_vect_class, "x", "F"));
float y = (float)env->GetFloatField (obj, env->GetFieldID(debug_vect_class, "y", "F"));
float z = (float)env->GetFloatField (obj, env->GetFieldID(debug_vect_class, "z", "F"));
char name[10];
{
jfieldID fid;
fid = env->GetFieldID(debug_vect_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
name[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_debug_vect_pack(system_id, component_id, &msg,name, time_usec, x, y, z);
}
jobject unpack_msg_named_value_float(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_named_value_float_t inp;
mavlink_msg_named_value_float_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(named_value_float_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(named_value_float_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(named_value_float_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(named_value_float_class, "value", "F");
env->SetFloatField (result, fid, (float)inp.value);
{
fid = env->GetFieldID(named_value_float_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
data[i] = inp.name[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(named_value_float_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(named_value_float_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_named_value_float(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(named_value_float_class, "time_boot_ms", "J"));
float value = (float)env->GetFloatField (obj, env->GetFieldID(named_value_float_class, "value", "F"));
char name[10];
{
jfieldID fid;
fid = env->GetFieldID(named_value_float_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
name[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_named_value_float_pack(system_id, component_id, &msg,time_boot_ms, name, value);
}
jobject unpack_msg_named_value_int(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_named_value_int_t inp;
mavlink_msg_named_value_int_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(named_value_int_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(named_value_int_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(named_value_int_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(named_value_int_class, "value", "J");
env->SetLongField (result, fid, (long) inp.value);
{
fid = env->GetFieldID(named_value_int_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
data[i] = inp.name[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(named_value_int_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(named_value_int_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_named_value_int(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(named_value_int_class, "time_boot_ms", "J"));
int32_t value = (int32_t)env->GetLongField (obj, env->GetFieldID(named_value_int_class, "value", "J"));
char name[10];
{
jfieldID fid;
fid = env->GetFieldID(named_value_int_class, "name", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 10; i++)
name[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_named_value_int_pack(system_id, component_id, &msg,time_boot_ms, name, value);
}
jobject unpack_msg_statustext(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_statustext_t inp;
mavlink_msg_statustext_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(statustext_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(statustext_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(statustext_class, "severity", "I");
env->SetIntField (result, fid, (int) inp.severity);
{
fid = env->GetFieldID(statustext_class, "text", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(result, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 50; i++)
data[i] = inp.text[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
fid = env->GetFieldID(statustext_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(statustext_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_statustext(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t severity = (uint8_t)env->GetIntField (obj, env->GetFieldID(statustext_class, "severity", "I"));
char text[50];
{
jfieldID fid;
fid = env->GetFieldID(statustext_class, "text", "[C");
jcharArray charArr = (jcharArray) env->GetObjectField(obj, fid);
jchar* data = env->GetCharArrayElements(charArr, NULL);
for(int i = 0; i < 50; i++)
text[i] = data[i];
// Don't forget to release it
env->ReleaseCharArrayElements(charArr, data, 0);
}
mavlink_msg_statustext_pack(system_id, component_id, &msg,severity, text);
}
jobject unpack_msg_debug(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_debug_t inp;
mavlink_msg_debug_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(debug_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(debug_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(debug_class, "time_boot_ms", "J");
env->SetLongField (result, fid, (long) inp.time_boot_ms);
fid = env->GetFieldID(debug_class, "value", "F");
env->SetFloatField (result, fid, (float)inp.value);
fid = env->GetFieldID(debug_class, "ind", "I");
env->SetIntField (result, fid, (int) inp.ind);
fid = env->GetFieldID(debug_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(debug_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_debug(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint32_t time_boot_ms = (uint32_t)env->GetLongField (obj, env->GetFieldID(debug_class, "time_boot_ms", "J"));
float value = (float)env->GetFloatField (obj, env->GetFieldID(debug_class, "value", "F"));
uint8_t ind = (uint8_t)env->GetIntField (obj, env->GetFieldID(debug_class, "ind", "I"));
mavlink_msg_debug_pack(system_id, component_id, &msg,time_boot_ms, ind, value);
}
/*
jobject unpack_msg_extended_message(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_extended_message_t inp;
mavlink_msg_extended_message_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(extended_message_class, "<init>", "()V");
if (cid == NULL) return NULL; // exception thrown
jobject result = env->NewObject(extended_message_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(extended_message_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(extended_message_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(extended_message_class, "protocol_flags", "I");
env->SetIntField (result, fid, (int) inp.protocol_flags);
fid = env->GetFieldID(extended_message_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(extended_message_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
// Free local references
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_extended_message(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(extended_message_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(extended_message_class, "target_component", "I"));
uint8_t protocol_flags = (uint8_t)env->GetIntField (obj, env->GetFieldID(extended_message_class, "protocol_flags", "I"));
mavlink_msg_extended_message_pack(system_id, component_id, &msg,target_system, target_component, protocol_flags);
}
*/
jobject unpack_msg_sensor_offsets(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_sensor_offsets_t inp;
mavlink_msg_sensor_offsets_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(sensor_offsets_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(sensor_offsets_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(sensor_offsets_class, "mag_declination", "F");
env->SetFloatField (result, fid, (float)inp.mag_declination);
fid = env->GetFieldID(sensor_offsets_class, "raw_press", "J");
env->SetLongField (result, fid, (long) inp.raw_press);
fid = env->GetFieldID(sensor_offsets_class, "raw_temp", "J");
env->SetLongField (result, fid, (long) inp.raw_temp);
fid = env->GetFieldID(sensor_offsets_class, "gyro_cal_x", "F");
env->SetFloatField (result, fid, (float)inp.gyro_cal_x);
fid = env->GetFieldID(sensor_offsets_class, "gyro_cal_y", "F");
env->SetFloatField (result, fid, (float)inp.gyro_cal_y);
fid = env->GetFieldID(sensor_offsets_class, "gyro_cal_z", "F");
env->SetFloatField (result, fid, (float)inp.gyro_cal_z);
fid = env->GetFieldID(sensor_offsets_class, "accel_cal_x", "F");
env->SetFloatField (result, fid, (float)inp.accel_cal_x);
fid = env->GetFieldID(sensor_offsets_class, "accel_cal_y", "F");
env->SetFloatField (result, fid, (float)inp.accel_cal_y);
fid = env->GetFieldID(sensor_offsets_class, "accel_cal_z", "F");
env->SetFloatField (result, fid, (float)inp.accel_cal_z);
fid = env->GetFieldID(sensor_offsets_class, "mag_ofs_x", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_x);
fid = env->GetFieldID(sensor_offsets_class, "mag_ofs_y", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_y);
fid = env->GetFieldID(sensor_offsets_class, "mag_ofs_z", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_z);
fid = env->GetFieldID(sensor_offsets_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(sensor_offsets_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_sensor_offsets(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float mag_declination = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "mag_declination", "F"));
int32_t raw_press = (int32_t)env->GetLongField (obj, env->GetFieldID(sensor_offsets_class, "raw_press", "J"));
int32_t raw_temp = (int32_t)env->GetLongField (obj, env->GetFieldID(sensor_offsets_class, "raw_temp", "J"));
float gyro_cal_x = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "gyro_cal_x", "F"));
float gyro_cal_y = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "gyro_cal_y", "F"));
float gyro_cal_z = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "gyro_cal_z", "F"));
float accel_cal_x = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "accel_cal_x", "F"));
float accel_cal_y = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "accel_cal_y", "F"));
float accel_cal_z = (float)env->GetFloatField (obj, env->GetFieldID(sensor_offsets_class, "accel_cal_z", "F"));
int16_t mag_ofs_x = (int16_t)env->GetIntField (obj, env->GetFieldID(sensor_offsets_class, "mag_ofs_x", "I"));
int16_t mag_ofs_y = (int16_t)env->GetIntField (obj, env->GetFieldID(sensor_offsets_class, "mag_ofs_y", "I"));
int16_t mag_ofs_z = (int16_t)env->GetIntField (obj, env->GetFieldID(sensor_offsets_class, "mag_ofs_z", "I"));
mavlink_msg_sensor_offsets_pack(system_id, component_id, &msg,mag_ofs_x, mag_ofs_y, mag_ofs_z, mag_declination, raw_press, raw_temp, gyro_cal_x, gyro_cal_y, gyro_cal_z, accel_cal_x, accel_cal_y, accel_cal_z);
}
jobject unpack_msg_set_mag_offsets(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_set_mag_offsets_t inp;
mavlink_msg_set_mag_offsets_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(set_mag_offsets_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(set_mag_offsets_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(set_mag_offsets_class, "mag_ofs_x", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_x);
fid = env->GetFieldID(set_mag_offsets_class, "mag_ofs_y", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_y);
fid = env->GetFieldID(set_mag_offsets_class, "mag_ofs_z", "I");
env->SetIntField (result, fid, (int) inp.mag_ofs_z);
fid = env->GetFieldID(set_mag_offsets_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(set_mag_offsets_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(set_mag_offsets_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(set_mag_offsets_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_set_mag_offsets(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int16_t mag_ofs_x = (int16_t)env->GetIntField (obj, env->GetFieldID(set_mag_offsets_class, "mag_ofs_x", "I"));
int16_t mag_ofs_y = (int16_t)env->GetIntField (obj, env->GetFieldID(set_mag_offsets_class, "mag_ofs_y", "I"));
int16_t mag_ofs_z = (int16_t)env->GetIntField (obj, env->GetFieldID(set_mag_offsets_class, "mag_ofs_z", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_mag_offsets_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(set_mag_offsets_class, "target_component", "I"));
mavlink_msg_set_mag_offsets_pack(system_id, component_id, &msg,target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z);
}
jobject unpack_msg_meminfo(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_meminfo_t inp;
mavlink_msg_meminfo_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(meminfo_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(meminfo_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(meminfo_class, "brkval", "I");
env->SetIntField (result, fid, (int) inp.brkval);
fid = env->GetFieldID(meminfo_class, "freemem", "I");
env->SetIntField (result, fid, (int) inp.freemem);
fid = env->GetFieldID(meminfo_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(meminfo_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_meminfo(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t brkval = (uint16_t)env->GetIntField (obj, env->GetFieldID(meminfo_class, "brkval", "I"));
uint16_t freemem = (uint16_t)env->GetIntField (obj, env->GetFieldID(meminfo_class, "freemem", "I"));
mavlink_msg_meminfo_pack(system_id, component_id, &msg,brkval, freemem);
}
jobject unpack_msg_ap_adc(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_ap_adc_t inp;
mavlink_msg_ap_adc_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(ap_adc_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(ap_adc_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(ap_adc_class, "adc1", "I");
env->SetIntField (result, fid, (int) inp.adc1);
fid = env->GetFieldID(ap_adc_class, "adc2", "I");
env->SetIntField (result, fid, (int) inp.adc2);
fid = env->GetFieldID(ap_adc_class, "adc3", "I");
env->SetIntField (result, fid, (int) inp.adc3);
fid = env->GetFieldID(ap_adc_class, "adc4", "I");
env->SetIntField (result, fid, (int) inp.adc4);
fid = env->GetFieldID(ap_adc_class, "adc5", "I");
env->SetIntField (result, fid, (int) inp.adc5);
fid = env->GetFieldID(ap_adc_class, "adc6", "I");
env->SetIntField (result, fid, (int) inp.adc6);
fid = env->GetFieldID(ap_adc_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(ap_adc_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_ap_adc(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint16_t adc1 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc1", "I"));
uint16_t adc2 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc2", "I"));
uint16_t adc3 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc3", "I"));
uint16_t adc4 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc4", "I"));
uint16_t adc5 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc5", "I"));
uint16_t adc6 = (uint16_t)env->GetIntField (obj, env->GetFieldID(ap_adc_class, "adc6", "I"));
mavlink_msg_ap_adc_pack(system_id, component_id, &msg,adc1, adc2, adc3, adc4, adc5, adc6);
}
jobject unpack_msg_digicam_configure(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_digicam_configure_t inp;
mavlink_msg_digicam_configure_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(digicam_configure_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(digicam_configure_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(digicam_configure_class, "extra_value", "F");
env->SetFloatField (result, fid, (float)inp.extra_value);
fid = env->GetFieldID(digicam_configure_class, "shutter_speed", "I");
env->SetIntField (result, fid, (int) inp.shutter_speed);
fid = env->GetFieldID(digicam_configure_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(digicam_configure_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(digicam_configure_class, "mode", "I");
env->SetIntField (result, fid, (int) inp.mode);
fid = env->GetFieldID(digicam_configure_class, "aperture", "I");
env->SetIntField (result, fid, (int) inp.aperture);
fid = env->GetFieldID(digicam_configure_class, "iso", "I");
env->SetIntField (result, fid, (int) inp.iso);
fid = env->GetFieldID(digicam_configure_class, "exposure_type", "I");
env->SetIntField (result, fid, (int) inp.exposure_type);
fid = env->GetFieldID(digicam_configure_class, "command_id", "I");
env->SetIntField (result, fid, (int) inp.command_id);
fid = env->GetFieldID(digicam_configure_class, "engine_cut_off", "I");
env->SetIntField (result, fid, (int) inp.engine_cut_off);
fid = env->GetFieldID(digicam_configure_class, "extra_param", "I");
env->SetIntField (result, fid, (int) inp.extra_param);
fid = env->GetFieldID(digicam_configure_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(digicam_configure_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_digicam_configure(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float extra_value = (float)env->GetFloatField (obj, env->GetFieldID(digicam_configure_class, "extra_value", "F"));
uint16_t shutter_speed = (uint16_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "shutter_speed", "I"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "target_component", "I"));
uint8_t mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "mode", "I"));
uint8_t aperture = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "aperture", "I"));
uint8_t iso = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "iso", "I"));
uint8_t exposure_type = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "exposure_type", "I"));
uint8_t command_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "command_id", "I"));
uint8_t engine_cut_off = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "engine_cut_off", "I"));
uint8_t extra_param = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_configure_class, "extra_param", "I"));
mavlink_msg_digicam_configure_pack(system_id, component_id, &msg,target_system, target_component, mode, shutter_speed, aperture, iso, exposure_type, command_id, engine_cut_off, extra_param, extra_value);
}
jobject unpack_msg_digicam_control(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_digicam_control_t inp;
mavlink_msg_digicam_control_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(digicam_control_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(digicam_control_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(digicam_control_class, "extra_value", "F");
env->SetFloatField (result, fid, (float)inp.extra_value);
fid = env->GetFieldID(digicam_control_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(digicam_control_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(digicam_control_class, "session", "I");
env->SetIntField (result, fid, (int) inp.session);
fid = env->GetFieldID(digicam_control_class, "zoom_pos", "I");
env->SetIntField (result, fid, (int) inp.zoom_pos);
fid = env->GetFieldID(digicam_control_class, "zoom_step", "I");
env->SetIntField (result, fid, (int) inp.zoom_step);
fid = env->GetFieldID(digicam_control_class, "focus_lock", "I");
env->SetIntField (result, fid, (int) inp.focus_lock);
fid = env->GetFieldID(digicam_control_class, "shot", "I");
env->SetIntField (result, fid, (int) inp.shot);
fid = env->GetFieldID(digicam_control_class, "command_id", "I");
env->SetIntField (result, fid, (int) inp.command_id);
fid = env->GetFieldID(digicam_control_class, "extra_param", "I");
env->SetIntField (result, fid, (int) inp.extra_param);
fid = env->GetFieldID(digicam_control_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(digicam_control_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_digicam_control(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
float extra_value = (float)env->GetFloatField (obj, env->GetFieldID(digicam_control_class, "extra_value", "F"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "target_component", "I"));
uint8_t session = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "session", "I"));
uint8_t zoom_pos = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "zoom_pos", "I"));
int8_t zoom_step = (int8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "zoom_step", "I"));
uint8_t focus_lock = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "focus_lock", "I"));
uint8_t shot = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "shot", "I"));
uint8_t command_id = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "command_id", "I"));
uint8_t extra_param = (uint8_t)env->GetIntField (obj, env->GetFieldID(digicam_control_class, "extra_param", "I"));
mavlink_msg_digicam_control_pack(system_id, component_id, &msg,target_system, target_component, session, zoom_pos, zoom_step, focus_lock, shot, command_id, extra_param, extra_value);
}
jobject unpack_msg_mount_configure(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mount_configure_t inp;
mavlink_msg_mount_configure_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mount_configure_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mount_configure_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mount_configure_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mount_configure_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mount_configure_class, "mount_mode", "I");
env->SetIntField (result, fid, (int) inp.mount_mode);
fid = env->GetFieldID(mount_configure_class, "stab_roll", "I");
env->SetIntField (result, fid, (int) inp.stab_roll);
fid = env->GetFieldID(mount_configure_class, "stab_pitch", "I");
env->SetIntField (result, fid, (int) inp.stab_pitch);
fid = env->GetFieldID(mount_configure_class, "stab_yaw", "I");
env->SetIntField (result, fid, (int) inp.stab_yaw);
fid = env->GetFieldID(mount_configure_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mount_configure_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mount_configure(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "target_component", "I"));
uint8_t mount_mode = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "mount_mode", "I"));
uint8_t stab_roll = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "stab_roll", "I"));
uint8_t stab_pitch = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "stab_pitch", "I"));
uint8_t stab_yaw = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_configure_class, "stab_yaw", "I"));
mavlink_msg_mount_configure_pack(system_id, component_id, &msg,target_system, target_component, mount_mode, stab_roll, stab_pitch, stab_yaw);
}
jobject unpack_msg_mount_control(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mount_control_t inp;
mavlink_msg_mount_control_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mount_control_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mount_control_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mount_control_class, "input_a", "J");
env->SetLongField (result, fid, (long) inp.input_a);
fid = env->GetFieldID(mount_control_class, "input_b", "J");
env->SetLongField (result, fid, (long) inp.input_b);
fid = env->GetFieldID(mount_control_class, "input_c", "J");
env->SetLongField (result, fid, (long) inp.input_c);
fid = env->GetFieldID(mount_control_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mount_control_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mount_control_class, "save_position", "I");
env->SetIntField (result, fid, (int) inp.save_position);
fid = env->GetFieldID(mount_control_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mount_control_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mount_control(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t input_a = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_control_class, "input_a", "J"));
int32_t input_b = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_control_class, "input_b", "J"));
int32_t input_c = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_control_class, "input_c", "J"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_control_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_control_class, "target_component", "I"));
uint8_t save_position = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_control_class, "save_position", "I"));
mavlink_msg_mount_control_pack(system_id, component_id, &msg,target_system, target_component, input_a, input_b, input_c, save_position);
}
jobject unpack_msg_mount_status(JNIEnv *env, mavlink_message_t& message){
jclass newMessage;
mavlink_mount_status_t inp;
mavlink_msg_mount_status_decode(&message, &inp);
// Create the object
jmethodID cid = env->GetMethodID(mount_status_class, "<init>", "()V");
if (cid == NULL) return NULL; /* exception thrown */
jobject result = env->NewObject(mount_status_class, cid);
//Set values
jfieldID fid;
fid = env->GetFieldID(mount_status_class, "pointing_a", "J");
env->SetLongField (result, fid, (long) inp.pointing_a);
fid = env->GetFieldID(mount_status_class, "pointing_b", "J");
env->SetLongField (result, fid, (long) inp.pointing_b);
fid = env->GetFieldID(mount_status_class, "pointing_c", "J");
env->SetLongField (result, fid, (long) inp.pointing_c);
fid = env->GetFieldID(mount_status_class, "target_system", "I");
env->SetIntField (result, fid, (int) inp.target_system);
fid = env->GetFieldID(mount_status_class, "target_component", "I");
env->SetIntField (result, fid, (int) inp.target_component);
fid = env->GetFieldID(mount_status_class, "sysID", "I");
env->SetIntField (result, fid, (int) message.sysid);
fid = env->GetFieldID(mount_status_class, "componentID", "I");
env->SetIntField (result, fid, (int) message.compid);
/* Free local references */
//env->DeleteLocalRef(heartbeatClass);
return result;
}
void pack_msg_mount_status(JNIEnv *env, jclass& classType, jobject& obj, mavlink_message_t& msg){
int32_t pointing_a = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_status_class, "pointing_a", "J"));
int32_t pointing_b = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_status_class, "pointing_b", "J"));
int32_t pointing_c = (int32_t)env->GetLongField (obj, env->GetFieldID(mount_status_class, "pointing_c", "J"));
uint8_t target_system = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_status_class, "target_system", "I"));
uint8_t target_component = (uint8_t)env->GetIntField (obj, env->GetFieldID(mount_status_class, "target_component", "I"));
mavlink_msg_mount_status_pack(system_id, component_id, &msg,target_system, target_component, pointing_a, pointing_b, pointing_c);
}
<file_sep>/app/src/main/java/com/atlas/aerospace/framework/Connection.java
package com.atlas.aerospace.framework;
import android.util.Log;
import com.MAVLink.Parser;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by killro on 15/02/16.
*/
public class Connection {
public OutputStream out;
public BufferedInputStream in;
private String ip;
private int port;
private Socket socket;
private boolean connected = false;
private Interfaces.OnDroneListener callback;
private Drone drone;
public Connection(String ip, int port, Drone drone, Interfaces.OnDroneListener callback) {
this.ip = ip;
this.port = port;
this.callback = callback;
this.drone = drone;
Log.d("copter", "let's connect");
new Thread(new ConnectionThread()).start();
}
public class ConnectionThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(ip);
socket = new Socket(serverAddr, port);
connected = true;
out = socket.getOutputStream();
in = new BufferedInputStream(socket.getInputStream());
callback.onDroneEvent(Interfaces.DroneEventsType.CONNECTED);
//comsThread.start();
//startup();
} catch (Exception e) {
connected = false;
}
}
}
}
| 008b6bf40d66bc4aed346d2bf325254d04e551da | [
"Java",
"C",
"C++"
] | 9 | C++ | AtlasAerospace/EridaCopter_Android | 53492ec7786047650ac62131b29eeb97d927aee3 | 2bb277a8d0818111c4009b7f72ed1eb77fde3514 |
refs/heads/master | <repo_name>Jialing-Huang/MEAN-Full-Stack-Project<file_sep>/src/app/Students/list-students.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Student } from '../Models/Student.model';
import { StudentServiceService } from '../Services/student-service.service';
import { HttpClient } from '@angular/common/http';
import {map} from 'rxjs/operators';
@Component({
selector: 'app-list-students',
templateUrl: './list-students.component.html',
styleUrls: ['./list-students.component.css']
})
export class ListStudentsComponent implements OnInit {
students:Student[] = [];
constructor(private _studentservice:StudentServiceService,
private http:HttpClient) { }
ngOnInit() {
//Get all students items from the mongoDB
this.http.get<{message:string, students:any}>("http://localhost:3000/students")
.pipe(map((transferData)=>{
return transferData.students
.map(
(student: { _id: any; FirstName: any; LastName: any; Gender: any; }) =>{
return {
mongoid:student._id,
FirstName:student.FirstName,
LastName:student.LastName,
Gender:student.Gender
}
}
)
;
})).subscribe((finalData) => {
this.students = finalData;
});
}
}
<file_sep>/backend/app.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const Student = require('./models/student');
mongoose
.connect(
"mongodb+srv://merlin:<EMAIL>/test?retryWrites=true&w=majority"
)
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//Set CORS
app.use((req,res,next)=>{
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-with, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET,POST,PATCH,DELETE,OPTIONS"
);
next();
});
//CRUD
//Read all
app.get('/students',(req,res,next)=>{
Student
.find()
.exec()
.then(docs=>{
console.log(docs);
console.log("get all students!");
res.status(200).json({
message:'Get stutent list db',
students:docs
});
})
.catch(err => {
res.status(500).json({
error:err
});
});
});
app.get('/count',(req,res,next)=>{
Student
.estimatedDocumentCount()
.exec()
.then(result=>{
console.log(result);
res.status(200).json({
message:'Get amount of documents in DB',
amount:result
});
})
.catch(err => {
res.status(500).json({
error:err
});
});
});
//Create
app.post('/create',(req,res,next)=>{
const student = new Student(
{
FirstName:req.body.FirstName,
LastName:req.body.LastName,
Gender:req.body.Gender
}
);
student
.save()
.then(result=>{
console.log(result);
// const amountOfDocument = result.estimatedDocumentCount();
res.status(200).json(
{
message:'Handling POST requests to /students/create',
storeId: result.mongoid,
// amount:result.estimatedDocumentCount()
}
);
})
.catch(err => {
res.status(500).json({
error:err
});
});
});
//Read item byid
app.get('/students/:mongoid',(req,res,next)=>{
const id = req.params.mongoid;
Student
.findById(id)
.exec()
.then(docs=>{
console.log(docs);
res.status(200).json({
message:"OK",
docs:docs
});
})
.catch(err => {
res.status(500).json({
error:err
});
});
});
//Another way of update, however, not verify it. Keep it as a reference
// app.patch('/students/:mongoid',(req,res,next)=>{
// const storeid = req.params.mongoid;
// const updateOps = {};
// for(const item of req.body){
// updateOps[item.propName] = item.value;
// };
// Student
// .update(
// {mongoid:storeid},
// {$set: updateOps}
// )
// .exec()
// .then((result) => {
// console.log(result);
// res.status(200).json(
// {
// message:'Update success!',
// result:result
// }
// );
// })
// .catch(err => {
// console.log(err);
// res.status(500).json({
// error:err
// })
// });
// });
app.patch('/update/:mongoid',(req,res,next)=>{
const storeid = req.params.mongoid;
Student
.findByIdAndUpdate(
storeid,
req.body,
{new: true}
)
.then((result) => {
console.log(result);
res.status(200).json(
{
message:'Update success!',
result:result
}
);
})
.catch(err => {
console.log(err);
res.status(500).json({
error:err
})
});
});
app.delete('/delete/:mongoid',(req,res,next)=>{
const storeid = req.params.mongoid;
Student
.findByIdAndRemove(storeid)
.then((result) => {
console.log(result);
res.status(200).json({message:'Delete success!'});
})
.catch(err => {
console.log(err);
res.status(500).json({
error:err
})
});
});
// app.delete('/delete/:mongoid',(req,res,next)=>{
// const storeid = req.params.mongoid;
// Student
// .remove({mongoid:storeid})
// .exec()
// .then((result) => {
// res.status(200).json(
// {
// message:'Delete success!'
// }
// );
// })
// .catch(err => {
// console.log(err);
// res.status(500).json({
// error:err
// })
// });
// });
module.exports = app; | 41f6fe03fa96d3261d8a084d3f64c8b6a3eac990 | [
"JavaScript",
"TypeScript"
] | 2 | TypeScript | Jialing-Huang/MEAN-Full-Stack-Project | 2a68cd69948008c487ec2633de6de5b7dc4c50b5 | 3dbb638d49562a5c4374e9b826101a5e86dc93c6 |
refs/heads/master | <repo_name>ramses429/cloudming<file_sep>/welcome.php
<html>
<body>
<select>
<option value="volvo" id="volvo">Volvo</option>
<option value="saab" id="saab">Saab</option>
<option value="vw" id="vw">VW</option>
<option value="audi" id="audi">Audi</option>
</select>
<script type="text/javascript">
var demo = "<?php echo $_POST["service"]; ?>";
document.getElementById(demo).setAttribute("selected","selected");
</script>
</body>
</html>
<file_sep>/README.md
# cloudming
the great code usefull
| b566297a3ca8a1b9390bc5e78436aad6b40dc955 | [
"Markdown",
"PHP"
] | 2 | PHP | ramses429/cloudming | fcc917f9d94d09ae48087d4fd83c0f3b63748d55 | c32b113c6031eec94bbb0740e42a25fe8083f2c9 |
refs/heads/master | <repo_name>maeda-naoya-fk/Constrained_ILC<file_sep>/show.py
import healpy as hp
import numpy as np
import matplotlib.pyplot as plt
def moview(alm, nside = 512, fwhm = 1.0):
map = hp.alm2map(alm, nside = nside, fwhm = fwhm*np.pi/180, verbose=False)
hp.mollview(map, cmap = 'jet', max = 0.2, min = -0.2)
plt.show()
def Dl(alm, lmax):
l = np.arange(lmax+1)
Cl = hp.alm2cl(alm, lmax = lmax)
Dl = Cl*l*(l+1)/(2*np.pi)*10**6
plt.plot(l, Dl, label = 'Dl')
plt.xscale('log')
plt.xlabel('Multipole l')
plt.ylabel('Dl[μK^2]')
plt.xlim([2, lmax])
plt.ylim([0, 6000])
plt.show()
<file_sep>/CILC_helpers.py
import healpy as hp
import numpy as np
from prepare import tSZ
class CILC:
def __init__(self, alms, lmax, nu):
self.alms = alms
self.lmax = lmax
self.nu = nu
self.len = len(self.nu)
#calculate Cl
def get_Cl(self):
Cl = np.zeros((self.lmax+1, self.len, self.len))
for i in range(self.len):
for j in range(self.len):
pre_Cl = hp.alm2cl(self.alms[i], self.alms[j], lmax = self.lmax)
for l in range(self.lmax+1):
Cl[l][i][j] = pre_Cl[l]
return Cl
#calculate inverse Cl
def get_inv_Cl(self):
Cl = self.get_Cl()
inv_Cl = []
for l in range(self.lmax+1):
inv = np.linalg.inv(Cl[l])
inv_Cl.append(inv)
return np.array(inv_Cl)
#calculate weight
def get_weight(self):
inv_Cl = self.get_inv_Cl()
a = np.ones((self.len, 1))
b = tSZ(self.nu).reshape(self.len, 1)
ainvCl = np.dot(a.T, inv_Cl)
binvCl = np.dot(b.T, inv_Cl)
ainvCla = np.dot(ainvCl, a)
binvClb = np.dot(binvCl, b)
ainvClb = np.dot(ainvCl, b)
weight = (binvClb*ainvCl - ainvClb*binvCl) / (ainvCla*binvClb - ainvClb**2)
return weight.reshape(self.lmax+1, self.len)
#CILCをする
def do_CILC(self):
weight = self.get_weight()
alm_clean = np.zeros(len(self.alms[0]), dtype = complex)
for l in range(self.lmax+1):
for m in range(l+1):
j = hp.sphtfunc.Alm.getidx(self.lmax, l, m)
for i in range(self.len):
alm_clean[j] += weight[l][i] * self.alms[i][j]
return alm_clean
<file_sep>/README.md
# Constrained_ILC
***Nonparametric component separation for Cosmic Microwave Background observations in harmonic space***
## Description
CILC(Constrained Internal Linear Combination) is the foreground removal method.
You can subtract foreground and noise from observation imaps using this method **in consideration of thermal SZ**, and get clean CMB map.
You should note that this method is perforemed in **harmonic space**.
For detail, see paper <a href="https://academic.oup.com/mnras/article/410/4/2481/1007333">'CMB and SZ effect separation with constrained Internal Linear Combinations'(<NAME>, <NAME> et al., MNRAS, 410, 2481)
## Usage
```CILC(alms, lmax, nu).get_Cl()```:return covariance matrix
```CILC(alms, lmax, nu).get_weight()```:return weight
```CILC(alms, lmax, nu).do_ILC()```: return clean_alm of CMB
If you want hint for this modules, you can use Examples.ipynb
## Requirement
- numpy(=1.18.1)
- healpy(=1.12.10)
- matplotlib(=3.2.1)
## Contributors
- <NAME> (MPA, KavliIPMU)
<file_sep>/prepare.py
import healpy as hp
import numpy as np
import os
import warnings
warnings.simplefilter('ignore')
#read imap.fits
def read_imap(lmax):
path = os.path.dirname(__file__) + '/wmap_band_smth_imap_r9_nineyear_v5'
os.chdir(path)
imaps = []
for b in ['K', 'Ka', 'Q', 'V', 'W']:
imap_fit = 'wmap_band_smth_imap_r9_9yr_' + b + '_v5.fits'
imap = hp.read_map(imap_fit, verbose = False)
imaps.append(imap)
return np.array(imaps)
#change imap to alm
def map_to_alm(imaps, lmax):
alms = []
for imap in imaps:
alm = hp.map2alm(imap, lmax = lmax, iter = 10)
alms.append(alm)
return np.array(alms)
#Calcuate thermal SZ frequency dependence (reference:eq.(9))
def tSZ(nu):
h = 6.62607015e-34
kB = 1.380649e-23
TCMB = 2.725
x = h*np.array(nu)*10e9 / (kB*TCMB)
b = x*(np.exp(x)+1)/(np.exp(x)-1) - 4
return b
| 6e21c4341b3519eeb4ddbe81a39060cad0573061 | [
"Markdown",
"Python"
] | 4 | Python | maeda-naoya-fk/Constrained_ILC | f41ddc2aa031ef1a3681da915b9905df388c5057 | 46099680ea9e6fb73e4d1b0d3d1333b41be5f1f2 |
refs/heads/master | <repo_name>palmtoy/node-native-boilerplate<file_sep>/app.js
var NativeExtension = require('./');
console.log(NativeExtension.aString());
console.log(NativeExtension.aBoolean());
console.log(NativeExtension.nothing());
console.log();
console.log(NativeExtension.aNumber());
console.log(NativeExtension.anObject());
console.log(NativeExtension.anArray());
console.log();
console.log(NativeExtension.callback);
NativeExtension.callback(function() {
console.log('Hello World');
});
| 35b03921bb9053268cae3a32bf489e72ae4da767 | [
"JavaScript"
] | 1 | JavaScript | palmtoy/node-native-boilerplate | 5a5a731569a1f01370d80c0441451a740d1a3a04 | 3ecd00dbfe4731024dfeef8743837a1348c3c49d |
refs/heads/master | <repo_name>Parnni/First_Genetic_Algorithm_code<file_sep>/Guess_word_using_GA.py
'''Class for guessing words.'''
# Importing modules.
import random
import string
import matplotlib.pyplot as plt
class guess():
'''This class guesses given string.'''
def __init__(self, target_string, iterations):
'''Initializing the paramters.
Parameters
----------
target_string: The string that needs to be guessed.
iterations: Number of iterations for calculating the
guessed value.
'''
self.iterations = iterations
self.target_string = target_string
# Complete string set.
# Not using digits and other punctuations as it increases the
# running time.
self.string_data = string.ascii_lowercase + string.ascii_uppercase \
+ ' ' + ',' + '!' + '.'
# Creating a function for generating parents.
def gen_parent(self):
'''Generates a parent string.
'''
# Length of target string.
l = len(self.target_string)
if l > len(self.string_data):
raise Exception('Provided input string is larger than population.')
# Creating random parent.
parent = random.sample(self.string_data, l)
return ''.join(parent)
# Creating function to calculate fitness.
def fitness(self, parent):
'''Calculates fitness of the string.
Parameters
----------
parent: Randomly generated string.
Returns
-------
Returns fitness value of the randomly generated string
by comparing it with target data.
'''
return sum(1 for i in range(len(self.target_string)) \
if self.target_string[i] == parent[i])
# Creating function for mutation.
def mutate(self, parent):
'''Mutates a value of the string.
Parameters
----------
parent: Randomly generated string.
Returns
-------
Returns mutated string after performing one-point
crossover mutation.
'''
# Selecting a random index for mutation.
index = random.randrange(0, len(parent))
child_list = list(parent)
# If the mutation value is same as index value then
# assign it with alternate value.
mutate_value, alternate_value = random.sample(self.string_data, 2)
if child_list[index] != mutate_value:
child_list[index] = mutate_value
else:
child_list[index] = alternate_value
return ''.join(child_list)
# Creating function for best gene.
def best_gene(self):
'''Loop for finding best solution.
Returns
-------
Finds and returns the best solution.
'''
# Parent data.
parent = self.gen_parent()
parent_fitness = self.fitness(parent)
# For breaking the loop after reaching a specified
# number of iteration.
i = 0
# Storage for fitness values.
fitness_list = []
# Loop for finding best genes.
while True:
i += 1
# Breaking the loop after reaching specified number of iteration.
if i >= self.iterations:
sol_iteration, best_sol, fit_val = i, child, child_fitness
print(f'Iteration no. {sol_iteration}')
print(f'Best solution is "{best_sol}" with fitness value {fit_val}.')
return fitness_list, best_sol
break
child = self.mutate(parent)
child_fitness = self.fitness(child)
fitness_list.append(child_fitness)
# Selecting the improved genes.
if parent_fitness >= child_fitness:
continue
if child_fitness >= parent_fitness:
parent = child
parent_fitness = child_fitness
# Breaking the loop after successful run.
if child_fitness >= len(self.target_string):
sol_iteration, best_sol, fit_val = i, child, child_fitness
print(f'Iteration no. {sol_iteration}')
print(f'Target string is: "{self.target_string}"')
print(f'Best solution is: "{best_sol}"')
return fitness_list, best_sol
break
# Running the model.
if __name__ == '__main__':
# Target string.
target_string = 'Hello, I am Parmeshwar a Data Scientist.'
# Iterations number.
iterations = 100000
guess_class = guess(target_string = target_string,
iterations = iterations)
# Finding the solution.
fitness_list, best_solution = guess_class.best_gene()
# Plotting the values.
plt.plot(range(len(fitness_list)), fitness_list)
plt.title('Fitness value over iterations.')
plt.xlabel('Iterations')
plt.ylabel('Fitness value')
plt.show()
<file_sep>/Readme.md
## Genetic Algorithm.
Guessing numbers with our typical python code is no longer fun.<br>
How about we use *genetic algorithm* to guess?
and why numbers? let's use strings instead.
In this project, I am developing a genetic algorithm to guess a given string.
## Results.
<img src = "https://github.com/Parnni/First_Genetic_Algorithm_code/blob/master/Result.PNG">
<img src = "https://github.com/Parnni/First_Genetic_Algorithm_code/blob/master/Graph.png">
## Technologies used.
[](https://www.python.org/)
## Further improvements.
- Include numbers and more punctuations.
- Deploying **it on Flask.**
<file_sep>/unit_testing.py
# Importing modules.
import unittest
from Guess_word_using_GA import guess
# Creating a test class.
class guess_class_test(unittest.TestCase):
'''Testing the Guess_word_using_GA class.'''
def setUp(self):
# Arranging the values.
print('Arranging the values.')
self.string_test = 'Hello there.'
def tearDown(self):
# Removing the values.
print('Tearing down the values.')
self.string_test = ''
def test1(self):
'''Checks whether the strings are same or not.'''
print('Running test1.')
# Number of iterations.
iterations = 100000
# Action.
guess_class = guess(target_string = self.string_test,
iterations = iterations)
_, best_solution = guess_class.best_gene()
# Assert.
self.assertEqual(self.string_test, best_solution)
# Running the script.
if __name__ == '__main__':
unittest.main() | c402305c583c65f62961932bc962dd08e9dd3770 | [
"Markdown",
"Python"
] | 3 | Python | Parnni/First_Genetic_Algorithm_code | 5dbda8c76cafb91a7391133dd20b796ed78f3ee8 | 680b12f5e317cb81ec187b8a04fb979fc43761a0 |
refs/heads/master | <repo_name>mmina001/cs425_fall18_hw03<file_sep>/scores.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="Questions Game">
<meta name="author" content="<NAME>">
<meta name="description" content="Implementation of a questions game using PHP">
<meta name="keywords" content="questions,choices,multiple choice">
<title>Questions Game</title>
<link rel="icon" href="favicon.png" type="image/png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="index-style.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<header>
<nav class="navbar fixed-top navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="index.php">Home Page</a>
</li>
<li class="nav-item">
<a class="nav-link" href="help.php">Help Page</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="scores.php">High Scores Page</a>
</li>
</ul>
</nav>
</header>
<a href="#top" id="myBtn" title="Go to top">Top</a>
<?php
if (!file_exists('players_scores.txt')){ ?>
<h1 class="display-4">No scores to display</h1>
<?php }else {
$array = file('players_scores.txt');
$size=sizeof($array);
$scores=array();
$nicknames=array();
for($i=0;$i<$size;$i++){
$tmp_array = explode("\t", $array[$i]);
array_push($nicknames,$tmp_array[0]);
array_push($scores,$tmp_array[1]);
}
$max = $scores[0];
$max_nickname = $nicknames[0];
for($i=1;$i<$size;$i++){
if($max<$scores[$i]){
$tmp_score=$scores[$i];
$scores[$i]=$max;
$max=$tmp_score;
$tmp_name=$nicknames[$i];
$nicknames[$i]=$max_nickname;
$max_nickname=$tmp_name;
}
}
if($size>10){
$size=10;
} ?>
<h1 class="display-4"><?php echo "Top $size players" ?></h1>
<div class="table-responsive">
<table id="scores_t" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nickname</th>
<th scope="col">Score</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$size;$i++){ ?>
<tr>
<th scope="row"><?php $tmp=$i+1; echo $tmp; ?></th>
<td><?php echo $nicknames[$i]; ?></td>
<td><?php echo $scores[$i]; ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
<br>
<?php } ?>
<footer>
</footer>
</body>
</html>
<file_sep>/help.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="Questions Game">
<meta name="author" content="<NAME>">
<meta name="description" content="Implementation of a questions game using PHP">
<meta name="keywords" content="questions,choices,multiple choice">
<title>Questions Game</title>
<link rel="icon" href="favicon.png" type="image/png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="index-style.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<header>
<nav class="navbar fixed-top navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="index.php">Home Page</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="help.php">Help Page</a>
</li>
<li class="nav-item">
<a class="nav-link" href="scores.php">High Scores Page</a>
</li>
</ul>
</nav>
</header>
<a href="#top" id="myBtn" title="Go to top">Top</a>
<h1 class="display-4">Instruction for the game</h1>
<h4>This is a questions game related to Internet technologies knowledge. To start the game press the button start.
By clicking the start button the first question will appear with multiple choice answers. You can select only
one answer, by clicking on the answer that you think is the correct one. After you choose an answer you must
click the Next button. The next button moves you to the next question. You choose again the answer that you believe
is the correct one and you press again the next button. You repeat this until you reach the last question. As you will
see the button of the final question is renamed to Finish. By clicking this button, after you choose an answer of
course, you will see for each question if you answered correctly or not, the level of difficulty of the question,
the score that you have get and your overall score. Also, you can save your overall score by entering a nickname
in the text box and by clicking the button Save Score. If you do not want to save your score you can press the
button Return to start in order to return at start page.
</h4>
<footer>
</footer>
</body>
</html>
<file_sep>/index.php
<?php
session_start();
if(!isset($_SESSION['flag'])){
$_SESSION['flag']=0;
}
$result="";
$refresh=0;
$_SESSION['max_questions']=6;
if(!isset($_SESSION['xml_array'])){
$source = 'questions.xml';
// load as string
$xmlstr = file_get_contents($source);
$xml=simplexml_load_string($xmlstr) or die("Error: Cannot create object");
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$_SESSION['xml_array']=$array;
}
if(!isset($_SESSION['array_answers'])){
$_SESSION['array_answers'] = array();
}
if(!isset($_SESSION['array_difficulty'])){
$_SESSION['array_difficulty'] = array();
}
if(!isset($_SESSION['difficulty'])){
$_SESSION['difficulty']=1;
}
if(!isset($_SESSION['num_question'])){
$_SESSION['num_question']=1;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="Questions Game">
<meta name="author" content="<NAME>">
<meta name="description" content="Implementation of a questions game using PHP">
<meta name="keywords" content="questions,choices,multiple choice">
<title>Questions Game</title>
<link rel="icon" href="favicon.png" type="image/png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="index-style.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['Start'])){
$_SESSION['flag']=1;
}
if (isset($_POST['Next']) || isset($_POST['Finish'])) {
$_SESSION['num_question'] += 1 ;
}
if(isset($_POST['choice_btn'])){
array_push($_SESSION['array_difficulty'],$_SESSION['difficulty']);
$choice = $_POST['choice_btn'];
echo $_SESSION['random'];
$correct = $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['correct'];
if(strcmp($choice,$correct) == 0){
array_push($_SESSION['array_answers'],1);
if($_SESSION['difficulty']==1 || $_SESSION['difficulty']==0){
$_SESSION['difficulty'] += 1;
}
}else{
array_push($_SESSION['array_answers'],0);
if($_SESSION['difficulty']==1 || $_SESSION['difficulty']==2){
$_SESSION['difficulty'] -= 1;
}
}
array_splice($_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'], $_SESSION['random'], 1);
}
if (isset($_POST['Finish'])) {
$_SESSION['overall_score'] = 0;
for($i=0;$i<$_SESSION['max_questions'];$i++){
if($_SESSION['array_answers'][$i]==1){
if($_SESSION['array_difficulty'][$i]==0){
$_SESSION['overall_score']+=10;
}else if($_SESSION['array_difficulty'][$i]==1){
$_SESSION['overall_score']+=20;
}else if($_SESSION['array_difficulty'][$i]==2){
$_SESSION['overall_score']+=40;
}
}
}
}
if (isset($_POST['saveScore'])) {
$txt = $_POST['nickname']."\t".$_SESSION['overall_score']."\n";
if(file_put_contents("players_scores.txt", $txt,FILE_APPEND) === strlen($txt)){
$result='<div class="alert alert-success">Success!!!</div>';
}else{
$result='<div class="alert alert-danger">Failure...</div>';
}
$refresh=1;
}
if (isset($_POST['returnStart']) || isset($_POST['end']) ) {
session_unset();
session_destroy();
$_SESSION['flag']=0;
}
}
?>
<header>
<nav class="navbar fixed-top navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="index.php">Home Page</a>
</li>
<li class="nav-item">
<a class="nav-link" href="help.php">Help Page</a>
</li>
<li class="nav-item">
<a class="nav-link" href="scores.php">High Scores Page</a>
</li>
</ul>
</nav>
</header>
<a href="#top" id="myBtn" title="Go to top">Top</a>
<form action="" method="post">
<?php if($_SESSION['flag']==0) { ?>
<h1 class="display-4">Welcome to our Questions Game!Are you ready to test your knowledge?</h1>
<div class="container">
<div class="row">
<div class="col-12 text-center">
<input id="start" class="btn btn-primary btn-lg" type="submit" value="Start" name="Start" />
</div>
</div>
</div>
<?php }else if($_SESSION['flag']==1) {
if($_SESSION['num_question']<=$_SESSION['max_questions']){
$max=sizeof($_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question']);
$max-=2;
$_SESSION['random']=mt_rand(0,$max); ?>
<h1 class="display-4"><?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['question'];?><h1>
<label><input type="radio" name="choice_btn" value="<?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][0];?>"/><?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][0];?></label>
<br>
<label><input type="radio" name="choice_btn" value="<?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][1];?>"/><?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][1];?></label>
<br>
<label><input type="radio" name="choice_btn" value="<?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][2];?>"/><?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][2];?></label>
<br>
<label><input type="radio" name="choice_btn" value="<?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][3];?>"/><?php echo $_SESSION['xml_array']['questions_difficulty'][$_SESSION['difficulty']]['multiple_choice_question'][$_SESSION['random']]['choice'][3];?></label>
<br><br>
<div>
<label><?php echo $_SESSION['num_question'] ?></label>
<label>/</label>
<label><?php echo $_SESSION['max_questions'] ?></label>
</div>
<?php $sub=$_SESSION['max_questions']-$_SESSION['num_question']; ?>
<label><?php echo "Remaining Questions: $sub"; ?></label>
<br><br>
<?php if($_SESSION['num_question']<$_SESSION['max_questions']){ ?>
<input class="btn btn-success btn-lg" type="submit" value="Next" name="Next" id="next" />
<input class="btn btn-danger btn-lg" type="submit" value="End" name="end" id="end" />
<?php }else if($_SESSION['num_question']==$_SESSION['max_questions']){ ?>
<input class="btn btn-success btn-lg" type="submit" value="Finish" name="Finish" id="finish" />
<input class="btn btn-danger btn-lg" type="submit" value="End" name="end" id="end" />
<?php }
}else { ?>
<h1 class="display-4">Score</h1>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Answer</th>
<th scope="col">Level of Difficulty</th>
<th scope="col">Score</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$_SESSION['max_questions'];$i++){ ?>
<tr>
<th scope="row"><?php $tmp=$i+1; echo $tmp; ?></th>
<td><?php if($_SESSION['array_answers'][$i]==1) { echo "Correct"; }else { echo "Wrong"; } ?></td>
<td><?php if($_SESSION['array_difficulty'][$i]==0) { echo "1"; }else if($_SESSION['array_difficulty'][$i]==1) { echo "2";}else{echo "3"; } ?></td>
<td><?php if($_SESSION['array_answers'][$i]==1){if($_SESSION['array_difficulty'][$i]==0) { echo "10"; }else if($_SESSION['array_difficulty'][$i]==1) { echo "20";}else{echo "40"; }}else{echo "0";} ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
<h2 style="text-align:center">Overall Score: <?php echo $_SESSION['overall_score'] ?></h2>
<div class="form-group">
<input type="text" class="form-control form-control-lg" placeholder="Enter a nickname" name="nickname">
</div>
<div class="col-12 text-center">
<input class="btn btn-danger btn-lg" type="submit" value="Save Score" name="saveScore" id="save" />
<input class="btn btn-primary btn-lg" type="submit" value="Return to start" name="returnStart" id="return" />
<div id="msg" class="form-group">
<div class="col-12 text-center">
<?php
echo $result;
if($refresh==1){
session_unset();
session_destroy();
$_SESSION['flag']=0;
echo "<meta http-equiv='refresh' content='3'>";
}
?>
</div>
</div>
</div>
<?php }
} ?>
</div>
</form>
<footer>
</footer>
</body>
</html>
| 966c108a8d0b418c992a344cab37fe835820bb7f | [
"PHP"
] | 3 | PHP | mmina001/cs425_fall18_hw03 | a654859a766dd00ec68111ccbf6911efab2f4dd7 | 7402e01ee6accdb26043fb491b25c04a7c20ca7d |
refs/heads/master | <file_sep>import collections
import os
import json
from pprint import pprint
from collections import Counter
def read_json(file_path, max_len_word=6, top_words=3):
with open(file_path, encoding='utf-8') as new_file:
news = json.load(new_file)
description_words = []
for item in news['rss']['channel']['items']:
description = [word for word in item['description'].split(' ') if len(word) > max_len_word]
description_words.extend(description)
counter_words = collections.Counter(description_words)
pprint(counter_words.most_common(top_words))
if __name__ == '__main__':
read_json('newsafr.json')
# read_json(file)
| 5388d189c5e73ba48c6f9facc0003f27ce35eb68 | [
"Python"
] | 1 | Python | nvetrov/hero | c388333f2c2faa4fa5d1e53638725226a86775f5 | 6a28792457d00e576be65e8802c26c2971f3da72 |
refs/heads/master | <file_sep>"""
Post
Represents a post made by a user
"""
import re
import random
class Post():
def __init__(self, idnum: int = -1, author: str = "No Author", contents: str = "CAW CAW CAW", points: int = -1):
self.idnum = idnum
self.author = author
self.contents = contents
self.points = points
self.img = 'crob'
# defines valid regex for a message
# valid_regex = re.compile('((k|c)r?a+w+\s?)+', flags=re.RegexFlag.I)
def translate_message(input: str) -> str:
"""
Translate a sentence into CRAW speak
>>> translate_message("Y'all ever just YEET?")
'CAAWW CAAW CAAW CAAWW'
"""
# TODO need to handle symbols and stuff
return ' '.join([translate_word(x) for x in input.split()])
def translate_word(input: str) -> str:
"""
Translate a word into CAW speak
>>> translate_word("tests")
'CAAWW'
>>> translate_word("test")
'CAAW'
>>> translate_word("")
''
>>> translate_word("a")
'CA'
>>> translate_word("ab")
'CAW'
>>> translate_word("abc")
'CAW'
"""
random.seed("CAAAAAWWWWW")
if len(input) == 0:
return ''
if len(input) == 1:
return 'CA'
if len(input) == 2 or len(input) == 3:
return 'CAW'
# subtract the starting C and the ending W
x = len(input) - 2
# must have at least one A
num_a = random.randint(1, x)
return 'C' + ('A'*num_a) + ('W'*(x - (num_a - 1)))
<file_sep># CROBBER
Made for UWB Hacks 2019. The social media site for CROBS. Caw with fellow crobs at [crobber.rodeo](https://crobber.rodeo/).
<file_sep>### Deployment Instructions for Flask, Gunicorn, and Nginx
Most of the deployment was done by following [these instructions](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04).
Ensure you have `gunicorn` and `flask` installed. Both can be installed via `pip`.
The `nginx` and `systemd` files are located in this folder.
##### TL;DR Steps
Perform basic DNS and domain setup. Then, in your server box, run the following commands
```console
$ cd /var/www
$ git clone https://www.github.com/Chris-Johnston/CROBBER
$ cd CROBBER/deployment
$ sudo cp crobber.service /etc/systemd/system
$ sudo systemctl start crobber
$ sudo systemctl enable crobber
$ sudo cp crobber.rodeo /etc/nginx/sites-available
$ cd /etc/nginx/sites-enabled
$ sudo ln -s ../sites-available/crobber.rodeo .
$ sudo systemctl restart nginx
```
If you want HTTPS enforcing, run `certbot` for the domain and restart `nginx` again.
<file_sep>import unittest
import doctest
import post
import sys
test_modules = [
post
]
def load(tests):
for m in test_modules:
tests.addTests(doctest.DocTestSuite(m))
return tests
if __name__ == "__main__":
"""
Runs the tests
"""
tests = unittest.TestSuite()
test = load(tests)
run = unittest.TextTestRunner()
ret = not run.run(tests).wasSuccessful()
sys.exit(ret)<file_sep>from flask import Flask, send_from_directory, session, url_for, request, flash, redirect, render_template, g
import os
import sqlite3
from post import Post, translate_message
import hashlib
import time
app = Flask(__name__)
images = ['angry-crob', 'crob-viking', 'crob', 'goatee-crob', 'interest-crob', 'thunder-crob', 'void-crob']
# totally secret
# security for this app is a joke
# because this app is a joke
app.secret_key = 'CRAWWWW'
DATABASE = 'craw.db'
# http://flask.pocoo.org/docs/1.0/patterns/sqlite3/
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
# init the database if not exists
init_db(db)
return db
def init_db(db):
"""
Creates db tables if not already set up
"""
cur = db.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT)
''')
cur.execute('''
CREATE TABLE IF NOT EXISTS posts
(id INTEGER PRIMARY KEY AUTOINCREMENT,
author TEXT,
content TEXT,
posted INTEGER,
fries INTEGER)
''')
# crows love fries, fries are the points
def get_posts():
with app.app_context():
print('getting posts')
cur = get_db().cursor()
cur.execute("SELECT * FROM posts ORDER BY posted DESC LIMIT 50")
posts = []
for row in cur.fetchall():
print(row)
p = Post(row[0], row[1], row[2], row[4])
username = row[1]
user_hash = int(hashlib.sha1(username.encode('utf-8')).hexdigest(), 16) % (10 ** 8)
image = images[user_hash % len(images)]
p.img = image
posts.append(p)
return posts
return None
@app.teardown_appcontext
def close_db_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
# app.register_blueprint(newcaw)
@app.route('/', methods=['GET', 'POST'])
@app.route('/index.html')
def landing():
posts = get_posts()
print(len(posts))
if 'user_id' in session and session['user_id']:
# logged in
return render_template('homepage.html', user_id = session['user_id'],
posts=posts,
username=session['username'])
# not logged in
return send_from_directory('static', filename='landing.html')
@app.route('/crawwwwww')
@app.route('/logout')
def logout():
if 'user_id' in session:
session['user_id'] = None
return redirect('/')
def post_messge(author: str, message: str):
"""
submits a post
"""
with app.app_context():
db = get_db()
cur = db.cursor()
message = translate_message(message)
cur.execute('''INSERT INTO posts (content, posted, fries, author) VALUES (?, ?, ?, ?);''', (message, time.time(), 1, author))
print(f'inserting message {message} from user {author}')
db.commit()
@app.route('/caw', methods=['POST'])
def caw():
"""
new post, from form parameters
message is from le_caw
"""
if 'user_id' in session and session['user_id']:
# logged in
if 'le_caw' in request.form and request.form['le_caw']:
user_id = session['user_id']
username = session['username']
message = request.form['le_caw']
post_messge(username, message)
# not logged in, yell at them to log in
return redirect('/')
@app.route('/give_fry', methods=['POST'])
def fries_for_crobs():
if 'user_id' in session and session['user_id']:
# logged in
if 'postiboi' in request.form and request.form['postiboi']:
post_id = request.form.get('postiboi')
fries = request.form.get('frybois')
print(type(post_id))
print("current fry count is " + str(fries))
print(type(fries))
with app.app_context():
db = get_db()
cur = db.cursor()
cur.execute('''UPDATE posts SET fries = ? WHERE id = ?''', (int(fries) + 1, post_id))
db.commit()
return redirect('/')
def get_user_id(username: str, password: str) -> int:
"""
gets the user id for the user, registers them if not
if wrong, returns None
"""
with app.app_context():
db = get_db()
cur = db.cursor()
hash_pw = hashlib.sha256(password.encode('utf-8'))
hash_str = hash_pw.hexdigest()
# print(hash_str)
cur.execute('SELECT id FROM users WHERE username = ? AND password = ?', (username, hash_str,))
result = cur.fetchone()
# print(result)
if result is None:
print(f'inserting user {username}')
cur.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, hash_str,))
db.commit()
return cur.lastrowid
else:
return result[0]
return None
@app.route('/craww', methods=['POST'])
@app.route('/login', methods=['POST'])
def login():
"""
Login route, accept a user and password,
if successful, stores a logged in user id in the session
"""
session['user_id'] = None
if 'username' in request.form and 'password' in request.form:
username = request.form['username']
password = request.form['<PASSWORD>']
# print('user', username, 'password', password)
id = get_user_id(username, password)
print('got id', id)
if id:
session['user_id'] = id
session['username'] = username
return redirect('/')
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0')
| 76b7ae8df988defe9802f4123a7fc40842e2f9d2 | [
"Markdown",
"Python"
] | 5 | Python | Chris-Johnston/CROBBER | 30aca339fa2294d4e7e9001cff2c049189dda39e | 44da2eb0437587c9b985e6858d52a64dcea12874 |
refs/heads/master | <repo_name>HwangToeMat/MASRN_Pytorch_HTM<file_sep>/data_augment.py
import argparse, os
import glob
import h5py
import cv2
from PIL import Image
import numpy as np
# AUGMENT SETTINGS
parser = argparse.ArgumentParser(description="PyTorch MASRN")
parser.add_argument("--HRpath", type=str, default='data/DIV2K_train_HR')
parser.add_argument("--Savepath", type=str, default='data/train_x234.h5')
parser.add_argument("--LRsize", type=int, default=48)
parser.add_argument("--Cropnum", type=int, default=10)
def data_aug():
global opt
opt = parser.parse_args()
print(opt)
sub_ip_2 = []
sub_la_2 = []
sub_ip_3 = []
sub_la_3 = []
sub_ip_4 = []
sub_la_4 = []
num = 1
HRpath = load_img(opt.HRpath)
for _ in HRpath:
HR_img = read_img(_)
sub_image = random_crop(HR_img, opt.Cropnum, opt.LRsize * 2, 2)
input, label = img_downsize(sub_image, 2)
sub_ip_2 += input
sub_la_2 += label
sub_image = random_crop(HR_img, opt.Cropnum, opt.LRsize * 3, 3)
input, label = img_downsize(sub_image, 3)
sub_ip_3 += input
sub_la_3 += label
sub_image = random_crop(HR_img, opt.Cropnum, opt.LRsize * 4, 4)
input, label = img_downsize(sub_image, 4)
sub_ip_4 += input
sub_la_4 += label
print('data no.',num)
num += 1
sub_ip_2 = np.asarray(sub_ip_2)
sub_ip_3 = np.asarray(sub_ip_3)
sub_ip_4 = np.asarray(sub_ip_4)
sub_la_2 = np.asarray(sub_la_2)
sub_la_3 = np.asarray(sub_la_3)
sub_la_4 = np.asarray(sub_la_4)
print('input shape : x2[',sub_ip_2.shape,'], x3[',sub_ip_3.shape,'], x4[',sub_ip_4.shape,']')
print('label shape : x2[',sub_la_2.shape,'], x3[',sub_la_3.shape,'], x4[',sub_la_4.shape,']')
save_h5(sub_ip_2, sub_ip_3, sub_ip_4, sub_la_2, sub_la_3, sub_la_4, opt.Savepath)
print('---------save---------')
def load_img(file_path):
dir_path = os.path.join(os.getcwd(), file_path)
img_path = glob.glob(os.path.join(dir_path, '*.png'))
return img_path
def read_img(img_path):
# read image
image = cv2.imread(img_path)
return image
def mod_crop(image, scale):
h = image.shape[0]
w = image.shape[1]
h = h - np.mod(h,scale)
w = w - np.mod(w,scale)
return image[0:h,0:w,:]
def random_crop(image, Cropnum, Cropsize, scale):
sub_img = []
i = 0
while i < Cropnum:
h = np.random.randint(0, image.shape[0] - Cropsize)
w = np.random.randint(0, image.shape[1] - Cropsize)
sub_i = image[h:h+Cropsize,w:w+Cropsize]
sub_i = mod_crop(sub_i, scale)
sub_img.append(sub_i)
i += 1
return sub_img
def img_downsize(img, scale):
dst_list = []
img_list = []
for _ in img:
h = _.shape[0]
w = _.shape[1]
img_list.append(_.reshape(3, h, w))
dst = cv2.resize(_, dsize=(0, 0), fx=1/scale, fy=1/scale, interpolation=cv2.INTER_CUBIC)
dst_list.append(dst.reshape(3, int(h/scale), int(w/scale)))
return dst_list, img_list
def save_h5(sub_ip_2, sub_ip_3, sub_ip_4, sub_la_2, sub_la_3, sub_la_4, savepath):
path = os.path.join(os.getcwd(), savepath)
with h5py.File(path, 'w') as hf:
hf.create_dataset('input_x2', data=sub_ip_2)
hf.create_dataset('input_x3', data=sub_ip_3)
hf.create_dataset('input_x4', data=sub_ip_4)
hf.create_dataset('label_x2', data=sub_la_2)
hf.create_dataset('label_x3', data=sub_la_3)
hf.create_dataset('label_x4', data=sub_la_4)
if __name__ == '__main__':
print('starting data augmentation...')
data_aug()
<file_sep>/get_model_parm.py
import torch
def get_n_params(model):
pp=0
for p in list(model.parameters()):
nn=1
for s in list(p.size()):
nn = nn*s
pp += nn
return pp
if __name__ == '__main__':
num = data_aug()
print('Number of parameters is : ', num)
<file_sep>/LossFunction.py
import torch
from torch import nn
import torch.backends.cudnn as cudnn
import numpy as np
def PSNR(HR, fake_img):
mse = nn.MSELoss()
loss = mse(HR, fake_img)
psnr = 10 * np.log10(1 / (loss.item() + 1e-10))
return psnr
<file_sep>/MASRN.py
import torch
import torch.nn as nn
import torch.functional as F
import common
class FERB(nn.Module):
def __init__(self, in_channels, k_size):
super(FERB, self).__init__()
self.block_0 = nn.Sequential(
nn.Conv2d(in_channels, 64, (1, k_size), stride=1, padding=(0,(k_size//2))),
nn.Conv2d(64, 64, (k_size, 1), stride=1, padding=((k_size//2),0)),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, (1, k_size), stride=1, padding=(0,(k_size//2))),
nn.Conv2d(64, 64, (k_size, 1), stride=1, padding=((k_size//2),0)),
nn.ReLU(inplace=True)
)
self.block_1 = nn.Sequential(
nn.Conv2d(in_channels, 64, (1, k_size), stride=1, padding=(0,(k_size//2))),
nn.Conv2d(64, 64, (k_size, 1), stride=1, padding=((k_size//2),0)),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, (1, k_size), stride=1, padding=(0,(k_size//2))),
nn.Conv2d(64, 64, (k_size, 1), stride=1, padding=((k_size//2),0)),
nn.ReLU(inplace=True)
)
def forward(self, x):
residual_0 = self.block_0(x)
residual_0 += x
residual_1 = self.block_1(residual_0)
residual_1 += residual_0
residual_1 += x
return residual_1
class Extraction_net(nn.Module):
def __init__(self):
super(Extraction_net, self).__init__()
# RGB mean for DIV2K
rgb_mean = (0.4488, 0.4371, 0.4040)
rgb_std = (1.0, 1.0, 1.0)
self.sub_mean = common.MeanShift(255, rgb_mean, rgb_std)
self.input = nn.Conv2d(3, 64, 3, stride=1, padding=1)
self.FERB_3 = FERB(64, 3)
self.FERB_5 = FERB(64, 5)
self.FERB_7 = FERB(64, 7)
self.FERB_9 = FERB(64, 9)
def forward(self, x):
x = self.sub_mean(x)
input = self.input(x)
FERB_3 = self.FERB_3(input)
FERB_5 = self.FERB_5(FERB_3)
FERB_7 = self.FERB_7(FERB_5)
FERB_9 = self.FERB_9(FERB_7)
BottleNeck = torch.cat([input, FERB_3, FERB_5, FERB_7, FERB_9], 1)
return BottleNeck
class Upscale_net(nn.Module):
def __init__(self):
super(Upscale_net, self).__init__()
conv= common.default_conv
self.input = nn.Sequential(
nn.Conv2d(320, 64, 1, stride=1, padding=0),
nn.Conv2d(64, 64, 3, stride=1, padding=1)
)
self.upscale = nn.ModuleList([
common.Upsampler(conv, s, 64, act=False) for s in [2, 3, 4]
])
self.output = nn.Conv2d(64, 3, 3, stride=1, padding=1)
def forward(self, x, scale_idx):
x = self.input(x)
x = self.upscale[scale_idx](x)
x = self.output(x)
return x
class Refine_net(nn.Module):
def __init__(self):
super(Refine_net, self).__init__()
# RGB mean for DIV2K
rgb_mean = (0.4488, 0.4371, 0.4040)
rgb_std = (1.0, 1.0, 1.0)
self.input = nn.Conv2d(3, 16, 3, stride=1, padding=1)
self.Asym_Block_1 = nn.Sequential(
nn.Conv2d(16, 16, (1, 1), stride=1, padding=0),
nn.ReLU(inplace=True),
nn.Conv2d(16, 16, (1, 3), stride=1, padding=(0,1)),
nn.Conv2d(16, 16, (3, 1), stride=1, padding=(1,0)),
nn.ReLU(inplace=True)
)
self.Asym_Block_2 = nn.Sequential(
nn.Conv2d(16, 16, (1, 3), stride=1, padding=(0,1)),
nn.Conv2d(16, 16, (3, 1), stride=1, padding=(1,0)),
nn.ReLU(inplace=True),
nn.Conv2d(16, 16, (1, 5), stride=1, padding=(0,2)),
nn.Conv2d(16, 16, (5, 1), stride=1, padding=(2,0)),
nn.ReLU(inplace=True)
)
self.Asym_Block_3 = nn.Sequential(
nn.Conv2d(16, 16, (1, 5), stride=1, padding=(0,2)),
nn.Conv2d(16, 16, (5, 1), stride=1, padding=(2,0)),
nn.ReLU(inplace=True),
nn.Conv2d(16, 16, (1, 7), stride=1, padding=(0,3)),
nn.Conv2d(16, 16, (7, 1), stride=1, padding=(3,0)),
nn.ReLU(inplace=True)
)
self.Asym_Block_4 = nn.Sequential(
nn.Conv2d(16, 16, (1, 7), stride=1, padding=(0,3)),
nn.Conv2d(16, 16, (7, 1), stride=1, padding=(3,0)),
nn.ReLU(inplace=True),
nn.Conv2d(16, 16, (1, 9), stride=1, padding=(0,4)),
nn.Conv2d(16, 16, (9, 1), stride=1, padding=(4,0)),
nn.ReLU(inplace=True)
)
self.concat = nn.Conv2d(64, 3, 1, stride=1, padding=0)
self.add_mean = common.MeanShift(255, rgb_mean, rgb_std, 1)
def forward(self, HR):
input = self.input(HR)
Asym_1 = self.Asym_Block_1(input)
Asym_2 = self.Asym_Block_2(input)
Asym_3 = self.Asym_Block_3(input)
Asym_4 = self.Asym_Block_4(input)
residual = self.concat(torch.cat([Asym_1, Asym_2, Asym_3, Asym_4], 1))
HR += residual
HR = self.add_mean(HR)
return HR
class MASRN_Net(nn.Module):
def __init__(self):
super(MASRN_Net, self).__init__()
self.Extraction = Extraction_net()
self.Upscale = Upscale_net()
self.Refine = Refine_net()
self.scale_idx = 2
def forward(self, x):
Extraction = self.Extraction(x)
Upscale = self.Upscale(Extraction, self.scale_idx - 2)
HR = self.Refine(Upscale)
return HR
def set_scale(self, scale_idx):
self.scale_idx = scale_idx
<file_sep>/data/sameHRsize/data_augment.py
import argparse, os
import glob
import h5py
import cv2
from PIL import Image
import numpy as np
# AUGMENT SETTINGS
parser = argparse.ArgumentParser(description="PyTorch MASRN")
parser.add_argument("--HRpath", type=str, default='data/DIV2K_train_HR')
parser.add_argument("--Savepath", type=str, default='data/train_x234.h5')
parser.add_argument("--Cropsize", type=int, default=48)
parser.add_argument("--Cropnum", type=int, default=100)
def data_aug():
global opt
opt = parser.parse_args()
print(opt)
sub_ip = []
sub_la = []
num = 1
HRpath = load_img(opt.HRpath)
for _ in HRpath:
HR_img = read_img(_)
sub_image = random_crop(HR_img, opt.Cropnum, opt.Cropsize)
input = transfer_input(sub_image)
label_x2 = img_downsize(sub_image, 2)
label_x3 = img_downsize(sub_image, 3)
label_x4 = img_downsize(sub_image, 4)
sub_ip += input
sub_la_2 += label_x2
sub_la_3 += label_x3
sub_la_4 += label_x4
print('data no.',num)
num += 1
sub_ip = np.asarray(sub_ip)
sub_la_2 = np.asarray(sub_la_2)
sub_la_3 = np.asarray(sub_la_3)
sub_la_4 = np.asarray(sub_la_4)
print('input shape : ',sub_ip.shape)
print('label shape : x2[',sub_la_2.shape,'], x3[',sub_la_3.shape,'], x4['sub_la_4.shape,']')
save_h5(sub_ip, sub_la_2, sub_la_3, sub_la_4, opt.Savepath)
print('---------save---------')
def load_img(file_path):
dir_path = os.path.join(os.getcwd(), file_path)
img_path = glob.glob(os.path.join(dir_path, '*.png'))
return img_path
def read_img(img_path):
# read image
image = cv2.imread(img_path)
return image
def mod_crop(image, scale):
h = image.shape[0]
w = image.shape[1]
h = h - np.mod(h,scale)
w = w - np.mod(w,scale)
return image[0:h,0:w,:]
def random_crop(image, Cropnum, Cropsize):
sub_img = []
i = 0
while i < Cropnum:
h = np.random.randint(0, image.shape[0] - Cropsize)
w = np.random.randint(0, image.shape[1] - Cropsize)
sub_i = image[h:h+Cropsize,w:w+Cropsize]
sub_i = mod_crop(sub_i, 4)
sub_i = mod_crop(sub_i, 3)
sub_img.append(sub_i)
i += 1
return sub_img
def transfer_input(img):
img_list = []
for _ in img:
h = _.shape[0]
w = _.shape[1]
img_list.append(_.reshape(3, h, w))
return img_list
def img_downsize(img, scale):
dst_list = []
for _ in img:
h = _.shape[0]
w = _.shape[1]
dst = cv2.resize(_, dsize=(0, 0), fx=1/scale, fy=1/scale, interpolation=cv2.INTER_CUBIC)
dst_list.append(dst.reshape(3, h/scale, w/scale))
return dst_list
def save_h5(sub_ip, sub_la_2, sub_la_3, sub_la_4, savepath):
path = os.path.join(os.getcwd(), savepath)
with h5py.File(path, 'w') as hf:
hf.create_dataset('input', data=sub_ip)
hf.create_dataset('label_x2', data=sub_la_2)
hf.create_dataset('label_x3', data=sub_la_3)
hf.create_dataset('label_x4', data=sub_la_4)
if __name__ == '__main__':
print('starting data augmentation...')
data_aug()
<file_sep>/dataset_h5.py
import torch.utils.data as data
import torch
import h5py
class Read_dataset_h5(data.Dataset):
def __init__(self, file_path):
super(Read_dataset_h5, self).__init__()
hf = h5py.File(file_path)
self.input_x2 = hf.get('input_x2')
self.input_x3 = hf.get('input_x3')
self.input_x4 = hf.get('input_x4')
self.label_x2 = hf.get('label_x2')
self.label_x3 = hf.get('label_x3')
self.label_x4 = hf.get('label_x4')
def __getitem__(self, index):
i_x2 = torch.from_numpy(self.input_x2[index,:,:,:]).float()
i_x3 = torch.from_numpy(self.input_x3[index,:,:,:]).float()
i_x4 = torch.from_numpy(self.input_x4[index,:,:,:]).float()
l_x2 = torch.from_numpy(self.label_x2[index,:,:,:]).float()
l_x3 = torch.from_numpy(self.label_x3[index,:,:,:]).float()
l_x4 = torch.from_numpy(self.label_x4[index,:,:,:]).float()
return i_x2, i_x3, i_x4, l_x2, l_x3, l_x4
def __len__(self):
return self.input_x2.shape[0]
| f71e5008722da412580bd021ff78444195702742 | [
"Python"
] | 6 | Python | HwangToeMat/MASRN_Pytorch_HTM | f1150edcee52b8d8ed9029b6870f72b3d9882b0e | 092d8fb617690777fb007f9d6246c672a1747c5b |
refs/heads/master | <file_sep>export function createGLShader(gl: WebGLRenderingContext, type: number, source: string) {
const shader = gl.createShader(type)
if (!shader) {
return null
}
gl.shaderSource(shader, source)
gl.compileShader(shader)
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (success) {
return shader
}
console.log(gl.getShaderInfoLog(shader))
gl.deleteShader(shader)
return null
}
export function createGLProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader | null, fragmentShader: WebGLShader | null) {
const program = gl.createProgram()
if (!(program && vertexShader && fragmentShader)) {
return null
}
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
gl.linkProgram(program)
const success = gl.getProgramParameter(program, gl.LINK_STATUS)
if (success) {
return program
}
console.log(gl.getProgramInfoLog(program))
gl.deleteProgram(program)
return null
}
/* eslint-disable no-param-reassign */
export function resizeToDisplaySize(canvas: HTMLCanvasElement, doSetDevicePixelRatio = true) {
const realToCSSPixels = doSetDevicePixelRatio ? window.devicePixelRatio : 1
const { clientWidth, clientHeight } = canvas
const [width, height] = [
clientWidth * realToCSSPixels,
clientHeight * realToCSSPixels,
]
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width
canvas.height = height
}
}
/* eslint-enable no-param-reassign */
| 2b9e1301a7ee9529c5c7c69927e21dc1ad65347c | [
"TypeScript"
] | 1 | TypeScript | xiaomingTang/webgl-sample | a92bc70c6dd2d2e85d392f2bd4f8f85db64a3445 | 02f0de092a2ac6c5c62548389ec9f82274d3fa94 |
refs/heads/master | <repo_name>MichaelSipayung/Eigen-Lecture-1<file_sep>/README.md
# Eigen-Lecture-1
Eigen++ is the matrix library and another numeric solver . this repository is intended for remembering and acess from every where .
Eigen++ is the matrix library and another numeric solver .
this repository is intended for remembering and access my code from every where .
written in pure c++
#include standart temlate library c++
<file_sep>/Eigen Lecture 1/CMakeLists.txt
# CMakeList.txt : CMake project for Eigen Lecture 1, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
find_package(Eigen3 CONFIG REQUIRED)
# Add source to this project's executable.
add_executable (CMakeTarget "Eigen Lecture 1.cpp" "Eigen Lecture 1.h" )
target_link_libraries(CMakeTarget PRIVATE Eigen3::Eigen)
# TODO: Add tests and install targets if needed.
<file_sep>/Eigen Lecture 1/Eigen Lecture 1.cpp
// Eigen Lecture 1.cpp : Defines the entry point for the application.
//
#include "Eigen Lecture 1.h"
using namespace std;
int main()
{
Eigen::Matrix<float, 2, 2> nameMatr;
nameMatr << 1, 2, 3, 4;
std::cout << "Use matrix 4 x 4" << std::endl;
Eigen::Matrix4f nameMat;
nameMat << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
std::cout << "Show 4x4 matrix \:t[ \n "<<nameMat;
std::cout << "]" << std::endl;
std::cout << "Test Vector column " << std::endl;
Eigen::Vector3f vectorColumn;
vectorColumn<< 1, 2, 4;
std::cout << "Show vector \t:[ " << vectorColumn << "]" << std::endl;
std::cout << "Row vector " << std::endl;
Eigen::RowVector2f row;
row << 1, 2;
std::cout << "Show vector \t:[ " << row << "]" << std::endl;
std::cout << "Special case for dynamic size" << std::endl;
Eigen::Matrix<float,3,Eigen::Dynamic> dynamic;
Eigen::MatrixXd allocateArra(10, 15); //150 element
std::cout << "Show size dynamic matrix \t: [" << allocateArra.size() << "]" << std::endl;
std::cout << "Allocate dynamic column vector " << std::endl;
Eigen::VectorXf vecTen(10);
std::cout << "Show size dynamic vector \t: [" <<vecTen.size() << "]" << std::endl;
std::cout << "Initialized from list coefficients" << std::endl;
Eigen::Vector2d twoDimen(8.0, 9.0);
std::cout << "Show vector from list initialized \t: [ \n" << twoDimen << "\n]" << std::endl;
std::cout << "Hello Eigen\n" <<nameMatr << endl;
Eigen::MatrixXd input(2, 2);
std::cout << "Input Matrix \t: [";
for (auto i = 0; i != 2; ++i) {
for (auto j = 0; j != 2; ++j) {
//testing input from user
//std::cin >> input(i, j);
input(i, j) = i * j + 12;
}
}
std::cout << "Result matrix \t: [ \n" << input;
std::cout << "]" << std::endl;
std::cout << "Result transpose \t: [ \n" << input.transpose();
std::cout << "]" << std::endl;
std::cout << "Input Vector \t: [";
Eigen::VectorXd interAct(9);
auto inVec = 0;
while (inVec!=interAct.size())
{
interAct(inVec) = inVec+2*4;
++inVec;
}
std::cout << "Show vector \t: [ " << interAct <<"]"<<std::endl;
std::cout << "Show the norm \t: [" << interAct.norm() << "]" << std::endl;
std::cout << "Test assign the eigen vector to standart vector in c++" << std::endl;
Eigen::VectorXi vecIni(10); //contain 10 element , column vector
for (auto i = 0; i != vecIni.size();++i) {
vecIni(i) = 2 * i * 34;
}
std::vector<double> assign;
for (auto i = 0; i != vecIni.size(); ++i) {
assign.push_back(vecIni(i));
}
std::cout << "After assign eigen matrix to standart vector\t:[ ";
for (auto& i : assign)
{
std::cout << i << "|";
}
std::cout << "]" << std::endl;
std::cout << "vice versa of the operation" << std::endl;
std::vector<int> findNorm{ 10,28,37,47,6,7,8,4,1 };
Eigen::VectorXd destNorm(9);
for (size_t i = 0; i != findNorm.size(); ++i)
{
destNorm(i) = findNorm[i];
}
std::cout << "Show matrix to find \t: [";
for (auto& i : findNorm)
{
std::cout << i << "|";
}
std::cout << "]" << std::endl;
std::cout << "And it has norm \t: [" << destNorm.norm() << "]" << std::endl;
std::cout << "Resize matrix" << std::endl;
Eigen::MatrixXi resize(8, 4);
std::cout << "current row \t:[" << resize.rows() << "\tand col \t: " << resize.cols() << "]" << std::endl;
std::cout << "After resizing the current matrix " << std::endl;
resize.resize(8, 6);
std::cout << "current row \t:[" << resize.rows() << "\tand col \t: " << resize.cols() << "]" << std::endl;
std::cout << "Test resize vector " << std::endl;
Eigen::VectorXi nameTore(9);
std::cout << "Before resing the current vector" << std::endl;
std::cout << "current row \t:[" << nameTore.rows() << "\tand col \t: " << nameTore.cols() << "]" << std::endl;
nameTore.resize(19);
std::cout << "After resizing the current vector" << std::endl;
std::cout << "current row \t:[" << nameTore.rows() << "\tand col \t: " << nameTore.cols() << "]" << std::endl;
std::cout << "Assignments and resizing" << std::endl;
Eigen::MatrixXd doubleTwo(2, 2);
std::cout << "Matrix size , current row \t: [ " << doubleTwo.rows() << " and cols \t: " << doubleTwo.cols() << "]" << std::endl;
Eigen::MatrixXd doubleThree(3, 3);
std::cout << "Matrix size , current row \t: [ " << doubleThree.rows() << " and cols \t: " << doubleThree.cols() << "]" << std::endl;
doubleTwo = doubleThree;
std::cout << "After assign the matrix" << std::endl;
std::cout << "Matrix size , current row \t: [ " << doubleTwo.rows() << " and cols \t: " << doubleTwo.cols() << "]" << std::endl;
std::cout << "Using fix sized for matrix less than 16 or more " << std::endl;
Eigen::Matrix<int, 15, 15> fifteen;
std::default_random_engine generator;
std::binomial_distribution<int> distribution(198, 0.5);
for (auto i = 0; i != fifteen.rows(); ++i) {
for (auto j = 0; j != fifteen.cols(); ++j) {
fifteen(i, j) = distribution(generator);
}
}
std::cout << "Result matrix after generate random (binomial distribution)" << std::endl;
std::cout<<fifteen<<std::endl;
std::vector<std::vector<int>> secDimen(5,std::vector<int> (5,distribution(generator)));
/*for (size_t i = 0; i !=8; ++i)
{
for (size_t j = 0; j != 8; ++j) {
secDimen[i][j] = distribution(generator);
}
} */
//my style initilized at runtime
for (auto& i : secDimen)
{
for (auto& j : i) {
j = distribution(generator);
}
}
std::cout << "Explorer vector template for 2 dimension" << std::endl;
for (auto& i : secDimen)
{
for (auto& j : i) {
std::cout << j << "|";
}
std::cout << std::endl;
}
std::cout << "]" << std::endl;
//another way
std::vector<std::vector<int>> vecDis{ {11,22,31},{11,21,32} };
std::cout << "Show the new style" << std::endl;
for (auto& i : vecDis)
{
for (auto& j : i) {
std::cout << j << "|";
}
std::cout << std::endl;
}
std::cout << "]" << std::endl;
return 0;
}
| a330010e992238db5c17a6f7370ba3e6c66208ef | [
"Markdown",
"CMake",
"C++"
] | 3 | Markdown | MichaelSipayung/Eigen-Lecture-1 | 99ad319396cb5f7d0f97f19724ddf524dd39499b | 783f5cf2dc155682acadc5a6b8dbe18a0756e328 |
refs/heads/master | <repo_name>dwaxemberg/dotfiles<file_sep>/zshrc
setopt PROMPT_SUBST
autoload -U promptinit compinit zmv edit-command-line
promptinit
prompt grb
compinit -Cu
HISTFILE=~/.history
HISTSIZE=100000
SAVEHIST=$HISTSIZE
export TERM='xterm-256color'
export EDITOR='vim'
set -o emacs
setopt inc_append_history
zle -N edit-command-line
bindkey '\C-x\C-e' edit-command-line
bindkey -e
#Better completion
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' menu select
zstyle ':completion:*:*:kill:*:processes' command 'ps --forest -e -o pid,user,tty,cmd'
source $HOME/.aliases
[[ `uname -a` =~ Ubuntu ]] && source /etc/zsh_command_not_found
source ~/.zsh/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
source ~/.zsh/zsh-history-substring-search/zsh-history-substring-search.zsh
#Functions
ssh-reagent () {
ssh-add -l &> /dev/null && return 0
for agent in /tmp/ssh-*/agent.*; do
export SSH_AUTH_SOCK=$agent
if ssh-add -l 2>&1 > /dev/null; then
echo Found working SSH Agent:
ssh-add -l
return
fi
done
echo "Cannot find ssh agent - maybe you should reconnect and forward it?"
}
<file_sep>/README.md
# Dotfiles
These are my personal dotfiles. They are primarily designed to work on Linux
(specifically Ubuntu) systems, but they're pretty portable and I've frequently
used them on CentOS and OSX systems.
Various parts stolen from [ted27/.files](https://github.com/ted27/.files) as
well as [sds/dot](https://github.com/sds/dot).
## Installation
Clone the repo
```
git clone git://github.com/Aaronneyer/dotfiles
```
Install. You will need ruby and vim on your system for this to work.
```
cd dotfiles
./bootstrap.rb
```
| 7fafbd22c6af31c5a376030b2fda773628dd1dd8 | [
"Markdown",
"Shell"
] | 2 | Shell | dwaxemberg/dotfiles | d6eb515343969266168691666484e1428175fdb6 | 774d45d1fe80df3317f38bbc945e16c593b1b12d |
refs/heads/master | <repo_name>nickschiffer/discord-soundbot<file_sep>/Dockerfile
FROM node:carbon-alpine
LABEL maintainer="<NAME> <<EMAIL>>"
# Install ffmpeg and other deps
RUN apk add --no-cache --quiet build-base ffmpeg git make python
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn --silent
COPY . /app
# Cleanup
RUN apk del --quiet build-base
# Build
RUN yarn build
CMD ["yarn", "serve"]
<file_sep>/src/types/replace-in-file.d.ts
declare module 'replace-in-file' {
interface ReplaceOptions {
files: string[];
from: RegExp[];
to: (...args: string[]) => string;
}
function sync(options: ReplaceOptions): string[];
}
<file_sep>/src/bot/MessageHandler.ts
import { Message } from 'discord.js';
import '../discord/Message';
import Config from '@config/Config';
import * as ignoreList from '@util/db/IgnoreList';
import CommandCollection from './CommandCollection';
export default class MessageHandler {
private readonly config: Config;
private readonly commands: CommandCollection;
constructor(config: Config, commands: CommandCollection) {
this.config = config;
this.commands = commands;
}
public handle(message: Message) {
if (!this.isValidMessage(message)) return;
const messageToHandle = message;
messageToHandle.content = message.content.substring(this.config.prefix.length);
if (this.config.deleteMessages) {
message.delete();
}
this.commands.execute(message);
}
private isValidMessage(message: Message) {
if (!message.hasPrefix(this.config.prefix)){
return false;
}
if (message.isDirectMessage()){
message.author.send(`DM support still in development :/`);
return false;
}
if (message.author.bot){
return false;
}
if (!message.member){
message.author.send(`Doesn't look like you're a member`);
message.delete();
return false;
}
if (ignoreList.exists(message.author.id)) {
message.author.send(`You don't have permission to do that.`);
message.delete();
return false;
}
return true;
return (
!message.author.bot &&
!message.isDirectMessage() &&
message.hasPrefix(this.config.prefix) &&
!ignoreList.exists(message.author.id)
);
}
}
<file_sep>/src/bot/commands/SoundCommand.ts
import { Message } from 'discord.js';
import QueueItem from '@queue/QueueItem';
import SoundQueue from '@queue/SoundQueue';
import localize from '@util/i18n/localize';
import { existsSound } from '@util/SoundUtil';
import Command from './base/Command';
import Config from '@config/Config';
export default class SoundCommand implements Command {
public readonly TRIGGERS = [];
private readonly config: Config;
private readonly queue: SoundQueue;
constructor(config: Config, queue: SoundQueue) {
this.queue = queue;
this.config = config;
}
public run(message: Message) {
const sound = message.content;
if (!existsSound(sound)) {
message.author.send(`sound not found, try ${this.config.prefix}sounds for a list of sounds.`);
return;
}
const { voiceChannel } = message.member;
if (!voiceChannel) {
message.reply(localize.t('helpers.voiceChannelFinder.error'));
return;
}
this.queue.add(new QueueItem(sound, voiceChannel, message));
}
}<file_sep>/src/util/__mocks__/Container.ts
export default {
config: {
acceptedExtensions: ['.mp3']
}
};
<file_sep>/src/bot/commands/AddCommand.ts
import { Message, Permissions } from 'discord.js';
import Command from './base/Command';
import AttachmentDownloader from './helpers/downloader/AttachmentDownloader';
import YoutubeDownloader from './helpers/downloader/YoutubeDownloader';
import Config from '@config/Config';
export default class AddCommand implements Command {
public readonly TRIGGERS = ['add'];
readonly config: Config;
private readonly attachmentDownloader: AttachmentDownloader;
private readonly youtubeDownloader: YoutubeDownloader;
constructor(config: Config, attachmentDownloader: AttachmentDownloader, youtubeDownloader: YoutubeDownloader) {
this.attachmentDownloader = attachmentDownloader;
this.youtubeDownloader = youtubeDownloader;
this.config = config;
}
public run(message: Message) {
if (!message.member.hasPermission(Permissions.FLAGS.ADMINISTRATOR!)){
message.author.send(`Only mods can do that`);
return;
}
if (!message.attachments.size) {
this.youtubeDownloader.handle(message);
return;
}
this.attachmentDownloader.handle(message);
}
}
<file_sep>/src/config/DefaultConfig.ts
import ConfigInterface from './ConfigInterface';
const DEFAULT_CONFIG: ConfigInterface = {
clientId: '',
token: '',
language: 'en',
prefix: '!',
acceptedExtensions: ['.mp3', '.wav'],
maximumFileSize: 1000000,
volume: 1.0,
deleteMessages: false,
stayInChannel: false,
deafen: false,
game: ''
};
export default DEFAULT_CONFIG;
<file_sep>/src/bot/__jest__/MessageHandler.test.ts
import { Message, DMChannel } from 'discord.js';
import '../../discord/Message';
import Config from '@config/Config';
import * as ignoreList from '@util/db/IgnoreList';
import MessageHandler from '../MessageHandler';
import CommandCollection from '../CommandCollection';
const PREFIX = '!';
const config = { prefix: PREFIX } as Config;
const commandCollection = new CommandCollection([]);
describe('MessageHandler', () => {
const messageHandler = new MessageHandler(config, commandCollection);
describe('handle', () => {
jest.spyOn(commandCollection, 'execute');
describe('when message is from bot', () => {
const message = ({
author: { bot: true }
} as unknown) as Message;
Object.setPrototypeOf(message, Message.prototype);
it('does nothing', () => {
jest.spyOn(message, 'isDirectMessage');
messageHandler.handle(message);
expect(commandCollection.execute).not.toHaveBeenCalled();
expect(message.isDirectMessage).not.toHaveBeenCalled();
});
});
describe('when message is DM', () => {
const channel = ({} as unknown) as DMChannel;
Object.setPrototypeOf(channel, DMChannel.prototype);
const message = ({
author: { bot: false },
channel
} as unknown) as Message;
Object.setPrototypeOf(message, Message.prototype);
it('does nothing', () => {
jest.spyOn(message, 'hasPrefix');
messageHandler.handle(message);
expect(commandCollection.execute).not.toHaveBeenCalled();
expect(message.hasPrefix).not.toHaveBeenCalled();
});
});
describe('when message does not have prefix', () => {
const message = ({
author: { bot: false },
content: `NOT_${PREFIX}`
} as unknown) as Message;
Object.setPrototypeOf(message, Message.prototype);
it('does nothing', () => {
jest.spyOn(ignoreList, 'exists');
messageHandler.handle(message);
expect(commandCollection.execute).not.toHaveBeenCalled();
expect(ignoreList.exists).not.toHaveBeenCalled();
});
});
describe('when user is ignored', () => {
const message = ({
author: { bot: false },
content: PREFIX
} as unknown) as Message;
Object.setPrototypeOf(message, Message.prototype);
it('does nothing', () => {
jest.spyOn(ignoreList, 'exists').mockImplementation(() => true);
messageHandler.handle(message);
expect(commandCollection.execute).not.toHaveBeenCalled();
});
});
describe('when message is valid', () => {
const message = ({
author: { bot: false },
content: PREFIX
} as unknown) as Message;
Object.setPrototypeOf(message, Message.prototype);
it('executes the command', () => {
jest.spyOn(ignoreList, 'exists').mockImplementation(() => false);
jest.spyOn(commandCollection, 'execute').mockImplementation();
messageHandler.handle(message);
expect(commandCollection.execute).toHaveBeenCalledWith({ ...message, content: '' });
});
});
});
});
<file_sep>/src/bot/SoundBot.ts
import { Client, Guild, GuildMember, Message, TextChannel } from 'discord.js';
import Config from '@config/Config';
import QueueItem from '@queue/QueueItem';
import SoundQueue from '@queue/SoundQueue';
import * as entrances from '@util/db/Entrances';
import * as exits from '@util/db/Exits';
import localize from '@util/i18n/localize';
import { getSounds } from '@util/SoundUtil';
import CommandCollection from './CommandCollection';
import Command from './commands/base/Command';
import MessageHandler from './MessageHandler';
export default class SoundBot extends Client {
private readonly config: Config;
private readonly commands: CommandCollection;
private readonly messageHandler: MessageHandler;
private readonly queue: SoundQueue;
constructor(
config: Config,
commands: CommandCollection,
messageHandler: MessageHandler,
queue: SoundQueue
) {
super();
this.config = config;
this.commands = commands;
this.messageHandler = messageHandler;
this.queue = queue;
this.addEventListeners();
}
public start() {
this.login(this.config.token);
}
public registerAdditionalCommands(commands: Command[]) {
this.commands.registerCommands(commands);
}
private addEventListeners() {
this.on('ready', this.onReady);
this.on('message', this.onMessage);
this.on('voiceStateUpdate', this.onUserLeavesVoiceChannel);
this.on('voiceStateUpdate', this.onUserJoinsVoiceChannel);
this.on('guildCreate', this.onBotJoinsServer);
}
private onReady() {
this.user.setActivity(this.config.game);
this.commands.registerUserCommands(this.user);
}
private onUserJoinsVoiceChannel(prevState: GuildMember, user: GuildMember) {
if (user.id === this.user.id) return;
if (!user.voiceChannelID || prevState.voiceChannelID === user.voiceChannelID) return;
if (!entrances.exists(user.id)) return;
const sound = entrances.get(user.id);
if (!getSounds().includes(sound)) return;
const { voiceChannel } = user;
this.queue.add(new QueueItem(sound, voiceChannel));
}
private onUserLeavesVoiceChannel(prevState: GuildMember, user: GuildMember) {
if (user.id === this.user.id) return;
if (!prevState.voiceChannelID || prevState.voiceChannelID === user.voiceChannelID) return;
if (!exits.exists(user.id)) return;
const sound = exits.get(user.id);
if (!getSounds().includes(sound)) return;
const { voiceChannel } = prevState;
this.queue.add(new QueueItem(sound, voiceChannel));
}
private onMessage(message: Message) {
this.messageHandler.handle(message);
}
private onBotJoinsServer(guild: Guild) {
if (!guild.available) return;
const channel = this.findFirstWritableChannel(guild);
if (!channel) return;
channel.send(localize.t('welcome', { prefix: this.config.prefix }));
}
private findFirstWritableChannel(guild: Guild) {
const channels = guild.channels.filter(
channel => channel.type === 'text' && channel.permissionsFor(guild.me)!.has('SEND_MESSAGES')
);
if (!channels.size) return undefined;
return channels.first() as TextChannel;
}
}
<file_sep>/bin/soundbot.ts
#!/usr/bin/env node
import localize from '@util/i18n/localize';
import container from '../src/util/Container';
const { config } = container;
localize.setLocale(config.language);
const bot = container.soundBot;
bot.start();
console.info(localize.t('url', { clientId: config.clientId }));
| b196430d63a937c207178bf4c1f4cf3323194dd6 | [
"JavaScript",
"TypeScript",
"Dockerfile"
] | 10 | Dockerfile | nickschiffer/discord-soundbot | 1085b3f6c08ce272ed222c41f918ccdb36a9c28a | 79acdfe23f416851760ab71a70290179ae1c76c8 |
refs/heads/master | <file_sep>import io
import numpy as np
from conllu.parser import parse
import os
import itertools
#####INIT DATA###########
def readFile(txtFile):
with open(txtFile,encoding='utf8') as myfile:
return myfile.read().lower()
def parse_sentence_conllu(conllu_raw_string):
#list of POS access: parsed[id_sent][id_word][x] x=0-> form,x = 1=pos
conllu_list_raw = conllu_raw_string.split("\n\n")
conllu_list_final = []
for clr in conllu_list_raw:
if len(clr)>2:
clr_part = clr.split("\n")
conllu_final= ""
for cline in range(2,len(clr_part)):
conllu_final += clr_part[cline].replace("\t"," ")+"\n"
parsed = parse(conllu_final)
conllu_list_final.append([])
for idx in range(0,len(parsed[0])):
par = []
par.append(parsed[0][idx]['form'])
par.append(parsed[0][idx]['upostag'])
conllu_list_final[-1].append(par)
return conllu_list_final
def init_pos_list(folder):
files = os.listdir(folder)
for f in files:
word_list = readFile(folder+"/"+f).lower().split("\n")
if word_list.count(' ')>0:
word_list = word_list.remove('')
pos_list[f]= word_list
######COUNT DATA#########
def tag_loc_in_sentence(parsed_sentence,tag):
tag_loc = []
for id_word in range (0,len(parsed_sentence)):
if (parsed_sentence[id_word][1]).lower()==tag.lower():
tag_loc.append(id_word)
return tag_loc
def count_tag_pair_sentence(parsed_sentence,tag1,tag2):
tag1_loc = tag_loc_in_sentence(parsed_sentence,tag1)
if tag1_loc!=[]:
pair_count=0
for id_tag1 in tag1_loc:
if (id_tag1!=len(parsed_sentence)-1):
if (parsed_sentence[id_tag1+1][1]).lower()==tag2.lower():
pair_count+= 1
return pair_count
return 0
def count_tag_pair_corpus(parsed,tag1,tag2):
count_pair = 0
for parsed_sentence in parsed:
count_pair += count_tag_pair_sentence(parsed_sentence,tag1,tag2)
return count_pair
#======= DATA INIT =========
pos_list = {}
all_tag_pair = 0
parsed = parse_sentence_conllu(readFile('UD_Indonesian/id-ud-dev.conllu'))
init_pos_list('tag')
for i in pos_list:
for y in pos_list:
all_tag_pair += count_tag_pair_corpus(parsed,i,y)
#==========================
def listing_word_tags(word):
tag_list = []
for i in pos_list:
if word in pos_list[i]:
tag_list.append(i)
return tag_list
#print(tag_list)
def listing_sentc_tag_seq(sentence):
tags_list = []
words = sentence.lower().split(" ")
for word in words:
tags_list.append(listing_word_tags(word))
return list(itertools.product(*tags_list))
#P(tag & tag+1)
def count_tag_prob(parsed,el_id,elmt):
#el_id = 0-> word, 1->tag
elmt_count = 0
corpus_len = 0
for parsed_sentence in parsed:
corpus_len+= len(parsed_sentence)
elmt_list = [word[el_id].lower() for word in parsed_sentence]
elmt_count += elmt_list.count(elmt.lower())
return elmt_count/corpus_len
def prob_tag_and_word(parsed,tag,word):
corpus_len=0
pair_count = 0
for parsed_sentence in parsed:
corpus_len+= len(parsed_sentence)
id_words = [word[0].lower() for word in parsed_sentence]
id_words = [i for i,val in enumerate(id_words) if val==word]
for id_parsed_word in id_words:
if parsed_sentence[id_parsed_word][1].lower()==tag.lower():
pair_count += 1
return pair_count/corpus_len
def prob_w_given_t(parsed,w,t):
#P(w & t)/p(t)
p_w_and_t = prob_tag_and_word(parsed,t,w)
p_tag = count_tag_prob(parsed,1,t)
return p_w_and_t/p_tag
def prob_t_given_tbev(parsed,t,tbev):
#P(t & t-1)/P(t-1)
c_and_tags = count_tag_pair_corpus(parsed,tbev,t)
p_and_tags = c_and_tags/all_tag_pair
p_tbev = count_tag_prob(parsed,1,tbev)
return p_and_tags/p_tbev
def prob_all_t_given_tbev(parsed,tag_seq):#one sequence
prob = 0
for i in range (1, len(tag_seq)):
prob+= prob_t_given_tbev(parsed,tag_seq[i],tag_seq[i-1])
return prob
def prob_all_w_given_t(parsed,word_list,tag_list):#one sequence
prob = 0
for i in range (0,len(word_list)):
prob+= prob_w_given_t(parsed,word_list[i],tag_list[i])
return prob
#-------------HMM---------------
#def p_tag_given_word(parsed,tag,word):
#print(tag_loc_in_sentence(parsed[0],'propn'))
#print(count_tag_pair_sentence(parsed[0],'punct','noun'))
#print(parsed[-1][0][1])
#print(count_tag_prob(parsed,0,'saya'))
#print(count_tag_and_word_prob(parsed,'punct',','))
#listing_word_tags('yaitu')
tag_seq = (listing_sentc_tag_seq('Ahli rekayasa optik'))
word_list = ('Ahli rekayasa optik').split(' ')
'''
for tag in tag_seq:
print(count_all_t_given_tbev(parsed,tag))
'''
prob_list = []
for i in range (0,len(tag_seq)):
tt = (prob_all_t_given_tbev(parsed,tag_seq[i]))
wt = prob_all_w_given_t(parsed,word_list,tag_seq[i])
pt = count_tag_prob(parsed,1,tag_seq[i][0])
print(tag_seq[i])
print(tt*wt*pt)
<file_sep>import io
import numpy as np
from conllu.parser import parse
import os
import itertools
from func_PerformanceMetric import calc_PosNegValue,calc_Acc,calc_Prec,calc_Recall,calc_FScore
#####INIT DATA###########
def readFile(txtFile):
with open(txtFile,encoding='utf8') as myfile:
return myfile.read().lower()
def parse_sentence_conllu(conllu_raw_string):
#list of POS access: parsed[id_sent][id_word][x] x=0-> form,x = 1=pos
conllu_list_raw = conllu_raw_string.replace("\t"," ").split("\n\n")
conllu_list_final = []
for clr in conllu_list_raw:
if len(clr)>2:
clr_part = clr.split("\n")
conllu_final= ""
for cline in range(2,len(clr_part)):
conllu_final += clr_part[cline] +"\n"
parsed = parse(conllu_final)
conllu_list_final.append([])
for idx in range(0,len(parsed[0])):
par = []
par.append(parsed[0][idx]['form'])
par.append(parsed[0][idx]['upostag'])
conllu_list_final[-1].append(par)
return conllu_list_final
def init_pos_list(folder):
files = os.listdir(folder)
for f in files:
word_list = readFile(folder+"/"+f).lower().split("\n")
if word_list.count(' ')>0:
word_list = word_list.remove('')
if f=='aux_list':
pos_list['aux']=word_list
else:
pos_list[f]= word_list
######COUNT DATA#########
def tag_loc_in_sentence(parsed_sentence,tag):
tag_loc = [word[1].lower() for word in parsed_sentence]
return [i for i, s in enumerate(tag_loc) if tag==s]
def count_tag_pair_sentence(parsed_sentence,tag1,tag2):
tag1_loc = tag_loc_in_sentence(parsed_sentence,tag1)
if tag1_loc!=[]:
pair_count=0
for id_tag1 in tag1_loc:
if (id_tag1!=len(parsed_sentence)-1):
if (parsed_sentence[id_tag1+1][1]).lower()==tag2.lower():
pair_count+= 1
return pair_count
return 0
def count_tag_pair_corpus(parsed,tag1,tag2):
count_pair = 0
for parsed_sentence in parsed:
count_pair += count_tag_pair_sentence(parsed_sentence,tag1,tag2)
return count_pair
def count_tag_prob(parsed,el_id,elmt):
#el_id = 0-> word, 1->tag
elmt_count = 0
corpus_len = 0
for parsed_sentence in parsed:
corpus_len+= len(parsed_sentence)
elmt_list = [word[el_id].lower() for word in parsed_sentence]
elmt_count += elmt_list.count(elmt.lower())
return elmt_count/corpus_len
#======= DATA INIT =========
pos_list = {}
tag_pair_t1 = []
tag_pair_t2 = []
tag_pair_count = []
tag_prob_tag = []
tag_prob_value = []
all_tag_pair = 0
parsed = parse_sentence_conllu(readFile('UD_Indonesian/id-ud-train.conllu'))
parsed_dev = parse_sentence_conllu(readFile('UD_Indonesian/id-ud-dev.conllu'))
init_pos_list('tag')
for i in pos_list:
tag_prob_tag.append(i)
tag_prob_value.append(count_tag_prob(parsed,1,i))
for y in pos_list:
tag_pair_t1.append(i)
tag_pair_t2.append(y)
a = count_tag_pair_corpus(parsed,i,y)
tag_pair_count.append(a)
all_tag_pair += a
combine_parsed = []
for parsed_s in parsed:
for parsed_w in parsed_s:
combine_parsed.append(parsed_w[0].lower()+"_"+str(parsed_w[1].lower()))
print(len(combine_parsed))
#==========================
def count_tag_pair_corpus2(tag1,tag2):
idx = tag_pair_t1.index(tag1)
c = -1
while (idx<len(tag_pair_t1) and tag_pair_t1[idx]==tag1 and c==-1):
if tag_pair_t2[idx]==tag2:
c = tag_pair_count[idx]
else:
idx+=1
return c
print(count_tag_pair_corpus2('noun','noun'))
def listing_word_tags(word):
tag_list = []
for i in pos_list:
if word in pos_list[i]:
tag_list.append(i)
return tag_list
def listing_sentc_tag_seq(sentence):
tags_list = []
words = sentence.lower().split(" ")
for word in words:
tags_list.append(listing_word_tags(word))
#print(tags_list)
return list(itertools.product(*tags_list))
def prob_tag_and_word(parsed,tag,word):
corpus_len=0
pair_count = 0
for parsed_sentence in parsed:
corpus_len+= len(parsed_sentence)
id_words = [word[0].lower() for word in parsed_sentence]
id_words = [i for i,val in enumerate(id_words) if val==word]
for id_parsed_word in id_words:
if parsed_sentence[id_parsed_word][1].lower()==tag.lower():
pair_count += 1
return pair_count/corpus_len
def prob_tag_and_word2(tag,word):
return combine_parsed.count(word.lower()+"_"+tag.lower())/len(combine_parsed)
def prob_w_given_t(w,t):
#P(w & t)/p(t)
p_w_and_t = prob_tag_and_word2(t,w)
p_tag = tag_prob_value[tag_prob_tag.index(t)]
return p_w_and_t/p_tag,p_tag
def prob_w_given_t2(w,t):
#P(w & t)/p(t)
p_w_and_t = prob_tag_and_word2(t,w)
p_tag = tag_prob_value[tag_prob_tag.index(t)]
return p_w_and_t/p_tag
def prob_t_given_tbev(t,tbev):
#P(t & t-1)/P(t-1)
p_and_tags = count_tag_pair_corpus2(tbev,t)/all_tag_pair
p_tbev = tag_prob_value[tag_prob_tag.index(tbev)] #count_tag_prob(parsed,1,tbev)
return p_and_tags/p_tbev
def prob_all_t_given_tbev(parsed,tag_seq):#one sequence
prob = 0
for i in range (1, len(tag_seq)):
prob+= prob_t_given_tbev(parsed,tag_seq[i],tag_seq[i-1])
return prob
def prob_all_w_given_t(parsed,word_list,tag_list):#one sequence
prob = 0
for i in range (0,len(word_list)):
prob+= prob_w_given_t(word_list[i],tag_list[i])
return prob
def prob_all_wgt_tgt(tag_seq,word_seq):
wt = 0
tt = 0
pt = 0
for i in range (0,len(tag_seq)):
print(word_seq[i])
wgt,ct = prob_w_given_t(word_seq[i],tag_seq[i])
wt+= wgt
if i>0:
tt+= prob_t_given_tbev(tag_seq[i],tag_seq[i-1])
return wt,tt
#-------------HMM---------------
#def pod_tag_hmm_unigram_one_s(parsed,tag_seq,word_list):
def pos_tag_hmm_bigram_one_s(parsed,tag_seq,word_list):#one sentence
tags_prob = []#
for i in range (0,len(tag_seq)):
wt,tt = prob_all_wgt_tgt(tag_seq[i],word_list)
pt = tag_prob_value[tag_prob_tag.index(tag_seq[i][0])]
tags_prob.append(tt*wt*pt)
return tags_prob
def pos_tag_hmm_bigram_set(parsed,sentences):#whole dataset
tags_max_prob = []
tags_final_seq = []
for sent in sentences:
tag_seq = listing_sentc_tag_seq(sent)
word_list = sent.split(' ')
tags_prob = pos_tag_hmm_bigram_one_s(parsed,tag_seq,word_list)
id_max = tags_prob.index(max(tags_prob))
tags_max_prob.append(tags_prob[id_max])
tags_final_seq.append(tag_seq[id_max])
return tags_final_seq,tags_max_prob
def count_performance(all_tag_pred,all_tag_ground):
tp,tn,fp,fn = 0
for i in pos_list:
tp1,tn1,fp1,fn1 = calc_PosNegValue(all_tag_ground, all_tag_pred, i)
tp+=tp1
tn+=tn1
fp+=fp1
fn+=fn1
return calc_FScore(tp,tn,fp,fn)
def pos_tag_hmm_unigram_one_s(sentence):
tag_seq = []
sentence = sentence.split(' ')
i =0
for word in sentence:
print(word)
possible_tag = listing_word_tags(word)
print(possible_tag)
prob = -1
curr_tag = 'noun'
if i==0:
for tag in possible_tag:
wt,t = prob_w_given_t(word,tag)
if wt*t>prob:
prob = wt*t
curr_tag = tag
else:
for tag in possible_tag:
wt,t = prob_w_given_t(word,tag)
t = prob_t_given_tbev(tag,tag_seq[-1])
if wt*t>prob:
prob = wt*t
curr_tag = tag
i+=1
tag_seq.append(curr_tag)
return tag_seq
def pos_tag_hmm_unigram_set(sentences):
'''
11490
12612
'''
tag_seq_sentence = []
for s in sentences:
print(s)
tag_seq_sentence.append(pos_tag_hmm_unigram_one_s(s))
return tag_seq_sentence
def b_viterbi(word_seq):
b_word_tag_list = []
b_prob_list = [] #p(w|t)
for word in word_seq:
for tag in pos_list:
b_word_tag_list.append(word+"_"+tag)
b_prob_list.append(prob_w_given_t2(word,tag))
return b_word_tag_list,b_prob_list
def viterbi_hmm(word_seq):#one sent
b_wt,b_prob = b_viterbi(word_seq)
viterbi = []
backpointer = []
tags = []
for pos in pos_list:
tags.append(pos)
for state in pos_list:
viterbi.append([tag_prob_value[tag_prob_tag.index(state)]*b_prob[b_wt.index(word_seq[0].lower()+"_"+state)]])
backpointer.append([-1])
for w in range(1,len(word_seq)):
for t in pos_list:
max_viterbi = -1
max_viterbi_idx = -1
idx_pos= 0
for prev_t in pos_list:
if b_prob[b_wt.index(word_seq[w]+"_"+t)]>0:
score = viterbi[idx_pos][w-1]*prob_t_given_tbev(t,prev_t)*b_prob[b_wt.index(word_seq[w]+"_"+t)]
else:
score = -1
if score>max_viterbi:
max_viterbi = score
max_viterbi_idx = tags.index(prev_t)
idx_pos+=1
t_idx = list(pos_list.keys()).index(t)
viterbi[t_idx].append(max_viterbi)
#print("=="+str(max_viterbi_idx))
backpointer[t_idx].append(max_viterbi_idx)
#print(word_seq[w]+"_"+str(max_viterbi_idx))
#check if all 0
idx_all_pos = 0
while (idx_all_pos<len(pos_list) and viterbi[idx_all_pos][w]==-1):
idx_all_pos+=1
#if all 0
if idx_all_pos==len(pos_list):
possible_tag = listing_word_tags(word_seq[w])
t_idx = 0
for t in possible_tag:
max_viterbi = -1
max_viterbi_idx = tags.index('noun')
idx_pos=0
for prev_t in pos_list:
score = viterbi[idx_pos][w-1]*prob_t_given_tbev(t,prev_t)
if score>max_viterbi:
max_viterbi = score
max_viterbi_idx = tags.index(prev_t)
idx_pos+=1
viterbi[list(pos_list.keys()).index(t)][w]= max_viterbi
backpointer[list(pos_list.keys()).index(t)][w]=max_viterbi_idx
t_idx+=1
#final track
final_track = []
final_tag = []
max_prob = -1
max_id = 0
for t in range(0,len(pos_list)):
if max_prob < viterbi[t][-1]:
max_prob = viterbi[t][-1]
max_id = backpointer[t][-1]
#print(max_id)
final_track.append(max_id) #id_track
final_tag.append(tags[max_id]) #tag_track
#print(final_track[-1])
idx_w = len(viterbi[0])-2
while (idx_w>0):
#print(word_seq[idx_w]+"|")
#print(final_track)
final_track.append(backpointer[final_track[-1]][idx_w])
#final_tag.append(tags[final_track[-1]])
final_tag.insert(0,tags[final_track[-1]])
idx_w-=1
#print(backpointer)
#print(final_tag)
'''
for w in range(0,len(viterbi[0])):
max_prob = 0
max_id = 0
for t in range(0,len(pos_list)):
if max_prob<viterbi[t][w]:
max_prob = viterbi[t][w]
max_id = backpointer[t][w]
final_track.append(max_id)
'''
return final_tag #viterbi
def viterbi_hmm_set(sentences):
'''
10098
12612
'''
tag_seq_sentence = []
for s in sentences:
print(s)
tag_seq_sentence.append(viterbi_hmm(s.split(" ")))
return tag_seq_sentence
sentence_dev = []
i=0
for dev_p in parsed_dev:
i+=1
sentence_dev.append("")
for word in dev_p:
sentence_dev[-1]+=word[0]+" "
'''
print("------------------")
print(sentence_dev)
print("------------------")
prob_w,ori = b_viterbi(sentence_dev[0].split(" "))
for i in range(0,len(ori)):
print(prob_w[i]+" "+str(ori[i]))
'''
#print(viterbi_hmm(sentence_dev[0].split(" ")))
#tags,probs = pos_tag_hmm_bigram_set(parsed,sentence_dev[:1])
#print(sentence_dev[:1])
#tag = (pos_tag_hmm_unigram_set(sentence_dev))
tag = (viterbi_hmm_set(sentence_dev))
corr=0
alle=0
for i in range(0,len(tag)):
for y in range (0,len(parsed_dev[i])):
alle+=1
if tag[i][y]==parsed_dev[i][y][1]:
corr+=1
print(tag)
print(corr)
print(alle)
| 953dd60d6aff75c4d2744c488c70bb31debd7a0b | [
"Python"
] | 2 | Python | sashinovitasari/POS_Tagger | 58d54526b2f0492fb708e3591d634d9b70dd2ad9 | 86ca126345417a4563cee076254794d9b28219d0 |
refs/heads/master | <file_sep>#include "Program.h"
int main(int argc, char* argv)
{
Program program(std::to_string(argv[1]));
program.Run();
}<file_sep>#include "Program.h"
#include <Stream.h>
Program::Program(std::string file_name)
{
this->file_name = file_name;
}
void Program::Run()
{
}
<file_sep>#pragma once
#include <string>
class Program
{
public:
Program(std::string file_name);
void Run();
private:
std::string file_name;
};
| 6313c07ed8d7516fb0efcf1f9536fcf39664b2da | [
"C++"
] | 3 | C++ | prevostcorentin/mla | 3a58b4ffbba3eb8236f01d44767c89dfd7bea856 | 5f884835f58b0db9a401c8491b2b4e5727a35892 |
refs/heads/master | <file_sep>"""App configuration."""
from os import environ
import os
import redis
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
"""Set Flask configuration vars from .env file."""
# General Config
FLASK_APP = environ.get('FLASK_APP')
FLASK_ENV = environ.get('FLASK_ENV')
# Flask-Session
SECRET_KEY = 'you cannot figure out'
SESSION_TYPE = 'filesystem'
SESSION_REDIS = 'redis://127.0.0.1:6379'
# Flask-Assets
LESS_BIN = environ.get('LESS_BIN')
ASSETS_DEBUG = environ.get('ASSETS_DEBUG')
LESS_RUN_IN_DEBUG = environ.get('LESS_RUN_IN_DEBUG')
# Static Assets
STATIC_FOLDER = environ.get('STATIC_FOLDER')
TEMPLATES_FOLDER = environ.get('TEMPLATES_FOLDER')
COMPRESSOR_DEBUG = environ.get('COMPRESSOR_DEBUG')
# Flask-SQLAlchemy
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'user.db')
SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = False<file_sep>#!/usr/bin/python
import sys
sys.path.insert(0, 'xxx/.local/lib/python2.6/site-packages')
from wsgiref.handlers import CGIHandler
from myapp import app
CGIHandler().run(app)
<file_sep>drop table if exists user;
create table user(
user_id integer primary key autoincrement,
username string not null,
email string not null,
pw_hash string not null
);<file_sep>"""Routes for logged-in application."""
from flask import Blueprint, render_template, session,request, Flask, request, session, url_for, redirect, render_template, g, flash
from flask_login import current_user
from flask import current_app as app
from .assets import compile_auth_assets
from flask_login import login_required
import json
from pathlib import Path
# Blueprint Configuration
main_bp = Blueprint('main_bp', __name__,
template_folder='templates',
static_folder='static')
compile_auth_assets(app)
@main_bp.route('/', methods=['GET'])
@login_required
def dashboard():
"""Serve logged in Dashboard."""
session['redis_test'] = 'This is a session variable.'
return render_template('dashboard.html',
title='Flask-Session Tutorial.',
template='dashboard-template',
current_user=current_user,
body="You are now logged in!")
@main_bp.route('/session', methods=['GET'])
@login_required
def session_view():
"""Route which displays session variable value."""
return render_template('session.html',
title='Flask-Session Tutorial.',
template='dashboard-template',
session_variable=str(session['redis_test']))
@main_bp.route('/calendar',methods=['GET'])
@login_required
def calendar_view():
return render_template("index.html")
def return_data():
start_date = request.args.get('start', '')
end_date = request.args.get('end', '')
with open("templates/events.json", "r") as input_data:
return input_data.read()
@main_bp.route('/bus',methods=['GET'])
@login_required
def bus():
return render_template("bus.html")
@main_bp.route('/map',methods=['GET'])
@login_required
def map():
return render_template("new_map.html")
@main_bp.route('/yangsan',methods=['GET'])
@login_required
def yangsan():
return render_template("yangsan.html")
@main_bp.route('/miryang',methods=['GET'])
@login_required
def miryang():
return render_template("miryang.html")
@main_bp.route("/home", methods=["GET", "POST"])
@login_required
def home():
if request.method == "POST":
req = request.form
name = req["name"].lower()
data = read_json('users')
if not name in data:
return render_template('user not found.html', username=name)
return redirect("/home/user/{}".format(name))
return render_template("home.html")
@main_bp.route("/home/user/<name>/")
@login_required
def getUser(name):
data = read_json('users')
if not name in data:
return render_template('user not found.html', username=name)
list = data[name]['timetable']
name = name.title()
cssList = []
for item in list:
if item == "":
cssList.append("")
else:
cssList.append("selected")
return render_template(
'timetable template.html', list=list, cssList=cssList, username=name)
@main_bp.route("/register", methods=["GET", "POST"])
@login_required
def register():
if request.method == "POST":
req = request.form
name = req["name"].lower()
data = read_json('users')
if not name in data:
data[name] = {}
data[name]['timetable'] = []
for item in req:
if item not in ['name']:
data[name]['timetable'].append(req[item])
write_json(data, 'users')
return redirect("/home/user/{}".format(name))
return render_template(
'input form.html',
nameList=['월요일', '화요일', '수요일', '목요일', '금요일'],
idList=['monday8am', 'tuesday8am', 'wednesday8am', 'thursday8am', 'friday8am', 'monday9am', 'tuesday9am', 'wednesday9am', 'thursday9am', 'friday9am', 'monday10am', 'tuesday10am', 'wednesday10am', 'thursday10am', 'friday10am', 'monday11am', 'tuesday11am', 'wednesday11am', 'thursday11am', 'friday11am', 'monday12pm', 'tuesday12pm', 'wednesday12pm', 'thursday12pm', 'friday12pm', 'monday1pm', 'tuesday1pm', 'wednesday1pm', 'thursday1pm', 'friday1pm', 'monday2pm', 'tuesday2pm', 'wednesday2pm', 'thursday2pm', 'friday2pm', 'monday3pm', 'tuesday3pm', 'wednesday3pm', 'thursday3pm', 'friday3pm', 'monday4pm', 'tuesday4pm', 'wednesday4pm', 'thursday4pm', 'friday4pm'],
typeList=['text', 'text', 'text', 'text', 'text'],
placeholder=[' 월요일 과목을 입력하세요', ' 화요일 과목을 입력하세요', ' 수요일 과목을 입력하세요', ' 목요일 과목을 입력하세요', ' 금요일 과목을 입력하세요']
)
def get_path():
cwd = Path(__file__).parents[0]
cwd = str(cwd)
return cwd
def read_json(filename):
cwd = get_path()
with open(cwd+'/'+filename+'.json', 'r') as file:
data = json.load(file)
return data
def write_json(data, filename):
cwd = get_path()
with open(cwd+'/'+filename+'.json', 'w') as file:
json.dump(data, file, indent=4)
@login_required
@main_bp.route('/school')
def school():
return render_template('school.html')<file_sep>{% extends "layout.html" %}
{% block title %}회원 등록{% endblock %}
{% block body %}
<h2>사용자 등록</h2>
{% if error %}
<div class=error><strong></strong>{{error}}</div>
{% endif %}
<form action="" method="post">
<dl>
<dt>사용자 이름 : </dt>
<dd><input type="text" name = "username" size=30 value = "{{request.form.username}}"/></dd>
<dt>E-mail : </dt>
<dd><input type="text" name = "email" size=30 value = "{{request.form.email}}"/></dd>
<dt>비밀번호 : </dt>
<dd><input type="<PASSWORD>" name = "password" size=30/></dd>
<dt>비밀번호 확인 : </dt>
<dd><input type="<PASSWORD>" name = "<PASSWORD>" size=30></dd>
</dl>
<div class = actions><input type=submit value = "등록하기" /></div>
</form>
{% endblock %}<file_sep>Recently, because of the Covid-19 Virus, a freshman has entered, but he is attending classes at home without attending school.
When I enrolled in the second semester, I thought it would be helpful to know the location of the classroom in class
and the route to the classroom when preparing the timetable. So, we added timetable function, map circulation function,
and circular bus notification function, and added a calendar function to know the school schedule.
| bb5673531f3e34861d9d41792d4fb92f09dc9187 | [
"SQL",
"Python",
"Text",
"HTML"
] | 6 | Python | ohdowon064/timetable_web | 9d5065ed36c27d7c7080ff0ad2983bc151b0f699 | 7db454bda67e68c86b4468472ac58fc517a790f0 |
refs/heads/development | <file_sep># frozen_string_literal: true
# Services: Module ChecklistService and its Class SetAuditData
module ChecklistService
class SetAuditData < ApplicationService
def initialize(checklist)
@checklist = checklist
end
def call
unless @checklist.audit
@checklist.build_audit
else
@checklist.audit.touch
end
@checklist
end
end
end
<file_sep># frozen_string_literal: true
Rails.application.routes.draw do
devise_for :users
resources :audits
resources :checklists do
resource :audit
get :switch_publishing_status, on: :member
get :add_audit_fields, on: :member
patch :update_audit_fields, on: :member
end
root 'checklists#index'
get '*path', to: 'checklists#index'
end
<file_sep># frozen_string_literal: true
class Audit < ApplicationRecord
belongs_to :checklist
belongs_to :user, optional: true
end
<file_sep># frozen_string_literal: true
# Controller for user sees the list of checklists
class ChecklistsController < ApplicationController
before_action :set_checklist, only: [:show, :edit, :update,
:add_audit_fields, :update_audit_fields,
:switch_publishing_status, :destroy]
def index
@checklists = Checklist.page(params[:page]).per(10)
end
def new
@checklist = Checklist.new
@checklist.questions.build
end
def create
@checklist = Checklist.new(checklist_params)
if @checklist.save
redirect_to checklists_url, notice: 'Checklist was successfully created.'
else
render :new
end
end
def show; end
def edit
end
def update
if @checklist.update(checklist_params)
redirect_to @checklist, notice: 'Checklist was successfully updated.'
else
render :edit
end
end
def add_audit_fields
end
def update_audit_fields
@checklist = ChecklistService::SetAuditData.call(@checklist)
if @checklist.update(checklist_params)
redirect_to audits_path, notice: 'Audit was successfully created.'
else
render :add_audit_fields
end
end
def switch_publishing_status
@checklist.published = !@checklist.published
@status_ar = ['Unpublish', 'Publish']
@checklist.next_publish_status = @status_ar.delete(@checklist.next_publish_status)
@checklist.next_publish_status = @status_ar[0]
@checklist.save
redirect_to checklist_path(@checklist), notice: 'Checklist Status was successfully updated.'
end
def destroy
@checklist.destroy
redirect_to checklists_url, notice: 'Checklist was successfully destroyed.'
end
private
def set_checklist
@checklist = Checklist.find(params[:id])
end
# Only allow a list of trusted parameters through.
def checklist_params
params
# .require(:checklist)
# .permit(:title, :description,
# questions_attributes: [:id, :checklist_id, :title, :description, :created_at,
# :updated_at, :answer, :comment, :skip_validation, :_destroy,
# answer: [:answer, :comment, :id, :question_id, :_destroy]])
params
.require(:checklist)
.permit(:title, :description,
questions_attributes: Question.attribute_names.map(&:to_sym).push(:_destroy))
end
end
<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :checklists
has_many :audits
validates :email, length: { maximum: 50 }
end
<file_sep># frozen_string_literal: true
class Question < ApplicationRecord
# has_many :answer, dependent: :destroy
belongs_to :checklist, optional: true
# accepts_nested_attributes_for :answer
validates :title, presence: true, length: { minimum: 12, maximum: 40 }
validates :description, presence: true
end
<file_sep># frozen_string_literal: true
class Checklist < ApplicationRecord
has_many :questions, dependent: :destroy
has_one :audit
has_one :answer, through: :questions
belongs_to :user, optional: true
accepts_nested_attributes_for :questions,
allow_destroy: true
# , reject_if: proc { |att| att['title'].blank? }
validates :title, presence: true, length: { maximum: 40 }
validates :description, presence: true
end
<file_sep># frozen_string_literal: true
# Controller for user sees the list of audits
class AuditsController < ApplicationController
before_action :set_audit, only: [:show, :destroy]
def index
@audits = Audit.page(params[:page]).per(10)
@checklists = Checklist.where published: true
end
def show
@checklist = Checklist.find(@audit.checklist_id)
end
def destroy
@audit.destroy
redirect_to audits_path, notice: 'Audit was successfully destroyed.'
end
private
def set_audit
@audit = Audit.find(params[:id])
end
# Only allow a list of trusted parameters through.
def checklist_params
params
.require(:checklist)
.permit(:title, :description,
questions_attributes: Question.attribute_names.map(&:to_sym).push(:_destroy))
end
end
<file_sep>class Answer < ApplicationRecord
belongs_to :question, optional: true
validates :answer, presence: true
validates :comment, presence: true, length: { minimum: 12 }
end
| 3b3ecf252998989439e824058d17d4e4e9b3209b | [
"Ruby"
] | 9 | Ruby | VitalinaLiane8/ssandbox | e23589059bbd585f20444165ba2c345eb7347dc8 | 3cfed475f36ed1e8bfe8b79d871f6566dcfe776a |
refs/heads/master | <repo_name>gartenkarte/unfairtobaccomap<file_sep>/testing.js
if(L.Browser.retina) var tp = "lr";
else var tp = "ls";
var lyrk = L.tileLayer('http://tiles.lyrk.org/'+tp+'/{z}/{x}/{y}?apikey=701dcc16672d4781b03ca506db3ef046', {
attribution: '<a href="http://geodienste.lyrk.de/copyright">Lizenzinformationen</a>, Tiles by <a href="http://geodienste.lyrk.de/">Lyrk</a>',
maxZoom: 18
});
var map = L.map('map', {
layers: [lyrk]
}).setView( new L.LatLng(20, 10), 2);
// POPUPS
function createModal(geojson) {
var modal = document.createElement("div");
var modal_url = geojson.properties.name.replace(/ /g,"-").replace(/[^a-zA-Z0-9 -]/g, '').toLowerCase();
modal.id = modal_url;
modal.className = "modal fade";
modal.innerHTML = '<div class="modal-dialog"><div class="modal-content"><div class="modal-header"><a href="#"><button>×</button></a><h2 class="modal-title">'+ geojson.properties.name +'</h2></div><div class="modal-body"><p>'+ geojson.properties.desc +'</p><p>'+geojson.properties.mail+'</p><p>'+geojson.properties.url+'</p></div></div></div>';
document.body.appendChild(modal);
}
function renderPopup(feature, url) {
partial_head = '<h2>'
if (feature.properties.url != '') {
link_start = '<a href="'+ feature.properties.url +'">';
link_end = '</a>'
}
else {
link_start = '';
link_end = '';
}
partial_foot = '</h2><br><a href="#'+ url +'">Read more</a>';
return partial_head + link_start + feature.properties.name + link_end + partial_foot;
}
function OnEachFeature(feature, layer){
if (feature.properties && feature.properties.name) {
var url = feature.properties.name.replace(/ /g,"-").replace(/[^a-zA-Z0-9 -]/g, '').toLowerCase();
createModal(feature);
/* layer.bindPopup(renderPopup(feature, url)
); */
/* layer.on('mouseover', function () {
this.openPopup();
});
layer.on('mouseout', function () {
this.closePopup();
});
*/
/* http://lea.verou.me/2011/05/change-url-hash-without-page-jump/ */
layer.on('click', function () {
/* this.openPopup(); */
/* if(history.pushState) {
history.pushState(null, null, '#' + url);
}
else { */
location.hash = '#' + url;
/*}*/
});
}
};
/*
function OnEachFeature(feature, layer){
if (feature.properties.name) {
layer.bindPopup('<b>' + feature.properties.name + '</b>' + '<br>' +
feature.properties.desc + '<br>' +
'<b>' + 'Website: ' + '</b>' + feature.properties.url + '<br>' +
'<b>' +'Contact: ' + '</b>' + feature.properties.mail
);
}
};
*/
function condense_geojson_locations ( element ) {
var callback = [];
callback[0] = unfairtobacco.locations[element].longitude;
callback[1] = unfairtobacco.locations[element].latitude;
//console.log(callback);
return callback;
}
function replace_geojson_locations ( element ) {
var copy = $.extend(true, {}, element, copy);
copy.locations = $.map(element.locations, condense_geojson_locations);
return copy;
}
function render_to_geojson ( projects ) {
var geojson_projects = {};
geojson_projects['type'] = 'FeatureCollection';
geojson_projects['features'] = [];
for (var k in projects) {
var obj = projects[k];
if (obj.locations[0] != null) {
var newFeature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": replace_geojson_locations(obj).locations
},
"properties": {
"id": projects[k].ID,
"name": projects[k].name,
"desc": projects[k].description,
"url": projects[k].website_url,
"mail": projects[k].contact_email,
"orgs": projects[k].organisations,
"areas": projects[k].countries
}
};
geojson_projects['features'].push(newFeature);
};
};
return geojson_projects;
}
var unfairtobacco;
var projekte_geojson;
$.getJSON( "data.json", function( data ) {
unfairtobacco = data;
projekte_geojson = render_to_geojson(unfairtobacco.projects);
console.log(projekte_geojson);
var Layer_project = L.geoJson(projekte_geojson, {
onEachFeature: OnEachFeature
}).addTo(map);
});
///////////////// hinzufügen der Länder-GEOJSONs
var countries_ISO = [];
var countries_meta = [];
// erstellt Array mit ISO-Daten der verwiesenen Länder
function iso_render_to_array ( countries ) {
for (var k in countries) {
var obj = countries[k];
if (obj.iso_code != null) {
countries_ISO.push(countries[k]);
};
};
return countries_ISO;
}
function CreateCountryCallback(unfair) {
return function (geojson) {
merge_unfair_countries(geojson, unfair);
};
}
function merge_unfair_countries(geojson, unfair) {
var merge = $.extend(true, {}, geojson.features[0].properties, unfair)
console.log(merge);
var Layer_countries = L.geoJson(geojson, {
style: style,
//TODO onEachFeature: OnEachCountryFeature
}).addTo(map);
};
// get geoJSON anhand des ISO-Array
function get_And_Merge_Countries_to_geoJSON ( array ) {
var countriesMerged = {};
var country = {};
for (i = 0; i <= array.length; ++i) {
if ( array[i] != null) {
// http://stackoverflow.com/questions/6129145/pass-extra-parameter-to-jquery-getjson-success-callback-function
$.getJSON("countries/" + array[i].iso_code.toLowerCase() + ".geojson", CreateCountryCallback(array[i]));
}
};
}
var unfairtobaccoCountries;
var arrayCountries;
var geoJsonCountries = {};
$.getJSON( "data.json", function( data ) {
unfairtobacco = data;
arrayCountriesISO = iso_render_to_array(unfairtobacco.countries);
get_And_Merge_Countries_to_geoJSON(arrayCountriesISO);
});
/////////// Länder hervorhoben
function style(feature) {
return {
fillColor: 'red',
weight: 1,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.8
};
}<file_sep>/readme.md
# unfairtobaccomap
Dies ist die wunderschöne Tabakkarte<file_sep>/merge.js
var map = L.map('map').setView( new L.LatLng(20, 10), 2);
var toner = new L.StamenTileLayer("toner");
map.addLayer(toner);
var baseLayers = {
"Toner": toner
};
// ########## //
// get data
//var unfairtobacco =
$.getJSON( "data.json", function( data ) {
//console.log(data)
unfairtobacco = data;
//var unfairtobacco = data;
//return obj;
}
);
/*
var unfairtobacco = getJson();
function getJson(){
var result =
$.getJSON( "data.json", function( data ){
result = data;
});
return result;
};
*/
//var projects = new Object();
//var projects = unfairtobacco["projects"];
//var json = JSON.parse(unfairtobacco);
//projects.ID = unfairtobacco.projects.ID
// ########## //
// GeoJSON für Projekte aus unfairtobacco (Struktur siehe Beispiel)
/*
var geojson_projects = {};
geojson['type'] = 'FeatureCollection';
geojson['features'] = [];
for (var k in projects) {
var newFeature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": parseFloat(projects[k].coordinates[0]), parseFloat(projects[k].coordinates[1])]
},
"properties": {
"title": projects[k].name,
"description": projects[k].description
}
}
geojson['features'].push(newFeature);
};
*/
// Beispiel manuell
var geojson_projects =
{
"type": "FeatureCollection",
"features":
[
{
"type": "Feature",
"properties":
{
"name":"<NAME>",
"description":"BlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtextBlindtext",
"website_url":"www.tobaccotobamboo.org",
"contact_email":"<EMAIL>",
"iso_code":"KE",
},
"geometry":
{
"type": "Point",
"coordinates": [37.99521440000001, -1.3750813]
}
},
]
};
// ########## //
// LAYER Projekte
var Layer_project = L.geoJson(geojson_projects, {
onEachFeature: OnEachFeatureFunction
}).addTo(map);
// MIT IF ELSE
//if (Layer_project)
// event hover
function OnEachFeatureFunction(feature, marker){
if (feature.properties.name) {
marker.bindPopup('<b>' + feature.properties.name + '</b>'
);
marker.on('mouseover', function () {
this.openPopup();
});
marker.on('mouseout', function () {
this.closePopup();
});
}
};
/*
// event click on
function OnEachFeatureFunction(feature, marker){
if (feature.properties.description) {
marker.bindPopup('<b>' + feature.properties.name + '</b>' + '<br>' +
feature.properties.description + '<br>' +
'Website: ' + feature.properties.website_url + '<br>' +
'Contact: ' + feature.properties.contact_email
);
}
};
*/ | b497f17327d1f591ba52694651e879a06efc0868 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | gartenkarte/unfairtobaccomap | 7081e7d14172fccfb93c5057149dc103f59cbc18 | a43115c3f8020d695639ed754da4b917e0cec348 |
refs/heads/master | <file_sep>## Loading Data From Text File
HPC <- read.csv("F:/RWorkingDir/household_power_consumption.txt", sep=";", header=TRUE)
## Creating Subset of the data for date '2007-02-01' and '2007-02-02'
x <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-01')
y <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-02')
data <- rbind(x,y)
## Creating Plot2 in Plot2.png
png('plot2.png', width = 480, height = 480)
datetime <- paste(data$Date,'-',data$Time)
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),as.numeric(data$Global_active_power),xlab="", ylab='Global Active Power (killowatts)', type='o', pch=27)
dev.off()
<file_sep>## Loading Data From Text File
HPC <- read.csv("F:/RWorkingDir/household_power_consumption.txt", sep=";", header=TRUE)
## Creating Subset of the data for date '2007-02-01' and '2007-02-02'
x <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-01')
y <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-02')
data <- rbind(x,y)
datetime <- paste(data$Date,'-',data$Time)
## Creating Plot3 in Plot3.png
png('plot3.png', width = 480, height = 480)
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_1 , type = 'n', ylab='Energy sub metering',xlab="")
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_1, type='o', pch=32, col='Black')
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_2, type='o', pch=32, col='Red')
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_3, type='o', pch=32, col='Blue')
legend('topright', c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"), lty=c(1,1,1), lwd=c(2.5,2.5,2.5), col=c("Black","red", "blue"))
dev.off()<file_sep>## Loading Data From Text File
HPC <- read.csv("F:/RWorkingDir/household_power_consumption.txt", sep=";", header=TRUE)
## Creating Subset of the data for date '2007-02-01' and '2007-02-02'
x <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-01')
y <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-02')
data <- rbind(x,y)
datetime <- paste(data$Date,'-',data$Time)
## Creating Plot3 in Plot3.png
png('plot4.png', width = 480, height = 480)
par(mfrow = c(2,2))
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),as.numeric(data$Global_active_power),xlab="", ylab='Global Active Power (killowatts)', type='o', pch=27)
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),as.numeric(data$Voltage), xlab='datetime', ylab='Voltage', type='o', pch=27)
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_1 , type = 'n', ylab='Energy sub metering',xlab="")
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_1, type='o', pch=32, col='Black')
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_2, type='o', pch=32, col='Red')
points(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),data$Sub_metering_3, type='o', pch=32, col='Blue')
legend('topright', c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"), lty=c(1,1,1), lwd=c(2.5,2.5,2.5), col=c("Black","red", "blue"))
plot(strptime(datetime,format='%d/%m/%Y - %H:%M:%S'),as.numeric(data$Global_reactive_power), ylab='Global_reactive_power', xlab='datetime', type='o', pch=27 )
dev.off()<file_sep>## Loading Data From Text File
HPC <- read.csv("F:/RWorkingDir/household_power_consumption.txt", sep=";", header=TRUE)
## Creating Subset of the data for date '2007-02-01' and '2007-02-02'
x <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-01')
y <- subset(HPC, as.Date(Date,format='%d/%m/%Y') == '2007-02-02')
data <- rbind(x,y)
## Creating Plot1 in Plot1.png
png('plot1.png', width = 480, height = 480)
hist(as.numeric(data$Global_active_power), col='Red', main='Global Active Power',xlab='Global Active Power (killowatts)')
dev.off() | ff924869619c7c708d3298455dafd9b477ff2e8a | [
"R"
] | 4 | R | ApurbaPandey/ExData_Plotting1 | 01070fe2fe3f5defc8e4454fe85db60f636ffd1e | 97c347dca5220064da61969d313cc475066f3a48 |
refs/heads/main | <file_sep><?php
include('includes/tabledata.php');
?>
<html>
<head>
<title>RESERVATION </title>
<link rel="stylesheet" type="text/css" href="css/table.css">
</head>
<body>
<div class="main">
<div class="logo">
<img src="logo.png">
</div>
<ul>
<li><a href="bb.html">Home</a></li>
<li><a href="pallex.html">Menu</a></li>
<li><a href="gal1.html">Gallery</a></li>
<li><a href="#">Account</a>
<ul>
<li><a href="login.html">login</a></li>
<li><a href="signups.html">signup</a></li></ul>
<li><a href="about.html">About</a></li>
</ul>
</li>
</ul>
</div>
<header>
<div class="reser"><h1>
<span>R</span>
<span>E</span>
<span>S</span>
<span>E</span>
<span>R</span>
<span>V</span>
<span>A</span>
<span>T</span>
<span>I</span>
<span>O</span>
<span>N</span>
</h1></div>
<div class="pause1">
<p><font color="white">__________</font><font color="darkred">♥♥</font><font color="white">__________</font></p>
</div>
</header>
<div>
<div class="section">
<div><p>Tel: 201122543<br>
E-Mail: <EMAIL></p></div>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3410.812548008813!2d75.70148031514414!3d31.253612153317544!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x391a5a594d22b88d%3A0x4cc934c58d0992ec!2sLovely+Professional+University!5e0!3m2!1sen!2sin!4v1554561003816!5m2!1sen!2sin" width="600" height="430" frameborder="0" style="border:0" allowfullscreen> </iframe>
</div>
</div>
<div class="form">
<fieldset><legend>CONTACT DETAILS</legend>
<form action="table.php" method="POST">
<div>
<label for="text">Name:</label>
<input type="text" name="name" >
</div>
<div >
<label for="text">Email:</label>
<input type="text" name="email" >
</div>
<div >
<label for="text">Phone:</label>
<input type="text" name="phn" >
</div>
</fieldset>
</div>
<div class="cont">
<fieldset>
<legend>BOOK A TABLE</legend>
Date: <input type="date" name="date">
<div>
Time: <input type="time" name="time">
</div>
<div>
Member: <input type="number" name="mem">
</div>
<div class="submit">
<input type="submit" name="submit" value="REQUEST BOOKING">
</div>
</form>
</fieldset>
</div>
<div>
</div>
<div>
<footer class="footer">
<div class="pause">
<p><font color="white">__________♥♥__________</font></p>
</div>
<div class="menu2">
<ul>
<li><a href="bb.html">Home |</a></li>
<li><a href="pallex.html">Menu |</a></li>
<li><a href="about.html">About |</a></li>
<li><a href="#">Account |</a>
<ul>
</ul>
</div>
</footer>
<div class="log">
<img src="lo.png">
</div>
</div>
</body>
</html><file_sep># ujjwal-kumar-tiwari-int219-project<file_sep><html>
<head>
<title>MENU</title>
<link rel="stylesheet" type="text/css" href="css/menu.css">
</head>
<body>
<div class="menu">
<ul>
<li><font color="red">♥</font> Chaat papdi</li>
<li>Fried papdi mixed with onions, tomatoes, mint, tamarind & yogurt</li>
<li>$3.99</li>
</ul>
<ul>
<li><font color="red">♥</font> Chana Chaat</li>
<li>Chickpeas mixed with onions, tomatoes, mint, tamarind & yogurt</li>
<li>$3.99</li>
</ul>
<ul>
<li><font color="red">♥</font>Vegetable Pakora</li>
<li>Mixed vegetables dipped in chickpea batter and deep fried</li>
<li>$3.99</li>
</ul>
</div>
</body> | 5986c00dcae5dbc480a990bcb413e9f51606d411 | [
"Markdown",
"HTML",
"PHP"
] | 3 | PHP | ujjwaltiwari07/ujjwal-kumar-tiwari-int219-project | ae2c98c5ee1e5a6b61156a950774aca03e1f0e4a | 28c78c5fd77df7630145ef2bb7ee1524ee7ab85d |
refs/heads/main | <file_sep>const Joi = require("joi");
Joi.objectId = require("joi-objectid")(Joi);
const mongoose = require("mongoose");
const startupDebugger = require("debug")("app:startup");
const dbDebugger = require("debug")("app:db");
const config = require("config");
const helmet = require("helmet");
const morgan = require("morgan");
const logger = require("./middleware/logger");
const genres = require("./routes/genres");
const customers = require("./routes/customers");
const express = require("express");
const { urlencoded } = require("express");
const app = express();
mongoose
.connect("mongodb://localhost/video-service")
.then(() => {
console.log("Connected to MongoDb...");
})
.catch((err) => {
console.error("Could not connect to MongoDB...", err);
});
//Set environment on node using the following
//export NODE_ENV=production (On Terminal)
//Code to run only on development
if (app.get("env") === "development") {
app.use(morgan("tiny"));
startupDebugger("Morgan enabled...");
}
//Db work...
dbDebugger("Connected to the database");
console.log("Application Name: " + config.get("name"));
// console.log("Mail Server: " + config.get("mail.host"));
// console.log("Mail Server: " + config.get("mail.password"));
//Middleware Function
//Built in middleware functions
app.use(express.json()); //req.body
app.use(express.urlencoded()); //when submitting form information through a URL (req.body)
//app.use(express.urlencoded({ extended: true })); //allows extended data through forms such as arrays
app.use(express.static("public")); //serve static assets
//Custom imported Middleware function
app.use(logger);
app.use("/api/genres", genres);
app.use("/api/customers", customers);
// //Creating a Custom Middleware Function (Moved to seperate Module)
// app.use((req, res, next) => {
// console.log("Logging..");
// next();
// });
app.use((req, res, next) => {
console.log("Authenticating..");
next();
});
//Third-party Middleware functions
app.use(helmet()); //Helps secure your apps by setting various HTTP headers
// app.use(morgan("tiny")); //HTTP request logger
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
<file_sep># node-js-sample
Sample Code for Node.js
<file_sep>//Used for Unit Testing
//Resolved Promise
const p = Promise.resolve({ id: 1 });
p.then((result) => console.log(result));
//Rejected Promise
const r = Promise.reject(new Error("Reason for rejection"));
r.catch((error) => console.log(error));
<file_sep>//Trade off between query performace vs consistency
// Using References (Normalization) -> Consistency
let author = {
name: "Cristian",
};
let course = {
author: "_id",
};
// Using Embedded Documentents (Denormalization) -> PERFORMANCE
let course = {
author: {
name: "Cristian",
},
};
// Hybrid Apporach
let author = {
name: "Cristian",
//50 other properties
};
let course = {
author: {
id: "ref", //-> to author document
name: "Cristian",
},
};
<file_sep>const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost/playground")
.then(() => {
console.log("Connected to MongoDB...");
})
.catch((err) => console.error("Could not connect to MongoDB...", err));
//Define Schema
const courseSchema = new mongoose.Schema({
//String
//Number
//Date
//Buffer
//Boolean
//ObjectID
//Array
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
});
//Convert Models
const Course = mongoose.model("Course", courseSchema);
async function getCoursesUsingQueryComparisonOperators() {
//Comparison query operators
// eq (equal)
// ne (not equal)
// gt (greater than)
// gte (greater than or equal to)
// lt (less than)
// n
// nin (not in)
const courses = await Course.find({ price: { $in: [10, 15, 20] } })
// .find({ price: { $gte: 10, $lte: 20 } })
.limit(10)
.sort({ name: 1 })
.select({ name: 1, tags: 1 });
console.log(courses);
}
<file_sep>const { Genre, validate } = require("../models/customer");
const express = require("express");
const router = express.Router();
//Route Handler Functions (Considered a Middleware Function)
router.get("/", async (req, res) => {
const genres = await Genre.find({}).sort("name");
res.send(genres);
});
router.post("/", async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = new Genre({ name: req.body.name });
await genre.save();
res.send(genre);
});
router.put("/:id", async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findByIdAndUpdate(
req.params.id,
{ name: req.body.name },
{ new: true }
);
// const genre = genres.find((c) => c.id === parseInt(req.params.id));
if (!genre)
return res.status(404).send("The genre with the given ID was not found.");
res.send(genre);
});
router.delete("/:id", async (req, res) => {
// const genre = genres.find((c) => c.id === parseInt(req.params.id));
const genre = await Genre.findByIdAndRemove(req.params.id);
if (!genre)
return res.status(404).send("The genre with the given ID was not found.");
res.send(genre);
});
router.get("/:id", async (req, res) => {
const genre = await Genre.findById(req.params.id);
if (!genre)
return res.status(404).send("The genre with the given ID was not found.");
res.send(genre);
});
module.exports = router;
<file_sep>const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost/playground")
.then(() => {
console.log("Connected to MongoDB...");
})
.catch((err) => console.error("Could not connect to MongoDB...", err));
//Define Schema
const courseSchema = new mongoose.Schema({
//String
//Number
//Date
//Buffer
//Boolean
//ObjectID
//Array
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
});
//Convert Models
const Course = mongoose.model("Course", courseSchema);
//Pagination
async function getCoursesPagination() {
const pageNumber = 2;
const pageSize = 10;
const courses = await Course.find({ author: "Cristian", isPublished: true })
.skip((pageNumber - 1)(pageSize))
.limit(pageSize)
.sort({ name: 1 })
.count();
console.log(courses);
}
<file_sep>const os = require("os");
var totalMemory = os.totalmem;
var freeMemory = os.freemem;
//console.log("Total Memory: " + totalMemory);
console.log(`Total Memory: ${totalMemory}`);
console.log(`Total Memory: ${freeMemory}`);
<file_sep>const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost/playground")
.then(() => {
console.log("Connected to MongoDB...");
})
.catch((err) => console.error("Could not connect to MongoDB...", err));
//Define Schema
const courseSchema = new mongoose.Schema({
//String
//Number
//Date
//Buffer
//Boolean
//ObjectID
//Array
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
});
//Convert Models
const Course = mongoose.model("Course", courseSchema);
//Creating and Saving Documents using Mongoose
async function createCourse() {
const course = new Course({
name: "Node.js Course",
author: "Cristian",
tags: ["node", "backend"],
isPublished: true,
});
const result = await course.save();
console.log("Result ", result);
}
createCourse();
| ef41180dce739308e7c70dee6c1a46efa55e2077 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | cristian-custodio/node-js-sample | 390d36ebe2503600392d0431fb51dc755c50272f | 40781bb425cc962686f8b015b6097852cceb9e89 |
refs/heads/master | <file_sep>package Collision;
import Sprites.Craft;
import Sprites.Missile;
import javax.accessibility.AccessibleIcon;
import javax.swing.*;
import javax.tools.Tool;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
/**
* Created by h3dg3wytch on 4/3/16.
*/
public class CollisonBoard extends JPanel implements ActionListener {
private final int ICRAFT_X = 40;
private final int ICRAFT_Y = 60;
private final int B_WIDTH = 400;
private final int B_HEIGHT = 300;
private final int DELAY = 15;
private Timer timer;
private SpaceShip spaceShip;
private ArrayList<Alien> aliens;
private boolean ingame;
private final int[][] pos = {
{2380, 29}, {2500, 59}, {1380, 89},
{780, 109}, {580, 139}, {680, 239},
{790, 259}, {760, 50}, {790, 150},
{980, 209}, {560, 45}, {510, 70},
{930, 159}, {590, 80}, {530, 60},
{940, 59}, {990, 30}, {920, 200},
{900, 259}, {660, 50}, {540, 90},
{810, 220}, {860, 20}, {740, 180},
{820, 128}, {490, 170}, {700, 30}
};
public CollisonBoard(){
initBoard();
}
private void initBoard() {
addKeyListener(new CollisonAdapter());
setFocusable(true);
setBackground(Color.black);
ingame = true;
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
spaceShip = new SpaceShip(ICRAFT_X, ICRAFT_Y);
initAliens();
timer = new Timer(DELAY, this);
timer.start();
}
private void initAliens() {
aliens = new ArrayList<Alien>();
for(int[] p : pos){
aliens.add(new Alien(p[0], p[1]));
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(ingame){
drawObjects(g);
}else{
drawGameOver(g);
}
Toolkit.getDefaultToolkit().sync();
}
private void drawGameOver(Graphics g) {
String message = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics fm = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(message, (B_WIDTH - fm.stringWidth(message)) / 2, B_HEIGHT / 2);
}
private void drawObjects(Graphics g) {
if(spaceShip.isVisible()){
g.drawImage(spaceShip.getImage(), spaceShip.getX(), spaceShip.getY(), this);
}
ArrayList<Missile> missiles = spaceShip.getMissiles();
for(Missile m: missiles){
if(m.isVisible()){
g.drawImage(m.getImage(), m.getX(), m.getY(), this);
}
}
for(Alien a : aliens){
if(a.isVisible()){
g.drawImage(a.getImage(), a.getX(), a.getY(), this);
}
}
g.setColor(Color.WHITE);
g.drawString("Aliens left: " + aliens.size(), 5, 15);
}
@Override
public void actionPerformed(ActionEvent e) {
inGame();
updateSpaceship();
updateMissiles();
updateAliens();
checkCollisions();
repaint();
}
private void inGame() {
if(!ingame){
timer.stop();
}
}
private void updateSpaceship() {
if(spaceShip.isVisible()){
spaceShip.move();
}
}
private void updateMissiles(){
ArrayList<Missile> list = spaceShip.getMissiles();
for(int i = 0; i < list.size(); i++){
Missile m = list.get(i);
if(m.isVisible()){
m.move();
}else{
list.remove(i);
}
}
}
private void updateAliens() {
}
private void checkCollisions() {
}
private class CollisonAdapter implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
//Nothing to see here, keep it moving
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
}
<file_sep>package Basics;
import javax.swing.*;
import java.awt.*;
/**
* Created by h3dg3wytch on 4/3/16.
*/
public class Application extends JFrame {
public Application(){
initUI();
}
private void initUI() {
//Entry point of the game
add(new Board());
//Pu the board in the center of the Jframe container
setSize(250, 200);
setTitle("App");
//Sets the size of the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Centers the window on the screen
setLocationRelativeTo(null);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Application ex = new Application();
ex.setVisible(true);
}
});
}
}
<file_sep>package Sprites;
/**
* Created by h3dg3wytch on 4/3/16.
*/
public class Missile extends Sprite {
private final int BOARD_WIDTH = 390;
private final int MISSILE_SPEED = 2;
public Missile(int x, int y){
super(x,y);
initMissile();
}
private void initMissile() {
loadImage("star.png");
getImageDimensions();
}
//Missile moves at constant speed. When it hits the right border of the board,
//it becomes invisble. It is then removed from the list of missles.
public void move(){
x += MISSILE_SPEED;
if(x > BOARD_WIDTH){
vis= false;
}
}
}
<file_sep>package Sprites;
import javax.swing.*;
import javax.tools.Tool;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
/**
* Created by h3dg3wytch on 4/3/16.
*/
public class MissileExample extends JPanel implements ActionListener {
private final int ICRAFT_X = 40;
private final int ICRAFT_Y = 60;
private final int DELAY = 10;
private Timer timer;
private Craft craft;
public MissileExample(){
initBoard();
}
private void initBoard() {
addKeyListener( new MissileAdapter());
setFocusable(true);
setBackground(Color.black);
setDoubleBuffered(true);
craft = new Craft(ICRAFT_X, ICRAFT_Y);
timer = new Timer(DELAY, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(), this);
ArrayList<Missile> list = craft.getMissiles();
for(Missile missile : list){
g2d.drawImage(missile.getImage(), missile.getX(), missile.getY(), this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
updateMissiles();
updateCraft();
repaint();
}
private void updateCraft() {
craft.move();
}
private void updateMissiles() {
ArrayList<Missile> list = craft.getMissiles();
for(int i = 0; i < list.size(); i++){
if(list.get(i).isVisible()){
list.get(i).move();
}else{
list.remove(i);
}
}
}
private class MissileAdapter implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
//Do nothing
}
@Override
public void keyPressed(KeyEvent e) {
craft.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
craft.keyReleased(e);
}
}
}
| fd721cb9c0d98d59b56d54791043ef45f02f792f | [
"Java"
] | 4 | Java | h3dg3-Wytch/Java-2d-Games | 2d9dde5601334a581fd8d4c2d14fc68c27ffef07 | 1fae9f130c68f6ea0400dc3cb1da3d5d50922bd2 |
refs/heads/master | <file_sep>package maybe
import (
"encoding/json"
"math"
)
// Float64 is an option type: it is either Some (a float64) or None
type Float64 struct {
Some float64
None bool
}
// NewFloat64 creates a Float64 from value. If the given value is NaN then it is
// assigned as None, which will be serialised as `null` in json.
func NewFloat64(value float64) Float64 {
if math.IsNaN(value) {
return Float64{None: true}
}
return Float64{Some: value, None: false}
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Float64) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
<file_sep>module github.com/dangreenhalgh/maybe
go 1.14
<file_sep>package maybe
import (
"encoding/json"
)
// Int is an option type: it is either Some (an int) or None
type Int struct {
Some int
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Int) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
// Int8 is an option type: it is either Some (an int8) or None
type Int8 struct {
Some int8
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Int8) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
// Int16 is an option type: it is either Some (an int16) or None
type Int16 struct {
Some int16
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Int16) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
// Int32 is an option type: it is either Some (an int32) or None
type Int32 struct {
Some int32
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Int32) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
// Int64 is an option type: it is either Some (an int64) or None
type Int64 struct {
Some int64
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Int64) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
<file_sep>package maybe
import (
"encoding/json"
"time"
)
// Time is an option type: it is either Some (a time.Time) or None
type Time struct {
Some time.Time
None bool
}
// MarshalJSON implements the Marshaller interface. Decodes None values to `null`.
func (o Time) MarshalJSON() ([]byte, error) {
if o.None {
return json.Marshal(nil)
}
return json.Marshal(o.Some)
}
<file_sep># Maybe
Maybe types for Go
This is a work-in-progress and only covers a few built-in types.
## Usage
```go
package main
import (
"encoding/json"
"fmt"
"math"
"github.com/dangreenhalgh/maybe"
)
func main() {
someInt := maybe.Int{Some: 4}
noneInt := maybe.Int{None: true}
someIntAsJSON, _ := json.Marshal(someInt)
noneIntAsJSON, _ := json.Marshal(noneInt)
fmt.Printf("%v\n", string(someIntAsJSON))
fmt.Printf("%v\n", string(noneIntAsJSON))
someFloat64 := maybe.NewFloat64(123.456)
noneFloat64 := maybe.NewFloat64(math.NaN())
someFloat64AsJSON, _ := json.Marshal(someFloat64)
noneFloat64AsJSON, _ := json.Marshal(noneFloat64)
fmt.Printf("%v\n", string(someFloat64AsJSON))
fmt.Printf("%v\n", string(noneFloat64AsJSON))
}
```
```
4
null
123.456
null
``` | ac0d8db0ae0ebb0d1de74a0ae9bf7286d2378205 | [
"Markdown",
"Go Module",
"Go"
] | 5 | Go | dangreenhalgh/maybe | fe71a89171a9d7b87263ff0f9ad990f76c8fa4d0 | 233865390af3b15da4a3ecada79e2482ab98e9d6 |
refs/heads/master | <file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <cstdlib>
#include <random>
#include "Randoms.h"
using namespace std;
std::default_random_engine generator;
unsigned int getRandomInt(int M, int N) {
int r = M + (rand() / (RAND_MAX + 1.0))*(N - M + 1);
return r;
}
unsigned int getRandomInt() {
return getRandomInt(0, 100000);
}
double getRandomReal(int max) {
int r = max * (rand() / (RAND_MAX + 1.0));
return r;
}
double getRandomNormalValue() {
normal_distribution<double> distribution(0, 1);
return distribution(generator);
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef PINAKASANATHESEWN_H
#define PINAKASANATHESEWN_H
class PinakasAnathesewn {
public:
PinakasAnathesewn(int N);
virtual ~PinakasAnathesewn();
void setAnathesi(unsigned int i, unsigned cluster_id) ;
int getAnathesi(unsigned int i) ;
int getAndCheckAnathesi(unsigned int i);
int getN();
void setEfedrikiAnathesi(unsigned int i, unsigned cluster_id) ;
int getEfedrikiAnathesi(unsigned int i) ;
int getAndCheckEfedrikiAnathesi(unsigned int i);
private:
int N;
int * anatheseis;
int * efedrikesanatheseis;
};
#endif /* PINAKASANATHESEWN_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef CLUSTERING_H
#define CLUSTERING_H
#include "PinakasDianismaton.h"
#include "PinakasKentron.h"
#include "PinakasAnathesewn.h"
#include <list>
using namespace std;
class Clustering {
public:
Clustering();
virtual ~Clustering();
PinakasKentron * random(PinakasDianismaton * pd, int plithos_clusters);
PinakasKentron * kmeanspp(PinakasDianismaton * pd, int plithos_clusters, AlgorithmosEktelesis ae);
PinakasAnathesewn * lloyd(PinakasDianismaton * pd, PinakasKentron *, AlgorithmosEktelesis ae);
PinakasAnathesewn * lsh(PinakasDianismaton * pd, PinakasKentron *, PinakaPinakon * pinakasPinakon, int K, int L, AlgorithmosEktelesis ae);
PinakasKentron * pam(PinakasDianismaton * pd, PinakasKentron *, PinakasAnathesewn * , AlgorithmosEktelesis ae);
PinakasKentron * kmeans(PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * anatheseis, AlgorithmosEktelesis ae);
double elegxosApostasisKentron(PinakasKentron *,PinakasKentron *, AlgorithmosEktelesis ae);
double * silouette(PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * anatheseis, AlgorithmosEktelesis ae);
private:
double silouette(int i,int cluster_inner,int cluster_outerm, PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * pinakasAnatheseon, list<unsigned int> * deiktis,AlgorithmosEktelesis ae);
void lloydOnlyOne(int offset, PinakasDianismaton * pd, PinakasKentron *, AlgorithmosEktelesis ae, PinakasAnathesewn * anatheseis);
};
#endif /* CLUSTERING_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef PINAKASDIANISMATON_H
#define PINAKASDIANISMATON_H
#include <fstream>
#include "Dianisma.h"
using namespace std;
class PinakaPinakon;
class PinakasDianismaton {
public:
PinakasDianismaton(unsigned int n);
virtual ~PinakasDianismaton();
unsigned int eisagogiDedomenon(ifstream & file);
unsigned int anazitisiDedomenon(PinakaPinakon * pinakasPinakon, ifstream & file, ostream & FileOutput, AlgorithmosEktelesis ae, double aktina);
Dianisma * getDianisma(unsigned int i);
Dianisma * getAndCheckDianisma(unsigned int i);
unsigned int getN();
private:
vector<string> * evresiPlisiesterouGeitonaProseggistikaSeAktina(PinakaPinakon * pp, Dianisma * dianysma, AlgorithmosEktelesis ae, double aktina);
vector<void*> * evresiPlisiesterouGeitona(Dianisma * dianysma, AlgorithmosEktelesis ae);
vector<void*> * evresiPlisiesterouGeitonaProseggistika(PinakaPinakon * pp, Dianisma * dianysma, AlgorithmosEktelesis ae);
Dianisma * deiktis;
unsigned int n;
};
#endif
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef SINARTISEIS_H
#define SINARTISEIS_H
#include <vector>
#include <string>
#include <unordered_map>
#include "Dianisma.h"
#include "PinakasDianismaton.h"
using namespace std;
class Sinartiseis {
public:
Sinartiseis();
virtual ~Sinartiseis();
// ------------------------ boithitikes --------------------------
std::vector<std::string> split(const std::string& s, char delimiter);
double pollaplasiasmos(Dianisma * left, Dianisma * right);
long int modulo(long int N, long int M);
double ypologismosApostasis(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae);
double ypologismosApostasisEuclidean(Dianisma * apo, Dianisma * mexri);
double ypologismosApostasisCosine(Dianisma * apo, Dianisma * mexri);
double ypologismosRizasApostasis(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae);
double ypologismosRizasApostasisAnalytika(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae);
double ypologismosRizasApostasisEuclidean(Dianisma * apo, Dianisma * mexri);
double ypologismosRizasApostasisCosine(Dianisma * apo, Dianisma * mexri);
// ------------------------ ypologismoi --------------------------
static void calculateDistanceMatrix(PinakasDianismaton * pinakasDianysmaton, AlgorithmosEktelesis ae);
static void cleanupDistanceMatrix();
void katharismosFlags(PinakasDianismaton * pinakasDianysmaton);
vector<void*> * exantlitikiAnazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae );
vector<void*> * proseggistikiAnazitisi(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae );
vector<string> * proseggistikiAnazitisiSeAktina(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina );
vector<int> * proseggistikiAnazitisiOffsetsSeAktina(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina );
private:
static double ** distanceMatrix;
static unsigned int distanceMatrixDimension;
};
#endif
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <fstream>
#include <cmath>
#include "Typoi.h"
#include "PinakasDianismaton.h"
#include "PinakaPinakon.h"
#include "Dianisma.h"
#include "PinakasDianismaton.h"
#include "Clustering.h"
#include "Ektiposeis.h"
#include "cluster.h"
using namespace std;
int main(int argc, char** argv) {
int m = argc; //plihos eisodou
char* arxeio_eisodou;
char* arxeio_exodou;
char* arxeio_config;
int h_functions; //k
int pinakes_katakermatismou; //L
AlgorithmosEktelesis algorithmos_ektelesis = Euclidean; //0:Euclidean 1:Cosine
bool leptomeries = false;
h_functions = 4;
pinakes_katakermatismou = 5;
srand(time(NULL));
for (int i = 1; i < m; i++) {
if (strcmp(argv[i], "-i") == 0) {
arxeio_eisodou = argv[i + 1];
} else if (strcmp(argv[i], "-c") == 0) {
arxeio_config = argv[i + 1];
} else if (strcmp(argv[i], "-o") == 0) {
arxeio_exodou = argv[i + 1];
} else if (strcmp(argv[i], "-a") == 0) {
if (strcmp(argv[i + 1], "euclidean") == 0) {
algorithmos_ektelesis = Euclidean;
} else {
algorithmos_ektelesis = Cosine;
}
} else if (strcmp(argv[i], "-complete") == 0) {
leptomeries = true;
}
}
return run_clustering(arxeio_eisodou, arxeio_exodou, arxeio_config, h_functions, pinakes_katakermatismou, leptomeries, algorithmos_ektelesis);
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "Dianisma.h"
#include "climits"
Dianisma::Dianisma() {
//arxikopoiisi dedomenon
id = UINT_MAX;
printed = false;
}
Dianisma::~Dianisma() {
}
unsigned int Dianisma::getID() {
//epistrefei to id toy dianismatos
return id;
}
void Dianisma::setID(unsigned int id) {
//ekxorei timi sto id tou dianismatos
this->id = id;
}
TDD Dianisma::GetDedomena(unsigned int i) const {
//epistrefonati ta dedoemna tou dianismatos ousiastika oi sintetagmenes tou
return dedomena[i];
}
void Dianisma::SetDedomena(unsigned int i, TDD value) {
//ekxorei sto dianisma oi sintetagmenes
dedomena[i] = value;
}
void Dianisma::SetAndCheckDedomena(unsigned int i, TDD value) {
//elegxei an eimaste enots orion tou pinaka gia na ginei resize tou pinaka kai na ekxorithoun sinettagmenes
if (i >= dedomena.size()) {
dedomena.resize(i + 1);
}
SetDedomena(i, value);
}
unsigned int Dianisma::mikos() {
//epistrefei to mikos dou dianismatos
return dedomena.size();
}
string Dianisma::GetTag() {
//epistrefei to id tou dianismatos query_id#
return tag;
}
void Dianisma::SetTag(string tag) {
//kataxorei query_id#
this->tag = tag;
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef PINAKASKENTRON_H
#define PINAKASKENTRON_H
#include "Dianisma.h"
class PinakasKentron {
public:
PinakasKentron(int n);
virtual ~PinakasKentron();
void setDianisma(unsigned int i, Dianisma * );
Dianisma * getDianisma(unsigned int i);
Dianisma * getAndCheckDianisma(unsigned int i);
unsigned int getN();
void print(ostream & os);
private:
Dianisma ** deiktis;
unsigned int n;
};
#endif /* PINAKASKENTRON_H */
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: TestDianysma.cpp
* Author: nikolaus
*
* Created on November 17, 2018, 2:45 PM
*/
#include "TestDianysma.h"
#include "Dianisma.h"
CPPUNIT_TEST_SUITE_REGISTRATION(TestDianysma);
TestDianysma::TestDianysma() {
}
TestDianysma::~TestDianysma() {
}
void TestDianysma::setUp() {
this->example = new int(1);
}
void TestDianysma::tearDown() {
delete this->example;
}
void TestDianysma::testMethod() {
CPPUNIT_ASSERT(*example == 1);
}
void TestDianysma::testFailedMethod() {
CPPUNIT_ASSERT(++*example == 1);
}
void TestDianysma::testMikosDianysmatos() {
Dianisma * d = new Dianisma();
d->SetAndCheckDedomena(0,10);
d->SetAndCheckDedomena(1,20);
d->SetAndCheckDedomena(2,30);
CPPUNIT_ASSERT(d->mikos() == 3);
delete d;
}
void TestDianysma::testTost() {
}<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <iostream>
#include <vector>
#include <iostream>
#include <cfloat>
#include <cstdlib>
#include "PinakasDianismaton.h"
#include "Sinartiseis.h"
using namespace std;
PinakasDianismaton::PinakasDianismaton(unsigned int n) : n(n) {
//arxikopoiisi dedomenon gia kathe dianisma
deiktis = new Dianisma[n];
for (unsigned int i = 0; i < n; i++) {
deiktis[i].setID(i);
}
}
Dianisma * PinakasDianismaton::getDianisma(unsigned int i) {
//epistrefei to dianisma api ti thesi i tou pinaka dianismaton
return &deiktis[i];
}
Dianisma * PinakasDianismaton::getAndCheckDianisma(unsigned int i) {
//epistrefei to dianisma elegxontas oti eimaste entos orion
if (i < n) {
return &deiktis[i];
} else {
return 0;
}
}
unsigned int PinakasDianismaton::getN() {
// epistrefei to plithos grammon
return n;
}
PinakasDianismaton::~PinakasDianismaton() {
delete [] deiktis;
}
unsigned int PinakasDianismaton::eisagogiDedomenon(ifstream & file) {
// se auti ti sinartisi eisagontai oi sintetagmenes ton dianismaton apo to arxeio eisodou sto pinaka dianismaton
string line;
Sinartiseis sin;
unsigned int d = 0;
int temp = 0;
for (unsigned int i = 1; i <= n + temp; i++) {
getline(file, line);
if (line[0] != '@') {
// cout << line << endl;
vector<string> words = sin.split(line, ',');
if (d == 0) {
d = words.size() - 1;
}
deiktis[i - 1 - temp].SetTag(words[0]);
for (unsigned int j = 1; j < words.size() - 1; j++) {
TDD number = (TDD) atof(words[j].c_str());
deiktis[i - 1 - temp].SetAndCheckDedomena(j - 1, number);
}
} else {
temp = 1;
}
}
return d;
}
unsigned int PinakasDianismaton::anazitisiDedomenon(PinakaPinakon * pinakasPinakon, ifstream & file, ostream & FileOutput, AlgorithmosEktelesis ae, double aktina) {
// se auti ti sinartisi ginetai anazitis dianismatos me vasi to dianisma anazitisis apo to queryfile me vasi panta ton algorithmo ektelesis
string line;
Sinartiseis sin;
double max_klasma_dlsh_dtrue = 0;
double min_klasma_dlsh_dtrue = DBL_MAX;
double mesi_timi_tlsh = 0;
int qn = 0;
while (true) {
getline(file, line);
// cout << line << endl;
vector<string> words = sin.split(line, ',');
if (words.size() == 0) {
break;
}
qn++;
Dianisma * query = new Dianisma();
query->SetTag(words[0]);
for (unsigned int j = 1; j < words.size() - 1; j++) {
TDD number = (TDD) atof(words[j].c_str());
query->SetAndCheckDedomena(j - 1, number);
}
FileOutput << " .............................................. " << endl;
FileOutput << "Query: " << query->GetTag() << endl;
// anazitisi tou evresiPlisiesterouGeitona me nasi ton algorithmo LSH entis aktinas R
if (aktina > 0) {
Sinartiseis si;
si.katharismosFlags(this);
FileOutput << "R - nearest neighbours: " << endl;
vector<string> * apotelesmata = evresiPlisiesterouGeitonaProseggistikaSeAktina(pinakasPinakon, query, ae, aktina);
for (unsigned int i=0;i<apotelesmata->size();i++) {
FileOutput << "\t" << apotelesmata->at(i) << endl;
}
delete apotelesmata;
}
// anazitisi tou evresiPlisiesterouGeitona me nasi ton algorithmo LSH
vector<void*> * lshApotelesmata = evresiPlisiesterouGeitonaProseggistika(pinakasPinakon, query, ae);
// anazitisi tou pragmatikou evresiPlisiesterouGeitona
vector<void*> * trueApotelesmata = evresiPlisiesterouGeitona(query, ae);
// ektiponntai ta apotelemsata me vasi to format pou dothike
FileOutput << "True nearest neighbour: " << ((Dianisma*) trueApotelesmata->at(0))->GetTag() << " - " << ((Dianisma*) trueApotelesmata->at(0))->getID() << endl;
if (lshApotelesmata->at(0) != NULL) {
FileOutput << "LSH nearest neighbour: " << ((Dianisma*) lshApotelesmata->at(0))->GetTag() << endl;
} else {
FileOutput << "LSH nearest neighbour: " << "not found" << endl;
}
FileOutput << "dTrue nearest neighbour: " << *((double*) trueApotelesmata->at(1)) << endl;
if (lshApotelesmata->at(0) != NULL) {
FileOutput << "dLSH nearest neighbour: " << *((double*) lshApotelesmata->at(1)) << endl;
}
FileOutput << "tTrue nearest neighbour: " << *((double*) trueApotelesmata->at(2)) << " nanosec" << endl;
FileOutput << "tLSH nearest neighbour: " << *((double*) lshApotelesmata->at(2)) << " nanosec" << endl;
if (lshApotelesmata->at(0) != NULL) {
double dlsh = *((double*) lshApotelesmata->at(1));
double dtrue = *((double*) trueApotelesmata->at(1));
double klasma = dlsh / dtrue;
max_klasma_dlsh_dtrue = max(max_klasma_dlsh_dtrue, klasma);
min_klasma_dlsh_dtrue = min(min_klasma_dlsh_dtrue, klasma);
}
double tlsh = *((double*) lshApotelesmata->at(2));
mesi_timi_tlsh = mesi_timi_tlsh + tlsh;
delete (double*) (trueApotelesmata->at(1));
delete (double*) (trueApotelesmata->at(2));
delete (double*) (lshApotelesmata->at(1));
delete (double*) (lshApotelesmata->at(2));
delete trueApotelesmata;
delete query;
}
FileOutput << "################################################" << endl;
mesi_timi_tlsh = mesi_timi_tlsh / qn;
FileOutput << "max klasma_dlsh_dtrue: " << max_klasma_dlsh_dtrue << endl;
FileOutput << "min klasma_dlsh_dtrue: " << min_klasma_dlsh_dtrue << endl;
FileOutput << "mesi_timi_tlsh : " << mesi_timi_tlsh << " nanosec" << endl;
return 0;
}
vector<void*> * PinakasDianismaton::evresiPlisiesterouGeitona(Dianisma * erotima, AlgorithmosEktelesis ae) {
Sinartiseis si;
vector<void*> * apotelesmata = si.exantlitikiAnazitisi(this, erotima, ae);
return apotelesmata;
}
vector<void*> * PinakasDianismaton::evresiPlisiesterouGeitonaProseggistika(PinakaPinakon * pp, Dianisma * erotima, AlgorithmosEktelesis ae) {
Sinartiseis si;
vector<void*> * apotelesmata = si.proseggistikiAnazitisi(pp, this, erotima, ae);
return apotelesmata;
}
vector<string> * PinakasDianismaton::evresiPlisiesterouGeitonaProseggistikaSeAktina(PinakaPinakon * pp, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina) {
Sinartiseis si;
return si.proseggistikiAnazitisiSeAktina(pp, this, erotima, ae, aktina);
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef CLUSTER_H
void loadconfiguration(char* arxeio_config, int& h_functions, int &pinakes_katakermatismou, int &plithos_systades);
int loadfile(char* arxeio_eisodou, AlgorithmosEktelesis & algorithmos_ektelesis, PinakasDianismaton * & pinakasDianismatwn, unsigned int & d);
int run_clustering(char* arxeio_eisodou, char* arxeio_exodou, char* arxeio_config, int h_functions,int pinakes_katakermatismou, bool leptomeries,AlgorithmosEktelesis algorithmos_ektelesis );
#endif /* CLUSTER_H */<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <fstream>
#include <cmath>
#include "Typoi.h"
#include "PinakasDianismaton.h"
#include "PinakaPinakon.h"
#include "Dianisma.h"
#include "PinakasDianismaton.h"
#include "Clustering.h"
#include "Ektiposeis.h"
#include "cluster.h"
#include "Sinartiseis.h"
using namespace std;
void loadconfiguration(char* arxeio_config, int& h_functions, int &pinakes_katakermatismou, int &plithos_systades) {
string line2;
ifstream cFile(arxeio_config);
if (cFile.is_open() == true) {
while (getline(cFile, line2)) {
size_t pos = line2.find(":");
string firstword = line2.substr(0, pos);
string secondword = line2.substr(pos + 2);
if (firstword == "number_of_hash_functions") {
h_functions = atoi(secondword.c_str());
//cout << h_functions << endl;
}
if (firstword == "number_of_hash_tables") {
pinakes_katakermatismou = atoi(secondword.c_str());
//cout << pinakes_katakermatismou << endl;
}
if (firstword == "number_of_clusters") {
plithos_systades = atoi(secondword.c_str());
//cout << plithos_systades << endl;
}
}
}
}
int loadfile(char* arxeio_eisodou, AlgorithmosEktelesis & algorithmos_ektelesis, PinakasDianismaton * & pinakasDianismatwn, unsigned int & d) {
string line, line2;
int n = 0;
ifstream File(arxeio_eisodou);
//anazitisi tou algorithmou ekteleseis anazitisis
if (File.is_open() == true) {
getline(File, line);
if (line.substr(0, 1) == "@") {
cout << line.substr(9, 9) << endl;
if (line.substr(8, 9) == "euclidean") {
algorithmos_ektelesis = Euclidean;
//cout << "euc" << endl;
} else if (line.substr(8, 6) == "cosine") {
algorithmos_ektelesis = Cosine;
//cout << "cos" << endl;
}
} else {
n++;
}
//metrisi plithous gramon arxeiou
while (getline(File, line2)) {
n++;
}
cout << "n = " << n << endl;
File.close();
File.open(arxeio_eisodou);
//ipologismos megethous pinaka katakermatismou
pinakasDianismatwn = new PinakasDianismaton(n);
d = pinakasDianismatwn->eisagogiDedomenon(File);
return n;
} else {
cout << "To arxeio den anoixtoike!" << endl;
return -1;
}
}
int run_clustering(char* arxeio_eisodou, char* arxeio_exodou, char* arxeio_config, int h_functions, int pinakes_katakermatismou, bool leptomeries, AlgorithmosEktelesis algorithmos_ektelesis) {
int megethos_pinakes_katakermatismou, plithos_systades;
unsigned int d;
unsigned int n = 0; //grammes arxeiou eisodou
PinakasDianismaton * pinakasDianismatwn = NULL;
loadconfiguration(arxeio_config, h_functions, pinakes_katakermatismou, plithos_systades);
//plithos_systades=4;
cout << "To programma tha ektelestei gia: " << endl;
cout << "i=" << arxeio_eisodou << " " << endl;
cout << "c=" << arxeio_config << " " << endl;
cout << "k=" << h_functions << " " << endl;
cout << "L=" << pinakes_katakermatismou << " " << endl;
cout << "K=" << plithos_systades << " " << endl;
n = loadfile(arxeio_eisodou, algorithmos_ektelesis, pinakasDianismatwn, d);
if (algorithmos_ektelesis == Euclidean) {
megethos_pinakes_katakermatismou = n / 4;
} else {
megethos_pinakes_katakermatismou = (int) pow(2, h_functions);
}
cout << "N = " << n << endl;
cout << "dim N = " << pinakasDianismatwn->getDianisma(0)->mikos() << endl;
PinakaPinakon * pinakasPinakon = new PinakaPinakon(pinakes_katakermatismou, megethos_pinakes_katakermatismou, h_functions, d, algorithmos_ektelesis);
//eisagogi dianismaton stis listes
for (unsigned int i = 0; i < n; i++) {
Dianisma * p = pinakasDianismatwn->getDianisma(i);
pinakasPinakon->eisagogi(p);
}
Sinartiseis::calculateDistanceMatrix(pinakasDianismatwn, algorithmos_ektelesis);
ofstream FileOutput(arxeio_exodou);
// ----------------------- clustering --------------------------
Clustering clustering;
Ektipotis ektipotis;
for (unsigned algorithmos_arxikopoiisis = Random; algorithmos_arxikopoiisis <= KmeansPP; ++algorithmos_arxikopoiisis) {
for (unsigned algorithmos_anathesis = LLOYD; algorithmos_anathesis <= LSH; ++algorithmos_anathesis) {
for (unsigned algorithmos_ananeosis = PAM; algorithmos_ananeosis <= Kmeans; ++algorithmos_ananeosis) {
timespec ts1, ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
cout << "===========================================" << endl;
switch (algorithmos_arxikopoiisis) {
case Random:
cout << "Arxikopoiisi: Random " << endl;
break;
case KmeansPP:
cout << "Arxikopoiisi: Kmeans++ " << endl;
break;
}
switch (algorithmos_anathesis) {
case LLOYD:
cout << "Anathesi : LLOYD " << endl;
break;
case LSH:
cout << "Anathesi : LSH " << endl;
break;
}
switch (algorithmos_ananeosis) {
case PAM:
cout << "Update : PAM " << endl;
continue;
case Kmeans:
cout << "Update : Kmeans " << endl;
break;
}
cout << endl;
// --------------------------- impl ------------------
PinakasKentron * kentra;
switch (algorithmos_arxikopoiisis) {
case Random:
kentra = clustering.random(pinakasDianismatwn, plithos_systades);
break;
case KmeansPP:
kentra = clustering.kmeanspp(pinakasDianismatwn, plithos_systades, algorithmos_ektelesis);
break;
}
kentra->print(cout);
// ...
bool stop = false;
int steps = 1;
PinakasAnathesewn * anatheseis = 0;
while (!stop) {
steps++;
switch (algorithmos_anathesis) {
case LLOYD:
anatheseis = clustering.lloyd(pinakasDianismatwn, kentra, algorithmos_ektelesis);
break;
case LSH:
anatheseis = clustering.lsh(pinakasDianismatwn, kentra, pinakasPinakon, h_functions, pinakes_katakermatismou, algorithmos_ektelesis);
break;
}
if (anatheseis) {
ektipotis.ektiposi(cout, algorithmos_arxikopoiisis, algorithmos_anathesis, algorithmos_ananeosis, pinakasDianismatwn, kentra, anatheseis, algorithmos_ektelesis, 0, false);
switch (algorithmos_ananeosis) {
case PAM:
{
cout << "-------------------------------- Update : PAM " << endl;
PinakasKentron * neakentra = clustering.pam(pinakasDianismatwn, kentra, anatheseis, algorithmos_ektelesis);
if (clustering.elegxosApostasisKentron(kentra, neakentra, algorithmos_ektelesis) < 0.0000001) {
stop = true;
} else {
kentra = neakentra;
}
break;
}
case Kmeans:
{
cout << "-------------------------------- Update : Kmeans " << steps << endl;
PinakasKentron * neakentra = clustering.kmeans(pinakasDianismatwn, kentra, anatheseis, algorithmos_ektelesis);
if (clustering.elegxosApostasisKentron(kentra, neakentra, algorithmos_ektelesis) < 0.0000001) {
stop = true;
} else {
kentra = neakentra;
}
break;
}
}
}
if (steps == 40) {
stop = true;
}
if (!stop && anatheseis != NULL) {
delete anatheseis;
}
}
clock_gettime(CLOCK_REALTIME, &ts2);
double dif = double( ts2.tv_nsec - ts1.tv_nsec); // nano
if (anatheseis != NULL) {
cout << "Calculating Silhouette..." << endl;
double * sil = clustering.silouette(pinakasDianismatwn, kentra, anatheseis, algorithmos_ektelesis);
ektipotis.ektiposi_ekfonisis(FileOutput, algorithmos_arxikopoiisis, algorithmos_anathesis, algorithmos_ananeosis, pinakasDianismatwn, kentra, anatheseis, algorithmos_ektelesis, sil, leptomeries, dif);
delete [] sil;
}
}
}
}
// -------------------------------------------------------------
FileOutput.close();
if (pinakasPinakon != NULL) {
delete pinakasPinakon;
}
if (pinakasDianismatwn != NULL) {
delete pinakasDianismatwn;
}
return 0;
}<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <cmath>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include "Sinartiseis.h"
#include "Dianisma.h"
#include "PinakaPinakon.h"
using namespace std;
double ** Sinartiseis::distanceMatrix;
unsigned int Sinartiseis::distanceMatrixDimension;
Sinartiseis::Sinartiseis() {
}
Sinartiseis::~Sinartiseis() {
}
std::vector<std::string> Sinartiseis::split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
double Sinartiseis::pollaplasiasmos(Dianisma * left, Dianisma * right) {
double v = 0;
for (unsigned int i = 0; i < left->mikos(); i++) {
v = v + left->GetDedomena(i) * right->GetDedomena(i);
}
return v;
}
long int Sinartiseis::modulo(long int N, long int M) {
if (N > 0) {
return N % M;
} else {
return N * (M - 1) % M;
}
}
double Sinartiseis::ypologismosApostasisEuclidean(Dianisma * apo, Dianisma * mexri) {
double apostasi = 0.0;
for (unsigned i = 0; i < apo->mikos(); i++) {
apostasi = apostasi + (apo->GetDedomena(i) - mexri->GetDedomena(i))*(apo->GetDedomena(i) - mexri->GetDedomena(i));
}
return sqrt(apostasi);
}
double Sinartiseis::ypologismosApostasisCosine(Dianisma * apo, Dianisma * mexri) {
double esgin = 0.0;
double m1 = 0.0, m2 = 0.0;
for (unsigned i = 0; i < apo->mikos(); i++) {
m1 = m1 + (apo->GetDedomena(i) * apo->GetDedomena(i));
m2 = m2 + (mexri->GetDedomena(i) * mexri->GetDedomena(i));
esgin = esgin + (apo->GetDedomena(i) * mexri->GetDedomena(i));
}
m1 = sqrt(m1);
m2 = sqrt(m2);
return 1 - esgin / (m1 * m2);
}
double Sinartiseis::ypologismosApostasis(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae) {
return ypologismosRizasApostasis(apo, mexri, ae);
// switch (ae) {
// case Euclidean:
// case HyperCubeEuclidean:
// return ypologismosApostasisEuclidean(apo, mexri);
// case HyperCubeCosine:
// case Cosine:
// return ypologismosApostasisCosine(apo, mexri);
// default:
// return ypologismosApostasisEuclidean(apo, mexri);
// }
}
double Sinartiseis::ypologismosRizasApostasisEuclidean(Dianisma * apo, Dianisma * mexri) {
double apostasi = 0.0;
for (unsigned i = 0; i < apo->mikos(); i++) {
apostasi = apostasi + (apo->GetDedomena(i) - mexri->GetDedomena(i))*(apo->GetDedomena(i) - mexri->GetDedomena(i));
}
return apostasi;
}
double Sinartiseis::ypologismosRizasApostasisCosine(Dianisma * apo, Dianisma * mexri) {
double esgin = 0.0;
double m1 = 0.0, m2 = 0.0;
for (unsigned i = 0; i < apo->mikos(); i++) {
m1 = m1 + (apo->GetDedomena(i) * apo->GetDedomena(i));
m2 = m2 + (mexri->GetDedomena(i) * mexri->GetDedomena(i));
esgin = esgin + (apo->GetDedomena(i) * mexri->GetDedomena(i));
}
return 1 - esgin / (m1 * m2);
}
double Sinartiseis::ypologismosRizasApostasis(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae) {
if (apo->getID() == UINT32_MAX || mexri->getID() == UINT32_MAX) {
switch (ae) {
case Euclidean:
case HyperCubeEuclidean:
return ypologismosRizasApostasisEuclidean(apo, mexri);
case HyperCubeCosine:
case Cosine:
return ypologismosRizasApostasisCosine(apo, mexri);
default:
return ypologismosRizasApostasisEuclidean(apo, mexri);
}
} else {
return distanceMatrix[apo->getID()][mexri->getID()];
}
}
double Sinartiseis::ypologismosRizasApostasisAnalytika(Dianisma * apo, Dianisma * mexri, AlgorithmosEktelesis ae) {
switch (ae) {
case Euclidean:
case HyperCubeEuclidean:
return ypologismosRizasApostasisEuclidean(apo, mexri);
case HyperCubeCosine:
case Cosine:
return ypologismosRizasApostasisCosine(apo, mexri);
default:
return ypologismosRizasApostasisEuclidean(apo, mexri);
}
}
vector<void*> * Sinartiseis::exantlitikiAnazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae) {
Dianisma * geitonas = 0;
double * apostasi = new double();
double * xrono = new double();
vector<void*> * apotelesmata = new vector<void*>();
timespec ts1, ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
for (unsigned i = 0; i < pinakasDianysmaton->getN(); i++) {
double trexousa = ypologismosApostasis(pinakasDianysmaton->getDianisma(i), erotima, ae);
if (geitonas == 0 || trexousa < *apostasi) {
*apostasi = trexousa;
geitonas = pinakasDianysmaton->getDianisma(i);
}
}
clock_gettime(CLOCK_REALTIME, &ts2);
double dif = double( ts2.tv_nsec - ts1.tv_nsec); // nano
*xrono = dif;
apotelesmata->push_back(geitonas);
apotelesmata->push_back(apostasi);
apotelesmata->push_back(xrono);
return apotelesmata;
}
vector<void*> * Sinartiseis::proseggistikiAnazitisi(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae) {
double * xrono = new double();
timespec ts1, ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
vector<void*> * apotelesmata = pinakasPinakon->anazitisi(pinakasDianysmaton, erotima, ae);
clock_gettime(CLOCK_REALTIME, &ts2);
double dif = double( ts2.tv_nsec - ts1.tv_nsec); // nano
*xrono = dif;
apotelesmata->push_back(xrono);
return apotelesmata;
}
vector<string> * Sinartiseis::proseggistikiAnazitisiSeAktina(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina) {
return pinakasPinakon->anazitisiSeAktina(pinakasDianysmaton, erotima, ae, aktina);
}
vector<int> * Sinartiseis::proseggistikiAnazitisiOffsetsSeAktina(PinakaPinakon * pinakasPinakon, PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina) {
return pinakasPinakon->anazitisiOffsetsSeAktina(pinakasDianysmaton, erotima, ae, aktina);
}
void Sinartiseis::katharismosFlags(PinakasDianismaton * pinakasDianysmaton) {
for (unsigned i = 0; i < pinakasDianysmaton->getN(); i++) {
pinakasDianysmaton->getDianisma(i)->printed = false;
}
}
void Sinartiseis::calculateDistanceMatrix(PinakasDianismaton * pd, AlgorithmosEktelesis ae) {
Sinartiseis s;
cout << "Building distance matrix ... \n";
Sinartiseis::distanceMatrixDimension = pd->getN();
distanceMatrix = new double*[pd->getN()];
for (unsigned int i = 0; i < pd->getN(); i++) {
distanceMatrix[i] = new double[pd->getN()];
}
for (unsigned int i = 0; i < pd->getN(); i++) {
for (unsigned int j = i; j < pd->getN(); j++) {
if (i == j) {
distanceMatrix[i][j] = 0;
} else {
double dist = s.ypologismosRizasApostasisAnalytika(pd->getDianisma(i), pd->getDianisma(j), ae);
distanceMatrix[i][j] = dist;
distanceMatrix[j][i] = dist;
}
}
}
}
void Sinartiseis::cleanupDistanceMatrix() {
cout << "destroying distance matrix ... \n";
for (unsigned int i = 0; i < Sinartiseis::distanceMatrixDimension; i++) {
delete [] distanceMatrix[i];
}
delete [] distanceMatrix;
}<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "Clustering.h"
#include "Randoms.h"
#include "Sinartiseis.h"
#include <map>
#include <set>
#include <iterator>
#include <list>
#include <cfloat>
using namespace std;
Clustering::Clustering() {
}
Clustering::~Clustering() {
}
PinakasKentron * Clustering::random(PinakasDianismaton * pd, int plithos_clusters) {
PinakasKentron * kentra = new PinakasKentron(plithos_clusters);
for (int i = 0; i < plithos_clusters; i++) {
kentra->setDianisma(i, pd->getDianisma(getRandomInt(0, pd->getN())));
}
return kentra;
}
PinakasKentron * Clustering::kmeanspp(PinakasDianismaton * pd, int plithos_clusters, AlgorithmosEktelesis ae) {
PinakasKentron * kentra = new PinakasKentron(plithos_clusters);
Sinartiseis sinartiseis;
set<unsigned int> selectedOffsets;
for (unsigned int i = 0; i < (unsigned) plithos_clusters; i++) {
if (i == 0) {
int roll = getRandomInt(0, pd->getN());
kentra->setDianisma(i, pd->getDianisma(roll));
selectedOffsets.insert(roll);
} else {
map<unsigned int, double> distanceMap;
double max = 0;
// build distance map
for (unsigned int j = 0; j < pd->getN(); j++) {
if (selectedOffsets.find(j) == selectedOffsets.end()) {
for (set<unsigned int>::iterator p = selectedOffsets.begin(); p != selectedOffsets.end(); p++) {
Dianisma * apo = pd->getDianisma(j);
Dianisma * mexri = pd->getDianisma(*p);
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (distanceMap.find(j) == distanceMap.end()) {
distanceMap[j] = temp;
if (temp > max) {
max = temp;
}
} else {
if (temp < distanceMap[j]) {
distanceMap[j] = temp;
if (temp > max) {
max = temp;
}
}
}
}
}
}
for (map<unsigned int, double>::iterator q = distanceMap.begin(); q != distanceMap.end(); ++q) {
distanceMap[q->first] = distanceMap[q->first] / max;
distanceMap[q->first] = distanceMap[q->first] * distanceMap[q->first];
}
double ** pr = new double*[2];
pr[0] = new double[distanceMap.size()];
pr[1] = new double[distanceMap.size()];
int c = 0;
max = 0;
for (map<unsigned int, double>::iterator q = distanceMap.begin(); q != distanceMap.end(); ++q) {
pr[0][c] = q->first;
if (c - 1 >= 0) {
pr[1][c] = q->second + pr[1][c - 1];
} else {
pr[1][c] = q->second;
}
if (pr[1][c] > max) {
max = pr[1][c];
}
c++;
}
double roll = getRandomReal(max);
unsigned int nextneighbour = 0;
for (unsigned int i = 0; i < distanceMap.size(); i++) {
if (roll < pr[1][i]) {
nextneighbour = pr[0][i];
break;
}
}
kentra->setDianisma(i, pd->getDianisma(nextneighbour));
selectedOffsets.insert(nextneighbour);
delete [] pr[0];
delete [] pr[1];
delete [] pr;
}
}
return kentra;
}
PinakasAnathesewn * Clustering::lloyd(PinakasDianismaton * pd, PinakasKentron * kentra, AlgorithmosEktelesis ae) {
PinakasAnathesewn * anatheseis = new PinakasAnathesewn(pd->getN());
map<unsigned int, double> distanceMap;
map<unsigned int, double> secondDistanceMap;
Sinartiseis sinartiseis;
for (unsigned int j = 0; j < pd->getN(); j++) {
Dianisma * apo = pd->getDianisma(j);
for (unsigned int i = 0; i < kentra->getN(); i++) {
Dianisma * mexri = kentra->getDianisma(i);
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (distanceMap.find(j) == distanceMap.end()) {
distanceMap[j] = temp;
anatheseis->setAnathesi(j, i);
} else {
if (temp < distanceMap[j]) {
secondDistanceMap[j] = distanceMap[j];
anatheseis->setEfedrikiAnathesi(j, anatheseis->getAnathesi(j));
distanceMap[j] = temp;
anatheseis->setAnathesi(j, i);
} else if (secondDistanceMap.find(j) == secondDistanceMap.end()) {
secondDistanceMap[j] = temp;
anatheseis->setEfedrikiAnathesi(j, i);
} else if (temp < secondDistanceMap[j]) {
secondDistanceMap[j] = temp;
anatheseis->setEfedrikiAnathesi(j, i);
}
}
}
}
return anatheseis;
}
PinakasAnathesewn * Clustering::lsh(PinakasDianismaton * pd, PinakasKentron * kentra, PinakaPinakon * pinakasPinakon, int K, int L, AlgorithmosEktelesis ae) {
PinakasAnathesewn * anatheseis = new PinakasAnathesewn(pd->getN());
double mindist = DBL_MAX;
Sinartiseis sinartiseis;
for (unsigned int i = 0; i < kentra->getN(); i++) { // gia kathe cluster. ..
for (unsigned int j = i + 1; j < kentra->getN(); j++) { // gia kathe cluster. ..
Dianisma * apo = kentra->getDianisma(i);
Dianisma * mexri = kentra->getDianisma(j);
if (i == j) {
continue;
}
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (temp < mindist) {
mindist = temp;
}
}
}
mindist *= 0.5;
double aktina = mindist;
unsigned int total = 0;
unsigned int countdown = 20;
while (total < pd->getN() && --countdown > 0) {
set<int> * trees = new set<int>[pd->getN()]();
for (unsigned int i = 0; i < kentra->getN(); i++) { // gia kathe cluster. ..
Dianisma * query = kentra->getDianisma(i);
vector<int> * apotelesmata = sinartiseis.proseggistikiAnazitisiOffsetsSeAktina(pinakasPinakon, pd, query, ae, aktina);
for (unsigned int i = 0; i < apotelesmata->size(); i++) {
int offset = apotelesmata->at(i);
trees[offset].insert(i);
}
delete apotelesmata;
}
for (unsigned int i = 0; i < pd->getN(); i++) {
if (trees[i].size() == 0) {
// do nothing
} else if (trees[i].size() == 1) {
if (anatheseis->getAnathesi(i) == -1) {
anatheseis->setAnathesi(i, *(trees[i].begin()));
total++;
}
} else {
if (anatheseis->getAnathesi(i) == -1) {
PinakasKentron *prosorinakentra = new PinakasKentron(trees[i].size());
int j = 0;
for (set<int>::iterator p = trees[i].begin(); p != trees[i].end(); ++p) {
prosorinakentra->setDianisma(j++, kentra->getDianisma(*p));
}
lloydOnlyOne(i, pd, prosorinakentra, ae, anatheseis);
total++;
delete prosorinakentra;
}
}
}
delete [] trees;
aktina = 2 * aktina;
}
for (int i = 0; i < anatheseis->getN(); i++) {
if (anatheseis->getAnathesi(i) == -1 || anatheseis->getEfedrikiAnathesi(i) == -1) {
lloydOnlyOne(i, pd, kentra, ae, anatheseis);
}
}
return anatheseis;
}
PinakasKentron * Clustering::pam(PinakasDianismaton * pd, PinakasKentron * kentra, PinakasAnathesewn * pinakasAnatheseon, AlgorithmosEktelesis ae) {
list<unsigned int> * deiktis = new list<unsigned int>[kentra->getN()];
PinakasKentron * neakentra = new PinakasKentron(kentra->getN());
Sinartiseis sinartiseis;
// moirazw ta simeia se listes, mia gia kathe kentro
for (unsigned int j = 0; j < pd->getN(); j++) {
deiktis[pinakasAnatheseon->getAnathesi(j)].push_back(j);
}
double djtotal = 0;
for (unsigned int c = 0; c < neakentra->getN(); c++) { // gia kathe cluster. ..
if (deiktis[c].size() > 1) {
// bres medoid:
double mindistance = DBL_MAX;
unsigned int medoid;
for (list<unsigned int>::iterator p1 = deiktis[c].begin(); p1 != deiktis[c].end(); p1++) {
double sumdist = 0;
for (list<unsigned int>::iterator p2 = deiktis[c].begin(); p2 != deiktis[c].end(); p2++) {
if (*p1 != *p2) {
Dianisma * apo = pd->getDianisma(c);
Dianisma * mexri = pd->getDianisma(c);
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
sumdist = sumdist + temp;
}
}
sumdist = sumdist / (deiktis[c].size() - 1);
if (sumdist < mindistance) {
mindistance = sumdist;
medoid = *p1;
}
}
// calculate DJ
double dj = 0;
for (unsigned int j = 0; j < pd->getN(); j++) {
if (pinakasAnatheseon->getAnathesi(j) == (int) c) { // internal
Dianisma * apo = pd->getDianisma(j);
Dianisma * mexri = pd->getDianisma(medoid);
double distance_i_t = sinartiseis.ypologismosApostasis(apo, mexri, ae);
mexri = kentra->getAndCheckDianisma(pinakasAnatheseon->getEfedrikiAnathesi(j));
double distance_i_cc = sinartiseis.ypologismosApostasis(apo, mexri, ae);
mexri = kentra->getAndCheckDianisma(c);
double distance_i_m = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (distance_i_t <= distance_i_cc) {
dj = dj + (distance_i_t - distance_i_m);
} else {
dj = dj + (distance_i_cc - distance_i_m);
}
} else { // external
Dianisma * apo = pd->getDianisma(j);
Dianisma * mexri = pd->getDianisma(medoid);
double distance_i_t = sinartiseis.ypologismosApostasis(apo, mexri, ae);
mexri = kentra->getAndCheckDianisma(pinakasAnatheseon->getAnathesi(j));
double distance_i_c = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (distance_i_t >= distance_i_c) {
dj = dj + 0;
} else {
dj = dj + (distance_i_t - distance_i_c);
}
}
}
if (dj < 0) {
djtotal = djtotal + dj;
neakentra->setDianisma(c, pd->getDianisma(medoid));
}
} else {
neakentra->setDianisma(c, kentra->getDianisma(c));
}
}
delete [] deiktis;
if (djtotal < 0) {
return neakentra;
} else {
return kentra;
}
}
PinakasKentron * Clustering::kmeans(PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * pinakasAnatheseon, AlgorithmosEktelesis ae) {
list<unsigned int> * deiktis = new list<unsigned int>[kentra->getN()];
int diastaseis = pd->getDianisma(0)->mikos();
PinakasKentron * neakentra = new PinakasKentron(kentra->getN());
// moirazw ta simeia se listes, mia gia kathe kentro
for (unsigned int j = 0; j < pd->getN(); j++) {
deiktis[pinakasAnatheseon->getAnathesi(j)].push_back(j);
}
for (unsigned int i = 0; i < neakentra->getN(); i++) { // gia kathe cluster. ..
// ftiaxe ena neo kentro
Dianisma * neokentro = new Dianisma();
// kai gemise tis sintetagmenes me midenika
for (int j = 0; j < diastaseis; j++) {
neokentro->SetAndCheckDedomena(j, 0);
}
int counter = 0;
// gia kathe simeio tou cluster
for (list<unsigned int>::iterator p = deiktis[i].begin(); p != deiktis[i].end(); p++) {
// gia kathe sintetagmeni
for (int j = 0; j < diastaseis; j++) {
// prosthese tin stin antistoixi sintetagmeni tou cluster
neokentro->SetDedomena(j, (neokentro->GetDedomena(j) + pd->getDianisma(*p)->GetDedomena(j)));
}
counter++;
}
// bres to meso oro gia kathe sintetagmeni
for (int j = 0; j < diastaseis; j++) {
neokentro->SetDedomena(j, neokentro->GetDedomena(i) / counter);
}
neakentra->setDianisma(i, neokentro);
}
delete [] deiktis;
return neakentra;
}
double Clustering::elegxosApostasisKentron(PinakasKentron * kentra, PinakasKentron * neakentra, AlgorithmosEktelesis ae) {
double maxdistance = 0.0;
Sinartiseis sinartiseis;
for (unsigned int i = 0; i < neakentra->getN(); i++) { // gia kathe cluster. ..
Dianisma * apo = kentra->getDianisma(i);
Dianisma * mexri = neakentra->getDianisma(i);
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (temp > maxdistance) {
maxdistance = temp;
}
}
return maxdistance;
}
double * Clustering::silouette(PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * pinakasAnatheseon, AlgorithmosEktelesis ae) {
double * results = new double[kentra->getN() + 1];
double stotal = 0;
list<unsigned int> * deiktis = new list<unsigned int>[kentra->getN()];
for (unsigned int j = 0; j < pd->getN(); j++) {
deiktis[pinakasAnatheseon->getAnathesi(j)].push_back(j);
}
for (unsigned int cluster_inner = 0; cluster_inner < kentra->getN(); cluster_inner++) {
double scluster = 0;
for (list<unsigned int>::iterator p1 = deiktis[cluster_inner].begin(); p1 != deiktis[cluster_inner].end(); p1++) {
int i = *p1;
int cluster_outer = pinakasAnatheseon->getEfedrikiAnathesi(i);
scluster = scluster + silouette(i, cluster_inner, cluster_outer, pd, kentra, pinakasAnatheseon, deiktis, ae);
}
scluster = scluster / deiktis[cluster_inner].size();
stotal = stotal + scluster;
results[cluster_inner] = scluster;
}
stotal = stotal / kentra->getN();
delete [] deiktis;
results[kentra->getN()] = stotal;
return results;
}
double Clustering::silouette(int i, int cluster_inner, int cluster_outer, PinakasDianismaton * pd, PinakasKentron *kentra, PinakasAnathesewn * pinakasAnatheseon, list<unsigned int> * deiktis, AlgorithmosEktelesis ae) {
double sil = 0;
double average_inner = 0;
double average_outer = 0;
int counter = 0;
Sinartiseis sinartiseis;
Dianisma * apo = pd->getDianisma(i);
// gia kathe simeio tou cluster
for (list<unsigned int>::iterator p = deiktis[cluster_inner].begin(); p != deiktis[cluster_inner].end(); p++) {
Dianisma * mexri = pd->getDianisma(*p);
average_inner = average_inner + sinartiseis.ypologismosApostasis(apo, mexri, ae);
counter++;
}
average_inner = average_inner / counter;
counter = 0;
for (list<unsigned int>::iterator p = deiktis[cluster_outer].begin(); p != deiktis[cluster_outer].end(); p++) {
Dianisma * mexri = pd->getDianisma(*p);
average_outer = average_outer + sinartiseis.ypologismosApostasis(apo, mexri, ae);
counter++;
}
average_outer = average_outer / counter;
sil = (average_outer - average_inner) / max(average_inner, average_outer);
return sil;
}
void Clustering::lloydOnlyOne(int offset, PinakasDianismaton * pd, PinakasKentron *kentra, AlgorithmosEktelesis ae, PinakasAnathesewn * anatheseis) {
map<unsigned int, double> distanceMap;
map<unsigned int, double> secondDistanceMap;
Sinartiseis sinartiseis;
unsigned int j = offset;
Dianisma * apo = pd->getDianisma(j);
for (unsigned int i = 0; i < kentra->getN(); i++) {
Dianisma * mexri = kentra->getDianisma(i);
double temp = sinartiseis.ypologismosApostasis(apo, mexri, ae);
if (distanceMap.find(j) == distanceMap.end()) {
distanceMap[j] = temp;
anatheseis->setAnathesi(j, i);
} else {
if (temp < distanceMap[j]) {
secondDistanceMap[j] = distanceMap[j];
anatheseis->setEfedrikiAnathesi(j, anatheseis->getAnathesi(j));
distanceMap[j] = temp;
anatheseis->setAnathesi(j, i);
} else if (secondDistanceMap.find(j) == secondDistanceMap.end()) {
secondDistanceMap[j] = temp;
anatheseis->setEfedrikiAnathesi(j, i);
} else if (temp < secondDistanceMap[j]) {
secondDistanceMap[j] = temp;
anatheseis->setEfedrikiAnathesi(j, i);
}
}
}
}<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef MYRANDOMS_H
#define MYRANDOMS_H
unsigned int getRandomInt(int min, int max);
unsigned int getRandomInt();
double getRandomReal(int max);
double getRandomNormalValue();
#endif /* MYRANDOMS_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef PINAKASPINAKON_H
#define PINAKASPINAKON_H
#include "Pinakas.h"
#include "Typoi.h"
#include <vector>
using namespace std;
class PinakaPinakon {
public:
PinakaPinakon(unsigned int L, unsigned int T, unsigned int k, unsigned int d, AlgorithmosEktelesis ae);
virtual ~PinakaPinakon();
void eisagogi(Dianisma * x);
vector<void*>* anazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * x, AlgorithmosEktelesis ae);
vector<string> * anazitisiSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * x, AlgorithmosEktelesis ae, double aktina);
vector<int> * anazitisiOffsetsSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * x, AlgorithmosEktelesis ae, double aktina);
unsigned int getL();
private:
Pinakas ** pinakes;
unsigned int L;
};
#endif
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "Ektiposeis.h"
#include "PinakasDianismaton.h"
#include "PinakasAnathesewn.h"
#include "PinakasKentron.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
void Ektipotis::ektiposi(ostream & out, unsigned algorithmos_arxikopoiisis, unsigned algorithmos_anathesis, unsigned algorithmos_ananeosis, PinakasDianismaton * pd, PinakasKentron * kentra, PinakasAnathesewn * pinakasAnatheseon, AlgorithmosEktelesis ae, double * sil, bool leptomereies) {
switch (algorithmos_arxikopoiisis) {
case Random:
out << "Arxikopoiisi: Random " << endl;
break;
case KmeansPP:
out << "Arxikopoiisi: Kmeans++ " << endl;
break;
}
switch (algorithmos_anathesis) {
case LLOYD:
out << "Anathesi : LLOYD " << endl;
break;
case LSH:
out << "Anathesi : LSH " << endl;
break;
}
switch (algorithmos_ananeosis) {
case PAM:
out << "Update : PAM " << endl;
break;
case Kmeans:
out << "Update : Kmeans " << endl;
break;
}
list<unsigned int> * deiktis = new list<unsigned int>[kentra->getN()];
for (unsigned int j = 0; j < pd->getN(); j++) {
// Dianisma * apo = pd->getDianisma(j);
deiktis[pinakasAnatheseon->getAnathesi(j)].push_back(j);
}
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << "Cluster-" << i << ":" << " { size: " << deiktis[i].size() << " " << kentra->getDianisma(i)->GetTag() << " } " << endl;
}
if (leptomereies) {
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << "*** Cluster-" << i << ":" << " { size: " << deiktis[i].size() << " " << kentra->getDianisma(i)->GetTag() << " } " << endl;
int counter = 0;
for (list<unsigned int>::iterator p = deiktis[i].begin(); p != deiktis[i].end(); p++) {
out << pd->getDianisma(*p)->getID() << "\t";
counter++;
if (counter == 5) {
counter = 0;
out << endl;
}
}
out << endl;
}
}
if (sil) {
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << "Silhouette for cluster " << i << ":" << sil[i] << endl;
}
out << "Silhouette total: " << sil[kentra->getN()] << endl;
}
out << endl;
delete [] deiktis;
}
void Ektipotis::ektiposi_ekfonisis(ostream & out, unsigned algorithmos_arxikopoiisis, unsigned algorithmos_anathesis, unsigned algorithmos_ananeosis, PinakasDianismaton * pd, PinakasKentron * kentra, PinakasAnathesewn * pinakasAnatheseon, AlgorithmosEktelesis ae, double * sil, bool leptomereies, double diff) {
out << "I" << algorithmos_arxikopoiisis << "A" << algorithmos_anathesis << "U" << algorithmos_ananeosis << endl;
if (ae == Euclidean) {
out << "Metric: euclidean " << endl;
} else {
out << "Metric: cosine " << endl;
}
list<unsigned int> * deiktis = new list<unsigned int>[kentra->getN()];
for (unsigned int j = 0; j < pd->getN(); j++) {
deiktis[pinakasAnatheseon->getAnathesi(j)].push_back(j);
}
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << "Cluster-" << i << ":" << " { size: " << deiktis[i].size() << ", " << kentra->getDianisma(i)->GetTag() << " } " << endl;
}
if (sil) {
out << "Silhouette: { ";
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << sil[i] << " ";
}
out << sil[kentra->getN()] << "}" << endl;
}
out << "Clustering time: " << diff << endl;
if (leptomereies) {
for (unsigned int i = 0; i < kentra->getN(); i++) {
out << "*** Cluster-" << i << ":" << " { ";
int counter = 0;
for (list<unsigned int>::iterator p = deiktis[i].begin(); p != deiktis[i].end(); p++) {
out << pd->getDianisma(*p)->getID() << "\t";
counter++;
if (counter == 5) {
counter = 0;
out << endl;
}
}
out << "}" << endl;
}
}
}<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef PINAKAS_H
#define PINAKAS_H
#include <list>
#include <vector>
#include "Typoi.h"
#include "HashFunction.h"
#include "PinakasDianismaton.h"
using namespace std;
class Pinakas {
public:
Pinakas(unsigned int T, unsigned int k, unsigned int d, AlgorithmosEktelesis ae);
virtual ~Pinakas();
void eisagogi(Dianisma * x);
vector<void*> * anazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * x);
void anazitisiSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * x, double aktina, vector<string> * apotelesmata);
void anazitisiOffsetsSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * x, double aktina, vector<int> * apotelesmata);
private:
list<unsigned int> * deiktis;
unsigned int T;
AlgorithmosEktelesis ae;
HashFunction hashfunction;
};
#endif
<file_sep>OBJS = Clustering.o Dianisma.o Ektiposeis.o HashFunction.o main.o PinakaPinakon.o Pinakas.o PinakasAnathesewn.o PinakasDianismaton.o PinakasKentron.o Randoms.o Sinartiseis.o cluster.o
SOURCE = Clustering.cpp Dianisma.cpp Ektiposeis.cpp HashFunction.cpp main.cpp PinakaPinakon.cpp Pinakas.cpp PinakasAnathesewn.cpp PinakasDianismaton.cpp PinakasKentron.cpp Randoms.cpp Sinartiseis.cpp cluster.cpp
HEADER = cluster.h Clustering.h Dianisma.h Ektiposeis.h HashFunction.h PinakaPinakon.h Pinakas.h PinakasAnathesewn.h PinakasDianismaton.h PinakasKentron.h Randoms.h Sinartiseis.h Statheres.h Typoi.h cluster.h
OUT = cluster
CC = g++
FLAGS = -g -c -Wall
LFLAGS =
all: $(OBJS)
$(CC) -g $(OBJS) -o $(OUT) $(LFLAGS)
Clustering.o: Clustering.cpp
$(CC) $(FLAGS) Clustering.cpp -std=c++11
Dianisma.o: Dianisma.cpp
$(CC) $(FLAGS) Dianisma.cpp -std=c++11
Ektiposeis.o: Ektiposeis.cpp
$(CC) $(FLAGS) Ektiposeis.cpp -std=c++11
HashFunction.o: HashFunction.cpp
$(CC) $(FLAGS) HashFunction.cpp -std=c++11
main.o: main.cpp
$(CC) $(FLAGS) main.cpp -std=c++11
PinakaPinakon.o: PinakaPinakon.cpp
$(CC) $(FLAGS) PinakaPinakon.cpp -std=c++11
Pinakas.o: Pinakas.cpp
$(CC) $(FLAGS) Pinakas.cpp -std=c++11
PinakasAnathesewn.o: PinakasAnathesewn.cpp
$(CC) $(FLAGS) PinakasAnathesewn.cpp -std=c++11
PinakasDianismaton.o: PinakasDianismaton.cpp
$(CC) $(FLAGS) PinakasDianismaton.cpp -std=c++11
PinakasKentron.o: PinakasKentron.cpp
$(CC) $(FLAGS) PinakasKentron.cpp -std=c++11
Randoms.o: Randoms.cpp
$(CC) $(FLAGS) Randoms.cpp -std=c++11
Sinartiseis.o: Sinartiseis.cpp
$(CC) $(FLAGS) Sinartiseis.cpp -std=c++11
cluster.o: cluster.cpp
$(CC) $(FLAGS) cluster.cpp -std=c++11
clean:
rm -f $(OBJS) $(OUT)
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <cstdlib>
#include <iostream>
#include <cmath>
#include "HashFunction.h"
#include "Sinartiseis.h"
#include "Randoms.h"
using namespace std;
HashFunction::HashFunction(AlgorithmosEktelesis ae, unsigned int k, unsigned int d) : ae(ae), k(k) {
if (ae == Euclidean) {
v = new Dianisma[k]; // k dianysmata me diastasi d
t = new float[k];
r = new float[k];
for (unsigned int i = 0; i < k; i++) {
r[i] = getRandomInt(); // random int (uniform distribution)
t[i] = getRandomReal(4); // random real (uniform distrubution in [0,W)
for (unsigned int j = 0; j < d; j++) {
float q = getRandomNormalValue();
v[i].SetAndCheckDedomena(j, q);
}
}
}
if (ae == Cosine) {
cr = new Dianisma[k]; // k dianysmata me diastasi d
for (unsigned int i = 0; i < k; i++) {
for (unsigned int j = 0; j < d; j++) {
float q = getRandomNormalValue();
cr[i].SetAndCheckDedomena(j, q);
}
}
}
}
HashFunction::~HashFunction() {
if (ae == Euclidean) {
delete [] v;
delete [] t;
delete [] r;
}
if (ae == Cosine) {
delete [] cr;
}
}
unsigned int HashFunction::ypologismosThesis(Dianisma * x) {
Sinartiseis sin;
unsigned long int M = (unsigned long int) (pow(2, 32) - 5);
if (ae == Euclidean) {
unsigned long int thesi = 0;
for (unsigned int i = 0; i < k; i++) {
thesi = thesi + ((long int) (sin.modulo((long int) ((r[i] * sin.pollaplasiasmos(x, &v[i]) + t[i]) / 4), M)));
}
thesi = sin.modulo(thesi, M);
return (unsigned int) thesi;
}
if (ae == Cosine || ae == HyperCubeEuclidean || ae == HyperCubeCosine) {
unsigned int thesi = 0;
for (unsigned int i = 0; i < k; i++) {
double hi = (sin.pollaplasiasmos(x, &cr[i]));
if (hi >= 0) {
hi = 1;
} else {
hi = 0;
}
thesi = thesi + (unsigned int) (hi * pow(2, i));
}
return thesi;
}
cout << "ae corrupted :( \n";
exit(0);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: TestDianysma.h
* Author: nikolaus
*
* Created on November 17, 2018, 2:45 PM
*/
#ifndef TESTDIANYSMA_H
#define TESTDIANYSMA_H
#include <cppunit/extensions/HelperMacros.h>
class TestDianysma : public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(TestDianysma);
CPPUNIT_TEST(testMethod);
CPPUNIT_TEST(testFailedMethod);
CPPUNIT_TEST_SUITE_END();
public:
TestDianysma();
virtual ~TestDianysma();
void setUp();
void tearDown();
private:
int *example;
void testMethod();
void testFailedMethod();
void testMikosDianysmatos();
void testTost();
};
#endif /* TESTDIANYSMA_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include <iterator>
#include <iostream>
#include "Pinakas.h"
#include "Sinartiseis.h"
using namespace std;
Pinakas::Pinakas(unsigned int T, unsigned int k, unsigned int d, AlgorithmosEktelesis ae) : T(T), ae(ae), hashfunction(ae, k, d) {
deiktis = new list<unsigned int>[T];
}
Pinakas::~Pinakas() {
delete [] deiktis;
}
void Pinakas::eisagogi(Dianisma * x) {
//ipologizetai i thesi tou dianismatos me vasi ti hashfucntion kai ginetao eisagogi
unsigned int thesi = hashfunction.ypologismosThesis(x) % T;
deiktis[thesi].push_back(x->getID());
}
vector<void*> * Pinakas::anazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima) {
//ginetai anazitisi tou kontinoteroy dianismastos stis listes
Sinartiseis si;
vector<void*> * apotelesmata = new vector<void*>();
unsigned int thesi = hashfunction.ypologismosThesis(erotima) % T;
list<unsigned int> & lista = deiktis[thesi];
Dianisma * geitonas = 0;
double * apostasi = new double();
for (list<unsigned int>::iterator p = lista.begin(); p != lista.end();p++) {
unsigned int index = *p;
Dianisma * d = pinakasDianysmaton->getDianisma(index);
double trexousa = si.ypologismosApostasis(d, erotima, ae);
if (geitonas == 0 || trexousa < *apostasi) {
*apostasi = trexousa;
geitonas = d;
}
}
apotelesmata->push_back(geitonas);
apotelesmata->push_back(apostasi);
return apotelesmata;
}
void Pinakas::anazitisiSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, double aktina, vector<string> * apotelesmata) {
//ginetai anazitisi dianismaton entos aktinas R
Sinartiseis si;
unsigned int thesi = hashfunction.ypologismosThesis(erotima) % T;
list<unsigned int> & lista = deiktis[thesi];
for (list<unsigned int>::iterator p = lista.begin(); p != lista.end();p++) {
unsigned int index = *p;
Dianisma * d = pinakasDianysmaton->getDianisma(index);
if (d->printed == false ){
double trexousa = si.ypologismosApostasis(d, erotima, ae);
if (trexousa <= aktina) {
d->printed = true;
apotelesmata->push_back(d->GetTag());
}
}
}
}
void Pinakas::anazitisiOffsetsSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, double aktina, vector<int> * apotelesmata) {
//ginetai anazitisi dianismaton entos aktinas R
Sinartiseis si;
unsigned int thesi = hashfunction.ypologismosThesis(erotima) % T;
list<unsigned int> & lista = deiktis[thesi];
for (list<unsigned int>::iterator p = lista.begin(); p != lista.end();p++) {
unsigned int index = *p;
Dianisma * d = pinakasDianysmaton->getDianisma(index);
if (d->printed == false ){
double trexousa = si.ypologismosApostasis(d, erotima, ae);
if (trexousa <= aktina) {
d->printed = true;
apotelesmata->push_back(index);
}
}
}
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef TYPOI_H
#define TYPOI_H
// typos dedomenon dianismatos
#define TDD double
enum AlgorithmosEktelesis { Euclidean, Cosine, HyperCubeEuclidean, HyperCubeCosine };
enum AlgorithmosInitialization { Random, KmeansPP };
enum AlgorithmosAssignment { LLOYD, LSH };
enum AlgorithmosUpdate { PAM, Kmeans };
#endif /* TYPOI_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "PinakasKentron.h"
#include <ostream>
#include <iostream>
using namespace std;
PinakasKentron::PinakasKentron(int n) : n(n) {
deiktis = new Dianisma*[n];
}
PinakasKentron::~PinakasKentron() {
delete [] deiktis;
}
Dianisma * PinakasKentron::getDianisma(unsigned int i) {
//epistrefei to dianisma api ti thesi i tou pinaka dianismaton
return deiktis[i];
}
Dianisma * PinakasKentron::getAndCheckDianisma(unsigned int i) {
//epistrefei to dianisma elegxontas oti eimaste entos orion
if (i < n) {
return deiktis[i];
} else {
return 0;
}
}
unsigned int PinakasKentron::getN() {
// epistrefei to plithos grammon
return n;
}
void PinakasKentron::setDianisma(unsigned int i, Dianisma * d) {
deiktis[i] = d;
}
void PinakasKentron::print(ostream & os) {
for (unsigned int i=0;i<n;i++) {
os << "Cluster " << i << " " << getDianisma(i)->GetTag() << endl;
}
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "PinakaPinakon.h"
PinakaPinakon::PinakaPinakon(unsigned int L, unsigned int T, unsigned int k, unsigned int d, AlgorithmosEktelesis ae) : L(L) {
pinakes = new Pinakas*[L];
for (unsigned int i = 0; i < L; i++) {
pinakes[i] = new Pinakas(T, k, d, ae);
}
}
PinakaPinakon::~PinakaPinakon() {
for (unsigned int i = 0; i < L; i++) {
delete pinakes[i];
}
delete [] pinakes;
}
void PinakaPinakon::eisagogi(Dianisma * x) {
//eisagetai to dianisam sto pinaka
for (unsigned int i = 0; i < L; i++) {
pinakes[i]->eisagogi(x);
}
}
unsigned int PinakaPinakon::getL() {
//mas epistrefei to plithos ton pinakon katakermatismou
return L;
}
vector<void*>* PinakaPinakon::anazitisi(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae) {
//anazitisi tou kontinoterou dianismatos erotimatos
vector<void*> * apotelesmata = new vector<void*>();
Dianisma * geitonas = 0;
double * apostasi = new double();
for (unsigned int i = 0; i < L; i++) {
vector<void*> * apotelesmataEnosPinaka = pinakes[i]->anazitisi(pinakasDianysmaton, erotima);
if (apotelesmataEnosPinaka != NULL) {
if (apotelesmataEnosPinaka->at(0) != 0) {
double tempapostasi = *((double*) apotelesmataEnosPinaka->at(1));
if (geitonas == 0 || tempapostasi < *apostasi) {
geitonas = (Dianisma*) apotelesmataEnosPinaka->at(0);
*apostasi = *((double*) apotelesmataEnosPinaka->at(1));
}
delete (double*) (apotelesmataEnosPinaka->at(1));
}
delete apotelesmataEnosPinaka;
}
}
apotelesmata->push_back(geitonas);
apotelesmata->push_back(apostasi);
return apotelesmata;
}
vector<string> * PinakaPinakon::anazitisiSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina) {
//anazitisi tou dianismatos se aktina R
vector<string> * apotelesmata = new vector<string>();
for (unsigned int i = 0; i < L; i++) {
pinakes[i]->anazitisiSeAktina(pinakasDianysmaton, erotima, aktina, apotelesmata);
}
return apotelesmata;
}
vector<int> * PinakaPinakon::anazitisiOffsetsSeAktina(PinakasDianismaton * pinakasDianysmaton, Dianisma * erotima, AlgorithmosEktelesis ae, double aktina) {
//anazitisi tou dianismatos se aktina R
vector<int> * apotelesmata = new vector<int>();
for (unsigned int i = 0; i < L; i++) {
pinakes[i]->anazitisiOffsetsSeAktina(pinakasDianysmaton, erotima, aktina, apotelesmata);
}
return apotelesmata;
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef DIANISMA_H
#define DIANISMA_H
#include <vector>
#include <string>
#include "Typoi.h"
using namespace std;
class Dianisma {
public:
Dianisma();
virtual ~Dianisma();
TDD GetDedomena(unsigned int i) const;
void SetAndCheckDedomena(unsigned int i, TDD value );
void SetDedomena(unsigned int i, TDD value );
unsigned int getID();
void setID(unsigned int id);
string GetTag();
void SetTag(string tag);
unsigned int mikos();
bool printed;
private:
unsigned int id;
string tag;
vector<TDD> dedomena;
};
#endif
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef HASHFUNCTION_H
#define HASHFUNCTION_H
#include "Typoi.h"
#include "Dianisma.h"
class HashFunction {
public:
HashFunction(AlgorithmosEktelesis ae, unsigned int k, unsigned int d);
virtual ~HashFunction();
unsigned int ypologismosThesis(Dianisma * x);
private:
AlgorithmosEktelesis ae;
// ae = euclidean or hypercube
unsigned int k;
Dianisma * v;
float * t;
float * r;
// ae = cosine
Dianisma * cr;
};
#endif
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#include "PinakasAnathesewn.h"
PinakasAnathesewn::PinakasAnathesewn(int N) : N(N) {
anatheseis = new int[N];
efedrikesanatheseis = new int[N];
for (int i = 0; i < N; i++) {
anatheseis[i] = -1;
efedrikesanatheseis[i] = -1;
}
}
PinakasAnathesewn::~PinakasAnathesewn() {
delete [] anatheseis;
delete [] efedrikesanatheseis;
}
int PinakasAnathesewn::getAnathesi(unsigned int i) {
return anatheseis[i];
}
void PinakasAnathesewn::setAnathesi(unsigned int i, unsigned cluster_id) {
anatheseis[i] = cluster_id;
}
int PinakasAnathesewn::getAndCheckAnathesi(unsigned int i) {
if ((int) i < N) {
return anatheseis[i];
} else {
return 0;
}
}
int PinakasAnathesewn::getEfedrikiAnathesi(unsigned int i) {
return efedrikesanatheseis[i];
}
void PinakasAnathesewn::setEfedrikiAnathesi(unsigned int i, unsigned cluster_id) {
efedrikesanatheseis[i] = cluster_id;
}
int PinakasAnathesewn::getAndCheckEfedrikiAnathesi(unsigned int i) {
if ((int) i < N) {
return efedrikesanatheseis[i];
} else {
return 0;
}
}
int PinakasAnathesewn::getN() {
return N;
}
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef STATHERES_H
#define STATHERES_H
#define W 4
#endif /* STATHERES_H */
<file_sep>/*
<NAME>
AM: 1115201300196
*/
#ifndef EKTIPOSEIS_H
#define EKTIPOSEIS_H
#include "PinakasDianismaton.h"
#include "PinakasKentron.h"
#include "PinakasAnathesewn.h"
class Ektipotis {
public:
void ektiposi(ostream & out, unsigned algorithmos_arxikopoiisis, unsigned algorithmos_anathesis, unsigned algorithmos_ananeosis,PinakasDianismaton * pd, PinakasKentron * kentra, PinakasAnathesewn * anatheseon, AlgorithmosEktelesis ae, double * sil, bool leptomereies);
void ektiposi_ekfonisis(ostream & out, unsigned algorithmos_arxikopoiisis, unsigned algorithmos_anathesis, unsigned algorithmos_ananeosis,PinakasDianismaton * pd, PinakasKentron * kentra, PinakasAnathesewn * anatheseon, AlgorithmosEktelesis ae, double * sil, bool leptomereies, double diff);
};
#endif /* EKTIPOSEIS_H */
| 23a99e54445d4926667cd32ac96e21428df5dd73 | [
"C",
"Makefile",
"C++"
] | 30 | C++ | Chavellas/Project2 | e58e2ccaf5beae29603ff987f62b4e6f08c97c0d | 94759f7396f1e0bed37f5a3ed191737ad0c5a9f2 |
refs/heads/master | <repo_name>cnxtech/aws-extensions-for-dotnet-cli<file_sep>/test/Amazon.Lambda.Tools.Test/UtilitiesTests.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Amazon.Lambda.Tools.Test
{
public class UtilitiesTests
{
[Theory]
[InlineData("dotnetcore2.1", "netcoreapp2.1")]
[InlineData("dotnetcore2.0", "netcoreapp2.0")]
[InlineData("dotnetcore1.0", "netcoreapp1.0")]
public void MapLambdaRuntimeWithFramework(string runtime, string framework)
{
Assert.Equal(runtime, LambdaUtilities.DetermineLambdaRuntimeFromTargetFramework(framework));
}
[Fact]
public void MapInvalidLambdaRuntimeWithFramework()
{
Assert.Null(LambdaUtilities.DetermineLambdaRuntimeFromTargetFramework("not-real"));
}
}
}
| 8b028f0cd21cd9e7759e8ede5967e9dcf84d3920 | [
"C#"
] | 1 | C# | cnxtech/aws-extensions-for-dotnet-cli | 24bb07227cdcb0b1d0bdbe314acf5c2474439849 | 6be70088b1eb577c21bd285d3e349287b9b48685 |
refs/heads/master | <file_sep># Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
# The following is needed for Firefox, as it doesn't handle mime type application/json correctly
#Mime::Type.register "text/javascript", :json
<file_sep>class ReviewsController < ApplicationController
def create
@product = Product.find(params[:product_id])
@review = @product.reviews.create(params[:review])
flash[:notice] = "Thank you for reviewing this product"
respond_to do |format|
format.html { redirect_to @review.product }
format.js
end
end
end
<file_sep>$(document).ready(function() {
$("#comment-dialog-form").delegate('.comment-list-item', 'click', function() {
var commentName = $(this).children(".comment-name").text();
var commentContent = $(this).children(".comment-content").text();
if ($(this).parent().hasClass("selected-comment-list")) {
$(this).remove()
} else {
var selectedCommentHtml =
"<div class=\"comment-list-item\">" +
"<span class=\"comment-name\" style=\"display: none;\">" + commentName + "</span>" +
"<span class=\"left-arrow\">◀</span>" +
"<span class=\"comment-text\">" + commentContent + "</span>" +
"</div>";
$(".selected-comment-list").append(selectedCommentHtml);
}
});
$("#comment-dialog-form").dialog({
autoOpen: false,
width: 700,
height: 500,
modal: true,
buttons: {
"Legg til valgt kommentar": function() {
var selectedCommentTextList = $(".selected-comment-list .comment-list-item .comment-text");
var selectedCommentNameList = $(".selected-comment-list .comment-list-item .comment-name");
var scNames = [];
var scTexts = [];
if (selectedCommentNameList.length != 0) {
/*
for (i = 0; i < selectedCommentNameList.length; i++) {
scNames[i] = selectedCommentNameList[i].innerText;
scTexts[i] = selectedCommentTextList[i].innerText;
}
*/
selectedCommentNameList.each(function(i) {
scNames[i] = $(this).text();
});
selectedCommentTextList.each(function(i) {
scTexts[i] = $(this).text();
});
$('#result').html('Følgende kommentarer be valgt: <tt>' + scNames.toString() + '</tt>');
var commentInputField = $('.selected-comments textarea');
var currentCommentText = commentInputField.val();
commentInputField.val(currentCommentText + scTexts.join("\n\n") + "\n\n");
}
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
$("#add-comment").button().click(function() {
$("#comment-dialog-form").dialog("open");
});
/*
$("#comment-dialog-form").dialog({
autoOpen: false,
height: 'auto',
width: 400,
modal: true,
buttons: {
"Legg til valgt kommentar": function() {
var checkedBoxes = $('[name="comment-checkbox-group"]:checked');
var commentLabels = $('label');
var cbNames = [];
if (checkedBoxes.length == 0) {
selectedComments[i] = '<tr><td>Ingen kommentar</td></tr>';
} else {
for (i = 0; i < checkedBoxes.length; i++) {
cbNames[i] = checkedBoxes[i].id;
selectedComments[i] = '<tr><td>' + commentLabels[i].innerText + '</td></tr>';
}
}
$('#result').html('The following checkboxes are selected: <tt>' + cbNames.toString() + '</tt>');
$('#selected-comments tbody').html(selectedComments.toString());
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
*/
});<file_sep>class CommentController < ApplicationController
def show
@comment_categories = CommentCategory.all
end
end
<file_sep>/*
Place all the behaviors and hooks related to the matching controller here.
All this logic will automatically be available in application.js.
You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
*/
$(document).ready(function() {
/*
See also: http://jqueryui.com/demos/dialog/#modal-form
*/
var name = $("#user-name"),
email = $("#user-email"),
password = <PASSWORD>"),
allFields = $([]).add(name).add(email).add(password);
$("#dialog-form").dialog({
autoOpen: false,
height: 'auto',
width: 350,
modal: true,
buttons: {
"Create an account": function() {
var bValid = true;
allFields.removeClass("ui-state-error");
if (bValid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
$(this).dialog("close");
}
},
Cancel: function() {
$(this).dialog("close");
}
},
close: function() {
allFields.val("").removeClass("ui-state-error");
}
});
$("#create-user").button().click(function() {
$("#dialog-form").dialog("open");
});
});
| 23036b7aca55d85a31b160557cb4d20fe6816249 | [
"JavaScript",
"Ruby"
] | 5 | Ruby | perspilling/store | 4b0e07aece6707038f2b2b3befc9ffb0ee0a9e5f | 81e4de7d9f4c7f8d19787b2cfa8ab3f04cfcdf75 |
refs/heads/master | <file_sep># ScriptsVirtualMachine
**How to:**
- Place le script dans le dossier qui servira de VM
```shell script
$ bash ./awesomeScript.sh
```
- Suis les instructions, attends d'arriver dans la VM.
- Une fois dans la vm, faire:
```shell script
$ bash /var/www/html/install.sh
```
- Choisir sa version de PHP
- Attendre l'installation des packets
- C'est fini!
**Ce que ce script installe:**
- Apache 2
- Libapache
- Php 7.3 / 7.2 / 5.6
- **Active les erreurs Php**
- MySQL
**Infos:**
- Mot de passe MySQL: `1234`
- Le script se supprime automatiquement une fois fini!
*Si quelque chose cloche, ne marche pas ou si vous avez des question, envoyez moi un email! <EMAIL>*
<file_sep>#!/bin/bash
# # # # # # # # # # This script is awesome! # # # # # # # # # #
clear
rm Vagrantfile ubuntu-xenial-16.04-cloudimg-console.log
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
echo 'Voici une liste des VMs:'
vboxmanage list vms
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Vieux trucs pour validation, inutile.
#echo 'Veux tu allumer une VM? 1)Oui 2)Non'
#select opt in Oui Non
#do
# case $opt in
# 'Oui') echo 'Rentrer le nom de la VM à allumer'
# VBoxManage list vms
# read choix
# VBoxManage startvm "$choix"
# ;;
# 'Non') break
# ;;
# esac
# break
#done
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#echo 'Veux tu éteindre une VM?'
#select opt2 in Oui Non
#do
# case $opt2 in
# 'Oui') echo 'Rentrer le nom de la VM à éteindre'
# VBoxManage list vms
# read choix2
# VBoxManage controlvm "$choix2" poweroff
# ;;
# 'Non') break
# ;;
# esac
# break
#done
# # # # # # # # # # # # # # Core # # # # # # # # # # # # # # # # #
echo "...Création d'une nouvelle VM..."
echo 'ip de la VM à utiliser dans le navigateur? (192.168.33.XX) ' #Choix de l'ip du serveur
read -r ip
while [[ "$ip" != "192.168.33."* ]]; do #redemmande l'ip si elle est incorrecte
echo 'ip doit être 192.168.33.XX, réentrer ip:'
read -r ip
done
echo 'Quel nom de dossier sync? (ne rien mettre pour "Data")' #customise le nom du dossier de syncronisation de Vagrant
read -r file
echo $'Quel nom de \e[31mVM\e[0m? (ne rien mettre pour "Défaut")' #customise le nom de la VM et ajoute l'addresse ip du server à coté
read -r nom
nom="$nom - ip:$ip"
if [[ "$nom" == " - ip:$ip" ]]; then #Nom par défaut de la VM
nom="Défaut-ip:$ip"
fi
if [[ "$file" == "" ]]; then #Nom par défaut du dossier de syncronisation de Vagrant
file='data'
fi
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
echo "
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(\"2\") do |config|
config.vm.box = \"ubuntu/xenial64\"
config.vm.network \"private_network\", ip: \"$ip\"
config.vm.synced_folder \"./$file\", \"/var/www/html/\"
config.vm.provider \"virtualbox\" do |v|
v.name = \"$nom\"
end
end
" > ./Vagrantfile #Ficher de config de Vagrant
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
mkdir ./${file} #Dossier sync
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
echo "Installation d'un gestionaire de base de donnée?"
select optSGBD in Adminer Phpmyadmin; do
case $optSGBD in
Adminer)
echo 'Installation de Adminer..'
wget -q https://github.com/vrana/adminer/releases/download/v4.7.1/adminer-4.7.1-mysql.php #Installation de Adminer
mv adminer-4.7.1-mysql.php ./${file}/adminer.php
echo 'Done!'
;;
Phpmyadmin)
echo 'Installation de PhpMyAdmin..'
wget -q https://files.phpmyadmin.net/phpMyAdmin/4.9.4/phpMyAdmin-4.9.4-all-languages.tar.gz #Installation de Adminer
mkdir ./${file}/phpmyadmin
tar -zxf phpMyAdmin-4.9.4-all-languages.tar.gz -C ./${file}/phpmyadmin --strip-components 1
rm -R phpMyAdmin-4.9.4-all-languages.tar.gz
echo 'Done!'
;;
esac
break
done
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #Création du script d'installation une fois dans la VM
# shellcheck disable=SC2016
echo '
#!/bin/bash
echo "Choisis une version de PHP"
select optPHP in php7.4 php7.3 php7.2 php5.6; do
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install apache2 -y
sudo apt install ${optPHP} -y
sudo apt install libapache2-mod-${optPHP} -y
sudo apt install php-xdebug -y
sudo apt install ${optPHP}-mysql -y
sudo apt install ${optPHP}-zip -y
sudo apt install ${optPHP}-mbstring -y
sudo apt install ${optPHP}-dom -y
sudo apt install ${optPHP}-curl -y
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password <PASSWORD>"
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password <PASSWORD>"
sudo apt install mysql-server -y
php -r "copy('\''https://getcomposer.org/installer'\'', '\''composer-setup.php'\'');"
php composer-setup.php
php -r "unlink('\''composer-setup.php'\'');"
sudo mv composer.phar /usr/local/bin/composer
case $optPHP in
php5.6)
sudo sed -i '\''466s/Off/On/'\'' /etc/php/5.6/apache2/php.ini
sudo sed -i '\''477s/Off/On/'\'' /etc/php/5.6/apache2/php.ini
sudo sed -i '\''16s/www-data/vagrant/'\'' /etc/apache2/envvars
sudo sed -i '\''17s/www-data/vagrant/'\'' /etc/apache2/envvars
;;
*)
sudo sed -i '\''474s/Off/On/'\'' /etc/php/7.3/apache2/php.ini
sudo sed -i '\''485s/Off/On/'\'' /etc/php/7.3/apache2/php.ini
sudo sed -i '\''16s/www-data/vagrant/'\'' /etc/apache2/envvars
sudo sed -i '\''17s/www-data/vagrant/'\'' /etc/apache2/envvars
;;
esac
sudo a2enmod rewrite
sudo service apache2 restart
echo "Done! Ton mot de passe mysql est 1234, change le!"
rm /var/www/html/install.sh
break
done
' > ./$file/install.sh
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
rm awesomeScript.sh
vagrant up
vagrant ssh
| 86409f7169e2205b92fb863223891058d6b17a06 | [
"Markdown",
"Shell"
] | 2 | Markdown | Kara-tatouille/ScriptsVirtualMachine | 1ecd613c1edbf15582318ae6638844a80dc97448 | eea126fd02bb3c744508e29ad6a410fd971671c2 |
refs/heads/master | <file_sep>from neo4j.v1 import GraphDatabase
import csv
from itertools import islice
'''
This program will import the roadNet-CA.txt file (containing 1965206 nodes and 5533214 edges)
into a Neo4j graph and then query a small subset of that and add it to a network x graph.
All nodes within 3 steps of road id 0 are stored in subgraph.csv for further processing
'''
class RoadNet(object):
def __init__(self, uri, user, password):
self._driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self._driver.close()
def query(self, query):
with self._driver.session() as session:
return session.run(query)
if __name__ == '__main__':
neo = RoadNet('bolt://localhost:7687', 'neo4j', '<PASSWORD>')
neo.query('MATCH (n) DETACH DELETE n')
neo.query('CREATE CONSTRAINT ON (r:Road) ASSERT r.id IS UNIQUE')
with open('roadNet-CA.txt', newline='') as csvfile:
next(islice(csvfile, 4, 4), None)
for r in csv.reader(csvfile, delimiter='\t'):
neo.query(f'MERGE (r1:Road {{id: {r[0]}}})'
f'MERGE (r2:Road {{id: {r[1]}}})'
'CREATE (r1)-[:CONNECTS]->(r2)')
results = [(r1, r2) for r1, r2 in neo.query('MATCH p=(:Road {id: 0})-[:CONNECTS*1..3]->(:Road) '
'WITH p '
'MATCH (r3:Road)-[:CONNECTS*1..3]->(r4:Road) '
'WHERE r3 IN nodes(p) AND r4 in nodes(p) AND r3 <> r4 '
'RETURN DISTINCT r3.id, r4.id')]
print(results)
with open('subgraph.csv', 'w') as write_file:
writer = csv.writer(write_file)
writer.writerows(results) | 4de26196841341becf3511ea701720f412de4f30 | [
"Python"
] | 1 | Python | brian-cuny/620assignment2 | 7a95f9f800fc417fa2707527f0b934aaf6d40a61 | 58f845fd4cd56a1cf2545f28bf42c4433f99d5d1 |
refs/heads/master | <file_sep>package com.javatest.yunpan.dao;
import com.javatest.yunpan.dto.UserInfo;
import com.javatest.yunpan.entity.MoreUserInfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MoreUserInfoDao {
UserInfo findUserInfo(int id);
int finishUserInfo(MoreUserInfo moreUserInfo);
int updateUserInfo(MoreUserInfo moreUserInfo);
int accoutnVertify(String email);
}
<file_sep>logging.config=classpath:log4j2.xml
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
spring.http.encoding.enabled=true
spring.http.multipart.location=/
spring.http.multipart.max-file-size=1024MB
spring.http.multipart.max-request-size=1024MB
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/yunpan?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.userPassword=<PASSWORD>
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0
<file_sep>package com.javatest.yunpan.service.impl;
import com.javatest.yunpan.service.FileService;
import com.javatest.yunpan.util.FileReceiver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
@Service
public class FileServiceImpl implements FileService {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
@Override
public boolean checkFileExits(String md5) {
return false;
}
@Override
public void saveFileByMD5(String md5, InputStream inputStream) throws IOException {
new FileReceiver(md5,inputStream).run();
}
@Override
public void finishFileUpload(String md5) {
SetOperations setOperations = redisTemplate.opsForSet();
Iterator iterator = setOperations.members(md5).iterator();
while (iterator.hasNext()) {
setOperations.remove(md5, iterator.next());
}
}
@Override
public void writeChunkToFileByMD5(String md5, InputStream inputStream, int chunk) throws IOException {
new FileReceiver(md5, inputStream, chunk).run();
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.add(md5, chunk);
}
@Override
public boolean checkChunkExits(String md5, int id) {
SetOperations setOperations = redisTemplate.opsForSet();
return setOperations.isMember(md5, id);
}
}
<file_sep>package com.javatest.yunpan.dao;
import com.javatest.yunpan.entity.BasicUserInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface BasicUserInfoDao {
Integer findOne(BasicUserInfo basicUserInfo);
int insertOne(BasicUserInfo basicUserInfo);
String selectEmailByEmail(String email);
List<BasicUserInfo> findMany();
}
<file_sep>package com.javatest.yunpan;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void connectTest() {
stringRedisTemplate.opsForValue().set("test", "success");
Assert.assertEquals("success", stringRedisTemplate.opsForValue().get("test"));
}
@Test
public void ObjectCRUDTest() {
String key = "md5";
SetOperations<String, Integer> setOperations = redisTemplate.opsForSet();
setOperations.add(key, 1);
setOperations.add(key, 2);
Assert.assertEquals(new Long(2), setOperations.size(key));
Assert.assertEquals(true, setOperations.isMember(key, 1));
Assert.assertEquals(true, setOperations.isMember(key, 2));
Assert.assertEquals(false, setOperations.isMember(key, 3));
}
}
<file_sep>package com.javatest.yunpan.controller;
import com.javatest.yunpan.dto.ResponseResult;
import com.javatest.yunpan.dto.ResponseResultFactory;
import com.javatest.yunpan.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@RestController
public class FileController {
@SuppressWarnings("all")
@Autowired
private HttpServletRequest httpServletRequest;
@Autowired
private FileService fileService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseResult fileUpload(@RequestParam("file")MultipartFile multipartFile) {
String md5 = httpServletRequest.getParameter("md5");
long size = Long.parseLong(httpServletRequest.getParameter("size"));
if (httpServletRequest.getParameter("chunks") != null) {
int chunk = Integer.parseInt(httpServletRequest.getParameter("chunk"));
try {
fileService.writeChunkToFileByMD5(md5, multipartFile.getInputStream(), chunk);
} catch (IOException e) {
e.printStackTrace();
return ResponseResultFactory.getResponseResult(false, "Fail to receive chunk:" + chunk);
}
} else {
try {
fileService.saveFileByMD5(md5,multipartFile.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return ResponseResultFactory.getResponseResult(false, "Fail to receive file");
}
}
return ResponseResultFactory.getResponseResult(true, "文件上传成功");
}
@RequestMapping(value = "/upload/{md5}", method = RequestMethod.POST)
public ResponseResult finishFileUpload(@PathVariable String md5) {
HttpSession httpSession = httpServletRequest.getSession();
System.out.println(httpSession.getId());
fileService.finishFileUpload(md5);
return ResponseResultFactory.getResponseResult(true, "文件上传完成");
}
@RequestMapping(value = "/fileMD5/{md5}", method = RequestMethod.GET)
public ResponseResult checkFileExits(@PathVariable String md5) {
System.out.println(md5);
return ResponseResultFactory.getResponseResult(true, md5);
}
@RequestMapping(value = "/chunk/{chunk}", method = RequestMethod.GET)
public ResponseResult checkChunkExits(@RequestParam("md5") String md5, @PathVariable("chunk") int id) {
if (!fileService.checkChunkExits(md5,id)) {
return ResponseResultFactory.getResponseResult(true, "Have not received this chunk");
}
return ResponseResultFactory.getResponseResult(false, "This chunk has be received");
}
}
| e36135be0bec9b92f83be0a189a99ee97eb2b377 | [
"Java",
"INI"
] | 6 | Java | wwwwwzy/yunpan | 05700478ae1f3ea54376d1c92f275918dd7cc046 | 4d82ce2867167fbed3eeb8a1ed5f40bff1846599 |
refs/heads/master | <file_sep>class User < ActiveRecord::Base
has_secure_password validation: false
has_many :comments
end
| 4fa48da8fca03a8dd0c1aba3510509c464b534a7 | [
"Ruby"
] | 1 | Ruby | p9690110/ruby-on-rail-food | 0bc413d38bc409f5de33c6655ea24643643c99c9 | a7775094e4f3393b21e002a2819891d15a834bed |
refs/heads/master | <repo_name>msinha132/FCMtest<file_sep>/README.md
# FCMtest
Everybody needs a push notification feature in their app
This is just a simple application of push notification.
What's different:
Once it is complete, I will be putting proper comments in the code so you don't need to study the whole code for its mere application in your app.
Plus I will also write stepwise how to work out on this functionality.
<file_sep>/webFirebase/register.php
<?php
error_reporting(E_ALL);
if(isset($_POST["Token"])){
$token= $_POST["Token"];
$conn = mysqli_connect("localhost","1013086","mohitsinha","1013086");
$query = "INSERT INTO users{Token} Values ('$token') ON DUPLICATE KEY UPDATE Token= '$token';";
mysqli_query($conn,$query);
mysqli_close($query);
}
?> | 70c80644a158bff6a762ec7020a9105f5b485472 | [
"Markdown",
"PHP"
] | 2 | Markdown | msinha132/FCMtest | 9f862801ee3fea456fb9f102af4459478343c9f1 | 8652c5af2f943529c21cf8da9012023198385483 |
refs/heads/master | <file_sep>import pygame
import random
from math import sqrt
FPS = 60
WIDTH, HEIGHT = 600, 400
GRAVITY = 980
RUNNING = True
class Target:
shape_radius = 10
color = (255, 255, 0)
speed = 10
def __init__(self, x: int, y: int):
self.x = x
self.y = y
self.speed = Target.speed
self.radius = Target.shape_radius
self.color = Target.color
def move(self):
pass
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
class Ball:
shape_radius = 5
color = (255, 0, 0)
def __init__(self, x: int, y: int, velocity_x: float, velocity_y: float):
self.x = x
self.y = y
self.velocity_x = velocity_x
self.velocity_y = velocity_y
self.shape_radius = Ball.shape_radius
self.color = Ball.color
self.active = True
def move(self, tick):
self.x += self.velocity_x * tick
self.y += self.velocity_y * tick
self.velocity_y += GRAVITY * tick
self.bounce()
def collide(self, targets):
index_of_collide = -1
for i, target in enumerate(targets):
if (self.x - target.x) ** 2 + (self.y - target.y) ** 2 <= (self.shape_radius + target.shape_radius) ** 2:
index_of_collide = i
break
if index_of_collide != -1:
targets.pop(index_of_collide)
self.active = False
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.shape_radius)
def bounce(self):
if self.x < self.shape_radius:
self.velocity_x = abs(self.velocity_x) * 0.6
self.velocity_y *= 0.6
if self.x > WIDTH - self.shape_radius:
self.velocity_x = -abs(self.velocity_x) * 0.6
self.velocity_y *= 0.6
if self.y < self.shape_radius:
self.velocity_y = abs(self.velocity_y) * 0.6
self.velocity_x *= 0.6
if self.y > HEIGHT - self.shape_radius:
self.velocity_y = -abs(self.velocity_y) * 0.6
self.velocity_x *= 0.6
if abs(self.velocity_x) < 10:
self.velocity_x = 0
if abs(self.velocity_y) < 10:
self.velocity_y = 0
class Cannon:
color = (50, 50, 50)
speed = 10
def __init__(self, x: int, y: int, fire_power: float):
self.x = x
self.y = y
self.width = 60
self.height = 30
self.fire_power = fire_power
self.speed = Cannon.speed
self.color = Cannon.color
self.aim_x = x
self.aim_y = y
self.direction = 0
def move(self):
new_x = self.x + self.direction * self.speed
if new_x < 0:
self.x = 0
elif new_x > WIDTH - self.width:
self.x = WIDTH - self.width
else:
self.x = new_x
def aim(self, mouse_x, mouse_y):
self.aim_x, self.aim_y = mouse_x, mouse_y
def fire(self, balls):
x = self.x + self.width // 2
y = self.y + self.height // 2
length = sqrt((x - self.aim_x) ** 2 + (y - self.aim_y) ** 2)
velocity_x = (self.aim_x - x) * self.fire_power / length
velocity_y = (self.aim_y - y) * self.fire_power / length
balls.append(Ball(x, y, velocity_x, velocity_y))
def draw(self, screen):
pygame.draw.rect(screen, self.color, (self.x, self.y + self.height // 2, self.width, self.height // 2)) # base of cannon
pygame.draw.circle(screen, self.color, (self.x + self.width // 2, self.y + self.height // 2), self.height // 2) # sphere of cannon
def generate_targets(targets, count=10):
t = Target.shape_radius
for _ in range(count):
x, y = random.randint(t, WIDTH - t), random.randint(t, HEIGHT // 2 - t)
targets.append(Target(x, y))
def input_handler(events, cannon: Cannon, balls):
global RUNNING
for event in events:
if event.type == pygame.QUIT:
RUNNING = False
if event.type == pygame.KEYDOWN:
key = event.key
if key == pygame.K_LEFT:
cannon.direction = -1
if key == pygame.K_RIGHT:
cannon.direction = 1
if event.type == pygame.KEYUP:
key = event.key
if key == pygame.K_LEFT or key == pygame.K_RIGHT:
cannon.direction = 0
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
cannon.fire(balls)
if event.type == pygame.MOUSEMOTION:
x, y = event.pos
cannon.aim(x, y)
# TODO change control. Then you going right an change to left, cannon is stopped becouse right is UP and direction is 0
def update_objects(cannon: Cannon, balls, targets, tick):
for target in targets:
target.move()
for ball in balls:
if ball.active:
ball.move(tick)
ball.collide(targets)
cannon.move()
def draw_objects(screen, cannon: Cannon, balls, targets):
screen.fill((120, 120, 120))
for ball in balls:
if ball.active:
ball.draw(screen)
for target in targets:
target.draw(screen)
cannon.draw(screen)
pygame.display.flip()
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
cannon = Cannon(WIDTH // 2, HEIGHT * 9 // 10, 900)
balls = []
targets = []
generate_targets(targets)
while RUNNING:
input_handler(pygame.event.get(), cannon, balls)
update_objects(cannon, balls, targets, clock.get_time() / 1000)
draw_objects(screen, cannon, balls, targets)
clock.tick(FPS)
if __name__ == "__main__":
main()
pygame.quit()
| 9b5bc2c5a62deda48dcae4af80656f04fd69c696 | [
"Python"
] | 1 | Python | DJan03/Pygame-Cannon_vs_Invaders | d687150ab20cd74fdc7bd6fad94211e27f93e427 | b0e6cfc02338ac0d39c68773590fdd55912c42a4 |
refs/heads/master | <file_sep>#include "Globals.h"
#include "Application.h"
#include "ModuleRender.h"
#include "ModuleSceneIntro.h"
#include "ModuleInput.h"
#include "ModuleTextures.h"
#include "ModulePhysics.h"
ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled)
{
circle = box = rick = NULL;
}
ModuleSceneIntro::~ModuleSceneIntro()
{}
// Load assets
bool ModuleSceneIntro::Start()
{
LOG("Loading Intro assets");
bool ret = true;
App->renderer->camera.x = App->renderer->camera.y = 0;
circle = App->textures->Load("pinball/wheel.png");
box = App->textures->Load("pinball/crate.png");
rick = App->textures->Load("pinball/rick_head.png");
return ret;
}
// Load assets
bool ModuleSceneIntro::CleanUp()
{
LOG("Unloading Intro scene");
circleList.clear();
boxList.clear();
chainList.clear();
return true;
}
// Update: draw background
update_status ModuleSceneIntro::Update()
{
// TODO 4: Move all creation of bodies on 1,2,3 key press here in the scene
// On space bar press, create a circle on mouse position
if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN)
{
PhysBody* body = App->physics->createCircle(25);
circleList.add(body);
}
if (App->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN)
{
// TODO 1: When pressing 2, create a box on the mouse position
// To have the box behave normally, set fixture's density to 1.0f
PhysBody* body = App->physics->createBox(50.0f, 25.0f);
boxList.add(body);
}
if (App->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN)
{
// TODO 2: Create a chain shape using those vertices
// remember to convert them from pixels to meters!
PhysBody* body = App->physics->createChain(App->physics->rick_head, 40);
chainList.add(body);
}
// TODO 6: Draw all the circles using "circle" texture
// circles draw
p2List_item<PhysBody*>* item = circleList.getFirst();
while (item != NULL)
{
App->renderer->Blit(circle, METERS_TO_PIXELS(item->data->GetPosition().x) - 25, METERS_TO_PIXELS(item->data->GetPosition().y) - 25,
NULL, 1.0f, item->data->GetRotation());
item = item->next;
}
// box draw
item = boxList.getFirst();
while (item != NULL)
{
App->renderer->Blit(box, METERS_TO_PIXELS(item->data->GetPosition().x) - 50, METERS_TO_PIXELS(item->data->GetPosition().y) - 25,
NULL, 1.0f, item->data->GetRotation());
item = item->next;
}
item = chainList.getFirst();
while (item != NULL)
{
App->renderer->Blit(rick, METERS_TO_PIXELS(item->data->GetPosition().x), METERS_TO_PIXELS(item->data->GetPosition().y),
NULL, 1.0f, item->data->GetRotation());
item = item->next;
}
return UPDATE_CONTINUE;
}
<file_sep>#pragma once
#include "Module.h"
#include "Globals.h"
#include "p2Point.h"
#define GRAVITY_X 0.0f
#define GRAVITY_Y -7.0f
#define PIXELS_PER_METER 50.0f // if touched change METER_PER_PIXEL too
#define METER_PER_PIXEL 0.02f // this is 1 / PIXELS_PER_METER !
#define METERS_TO_PIXELS(m) ((int) floor(PIXELS_PER_METER * m))
#define PIXEL_TO_METERS(p) ((float) METER_PER_PIXEL * p)
class b2World;
class b2Body;
// TODO 5: Create a small class that keeps a pointer to the b2Body
// and has a method to request the position
// then write the implementation in the .cpp
// Then make your circle creation function to return a pointer to that class
class PhysBody
{
private:
b2Body * body = nullptr;
public:
PhysBody() {};
//~PhysBody();
PhysBody(b2Body* b) : body(b) {};
p2Point<float> GetPosition();
double GetRotation();
};
class ModulePhysics : public Module
{
public:
ModulePhysics(Application* app, bool start_enabled = true);
~ModulePhysics();
bool Start();
update_status PreUpdate();
update_status PostUpdate();
bool CleanUp();
// TODO 3: Move body creation to 3 functions to create circles, rectangles and chains
PhysBody* createCircle(float radius);
PhysBody* createBox(float hx, float hy);
PhysBody* createChain(int vector[], int size);
int rick_head[80] = {
41, 0,
55, 10,
67, 22,
75, 31,
81, 22,
84, 14,
87, 5,
93, 16,
94, 26,
94, 40,
112, 35,
105, 57,
106, 62,
117, 66,
109, 75,
110, 81,
109, 88,
106, 94,
111, 100,
103, 105,
101, 117,
105, 121,
106, 126,
99, 127,
94, 139,
85, 147,
72, 149,
60, 146,
49, 137,
46, 132,
35, 137,
40, 127,
23, 125,
31, 115,
8, 103,
29, 92,
0, 77,
30, 63,
13, 36,
42, 39
};
private:
bool debug;
b2World* world;
};<file_sep># physics 2 dev
| fb2d344d87b213f2cec6dc7c5b5a6a4b47a0e838 | [
"Markdown",
"C++"
] | 3 | C++ | peterMcP/physics-2-dev | edf1371b5bebf4c44c5f7a102a4189b0602d1fcd | 1301941a373d327403f65a84edf5d50ac0aa387d |
refs/heads/master | <repo_name>silverXnoise/waveforms_linux<file_sep>/main.h
#ifndef __MAIN__H__
#define __MAIN__H__
#include<stdio.h>
#include <stdlib.h>
#include <unistd.h>
//The main header file, handling the running of the interface
void getInfo(HDWF * pDevice);
void configure(HDWF * pDevice, int channel, int * bufSize);
void run(HDWF * pDevice, int channel, int bufSize);
#define TRUE 1
#define FALSE 0
#endif
<file_sep>/README.md
# Interfacing with the Digilent Analog Discovery
* The shared library is located @ '/usr/lib/libdwf.so.2.7.5'
* The header file is located @ '/usr/local/include/digilent/waveforms/dwf.h'
* Command line executable is 'dwfcmd'
* Analog input ie) dwfcmd connect debug=2 pause=2 ai single freq=100000 channel=2 enable=1 range=2 samples=5000 start finish save=ao.txt show
<file_sep>/impl.c
#include<digilent/waveforms/dwf.h>
#include "main.h"
void getInfo(HDWF * pDevice) {
HDWF device = *pDevice;
//Get Trigger Info for device
int genIntVal;
FDwfDeviceTriggerInfo(device, &genIntVal);
if(IsBitSet(genIntVal,trigsrcNone)) {
} if(IsBitSet(genIntVal, trigsrcPC)) {
} if(IsBitSet(genIntVal, trigsrcDetectorAnalogIn)) {
} if(IsBitSet(genIntVal, trigsrcDetectorDigitalIn)) {
} if(IsBitSet(genIntVal, trigsrcAnalogIn)) {
} if(IsBitSet(genIntVal, trigsrcDigitalIn)) {
} if(IsBitSet(genIntVal, trigsrcDigitalOut)) {
} if(IsBitSet(genIntVal, trigsrcAnalogOut1)) {
} if(IsBitSet(genIntVal, trigsrcAnalogOut2)) {
} if(IsBitSet(genIntVal, trigsrcAnalogOut3)) {
} if(IsBitSet(genIntVal, trigsrcAnalogOut4)) {
} if(IsBitSet(genIntVal, trigsrcExternal1)) {
} if(IsBitSet(genIntVal, trigsrcExternal2)) {
} if(IsBitSet(genIntVal, trigsrcExternal3)) {
} if(IsBitSet(genIntVal, trigsrcExternal4)) {
}
FDwfAnalogInBitsInfo(device, &genIntVal);
printf("Num Bits: %d\n", genIntVal);
double minVolts, maxVolts, rSteps;
FDwfAnalogInChannelRangeInfo(device, &minVolts, &maxVolts, &rSteps);
printf("[RANGE] min: %f, max: %f, steps: %f\n",minVolts,maxVolts, rSteps);
int numSteps;
double rangeSteps[32];
FDwfAnalogInChannelRangeSteps(device, rangeSteps, &numSteps);
printf("Num Steps: %d\n",numSteps);
for(int i = 0; i < 32; ++i) {
printf("Step[%d]: %f\n",i,rangeSteps[i]);
}
FDwfAnalogInChannelOffsetInfo(device, &minVolts, &maxVolts, &rSteps);
printf("[OFFSET] min: %f, max: %f, steps: %f\n",
minVolts, maxVolts, rSteps);
printf("--------------\nDigital\n\n");
FDwfDigitalInBitsInfo(device, &genIntVal);
printf("Num Digital Bits: %d\n", genIntVal);
double genDouble;
FDwfDigitalInInternalClockInfo(device, &genDouble);
printf("Internal Clock Frequency: %f\n",genDouble);
FDwfDigitalInClockSourceInfo(device, &genIntVal);
printf("ClockSource %x\n",genIntVal);
if(IsBitSet(genIntVal, DwfDigitalInClockSourceInternal)){
printf("Digital Internal clock\n");
} if(IsBitSet(genIntVal, DwfDigitalInClockSourceExternal)) {
printf("Digital External clock\n");
}
unsigned int genUInt;
FDwfDigitalInDividerInfo(device, &genUInt);
printf("Max clock divider: %u\n", genUInt);
FDwfDigitalInBufferSizeInfo(device, &genIntVal);
printf("Max Digital BufferSize: %d\n", genIntVal);
FDwfDigitalInSampleModeInfo(device, &genIntVal);
if(IsBitSet(genIntVal, DwfDigitalInSampleModeSimple)){
printf("Simple Sample Mode supported\n");
} if(IsBitSet(genIntVal, DwfDigitalInSampleModeNoise)) {
printf("Noise Sample Mode supported\n");
}
FDwfDigitalInAcquisitionModeInfo(device, &genIntVal);
if(IsBitSet(genIntVal, acqmodeSingle)) {
printf("Acq single\n");
} if(IsBitSet(genIntVal, acqmodeScanShift)) {
printf("Acq scan shift\n");
} if(IsBitSet(genIntVal, acqmodeScanScreen)) {
printf("Acq scan screen\n");
}
}
void configure(HDWF * pDevice, int channel, int * bufSize) {
int genIntVal;
HDWF device = *pDevice;
//Autoconfigure (configures after every set if true)
FDwfDeviceAutoConfigureSet(device, FALSE);
BOOL genBool;
FDwfDeviceAutoConfigureGet(device, &genBool);
printf("Autonfigure: %d\n",genBool);
//Reset all AnalogIn Instruments
FDwfAnalogInReset(device);
//Set Parameters
double frequency = 100000;
*bufSize = 5000;
FDwfAnalogInAcquisitionModeSet(device, acqmodeScanScreen);
FDwfAnalogInFrequencySet(device, frequency);
FDwfAnalogInChannelEnableSet(device, channel, TRUE);
double rSteps;
FDwfAnalogInChannelRangeSet(device, channel, 2);
FDwfAnalogInChannelRangeGet(device, channel, &rSteps);
printf("Range set to %f\n",rSteps);
//FDwfAnalogInChannelOffsetSet(device, channel, -5);
FDwfAnalogInChannelOffsetGet(device, channel, &rSteps);
printf("Offset set to %f\n",rSteps);
FDwfAnalogInBufferSizeSet(device, *bufSize);
//Get actual values
FDwfAnalogInBufferSizeGet(device, bufSize);
FDwfAnalogInFrequencyGet(device, &frequency);
//FDwfAnalogInRecordLengthSet(device, *bufSize / frequency);
sleep(1);
}
void run(HDWF * pDevice, int channel, int bufSize) {
HDWF device = *pDevice;
int genIntVal;
BOOL genBool;
//Start
FDwfAnalogInConfigure(device, TRUE,//TRUE resets auto trigger
TRUE); //Starts acquisition
DwfState devState = DwfStateRunning;
//State machine running through
double * data = malloc(sizeof(double) * bufSize);
double dataSample;
FILE * fp = fopen("output.txt", "w");
int dataId = 0;
char line[4096];
while(devState != DwfStateDone) {
printf("Get Status\n");
fgets(line, sizeof(line), stdin);
FDwfAnalogInStatus(device, TRUE, &devState);
if(devState == DwfStateReady) {
printf("Ready\n");
} else if(devState == DwfStateConfig) {
printf("Config\n");
} else if(devState == DwfStatePrefill) {
printf("Prefill\n");
} else if(devState == DwfStateArmed) {
printf("Armed\n");
} else if(devState == DwfStateWait) {
printf("Wait\n");
} else if(devState == DwfStateTriggered) {
printf("Triggered\n");
} else if(devState == DwfStateRunning) {
printf("Running\n");
} else if(devState == DwfStateDone) {
printf("Done\n");
}
/*
switch((int)devState) {
case (const int)DwfStateReady:
printf("Ready\n");
break;
case (const int)DwfStateConfig:
printf("Config\n");
break;
case (const int)DwfStatePrefill:
printf("Prefill\n");
break;
case (const int)DwfStateArmed:
printf("Armed\n");
break;
case (const int)DwfStateWait:
printf("Wait\n");
break;
case (const int)DwfStateTriggered:
printf("Triggered\n");
break;
case (const int)DwfStateRunning:
printf("Running\n");
break;
case (const int)DwfStateDone:
printf("Running\n");
break;
}
*/
FDwfAnalogInStatusSamplesLeft(device, &genIntVal);
printf("Samples Left: %d\n", genIntVal);
FDwfAnalogInStatusSamplesValid(device, &genIntVal);
printf("Samples Valid: %d\n", genIntVal);
int numSamples = genIntVal;
FDwfAnalogInStatusAutoTriggered(device, &genBool);
printf("Auto Triggered: %d\n", genBool);
//Never happen on single because no valid samples
printf("Data Call: %d\n", FDwfAnalogInStatusData(device, channel, data, numSamples));
for(int i = 0; i < numSamples; ++i) {
fprintf(fp, "%d\t%f\n", dataId++, data[i]);
}
dataId = 0;
fprintf(fp, "\n");
printf("Sample Call: %d\n", FDwfAnalogInStatusSample(device, channel, &dataSample));
printf("Sample: %f\n", dataSample);
int dataAvail, dataLost, dataCorrupt;
FDwfAnalogInStatusRecord(device, &dataAvail, &dataLost, &dataCorrupt);
//This is difference since last read
printf("Avail:%d, Lost:%d, Corrupt:%d\n",
dataAvail, dataLost, dataCorrupt);
//Used in Scan Screen
FDwfAnalogInStatusIndexWrite(device, &genIntVal);
printf("Status Index Write: %d\n", genIntVal);
double rSteps;
FDwfAnalogInChannelRangeGet(device, channel, &rSteps);
printf("Range set to %f\n",rSteps);
FDwfAnalogInChannelOffsetGet(device, channel, &rSteps);
printf("Offset set to %f\n",rSteps);
}
//get data
FDwfAnalogInStatusData(device,channel, data, bufSize);
for(int i = 0; i < bufSize; ++i) {
printf("%d\t%f\n", i, data[i]);
}
//Stop instrument
FDwfAnalogInConfigure(device, FALSE, FALSE);
//free data & close
free(data);
}
<file_sep>/Makefile
OBJS := main.o impl.o
BIN := run
all: $(OBJS)
gcc -o $(BIN) $(OBJS) -L/usr/lib -ldwf
main.o: main.c main.h
gcc -c -std=c99 main.c
impl.o: impl.c main.h
gcc -c -std=c99 impl.c
clean:
rm $(OBJS) $(BIN)
| 7146e6a928cb000cfc70b655662e36d169567077 | [
"Markdown",
"C",
"Makefile"
] | 4 | C | silverXnoise/waveforms_linux | 162975a6f0c3d8fe92391d469e9c9fbfe4b21ada | 42bfaa37f8141f0b447f97ec029c9083344f1aa6 |
refs/heads/master | <file_sep>[English Version](./README-EN.md)
# vuejs-pwa-sample
## はじめに
本プロジェクトは、[Vue.js](https://jp.vuejs.org/index.html)、[Vue Material](https://vuematerial.io/)と[PWA(Progressive Web Apps)](https://developers.google.com/web/progressive-web-apps/)を用いて実装したサンプルである。
本サンプルでは、[Connpass Web API](https://connpass.com/about/api/)を利用している。
## 開発環境構築手順
以下の手順で開発環境を構築する。
1. [Node.js](https://nodejs.org/ja/)をダウンロード・インストールする。
1. [Visual Studio Code](https://code.visualstudio.com/)(以下、VS Code)をダウンロード・インストールする。
1. VS Codeの拡張機能である[vetur](https://github.com/vuejs/vetur)をインストールする。
1. 依存関係のあるライブラリをダウンロードする。
```bash
npm install
```
## 動作確認手順
以下の手順で動作を確認する。
1. 本リポジトリをクローンする。
1. ソースコードをビルドし実行する。
```bash
npm run serve
```
1. ブラウザで[http://localhost:8080/home](http://localhost:8080/home)にアクセスする。
開発環境では、Service Workerは動作しない設定となっている。
Service Workerの動作確認には[Service Worker for Chrome](https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb)を使うと良い。
1. Chromeブラウザに「Service Worker for Chrome」をインストールする。
1. 「Service Worker for Chrome」を起動する。
1. 「Service Worker for Chrome」の「choose folder」で``dist``ディレクトリを選ぶ。
1. 「Web Server URL」にアクセスする。
## 配布用ビルド手順
以下の手順でビルドする。
1. 配布用ビルドを実行する。
```bash
npm run build
```
## 画面一覧
表示する画面は以下の通りである。
|画面名|ファイル名|概要|
|:---|:---|:---|
|ホーム画面|``Home.vue``|Connpassでイベントを検索する画面|
|アプリ情報画面|``About.vue``|本アプリの情報を表示する画面|
## コンポーネント一覧
上記画面で利用するコンポーネントは以下の通りである。
|コンポーネント名|ファイル名|概要|
|:---|:---|:---|
|ヘッダー|``Header.vue``|Webアプリのヘッダーを定義|
|カード|``Card.vue``|コンテンツを表示するためのカードを定義|
## 利用ライブラリ
以下のライブラリを主に利用している。
|ライブラリ名|バージョン|概要|
|:---|:---:|:---|
|Vue.js|``2.6.10``|Javascriptフレームワーク|
|Vue Router|``3.0.3``|Vue.jsのためのルーティングライブラリ|
|Vue Material|``1.0.0-beta-10.2``|Vue.jsのためのマテリアルデザイン|
## ライセンス
本プロジェクトのライセンスは、MITライセンスです。
<file_sep># vuejs-pwa-sample
## Preface
This sample project uses [Vue.js](https://vuejs.org/index.html), [Vue Material](https://vuematerial.io/) and [PWA(Progressive Web Apps)](https://developers.google.com/web/progressive-web-apps/).
This sample uses the [Connpass Web API](https://connpass.com/about/api/).
## Install
Perform the following steps:
1. Download and install [Node.js](https://nodejs.org/ja/).
1. Download and install [Visual Studio Code(VS Code)](https://code.visualstudio.com/).
1. Install [vetur](https://github.com/vuejs/vetur) extension for VS Code.
1. Download and install npm packages.
```bash
npm install
```
## Starting Server
Perform the following steps:
1. Clone this repository.
1. Start the development server.
```bash
npm run serve
```
1. Access the following URL in Chrome.
[http://localhost:8080/home](http://localhost:8080/home)
By configuration, you cann't run Service Worker in the development environment.
So, I recommend using "[Service Worker for Chrome](https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb)" to run Service Worker.
1. Install "Service Worker for Chrome" in Chrome.
1. Start the "Service Worker for Chrome".
1. Select ``dist`` directory in "choose folder" of "Service Worker for Chrome".
1. Access the "Web Server URL".
## Creating a Production Build
Perform the following command:
```bash
npm run build
```
## Views
There are the following views in this sample.
|View Name|File Name|Description|
|:---|:---|:---|
|Home View|``Home.vue``|Search for events via the Connpass Web API.|
|About View|``About.vue``|About this sample.|
## Components
There are the following components in this sample.
|Component Name|File Name|Description|
|:---|:---|:---|
|Header|``Header.vue``|Define the header of this web app.|
|Card|``Card.vue``|Define a card to display content|
## Libraries
This sample uses the following library.
|Library Name|Version|Description|
|:---|:---|:---|
|Vue.js|``2.6.10``|Javascript Framework|
|Vue Router|``3.0.3``|Routing library for Vue.js|
|Vue Material|``1.0.0-beta-10.2``|Material Design for Vue.js|
## License
The License of this sample is *MIT License*.
<file_sep>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './registerServiceWorker'
import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default.css'
import VueJsonp from 'vue-jsonp'
Vue.use(VueMaterial)
Vue.use(VueJsonp)
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
| fb9e9a71a740f549d63c3faf422bc70d393e0c6c | [
"Markdown",
"JavaScript"
] | 3 | Markdown | ybkuroki/vuejs-pwa-sample | 86b58974d89d450779e4076bb40b7753da8251e2 | 1b7f460facf028fe2df8f7a696d4c05452153ccb |
refs/heads/master | <repo_name>LastStranger0/Huffman<file_sep>/TestProject/Huffman.cpp
#include "Huffman.h";
Huffman::Node::Node(Node* L, Node* R)
{
left = L;
right = R;
a = L->a + R->a;
}
Huffman::Node::Node() {
left = right = NULL;
}
bool Huffman::MyCompare::operator() (const Node* l, const Node* r) const {
return l->a < r->a;
}
void Huffman::BuildTable(Node* root) {
if (root->left != NULL)
{
code.push_back(0);
BuildTable(root->left);
}
if (root->right != NULL)
{
code.push_back(1);
BuildTable(root->right);
}
if (root->left == NULL && root->right == NULL) table[root->c] = code;
if (!code.empty())
{
code.pop_back();
}
}
void Huffman::print(Node* root, int k = 0) {
if (root != NULL)
{
print(root->right, k + 3);
for (int i = 0; i < k; i++)
{
cout << " ";
}
if (root->c) cout << root->a << "(" << root->c << ")" << endl;
else cout << root->a << endl;
print(root->left, k + 3);
}
}
Huffman::Huffman(string s) {
map<char, int> m;
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
m[c]++;
}
list<Node*> t;
for (map<char, int>::iterator itr = m.begin(); itr != m.end(); ++itr)
{
Node* p = new Node;
p->c = itr->first;
p->a = itr->second;
t.push_back(p);
}
////// создаем дерево
while (t.size() != 1)
{
t.sort(MyCompare());
Node* SonL = t.front();
t.pop_front();
Node* SonR = t.front();
t.pop_front();
Node* parent = new Node(SonL, SonR);
t.push_back(parent);
}
Node* root = t.front(); //root - указатель на вершину дерева
BuildTable(root);
print(root);
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
vector<bool> x = table[c];
for (int n = 0; n < x.size(); n++)
cout << x[n];
}
}<file_sep>/TestProject/Huffman.h
#pragma once
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <fstream>
#include <string>
using namespace std;
class Huffman
{
public:
Huffman(string);
class Node
{
public:
Node();
Node(Node*, Node*);
int a;
char c;
Node* left;
Node* right;
};
struct MyCompare
{
bool operator()(const Node*, const Node*) const;
};
vector<bool> code;
map<char, vector<bool>> table;
void BuildTable(Node*);
void print(Node*, int);
Node* root;
};
<file_sep>/Huffman/Huffman.cpp
#include <iostream>
#include <string>
#include "Huff.h"
using namespace std;
int main()
{
string m;
cin >> m;
Huffman t(m);
}
<file_sep>/TestProject/TestProject.cpp
#include <iostream>
#include <string>
#include "Huffman.h"
using namespace std;
int main()
{
string m;
cin >> m;
Huffman t(m);
}
| a7ec24767a4b9224a9f8fa69c71f90686a7c5bc0 | [
"C++"
] | 4 | C++ | LastStranger0/Huffman | e557fa13b14fbdba8f3062d04caf38d02e9c67c1 | e6e5c143344ad9008f4b1cb6a6284a6a8538229c |
refs/heads/master | <repo_name>SomuBhandari/UI_Improvement<file_sep>/assets/js/toucheffects.js
/** Used Only For Touch Devices **/
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
( function( window ) {
// for touch devices: add class cs-hover to the figures when touching the items
if( Modernizr.touch ) {
// classie.js https://github.com/desandro/classie/blob/master/classie.js
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else {
// browser global
window.classie = classie;
}
[].slice.call( document.querySelectorAll( 'ul.grid > li > figure' ) ).forEach( function( el, i ) {
el.querySelector( 'figcaption > a' ).addEventListener( 'touchstart', function(e) {
e.stopPropagation();
}, false );
el.addEventListener( 'touchstart', function(e) {
classie.toggle( this, 'cs-hover' );
}, false );
} );
}
})( window ); | f4065fb8f2e071e28396508d47100426659b4184 | [
"JavaScript"
] | 1 | JavaScript | SomuBhandari/UI_Improvement | e4675c4888f11f7be333deb0c644341308a9aa0d | da70b1e2fe4f385dbe6b407c36530992bc65aa45 |
refs/heads/master | <repo_name>arvindspal/stock<file_sep>/app.py
from flask import Flask, request, jsonify, render_template
from test import Test
app = Flask(__name__)
@app.route('/')
def home():
return '<h1>hello</h1>'
@app.route("/predict")
def predict():
test = Test()
predictedvalue = test.predict()
return render_template('index.html', prediction_text='Prediction $ {}'.format(predictedvalue[0][0]))
#return predictedvalue[0][0]
if __name__ == '__main__':
app.run()
<file_sep>/stockpriceprediction.py
import math
import pandas as pd
import pandas_datareader as web
import numpy as np
import datetime as dt
import time
import pickle
from datetime import timedelta
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.layers import Dropout
import matplotlib.pyplot as plt
import os
plt.style.use('fivethirtyeight')
##Initialize the parameters..
today = dt.date.today()
preDayDate = today - timedelta(1)
sDate = '2010-01-01'
eDate = preDayDate
retryCount = 3
datasource = 'yahoo'
stock = 'AAPL'
## hyperparameters..
batchsize=10
epochs=5
slots=60
LSTMNeurons=50
denseNeurons=25
## Read the data..
df = web.DataReader(stock, data_source=datasource, start=sDate, end=eDate, retry_count=retryCount)
plt.figure(figsize=(16,8))
plt.title('Price fluctuation')
plt.plot(df['Close'],color='skyblue', linewidth=1)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
## scale the data..
data = df.filter(['Close'])
dataset = data.values
train_data_len = math.ceil(len(dataset) * 0.8)
## Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaler_data = scaler.fit_transform(dataset)
train_data = scaler_data[0:train_data_len, :]
## Create x_train and y_train..
x_train = []
y_train = []
i=0
for i in range(slots, len(train_data)):
#print(i)
x_train.append(train_data[i-slots:i,0])
y_train.append(train_data[i,0])
## convert into numpy array..
x_train, y_train = np.array(x_train), np.array(y_train)
#reshape the array
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
def build_and_compile_model():
## Build the model
model = Sequential()
model.add(LSTM(LSTMNeurons, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(LSTMNeurons, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(denseNeurons))
model.add(Dropout(0.2))
model.add(Dense(1))
## Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
## Return the model
return model
def prepare_test_data():
## create test dataset
test_data = scaler_data[train_data_len - slots: ,:]
x_test = []
y_test = dataset[train_data_len: ,:]
i=0
for i in range(slots, len(test_data)):
#print(i)
x_test.append(test_data[i - slots:i,0])
## convert to array and reshape..
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
return x_test, y_test
def calculate_rmse(predictions, y_test):
## calculate RMSE
rmse = np.sqrt(np.mean(predictions - y_test)**2)
return rmse
def fit_model_and_make_prediction(model, x_test, b, e):
## fit the model
t1 = time.time()
model.fit(x_train, y_train, batch_size=b, epochs=e)
t2 = time.time()
total_time_taken = (t2-t1)
## Prediction..
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
return predictions, total_time_taken
def do_predictions(model, x_test):
## Prediction..
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
return predictions
def save_model(model, b, e):
## fit the model
model.fit(x_train, y_train, batch_size=b, epochs=e)
model_name = 'stockPicePrediction.sav'
if os.path.exists(model_name):
os.remove(model_name)
pickle.dump(model, open(model_name, 'wb'))
list_rmse = []
ep = [20,25,30,35,40,45,50]
bs = [30,35,40,45,50,55,60]
#===========
model = build_and_compile_model()
save_model(model, 45, 20)
#============
def call_iterations():
for e in ep:
for b in bs:
## get the model
model = build_and_compile_model()
## prepare the test data..
x_test, y_test = prepare_test_data()
## fit the model
predictions, total_time_taken = fit_model_and_make_prediction(model, x_test, b, e)
## make predictions
#predictions = do_predictions(fit_model, x_test)
## calculate rmse.
rmse = calculate_rmse(predictions, y_test)
r = []
r.append(e)
r.append(b)
r.append(rmse)
r.append(total_time_taken)
list_rmse.append(r)
#call_iterations() | 29327771efe1f1b5251395db7e1c36c7025d249b | [
"Python"
] | 2 | Python | arvindspal/stock | 39d18211d6c0bfe0c17075697be5ec9cf6d37f19 | 859d126657a68eb7253baa470c8eb15468be3014 |
refs/heads/master | <repo_name>StasOverflow/stm32_flash<file_sep>/app/utils.py
import wx
from itertools import cycle
import threading
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
def execute_every(func):
# def wrap(func=None):
def decorator(self=None):
# With this instruction we change receive bound method instead of a function
bound_method = func.__get__(self, type(self))
# if is not 0:
wx.CallLater(500, execute_every(bound_method))
return bound_method()
return decorator
# return wrap
def staying_alive():
string = (
("Ah", 0.5),
("Ah", 0.5),
("Ah", 0.5),
("Ah", 0.5),
("Staying_alive", 1),
("Staying_alive", 1),
)
iterator = cycle(string)
def do_cycle():
val = next(iterator)
text = val[0]
delay = val[1]
print(text)
threading.Timer(delay, do_cycle).start()
return do_cycle()
<file_sep>/app/application.py
import os
import sys
from app.back.back_data import AppData
from .gui.gui import GuiApplication
from app.utils import staying_alive
import threading
import time
from copy import deepcopy
from stm32loader.stm32loader import Stm32Loader
class Stm32Flash:
ACTION_READ = 1
ACTION_WRITE = 2
VALUE_DICTIONARY = {}
ACTION_TYPE = (
(ACTION_READ, 'ACTION_READ'),
(ACTION_WRITE, 'ACTION_WRITE'),
)
BAUDRATE_LIST = {
'9600': 9600,
'19200': 19200,
'38400': 38400,
'57600': 57600,
'115200': 115200,
'128000': 128000,
'230400': 230400,
'256000': 256000,
}
def __init__(self, **kwargs):
self._app = None
self._appdata = AppData()
self._ports = self._appdata.serial_ports_available
self._error_message = None
self.interface_data = None
self.write_action = False
self.read_action = False
kwargs['close_handler'] = self.close
kwargs['vals'] = self.VALUE_DICTIONARY
kwargs['read_handler'] = self.read_action_handler
kwargs['write handler'] = self.write_action_handler
self._port_poller = threading.Thread(target=self.port_poll)
self._input_data_thread = threading.Thread(target=self.input_data_collector)
self._back_thread = threading.Thread(target=self.background_loop_app)
self._staying_alive = threading.Thread(target=staying_alive)
self._input_data_thread.daemon = True
self._back_thread.daemon = True
self._staying_alive.daemon = True
self._port_poller.daemon = True
self.on_duty = False
self.gui_app(**kwargs)
@property
def on_action(self):
return self._app.action_is_on_going
@property
def error_message(self):
return self._error_message
def error_message_set(self, msg=None, code=None):
self._error_message = msg
if self.error_message is not None:
self._app.frame.panel.status_update(self._error_message)
self._app.frame.panel.error_is(code)
def read_thread_handler(self):
pass
def ports(self):
return self._ports
def input_data_collector(self):
"""
A function that should trigger gui provided interface functions
to get commands from front-end part of the app
"""
while True:
if self._app is not None:
if self.on_action is False:
self.interface_data = deepcopy(self._app.input_data_get())
time.sleep(0.2)
def background_loop_app(self):
while True:
if self._app is not None:
pass
time.sleep(0.3)
self._app.frame.panel.update_time_current()
def port_poll(self):
while True:
ports = self._appdata.serial_ports_available
if not self.on_duty:
self._ports = ports
time.sleep(0.3)
def gui_app(self, **kwargs):
kwargs['ports_getter'] = self.ports
kwargs['baud_list'] = self.BAUDRATE_LIST
self._app = GuiApplication(**kwargs)
def launch(self):
if self._app is not None:
self._input_data_thread.start()
self._back_thread.start()
self._staying_alive.start()
self._port_poller.start()
self._app.launch()
self._app.close()
# self.data_collect()
def close(self):
sys.exit()
def handler_init(self, action):
if not self.on_duty:
self.on_duty = True
file_path = self.interface_data['path']
port = self.interface_data['port']
baud_rate = self.interface_data['baud']
baud_rate = int(baud_rate) if baud_rate is not None else None
if port is not None:
pass
if baud_rate is not None:
if os.path.exists(file_path):
permission_to_execute = True
else:
permission_to_execute = False
self.error_message_set('Specify a path to file', 404)
else:
permission_to_execute = False
self.error_message_set('Specify a baudrate', 404)
else:
permission_to_execute = False
self.error_message_set('Specify a device port', 404)
if permission_to_execute:
self.on_duty = True
reset = self.interface_data['f_reset']
erase = True if self.interface_data['f_erase'] is False else False
verify = self.interface_data['f_verify']
self._app.action_is_on_going = False
self.error_message_set(('Started ' + ('writning' if action == self.ACTION_WRITE else 'reading') +
' operation'), None)
message = 'Done ' + ('writning' if action == self.ACTION_WRITE else 'reading')
kw_dict = {
'port': port,
'file_path': file_path,
'action': action,
'baud_rate': baud_rate,
'device': port,
'reset': reset,
'execute_flag': 1,
'callback': self.status_bar_update,
'verify': verify,
'erase': erase,
'message': message,
}
t = threading.Thread(target=self.launch_da_thread, kwargs=kw_dict)
t.daemon = True
t.start()
def read_action_handler(self):
self.handler_init(self.ACTION_READ)
def write_action_handler(self):
self.handler_init(self.ACTION_WRITE)
def launch_da_thread(self, **kwargs):
port = kwargs['port']
file_path_passed = kwargs['file_path']
action = kwargs['action']
baud_rate_passed = kwargs['baud_rate']
callback = kwargs['callback']
message = kwargs['message']
loader = Stm32Loader(logger=self._app.frame.panel.status_update)
argums = list()
argums.append('-p')
argums.append(port)
argums.append('-b')
argums.append(str(baud_rate_passed))
if action == self.ACTION_READ:
argums.append('-r')
argums.append('-v')
else:
argums.append('-e')
argums.append('-w')
argums.append('-v')
argums.append('-B')
argums.append('-R')
argums.append('-g')
argums.append('0x08000000')
try:
argums.append(file_path_passed)
loader.parse_arguments(argums, callback=callback)
loader.connect()
try:
loader.read_device_details()
loader.perform_commands()
finally:
loader.reset()
self.status_bar_update(100)
time.sleep(1)
self.error_message_set(message, 200)
finally:
self.on_duty = False
self._app.frame.panel.update_time_last()
self.on_duty = False
def status_bar_update(self, value):
self._app.frame.panel.status_bar_update(value)
<file_sep>/app/back/model/flasher.py
import ctypes
<file_sep>/app/gui/window/widgets/panel_widgets.py
import wx
import wx.adv
from app.gui.window.widgets.base import DynamicFlexibleChoice
from app.gui.window.widgets.base import StaticFlexibleChoice
from app.gui.window.widgets.base import InputFile
from app.gui.window.widgets.base import SettingsCheckBox
import datetime
class Panel(wx.Panel):
def __init__(self, parent, **kwargs):
self._size = kwargs['size']
self._read_action_handler = kwargs['read_handler']
self._write_action_handler = kwargs['write handler']
wx.Panel.__init__(self, parent, size=self._size)
self.interface_values = {
'port': None,
'baud': None,
'path': None,
'f_erase': None,
'f_verify': None,
'f_reset': None,
}
# Error Text Field
self.err_field = wx.StaticText(self, label="", pos=(20, 162))
# Error Iconio
self.err_icon = wx.StaticText(self, label="", pos=(230, 153))
font = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
'''
family can be:
wx.DECORATIVE, wx.DEFAULT, wx.MODERN, wx.ROMAN, wx.SCRIPT or wx.SWISS.
style can be:
wx.NORMAL, wx.SLANT or wx.ITALIC.
weight can be:
wx.NORMAL, wx.LIGHT, or wx.BOLD
'''
self.err_icon.SetFont(font)
self.err_icon.Hide()
# Choice 1
kwargs.setdefault('ports_getter', [None, None])
ports_property = kwargs['ports_getter']
print('ports property is', ports_property)
self.dyn_flex_dc = None
self._action_is_on_going = False
self.port_box = DynamicFlexibleChoice(self, label='Device port',
property_to_display=ports_property,
pos=(20, 20), width=110, dc=self.dyn_flex_dc)
self.Bind(self.port_box.event_on_choice, self.evt_choice_port, self.port_box)
# Choice 2
# kwargs.setdefault('baud_list', [None, None])
baud_property = kwargs['baud_list']
print(baud_property)
for baud in baud_property.keys():
if baud == '115200':
self.interface_values['baud'] = baud_property[baud]
self.baud_box = StaticFlexibleChoice(self, label='Baudrate',
property_to_display=baud_property,
pos=(240, 20), width=100)
self.Bind(self.port_box.event_on_choice, self.evt_choice_baud, self.baud_box)
# File Input
self.file_path_unit = InputFile(self, label='File path:', pos=(20, 60), callback=self.on_click)
# Settings sequence
# self.settings_label = wx.StaticText(self, label="Settings:", pos=(20, 100))
self.mode = SettingsCheckBox(self, label='Expert Mode', pos=(20, 100), checked=False)
self.Bind(wx.EVT_CHECKBOX, self.change_mode, self.mode)
self.erasing = SettingsCheckBox(self, label='Erase', pos=(20, 130), checked=True)
self.verify = SettingsCheckBox(self, label='Verify', pos=(120, 130), checked=True)
self.reset = SettingsCheckBox(self, label='Reset', pos=(210, 130), checked=True)
self.Bind(wx.EVT_CHECKBOX, self.evt_erase_checkbox, self.erasing)
self.Bind(wx.EVT_CHECKBOX, self.evt_verify_checkbox, self.verify)
self.Bind(wx.EVT_CHECKBOX, self.evt_reset_checkbox, self.reset)
self.interface_values['f_erase'] = self.erasing.flag
self.interface_values['f_verify'] = self.verify.flag
self.interface_values['f_reset'] = self.reset.flag
self.reset.Disable()
self.verify.Disable()
self.erasing.Disable()
button_pos_x = 310
# Execute Write operation
self.button_write = wx.Button(self, label="Write", pos=(button_pos_x, 155))
self.Bind(wx.EVT_BUTTON, self.on_press_write, self.button_write)
# Execute Read operation
self.button_read = wx.Button(self, label="Read", pos=(button_pos_x, 185))
self.button_read.Disable()
self.Bind(wx.EVT_BUTTON, self.on_press_read, self.button_read)
# Cancel Button
self.button_cancel = wx.Button(self, label="Cancel", pos=(button_pos_x, 215))
self.Bind(wx.EVT_BUTTON, self.on_press_cancel, self.button_cancel)
self.button_cancel.Disable()
self.button_cancel.Hide()
# Status progress bar
self.status_bar = wx.Gauge(self, range=100, pos=(20, 187), size=(230, 20), style=wx.GA_HORIZONTAL)
self.status_bar.SetValue(0)
width = 141
self.status_under_bar_status = wx.StaticText(self, label="", pos=(0, 222), size=(width, 17),
style=wx.ALIGN_LEFT)
self.status_under_bar_status.SetBackgroundColour((200, 200, 200)) # set text color
self.status_under_bar_current = wx.StaticText(self, label="", pos=(width + 1, 222), size=(width, 17),
style=wx.ALIGN_CENTRE_HORIZONTAL)
self.status_under_bar_current.SetBackgroundColour((200, 200, 200)) # set text color
self.update_time_current()
self.status_under_bar_last_one = wx.StaticText(self, label="", pos=((width + 1) * 2, 222), size=(width, 17),
style=wx.ALIGN_RIGHT)
self.status_under_bar_last_one.SetBackgroundColour((200, 200, 200)) # set text color
# self.status_bar.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
# self.status_bar.SetBorderColor(wx.BLACK)
# self.status_bar.SetBorderPadding(2)
parent.Bind(wx.EVT_CLOSE, self.on_close)
@property
def action_is_on_going(self):
return self._action_is_on_going
@action_is_on_going.setter
def action_is_on_going(self, value):
pass
def update_time_current(self):
self.status_under_bar_current.SetLabel(datetime.datetime.now().strftime("%I:%M:%S %p"))
pass
def update_time_last(self):
self.status_under_bar_last_one.SetLabel(datetime.datetime.now().strftime("%I:%M:%S %p "))
pass
def error_is(self, value):
ERROR = 404
OK = 200
self.err_icon.Show()
if value is not None:
if value == ERROR:
self.err_icon.SetForegroundColour((255, 0, 0)) # set text color
self.err_icon.SetLabel('\u26A0')
print('got 404')
self.status_under_bar_status.SetLabel(' Status: ERROR')
elif value == OK:
self.err_icon.SetForegroundColour((0, 255, 0)) # set text color
print('got 200')
self.status_under_bar_status.SetLabel(' Status: OK')
self.err_icon.SetLabel('\u2714')
else:
self.err_icon.Hide()
self.status_under_bar_status.SetLabel(' Status: Updating..')
def change_mode(self, event):
if event.IsChecked():
self.reset.Enable()
self.verify.Enable()
self.erasing.Enable()
self.button_read.Enable()
else:
self.reset.Disable()
self.verify.Disable()
self.erasing.Disable()
self.button_read.Disable()
def on_click(self, event):
self.file_path_unit.file_dialog.ShowModal()
self.file_path_unit.Clear()
path = self.file_path_unit.file_dialog.GetPath()
if path is not "":
self.file_path_unit.path_to_file = path
self.file_path_unit.caption = path
else:
self.file_path_unit.caption = "Select a file"
self.file_path_unit.write(self.file_path_unit.caption)
self.file_path_unit.file_dialog.Close()
self.status_bar_update(0)
def on_press_read(self, event):
self.status_bar_update(0)
self._read_action_handler()
pass
def on_press_write(self, event):
self.status_bar_update(0)
self._write_action_handler()
pass
def on_press_cancel(self, event):
self._write_action_handler()
pass
def interface_values_get(self):
self.interface_values['path'] = self.file_path_unit.path_to_file
return self.interface_values
def status_update(self, text, status=None):
self.err_field.SetLabel(text)
self.error_is(status)
def status_bar_update(self, value):
if value is 0:
self.err_icon.Hide()
self.status_update("")
self.status_bar.SetValue(value)
def evt_verify_checkbox(self, event):
self.status_bar_update(0)
self.interface_values['f_verify'] = event.IsChecked()
def evt_erase_checkbox(self, event):
self.status_bar_update(0)
self.interface_values['f_erase'] = event.IsChecked()
def evt_reset_checkbox(self, event):
self.status_bar_update(0)
self.interface_values['f_reset'] = event.IsChecked()
def evt_choice_baud(self, event):
self.status_bar_update(0)
self.interface_values['baud'] = event.GetString()
def evt_choice_port(self, event):
self.status_bar_update(0)
self.interface_values['port'] = event.GetString()
def on_close(self, event):
if event.CanVeto():
event.Veto()
event.Skip()
<file_sep>/app/back/back_data.py
from .ports.ports import serial_ports
import random
class AppData:
""" A class that provides interfaces to all types of data
for current application
"""
def __init__(self):
self._serial_ports_available = None
@property
def serial_ports_available(self):
self._serial_ports_available = serial_ports()
return self._serial_ports_available
def _serial_ports_call(self):
return self.serial_ports_available
def serial_ports_available_ref_get(self):
return self._serial_ports_call
<file_sep>/app/back/utils.py
def get_dict_attr(obj, attr):
""" Looks up attr in a given object's __dict__,
and returns the associated value if its there.
If attr is not a key in that __dict__, the object's
MRO's __dict__s are searched. If the key is not found,
an AttributeError is raised.
"""
for obj in [obj] + obj.__class__.mro():
# print(obj.__dict__)
if attr in obj.__dict__:
return obj.__dict__[attr]
raise AttributeError
<file_sep>/app/gui/window/main_frame.py
import wx
from .widgets.panel_widgets import Panel
class MainFrame(wx.Frame):
def __init__(self, *args, **kwargs):
kwargs['size'] = (425, 267)
kwargs['pos'] = (0, 0)
# self._size = kwargs['size']
style = wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
style = style ^ wx.MAXIMIZE_BOX
wx.Frame.__init__(self, None, title="STM32 flasher",
style=style,
size=kwargs['size'], pos=kwargs['pos'])
# icon = wx.Icon()
# icon.CopyFromBitmap(wx.Bitmap("st.png", wx.BITMAP_TYPE_ANY))
# self.SetIcon(icon)
self.Center()
self.panel = Panel(self, **kwargs)
# frame.Bind(wx.EVT_CLOSE, OnClose)
# print('binded', self)
self.Show()
self.storage = 0
def input_data_get(self):
return self.panel.interface_values_get()
@property
def action_is_on_going(self):
return self.panel.action_is_on_going
@action_is_on_going.setter
def action_is_on_going(self, value):
self.panel.action_is_on_going = value
<file_sep>/app/gui/gui.py
import wx
from .window.main_frame import MainFrame
class GuiApplication:
def __init__(self, *args, **kwargs):
self._close_handler = kwargs['close_handler']
print(self._close_handler)
self._action_is_on_going = False
self.application = wx.App(False)
self.frame = MainFrame(*args, **kwargs)
def launch(self):
self.application.MainLoop()
self.close()
self.frame.Destroy()
def close(self):
if callable(self._close_handler):
self._close_handler()
else:
pass
def input_data_get(self):
return self.frame.input_data_get()
@property
def action_is_on_going(self):
return self.frame.action_is_on_going
@action_is_on_going.setter
def action_is_on_going(self, value):
self.frame.action_is_on_going = value
if __name__ == '__main__':
app = GuiApplication()
<file_sep>/requirements.txt
altgraph==0.16.1
future==0.17.1
macholib==1.11
pefile==2018.8.8
Pillow==5.4.1
py2exe==0.9.2.2
PyInstaller==3.4
pypiwin32==223
pyserial==3.4
pywin32==224
pywin32-ctypes==0.2.0
six==1.12.0
stm32-flash==1.0
stm32loader==0.3.3
wxPython==4.0.4
<file_sep>/main.py
from app.application import Stm32Flash
if __name__ == '__main__':
session = Stm32Flash()
session.launch()
<file_sep>/app/gui/window/widgets/base.py
import wx
from app.utils import execute_every
class StaticFlexibleChoice(wx.Choice):
def __init__(self, parent, label='Sample_Label', property_to_display=None, pos=(1, 1), width=200, height=20):
self.pos_x = pos[0]
self.pos_y = pos[1]
self.width = width
self.height = height
self.label = wx.StaticText(parent, label=label, pos=(self.pos_x, self.pos_y+5))
self._property = dict(zip(property_to_display, list(map(int, property_to_display))))
super().__init__(parent, pos=(self.pos_x+width - 40, self.pos_y), size=(95, -1), choices=self.choices_data)
self.SetSelection(4)
# print('selecting ', self.choices_data[3])
self._event_on_choice = wx.EVT_CHOICE
@property
def choices_data(self):
if self._property is not None:
data = list(self._property.keys())
else:
data = ['Sample data 1', 'Sample data 2']
return data
@property
def event_on_choice(self):
return self._event_on_choice
class DynamicFlexibleChoice(wx.Choice):
def __init__(self, parent,
label='Sample_Label',
property_to_display=None,
pos=(1, 1), width=200, height=20, dc=None):
self.pos_x = pos[0]
self.pos_y = pos[1]
self.width = width
self.height = height
self.parent = parent
self.label = wx.StaticText(parent, label=label, pos=(pos[0], pos[1]+5))
self._property_to_display = property_to_display
super().__init__(parent, pos=(pos[0]+70, pos[1]), size=(95, -1), choices=self.choices_data)
self._event_on_choice = wx.EVT_CHOICE
self.data_update()
@property
def choices_data(self):
if callable(self._property_to_display):
data = self._property_to_display()
print(data)
else:
data = ['Sample data 1', 'Sample data 2']
return data
@execute_every
def data_update(self):
if self.GetItems() != self.choices_data:
self.Clear()
self.Append(self.choices_data)
@property
def event_on_choice(self):
return self._event_on_choice
class InputFile(wx.TextCtrl):
def __init__(self, parent, label='Sample_Label', pos=(1, 1), width=395, height=40, callback=None):
print('pos is ', pos)
self.label = wx.StaticText(parent, label=label, pos=(pos[0], pos[1]+5))
self.pos_x = pos[0]
self.pos_y = pos[1]
self.width = width
self.height = height
self.parent = parent
super().__init__(parent, value="Enter here your name",
pos=(pos[0]+70, pos[1]), size=(260, 25),
style=wx.TE_READONLY)
self.file_dialog = wx.FileDialog(parent, "Open", "", "",
"Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|Any file (*.*)|*.*",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
size=(480, 266))
self.caption = "Select a file"
self.path_to_file = ""
print(self.file_dialog.Size)
self.Clear()
self.write(self.caption)
self.button = wx.Button(parent, label="...", pos=(pos[0]+335, pos[1]-1), size=(40, 27))
if callback is not None and callable(callback):
parent.Bind(wx.EVT_BUTTON, callback, self.button)
class SettingsCheckBox(wx.CheckBox):
def __init__(self, parent, label='Sample_Label', pos=(1, 1), width=200, height=20, checked=False):
self.pos_x = pos[0]
self.pos_y = pos[1]
self.width = width
self.height = height
self.parent = parent
super().__init__(parent, label=label, pos=pos)
self.SetValue(checked)
@property
def flag(self):
return self.IsChecked()
| 0a8c0b0ca3faa7d057c6ec4de3c87e028798a4eb | [
"Python",
"Text"
] | 11 | Python | StasOverflow/stm32_flash | dd042b33c1252f78d16b3d8227cea67f053a750b | 83e97083d9eecd524e7a58307afdfb372651ac14 |
refs/heads/main | <repo_name>AleczeHarness/ff-dotnetcore-server-sdk<file_sep>/CfClient/client/cache/IMyCache.cs
using io.harness.cfsdk.HarnessOpenAPIService;
using System;
using System.Collections.Generic;
using System.Text;
namespace io.harness.cfsdk.client.cache
{
public interface IMyCache<K,V> : ICache<K, V>
{
Dictionary<K, V> CacheMap { get; set; }
new public void Put(K key, V value)
{
if (CacheMap.ContainsKey(key))
{
CacheMap.Remove(key);
}
CacheMap.Add(key, value);
}
new public V getIfPresent(K key)
{
if (!CacheMap.ContainsKey(key))
{
return default(V);
}
return CacheMap[key];
}
public Dictionary<K, V> GetAllElements()
{
return CacheMap;
}
}
}
<file_sep>/CfClient/client/cache/ICache.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace io.harness.cfsdk.client.cache
{
public interface ICache<K, V>
{
public void PutAll(ICollection<KeyValuePair<K, V>> keyValuePairs)
{
foreach (var item in keyValuePairs)
{
Put(item);
}
}
public void Put(K key, V value);
public void Put(KeyValuePair<K, V> keyValuePair)
{
Put(keyValuePair.Key, keyValuePair.Value);
}
public V getIfPresent(K key);
}
}
| f28a58dd3233927931098d4847b7a302ed8b0a8a | [
"C#"
] | 2 | C# | AleczeHarness/ff-dotnetcore-server-sdk | dbf35ddfe4607133425ccb1c35c8fa543a2f0d7f | 02506ff174b6007f225f671dbceba0fbb86cc58d |
refs/heads/master | <file_sep>var fs = require('fs');
var path = require('path');
var join = path.join;
var mkdirp = require('mkdirp');
var FirefoxExtension = require('???firefox-xpi|jpm???');
function Plugin(options) {
this.options = options || {};
if (!this.options.updateUrl) {
this.options.updateUrl = "http://localhost:8000/";
}
if (!this.options.updateFilename) {
this.options.updateFilename = "updates.xml";
}
// remove trailing slash
this.options.updateUrl = this.options.updateUrl.replace(/\/$/, "");
// setup paths
this.context = path.dirname(module.parent.filename);
this.keyFile = join(this.context, this.options.keyFile);
this.outputPath = join(this.context, this.options.outputPath);
this.contentPath = join(this.context, this.options.contentPath);
// set output info
this.xpiName = this.options.name + ".xpi";
this.xpiFile = join(this.outputPath, this.xpiName);
this.updateFile = join(this.outputPath, this.options.updateFilename);
this.updateUrl = this.options.updateUrl + "/" + this.options.updateFilename;
// initiate xpi
this.xpi = new FirefoxExtension({
privateKey: fs.readFileSync(this.keyFile),
codebase: this.options.updateUrl + '/' + this.xpiName
});
}
// hook into webpack
Plugin.prototype.apply = function(compiler) {
var self = this;
return compiler.plugin('done', function() {
self.package.call(self);
});
}
// package the extension
Plugin.prototype.package = function() {
var self = this;
self.xpi.load(self.contentPath).then(function() {
self.xpi.pack().then(function(buffer) {
mkdirp(self.outputPath, function(err) {
if (err) throw(err)
var updateXML = self.xpi.generateUpdateXML();
fs.writeFile(self.updateFile, updateXML);
fs.writeFile(self.xpiFile, buffer);
});
});
});
}
module.exports = Plugin;
| 43a8ecaaead3d8ad2e9c3e6def4a6b807570a5eb | [
"JavaScript"
] | 1 | JavaScript | gonzazoid/crx-webpack-plugin | 6b17de3ea1158f4b7fdf904f02e8573eea396c44 | d32c54ebe80b3163479ece6cde7f09281adbebb4 |
refs/heads/master | <file_sep>package Inventario;
public class Inventario {
public Inventario(int numerosLibro, int cantidadLibro, String codigo, String autor, double precio) {
super();
this.numerosLibro = numerosLibro;
this.cantidadLibro = cantidadLibro;
this.codigo = codigo;
this.autor = autor;
this.precio = precio;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public int getNumerosLibro() {
return numerosLibro;
}
public void setNumerosLibro(int numerosLibro) {
this.numerosLibro = numerosLibro;
}
public int getCantidadLibro() {
return cantidadLibro;
}
public void setCantidadLibro(int cantidadLibro) {
this.cantidadLibro = cantidadLibro;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public Inventario() {
super();
}
public int numerosLibro;
public int cantidadLibro;
public double precio;
public String codigo;
public String autor;
}
<file_sep>package Inventario;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
static List<Inventario> lstInventario = new ArrayList<>();
static Scanner entrada = new Scanner(System.in);
static boolean isMenu = true;
public static void main(String[] args) {
llenarListaDeInvertarios();
while (isMenu) {
menu();
}
System.out.println("FIN DE PROGRAMA");
}
private static void llenarListaDeInvertarios() {
lstInventario.add(new Inventario(1, 2, "lib2020", "Petita", 23.80));
lstInventario.add(new Inventario(1, 2, "lib2021", "rystov", 24.00));
lstInventario.add(new Inventario(1, 2, "lib2022", "Petita", 34.90));
lstInventario.add(new Inventario(1, 2, "lib2023", "Petita", 25.70));
lstInventario.add(new Inventario(1, 2, "lib2024", "Petita", 26.60));
lstInventario.add(new Inventario(1, 2, "lib2025", "Petita", 28.50));
lstInventario.add(new Inventario(1, 2, "lib2026", "Petita", 289.40));
lstInventario.add(new Inventario(1, 2, "lib2027", "Petita", 27.30));
lstInventario.add(new Inventario(1, 2, "lib2028", "Petita", 22.0));
lstInventario.add(new Inventario(1, 2, "lib2029", "Petita", 2.10));
}
private static void menu() {
System.out.println("Menu menu principal");
System.out.println("***********");
System.out.println("1. SOLICITAR DATOS");
System.out.println("2. ACTUALIZAR DATOS");
System.out.println("3. MOSTRAR VECTOR");
System.out.println("4. CONSULTAR DATOS");
System.out.println("5. SALIR");
System.out.println("MENU");
int option = entrada.nextInt();
switch (option) {
case 1:
ingresoDato();
break;
case 2:
actualizarDato();
break;
case 3:
PreciosAltos();
break;
case 4:
consultarDato();
break;
case 5:
isMenu = false;
break;
default:
isMenu = false;
break;
}
}
private static void PreciosAltos() {
List<Inventario> objInventario = retornoLosTresPerciosAltosInventario();
int i = 0;
for (Inventario temp : objInventario) {
if (i <= 2)
System.out.println(temp.getPrecio() + " precio");
else
break;
i++;
}
}
private static void consultarDato() {
String codigoLibro = null;
Inventario objLocalInventario;
try (Scanner entrada2 = new Scanner(System.in)) {
System.out.println("INGRESE EL CODIGO DEL LIBRO : ");
codigoLibro = entrada2.nextLine();
}
if (codigoLibro != null && !codigoLibro.isEmpty()) {
objLocalInventario = devolverEntidadInvetario(codigoLibro);
if (objLocalInventario != null)
System.out.println("Autor : " + objLocalInventario.getAutor() + " Existe : " + objLocalInventario.getCantidadLibro() + " Su codio es" + objLocalInventario.getCodigo() + " El numero del libro es" + objLocalInventario.getNumerosLibro() + " Su precio es : $" + objLocalInventario.getPrecio());
else
System.out.println("NO EXISTE INFORMACION");
}
}
private static void ingresoDato() {
String codigoLibro = null;
String autor = null;
int cantidadLibro;
int numeroLibro;
double precioLibro;
Inventario objLocalInventario;
try (Scanner entrada2 = new Scanner(System.in)) {
System.out.println("INGRESE EL CODIGO DEL LIBRO : ");
codigoLibro = entrada2.nextLine();
System.out.println("INGRESE EL NOMBRE DEL AUTOR DEL LIBRO : ");
autor = entrada2.nextLine();
System.out.println("INGRESE LA CANTIDAD DE LIBRO : ");
cantidadLibro = entrada2.nextInt();
System.out.println("INGRESE EL NUMERO DEL LIBRO : ");
numeroLibro = entrada2.nextInt();
System.out.println("INGRESE EL PRECIO DEL LIBRO : ");
precioLibro = entrada2.nextDouble();
}
if (codigoLibro != null && !codigoLibro.isEmpty()) {
objLocalInventario = devolverEntidadInvetario(codigoLibro);
if (objLocalInventario == null) {
boolean isValid = ingresarEntidadInventario(
new Inventario(numeroLibro, cantidadLibro, codigoLibro, autor, precioLibro));
if (isValid)
System.out.println("INFORMACION GUARDADA CON EXITO");
else
System.out.println("ERROR AL INGRESAR LA INFORMACION");
}
else
System.out.println("INFORMACION YA SE ENCUENTRA REGISTRADA");
}
}
private static void actualizarDato() {
String codigoLibro = null;
String autor = null;
int cantidadLibro;
int numeroLibro;
double precioLibro;
Inventario objLocalInventario;
try (Scanner entrada2 = new Scanner(System.in)) {
System.out.println("INGRESE EL CODIGO DEL LIBRO : ");
codigoLibro = entrada2.nextLine();
System.out.println("INGRESE EL NOMBRE DEL AUTOR DEL LIBRO : ");
autor = entrada2.nextLine();
System.out.println("INGRESE LA CANTIDAD DE LIBRO : ");
cantidadLibro = entrada2.nextInt();
System.out.println("INGRESE EL NUMERO DEL LIBRO : ");
numeroLibro = entrada2.nextInt();
System.out.println("INGRESE EL PRECIO DEL LIBRO : ");
precioLibro = entrada2.nextDouble();
}
if (codigoLibro != null && !codigoLibro.isEmpty()) {
objLocalInventario = devolverEntidadInvetario(codigoLibro);
if (objLocalInventario != null) {
boolean isValid = actualizarEntidadInventario(
new Inventario(numeroLibro, cantidadLibro, codigoLibro, autor, precioLibro));
if (isValid)
System.out.println("INFORMACION ACTUALIZADA CON EXITO");
else
System.out.println("ERROR AL ACTULIZAR LA INFORMACION");
}
else
System.out.println("NO EXISTE INFORMACION");
}
}
/**
* TRABAJO EN LAS ENTIDADES CRUD , CREA,UPDATE, READ, DELETE
*
*/
private static List<Inventario> retornoLosTresPerciosAltosInventario() {
List<Inventario> objInvetario = lstInventario.stream()
.sorted(Comparator.comparing(Inventario::getPrecio).reversed()).collect(Collectors.toList());
return objInvetario;
}
private static boolean actualizarEntidadInventario(Inventario ObjectoActualizoEntidadInventario) {
if (lstInventario != null && !lstInventario.isEmpty()) {
for (Inventario objInvetario : lstInventario) {
if (objInvetario.codigo.equalsIgnoreCase(ObjectoActualizoEntidadInventario.getCodigo())) {
objInvetario.setAutor(ObjectoActualizoEntidadInventario.getAutor());
objInvetario.setCantidadLibro(ObjectoActualizoEntidadInventario.getCantidadLibro());
objInvetario.setNumerosLibro(ObjectoActualizoEntidadInventario.getNumerosLibro());
return true;
}
}
}
return false;
}
private static boolean ingresarEntidadInventario(Inventario ObjectoActualizoEntidadInventario) {
if (lstInventario != null && !lstInventario.isEmpty()) {
lstInventario.add(ObjectoActualizoEntidadInventario);
return true;
}
return false;
}
private static Inventario devolverEntidadInvetario(String Codigo) {
if (lstInventario != null && !lstInventario.isEmpty()) {
for (Inventario objInvetario : lstInventario) {
if (objInvetario.codigo.equalsIgnoreCase(Codigo)) {
return objInvetario;
}
}
}
return null;
}
}
| f15fd6208feb8fe9d87026aae25aa6b01b5c489d | [
"Java"
] | 2 | Java | Evelyn-B-E/PROYECTO-DE-INVENTARIO | 9baf3926de67655c67dde324f4dea106fba87fe3 | dcddff3e003306ac9bb7d20460829bacbeca81be |
refs/heads/master | <repo_name>Zedmarstarboy/files<file_sep>/writetext.cpp
/*#include <iostream>
#include <fstream>
using namespace std;
int main( )
{
//create some data
short int a = -6730;
float b = 68.123;
char c = 'J';
//cout <<a " " << b <<" "<< c;//display data to console (i.e. as formatted chars)
ofstream writetext("abc.txt");
if(writetext){
writetext << a << " " << b << " " << c << " ";
}
else{
cout << "Error opening file" << endl;
}
writetext.close();
//cout << a << " " << b << " " << c;
//cout << endl << endl;
return 0;
}*/
//Binary
#include <iostream>
#include <fstream>
using namespace std;
int main( )
{
//create some data
short int a = -6730;
float b = 68.123;
char c = 'J';
//cout <<a " " << b <<" "<< c;//display data to console (i.e. as formatted chars)
ofstream writetext("abc.bin", ios::binary);
if(writetext){
//writetext << a << " " << b << " " << c << " ";
writetext.write(reinterpret_cast <char*> (&a), sizeof(a));//To a bin file
writetext.write(reinterpret_cast <char*> (&b), sizeof(b));
writetext.write(reinterpret_cast <char*> (&c), sizeof(c));
/*
writetext << a << " " << b << " " << c << " "; //To a txt file
*/
}
else{
cout << "Error opening file" << endl;
}
writetext.close();
/*
cout << a << " " << b << " " << c;
cout << endl << endl;
*/
return 0;
}
| 55093b2276f416a0081993734ee42e48ce8a7cef | [
"C++"
] | 1 | C++ | Zedmarstarboy/files | 611e511df018f4ea7edb7279f7b598fcdde728c2 | c35819d72e0b7af7bcd21458834cc3d14627a6cc |
refs/heads/master | <file_sep>
"# AndoidCalc"
<file_sep>package com.example.muszkie.calc;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class WriteMethodTest {
@Test
public void IfSignWrittenAndWritingSign() {
MainActivity mv = new MainActivity();
assertFalse( mv.ifNoSignWrittenAndWritingSign( " + ", true ) );
assertTrue( mv.ifSignWrittenAndWrittingSign( " + ", true ) ); //OK
assertFalse(mv.ifNoSignWrittenAndWrittingNoSign( " + ", true ) );
assertTrue(mv.ifSignWrittenAndWrittingNoSign( " + ", true)); //OK, number >> sign >> number
}
@Test
public void IfSignWrittenAndNotWritingNoSign(){
MainActivity mv = new MainActivity();
assertFalse( mv.ifNoSignWrittenAndWritingSign( "1", true ) );
assertFalse( mv.ifSignWrittenAndWrittingSign( "1", true ) );
assertFalse(mv.ifNoSignWrittenAndWrittingNoSign( "1", true ) );
assertTrue(mv.ifSignWrittenAndWrittingNoSign( "1", true)); // OK
}
@Test
public void IfNoSignWrittenAndWritingSign(){
MainActivity mv = new MainActivity();
assertTrue(mv.ifNoSignWrittenAndWritingSign( " + ", false ) ); //OK
assertFalse( mv.ifSignWrittenAndWrittingSign( " + ", false ) );
assertTrue(mv.ifNoSignWrittenAndWrittingNoSign( " + ", false ) ); //OK, writing sign >> number >> sign
assertFalse(mv.ifSignWrittenAndWrittingNoSign( " + ", false));
}
@Test
public void IfNoSignWrittenAndWritingNoSign(){
MainActivity mv = new MainActivity();
assertFalse(mv.ifNoSignWrittenAndWritingSign( "1", false ) );
assertFalse( mv.ifSignWrittenAndWrittingSign( "1", false ) );
assertTrue(mv.ifNoSignWrittenAndWrittingNoSign( "1", false ) ); //OK
assertFalse(mv.ifSignWrittenAndWrittingNoSign( "1", false));
}
//ifNoSignWrittenAndWritingSign
//ifSignWrittenAndWrittingSign
//writeDot
@Test
public void TrueIfWriteDot(){
MainActivity mv = new MainActivity();
assertTrue(mv.dotPressed("."));
}
@Test
public void FalseIfWriteDot(){
MainActivity mv = new MainActivity();
assertFalse(mv.dotPressed(","));
}
//writeDot
//ifEquationIsNotEmptyAndDotWasAlreadyWritten
//(equation.length() > 0 && dotflag == false && equation.charAt(equation.length() - 1) != ' ')
@Test
public void FalseIfEquationIsEmpty(){
MainActivity mv = new MainActivity();
assertFalse(mv.ifEquationIsNotEmptyAndDotWasntWritten(false,""));
}
@Test
public void FalseIfEquationLastIsSpace(){
MainActivity mv = new MainActivity();
assertFalse(mv.ifEquationIsNotEmptyAndDotWasntWritten(false," "));
}
@Test
public void FalseIfDotWritten(){
MainActivity mv = new MainActivity();
assertFalse(mv.ifEquationIsNotEmptyAndDotWasntWritten(true," "));
}
@Test
public void TrueIfEquationIsNotEmptyAndDotWasntWritten(){
MainActivity mv = new MainActivity();
assertTrue(mv.ifEquationIsNotEmptyAndDotWasntWritten(false,"12 1"));
}
//ifSecondMinusWasntWritten
@Test
public void ifSecondMinusWasntWritten(){
MainActivity mv = new MainActivity();
assertTrue(mv.ifSecondMinusWasntWritten(false," - ","2+2*2"));
assertFalse(mv.ifSecondMinusWasntWritten(true," - ","2+2*2"));
assertFalse(mv.ifSecondMinusWasntWritten(false," + ","2+2*2"));
assertFalse(mv.ifSecondMinusWasntWritten(false," - ","2"));
}
}
<file_sep>package com.example.muszkie.calc;
public enum Sign {
ADD,
SUBSTRACT,
MULTIPLY,
DIVIDE,
EQUAL,
POW,
DOT;
@Override
public String toString(){
switch (this) {
case ADD:
return "+";
case SUBSTRACT:
return "-";
case MULTIPLY:
return "*";
case DIVIDE:
return "/";
case EQUAL:
return "=";
case POW:
return "^";
case DOT:
return ".";
}
return null;
}
public char toChar(){
switch (this) {
case ADD:
return '+';
case SUBSTRACT:
return '-';
case MULTIPLY:
return '*';
case DIVIDE:
return '/';
case EQUAL:
return '=';
case POW:
return '^';
case DOT:
return '.';
}
return '1';
}
public String toSign(){
switch (this) {
case ADD:
return " + ";
case SUBSTRACT:
return " - ";
case MULTIPLY:
return " * ";
case DIVIDE:
return " / ";
case EQUAL:
return " = ";
case POW:
return " ^ ";
case DOT:
return " . ";
}
return null;
}
public String toMinus(){
switch (this) {
case SUBSTRACT:
return " -";
}
return null;
}
public String toDotSpace(){
switch (this) {
case DOT:
return ". ";
}
return null;
}
}
| 045f650be41ebeff82811b34e97ce7c03b1fc3d9 | [
"Markdown",
"Java"
] | 3 | Markdown | muszkie/AndroidCalc | ec142ae8fcf7863ebc9d36425e3fa001a15a3602 | c50ef1c58bc0829d2361c1d681239bdf73a8b62c |
HEAD | <repo_name>HolzbaumStudios/MichaProductions<file_sep>/Circle Game/Assets/GameOverScript.cs
using UnityEngine;
using System.Collections;
public class GameOverScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void goBackToMainMenu(){
Application.LoadLevel ("MainMenuScene");
}
public void retryTheGame(){
Application.LoadLevel ("MainGameScene");
}
}
<file_sep>/Circle Game/Assets/HighscoreScript.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HighscoreScript : MonoBehaviour {
int HighScore;
// Use this for initialization
void Start () {
HighScore = PlayerPrefs.GetInt ("Player HighScore");
gameObject.GetComponent<Text> ().text = "Your Highscore is: "+HighScore.ToString();
}
// Update is called once per frame
void Update () {
}
public void goBackToMainMenu(){
Application.LoadLevel ("MainMenuScene");
}
}
<file_sep>/Circle Game/Assets/Circle_point.cs
using UnityEngine;
using System.Collections;
public class Circle_point : MonoBehaviour {
float ReactionTime=2f;
GameObject GameMechanicsObject;
public int Score;
// Use this for initialization
void Start () {
GameMechanicsObject = GameObject.Find ("GameMechanics");
}
// Update is called once per frame
void Update () {
ReactionTime -= Time.fixedDeltaTime;
if (ReactionTime <= 0) {
GameMechanicsObject.SendMessage("CheckIfReactionTimeWasFastEnough");
}
}
public void Destroy_Circle(){
// Destroys Object
GameMechanicsObject.SendMessage("UpdateScore");
Destroy (this.gameObject);//reference to current object
}
}
<file_sep>/Circle Game/Assets/GameMechanicsScript.cs
using UnityEngine;
using System.Collections;
public class GameMechanicsScript : MonoBehaviour {
int PositionX;
int PositionY;
bool TimerForNextCircle = true;
bool ReactionTimeFailure = false;
int Score=0;
int Highscore;
float TimeFromOneCircleToNext;
public GameObject OrangeCircle;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (ReactionTimeFailure) {
PlayerPrefs.SetInt("Player Score", Score);
Highscore=PlayerPrefs.GetInt("Player HighScore");
Debug.Log(Highscore);
if (Score > Highscore){
PlayerPrefs.SetInt("Player HighScore", Score);
Debug.Log("hallo");
}
Application.LoadLevel("GameOverScene");
} else {
if (TimerForNextCircle) {
StartCoroutine (getTimeconstraint ());
getRandomScreenPosition ();
PopUpCircle ();
}
}
}
void getRandomScreenPosition(){
PositionX = Random.Range(-350,350);
PositionY = Random.Range(-100,100);
}
IEnumerator getTimeconstraint(){
TimerForNextCircle = false;
getTimeForNextCircle ();
yield return new WaitForSeconds (TimeFromOneCircleToNext);
TimerForNextCircle = true;
}
void getTimeForNextCircle(){
TimeFromOneCircleToNext = Random.Range (0f, 2f);
}
public void CheckIfReactionTimeWasFastEnough(){
ReactionTimeFailure = true;
}
void UpdateScore(){
Score += 1;
}
void PopUpCircle()
{
GameObject OrangeObject = Instantiate (OrangeCircle,new Vector2(PositionX,PositionY),transform.rotation) as GameObject;
OrangeObject.transform.parent = GameObject.Find ("Canvas").transform;
OrangeObject.transform.localPosition = new Vector2 (PositionX, PositionY);
}
}
<file_sep>/Circle Game/Assets/MainMenuMechanicsScript.cs
using UnityEngine;
using System.Collections;
public class MainMenuMechanicsScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void StartNewGame(){
Application.LoadLevel("MainGameScene");
}
public void ViewHighscore(){
Application.LoadLevel ("ViewHighscoreScene");
}
//todo public void ExitGame()
}
| c211040d6c6a8fff4791c722fd5dbd1b685450fc | [
"C#"
] | 5 | C# | HolzbaumStudios/MichaProductions | 6aa4ed959fa5d317596249f7757fb2c9689269ac | 22ab6727aa2bedd12b3194142a889f39bdb6e15a |
refs/heads/master | <repo_name>bdjenkin/omdb-search<file_sep>/src/Search.js
import React, { Component } from 'react';
import './Search.css';
import Movie from './Movie';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
searchResults: []
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
var trimmed = JSON.stringify(event.target.value.trim());
var root = encodeURI('https://www.omdbapi.com/?s=' + trimmed + '&apikey=cb62c109&r=json');
fetch(root)
.then(response => response.json())
.then(data => {
console.log(data.Search);
if(data.Search && data.Search.length > 0)
this.setState({searchResults: data.Search})
else {
console.log("No results with text")
}
})
}
componentDidMount() {console.log('search added')}
render() {
return (
<div className="search-wrap">
<div className="container">
<label htmlFor="search-text">Search:</label>
<input type="text" id="search-text" maxlength="30" className="form-control" value={this.state.value} onChange={this.handleChange} />
</div>
<div className="results-wrap">
<div className="container">
{
this.state.searchResults.length > 0
? this.state.searchResults.map(function(result) {return <Movie key={result.imdbID} mediaId={result.imdbID} />})
: <div className="empty-results">No results found</div>
}
</div>
</div>
</div>
);
}
}
export default Search;
<file_sep>/src/Post.js
import React, { Component } from 'react';
class Post extends Component {
constructor(props) {
super(props);
this.state = {
post: []
}
};
componentDidMount() {
var root = 'https://jsonplaceholder.typicode.com/posts/' + this.props.num;
fetch(root)
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({post: data})
})
}
render() {
return (
<div className="col-3">
<h5>{this.state.post.title}</h5>
<p>{this.state.post.body}</p>
<p><sub>Post by user: {this.state.post.userId} | Post number: {this.state.post.id}</sub></p>
</div>
);
}
}
export default Post;
<file_sep>/src/Movie.js
import React, { Component } from 'react';
import './Movie.css';
class Movie extends Component {
constructor(props) {
super(props);
this.state = {
movie: {},
imdbscores: {},
rtscores: {},
mcscores: {}
}
};
componentDidMount() {
var root = 'https://www.omdbapi.com/?i=' + this.props.mediaId + '&apikey=cb62c109';
fetch(root)
.then(response => response.json())
.then(data => {
console.log(data);
setTimeout(() => {
if(data) this.setState({movie: data})
if(data.Ratings[0])
this.setState({imdbscores: data.Ratings[0]})
if(data.Ratings[1])
this.setState({rtscores: data.Ratings[1]})
if(data.Ratings[2])
this.setState({mcscores: data.Ratings[2]})
}, 500)
})
}
render() {
return (
<div className="movie row mt-1 mb-1 wow fadeIn" data-wow-delay={this.props.indexOf > 3 ? "0.5s" : this.props.indexOf/3 + "s" }>
<div className="col-3 col-sm-12 col-md-4 col-lg-3">
<img src={this.state.movie.Poster !== "N/A" ? this.state.movie.Poster : "no-img.png" } alt={this.state.movie.Title} className="poster" />
</div>
<div className="col-6 col-sm-12 col-md-6 col-lg-6 wow fadeIn" data-wow-delay="1s">
<h6><a href={'https://www.imdb.com/title/' + this.props.mediaId} target="_new" title="View on IMDb">{this.state.movie.Title} {"(" + this.state.movie.Year + ")"}</a></h6>
<p className="details">{this.state.movie.Rated} | Runtime: {this.state.movie.Runtime} | Released: {this.state.movie.Released} {"(" + this.state.movie.Country + ")"}</p>
<p className="limit">
Starring: {this.state.movie.Actors} <br/>
Director: {this.state.movie.Director}
</p>
<p className="hide">Awards: {this.state.movie.Awards}</p>
<p className="hide">Genre: {this.state.movie.Genre}</p>
</div>
<div className="col-3 col-sm-12 col-md-2 col-lg-3">
<p className="rating imdb"><a href={'https://www.imdb.com/title/' + this.props.mediaId} target="_new"><img src="https://upload.wikimedia.org/wikipedia/commons/6/69/IMDB_Logo_2016.svg" alt="IMDb logo" /></a>{this.state.imdbscores.Value}</p>
<p className="rating rotten-tomatoes"><img src="https://vignette.wikia.nocookie.net/logopedia/images/9/9c/Rotten_Tomatoes_2.svg/revision/latest?cb=20160706062736" alt="Rotten Tomatoes logo" />{this.state.rtscores.Value}</p>
<p className="rating metacritic"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Metacritic.svg/2000px-Metacritic.svg.png" alt="Metacritic logo" />{this.state.mcscores.Value}</p>
<p className="limit hide">Writers: {this.state.movie.Writer}</p>
</div>
</div>
);
}
}
export default Movie;
<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//import Blog from './Blog';
import Movie from './Movie';
//import Search from './Search';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
searchResults: []
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: []});
this.render();
this.setState({value: event.target.value});
var trimmed = JSON.stringify(event.target.value.trim());
var root = encodeURI('https://www.omdbapi.com/?s=' + trimmed + '&apikey=cb62c109&r=json');
fetch(root)
.then(response => response.json())
.then(data => {
console.log(data.Search);
if(data.Search && data.Search.length > 0)
this.setState({searchResults: data.Search})
else {
console.log("No results with text");
let emptyResults = []
this.setState({searchResults: emptyResults})
}
})
}
componentDidMount() {console.log('App Started')}
componentDidUpdate() {console.log("App Updated")}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">React Search: OMDb</h1>
</header>
<div className="search-wrap">
<div className="container">
<label htmlFor="search-text">Search for a movie or TV show and see results instantly:</label>
<input type="text" id="search-text" maxLength="30" className="form-control" value={this.state.value} onChange={this.handleChange} />
</div>
<div className="results-wrap">
<div className="container" id="movies">
{
this.state.searchResults.length > 0
? this.state.searchResults.map((result, index)=> <Movie key={"key_" + index + "_" + result.imdbID} mediaId={result.imdbID} indexOf={index} />)
: <div className="empty-results">No movie found!</div>
}
</div>
</div>
</div>
</div>
);
}
}
export default App;
| 146ed65ea80c46b5b80fa1ae3b2c0e0abaac3d84 | [
"JavaScript"
] | 4 | JavaScript | bdjenkin/omdb-search | 131ccb69ca30dd6a2335ed5b67d3d6e29aa0dee6 | 41484867eee17a3d9dc430ac41ffb66fe0cafea7 |
refs/heads/master | <repo_name>alinurzaman/TugasBesarGPCOCR<file_sep>/README.md
TugasBesarGPCOCR
================
Tugas Besar GPC
Anggota Kelompok : (IF-2)
- <NAME> (10110059)
- <NAME> (10110057)
- <NAME> (10110083)
Cara menggunakan aplikasi:
- Klik Load (Huruf yang tersimpan dari A - Z)
- Klik Begin Training
- Gambar di Draw Area
- Klik Recognize
<file_sep>/src/tugasbesargpcocr/Sample.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tugasbesargpcocr;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
*
* @author ali
*/
public class Sample extends JPanel{
SampleData datasample;
Sample(final int width, final int height){
this.datasample = new SampleData(' ', width, height);
}
SampleData getData(){
return this.datasample;
}
@Override
public void paint(final Graphics g){
if (this.datasample == null){
return;
}
int x, y;
final int vertical = getHeight();
final int horizontal = getWidth();
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
for (y = 0; y < this.datasample.getHeight(); y++) {
g.drawLine(0, y * vertical, getWidth(), y * vertical);
}
for (x = 0; x < this.datasample.getWidth(); x++) {
g.drawLine(x * horizontal, 0, x * horizontal,
getHeight());
}
for (y = 0; y < this.datasample.getHeight(); y++) {
for (x = 0; x < this.datasample.getWidth(); x++) {
if (this.datasample.getData(x, y)) {
g.fillRect(x * horizontal, y * vertical, horizontal, vertical);
}
}
}
g.setColor(Color.black);
g.drawRect(0, 0, getWidth()-1, getHeight()-1);
}
void setData(final SampleData datasample){
this.datasample = datasample;
}
}
| 884a639d5ce97d6c1af635b3cbcc5a4e94f44b8c | [
"Markdown",
"Java"
] | 2 | Markdown | alinurzaman/TugasBesarGPCOCR | 63ac8461b6cf4da744e1551fdd8f08a270dc3aa9 | ccab24b793a636dbcda2d8aa5f4939901e6eef84 |
refs/heads/master | <file_sep>/*
MIT License
Copyright (c) 2018 Obrazcoff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
Test strings
*/
console.log(verify('---(++++)----')); // -> 1
console.log(verify('')); // -> 1
console.log(verify('before ( middle []) after ')); // -> 1
console.log(verify(') (')); // -> 0
console.log(verify('<( >)')); // -> 0
console.log(verify('( [ <> () ] <> )')); // -> 1
console.log(verify(' ( [)')); // -> 0
//right answers
/*
1
1
1
0
0
1
0
*/
function verify(str) {
let brackets = {
'(': ')',
'[': ']',
'<': '>',
};
let closeBr = ')]>';
let stack1type = [];
for (let i = 0; i <= str.length; i++) {
let currSymb = str[i];
if (brackets[currSymb]) {
stack1type.push(brackets[currSymb]);
} else {
let isCloseBr = closeBr.indexOf(currSymb);
if (isCloseBr >= 0) {
if (stack1type.length === 0) return 0;
let waitNxtBr = stack1type.pop();
if (currSymb != waitNxtBr) return 0;
}
}
}
if (stack1type.length > 0) {
return 0;
} else return 1;
}
| 53c7a148c93e75e3b494d831780f0a2d8ed039a3 | [
"JavaScript"
] | 1 | JavaScript | Obrazcoff/verifyBrackets | b5051fc9ce09bd5191c1cde92e84741ed23f952c | 255c7d9b7c7545bd91c70b633cac3a309099531a |
refs/heads/master | <repo_name>sathya050801/Flight-Management<file_sep>/README.md
# Flight-Management
Flight management using Python
Flight Management project is written in Python.The project file contains a python script (main.py) and login in details is given in (USERNAME AND PASSWORD) document file.The admin can manage all the management like managing members, adding or updating flights,viewing flight details, and canceling flights. I thank people who guided me through this project and I referred a lot of online resources as well.
<file_sep>/main.py
import tkinter as tk
import datetime
admin={"sathya":"sathya","tarun":"tarun",'admin':'admin'}
supervis={"sathya1":"sathya1","tarun1":"tarun1",'supervis':'supervis'}
standard={"sathya2":"sathya2","tarun2":"tarun2",'standard':'standard'}
scheduled={'MH370':["10:10",'Delhi',"Delayed"],'KI784':['1:20','Pune','Delayed'],'PH169':['12:20','Seattle','Scheduled'],'BH234':['15:20','Bangalore','Scheduled'],'PH234':['15:00','Prayagraj','Delayed'],'BT452':['18:30','Malaysia','Scheduled'],'KR234':['15:20','Cuba','Scheduled']}
cancelled={'AI169':["11:30","Bombay","Cancelled"]}
def reminder(): #This is the reminder function, takes current time from the system and compares it to the list of flights, if the time is greater it creates a pop up with the flight number
now=datetime.datetime.now()
for i in scheduled:
l=scheduled[i][0].split(":")
time=now.replace(hour=int(l[0]),minute=int(l[1]),second=0,microsecond=0)
if now>time:
remindersc=tk.Tk()
remindersc.title("Reminder!")
tk.Label(master=remindersc,text="Flight Number "+i+" Not Updated").grid(row=0,column=0)
remindersc.mainloop()
def deluser(): #This function is responsible for deleting users
def deluserback():
u=uname.get()
if not(u in admin or u in supervis or u in cancelled):
popup=tk.Tk()
popup.title("Username Not Found!")
tk.Label(master=popup,text="Username not found! Please try again!").grid(row=1,column=1)
else:
if uname.get()=='admin':
re=tk.Tk()
re.title("Can't Delete Superuser!")
tk.Label(master=re,text="Cannot Delete Superuser!").grid(row=1,column=1)
re.mainloop()
elif u in admin:
if u!='admin':
del admin[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text="Admin User Successfully Deleted!").grid(row=1,column=1)
elif u in supervis:
del supervis[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text=" Supervisor Successfully Deleted!").grid(row=1,column=1)
if u in standard:
del standard[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text="Standard User Successfully Deleted!").grid(row=1,column=1)
delusersc=tk.Tk()
delusersc.title("Delete A User")
tk.Label(master=delusersc,text="Enter the Username").grid(row=1,column=0)
uname=tk.Entry(master=delusersc)
unamne.grid(row=1,column=1)
r2=tk.Button(master=delusersc,text="Confirm Deletion",width=25,command=deluserback).grid(row=1,column=2)
def manageuser():#this function is responsible for adding users
def adduser():
def addadmin():
def adminusname():
def adminuserback():
p=passw.get()
admin[u]=p
popup=tk.Tk()
popup.title("Success")
tk.Label(master=popup,text="Admin Successfully Added!").grid(row=1,column=1)
u=usname.get()
if u in admin or u in supervis or u in standard:
popup=tk.Tk()
popup.title("Username Already Exists!")
tk.Label(master=popup,text="Username Already Exists! Please Try Again").grid(row=1,column=1)
manageusersc.destroy()
aa.destroy()
else:
tk.Label(master=aa,text="Enter the Password").grid(row=2,column=0)
passw=tk.Entry(master=aa,show='*')
passw.grid(row=2,column=1)
tk.Button(master=aa,text="Confirm Password",command=adminuserback,width=25).grid(row=2,column=3)
aa=tk.Tk()
aa.title("Add An Admin")
tk.Label(master=aa,text="Enter the Username").grid(row=1,column=0)
usname=tk.Entry(master=aa)
usname.grid(row=1,column=1)
a3=tk.Button(master=aa,text="Confirm Username",width=25,command=adminusname).grid(row=1,column=3)
def addsuper():
def superusname():
def superuserback():
p=passw.get()
supervis[u]=p
popup=tk.Tk()
popup.title("Success")
tk.Label(master=popup,text="Supervisor Successfully Added!").grid(row=1,column=1)
u=usname.get()
if u in admin or u in supervis or u in standard:
popup=tk.Tk()
popup.title("Username Already Exists!")
tk.Label(master=popup,text="Username Already Exists! Please Try Again").grid(row=1,column=1)
manageusersc.destroy()
aa.destroy()
else:
tk.Label(master=aa,text="Enter the Password").grid(row=2,column=0)
passw=tk.Entry(master=aa,show='*')
passw.grid(row=2,column=1)
tk.Button(master=aa,text="Confirm Password",command=superuserback,width=25).grid(row=2,column=3)
aa=tk.Tk()
aa.title("Add A Supervisor")
tk.Label(master=aa,text="Enter the Username").grid(row=1,column=0)
usname=tk.Entry(master=aa)
usname.grid(row=1,column=1)
a3=tk.Button(master=aa,text="Confirm Username",width=25,command=superusname).grid(row=1,column=3)
def addstand():
def standusname():
def standuserback():
p=passw.get()
standard[u]=p
popup=tk.Tk()
popup.title("Success")
tk.Label(master=popup,text="Standard User Successfully Added!").grid(row=1,column=1)
u=usname.get()
if u in admin or u in supervis or u in standard:
popup=tk.Tk()
popup.title("Username Already Exists!")
tk.Label(master=popup,text="Username Already Exists! Please Try Again").grid(row=1,column=1)
aa.destroy()
else:
tk.Label(master=aa,text="Enter the Password").grid(row=2,column=0)
passw=tk.Entry(master=aa,show='*')
passw.grid(row=2,column=1)
tk.Button(master=aa,text="Confirm Password",command=standuserback,width=25).grid(row=2,column=3)
aa=tk.Tk()
aa.title("Add A Standard User")
tk.Label(master=aa,text="Enter the Username").grid(row=1,column=0)
usname=tk.Entry(master=aa)
usname.grid(row=1,column=1)
a3=tk.Button(master=aa,text="Confirm Username",width=25,command=standusname).grid(row=1,column=3)
addusersc=tk.Tk()
addusersc.title("Add A User")
tk.Button(master=addusersc,width=25,text="Add An Admin",command=addadmin).grid(row=1,column=1)
tk.Button(master=addusersc,width=25,text="Add A Supervisor",command=addsuper).grid(row=2,column=1)
tk.Button(master=addusersc,width=25,text="Add A Standard User",command=addstand).grid(row=3,column=1)
def viewuser():
viewsc=tk.Tk()
viewsc.title("View Users")
tk.Label(master=viewsc,text="Admins Are:").grid(row=0,column=0)
c=0
for i in admin:
c+=1
tk.Label(master=viewsc,text=("------",i)).grid(row=c,column=0)
c+=1
tk.Label(master=viewsc,text="Supervisors Are:").grid(row=c,column=0)
for i in supervis:
c+=1
tk.Label(master=viewsc,text=("-----",i)).grid(row=c,column=0)
c+=1
tk.Label(master=viewsc,text="Standard Users Are:").grid(row=c,column=0)
for i in standard:
c+=1
tk.Label(master=viewsc,text=("-----",i)).grid(row=c,column=0)
def deluser():
def deluserback():
u=uname.get()
if not(u in admin or u in supervis or u in standard):
popup=tk.Tk()
popup.title("Username Not Found!")
tk.Label(master=popup,text="Username not found! Please try again!").grid(row=1,column=1)
else:
if u in admin:
del admin[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text="Admin User Successfully Deleted!").grid(row=1,column=1)
delusersc.destroy()
elif u in supervis:
del supervis[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text=" Supervisor Successfully Deleted!").grid(row=1,column=1)
delusersc.destroy()
if u in standard:
del standard[u]
r1=tk.Tk()
r1.title("Success!")
tk.Label(master=r1,text="Standard User Successfully Deleted!").grid(row=1,column=1)
delusersc.destroy()
delusersc=tk.Tk()
delusersc.title("Delete A User")
tk.Label(master=delusersc,text="Enter the Username").grid(row=1,column=0)
uname=tk.Entry(master=delusersc)
uname.grid(row=1,column=1)
r2=tk.Button(master=delusersc,text="Confirm Deletion",width=25,command=deluserback).grid(row=1,column=2)
manageusersc=tk.Tk()
manageusersc.title("Manage Users")
tk.Button(master=manageusersc,text="Add Users",width=25,command=adduser).grid(row=1,column=0)
tk.Button(master=manageusersc,text="Delete A User",width=25,command=deluser).grid(row=2,column=0)
tk.Button(master=manageusersc,text="View Current Users",width=25,command=viewuser).grid(row=3,column=0)
def update():
updatesc=tk.Tk()
updatesc.title("Update/Add A Flight")
tk.Label(master=updatesc,text="Enter The Flight Number").grid(row=1,column=0)
flightnum=tk.Entry(master=updatesc)
flightnum.grid(row=1,column=1)
def updatebutton1():
if flightnum.get() not in scheduled:
scheduled[flightnum.get()]=["","",""]
tk.Label(master=updatesc,text="Enter Departure Time").grid(row=3,column=0)
deptime=tk.Entry(master=updatesc)
deptime.grid(row=3,column=1)
tk.Label(master=updatesc,text="Enter Status").grid(row=4,column=0)
status=tk.Entry(master=updatesc)
status.grid(row=4,column=1)
tk.Label(master=updatesc,text="Enter Destination").grid(row=5,column=0)
dest=tk.Entry(master=updatesc)
dest.grid(row=5,column=1)
def updatebutton2():
if deptime.get()!="":
scheduled[flightnum.get()][0]=deptime.get()
if status.get()!="":
scheduled[flightnum.get()][2]=status.get()
if dest.get()!="":
scheduled[flightnum.get()][1]=dest.get()
updatepopup=tk.Tk()
updatepopup.title("Successfully Updated!")
tk.Label(master=updatepopup,text="Successfully Updated!!").grid(row=0,column=0)
updatesc.destroy()
tk.Button(master=updatesc,text="Confirm",command=updatebutton2).grid(row=6,column=1)
tk.Button(master=updatesc,text="Confirm",command=updatebutton1).grid(row=2,column=1)
updatesc.mainloop()
def cancel(): #this function cancels flights
def cancelback():
t=flightnum.get()
cancelsc.destroy()
if t in cancelled:
re=tk.Tk()
re.title("Already Cancelled!")
tk.Label(master=re,text="Flight Already Cancelled. Please try again!").grid(row=1,column=1)
cancel()
elif not(t in scheduled):
re=tk.Tk()
re.title("Flight Not Found!")
tk.Label(master=re,text="Flight Not Found. Please try again!").grid(row=1,column=1)
cancel()
else:
t1=scheduled.pop(t)
del t1[2]
t1.append("Cancelled")
cancelled[t]=t1
re=tk.Tk()
re.title("Success!")
tk.Label(master=re,text="Flight Successfully Cancelled!").grid(row=1,column=1)
cancelsc=tk.Tk()
cancelsc.title("Cancel a Flight")
tk.Label(master=cancelsc,text="Enter the flight number").grid(row=1,column=0)
flightnum=tk.Entry(master=cancelsc)
flightnum.grid(row=1,column=1)
t7=tk.Button(master=cancelsc,width=25,text="Confirm",command=cancelback).grid(row=2,column=1)
def admain():#admin control panel
def switchuserad():
admainsc.destroy()
login()
admainsc=tk.Tk()
admainsc.title("Admin Control Panel")
tk.Button(master=admainsc,text="View The Details Of Flights",command=view).grid(row=1,column=1)
tk.Button(master=admainsc,text="Switch User",command=switchuserad).grid(row=2,column=1)
tk.Button(master=admainsc,text="Cancel A Flight",command=cancel).grid(row=4,column=1)
tk.Button(master=admainsc,text="Manage Users",command=manageuser).grid(row=5,column=1)
tk.Button(master=admainsc,text="Exit The Program",command=exit).grid(row=6,column=1)
tk.Button(master=admainsc,text="Update/Add A Flight",command=update).grid(row=3,column=1)
def supmain():#supervisor control panel
def switchusersup():
supmainsc.destroy()
login()
supmainsc=tk.Tk()
img=tk.PhotoImage(file="ActualLogo.png")
rp=tk.Label(master=supmainsc,image=img).grid(row=0,column=0)
supmainsc.title("Supervisor Control Panel")
tk.Label(master=supmainsc,text="").grid(row=6,column=0)
tk.Button(master=supmainsc,text="View The Details Of Flights",command=view).grid(row=1,column=1)
tk.Button(master=supmainsc,text="Switch User",command=switchusersup).grid(row=2,column=1)
tk.Button(master=supmainsc,text="Cancel A Flight",command=cancel).grid(row=4,column=1)
tk.Button(master=supmainsc,text="Exit The Program",command=exit).grid(row=5,column=1)
tk.Button(master=supmainsc,text="Update/Add A Flight",command=update).grid(row=3,column=1)
supmainsc.mainloop()
def view():#viewing flights
c=0
r=1
view=tk.Tk()
view.title("View Details Of Flights")
tk.Label(master=view,text="Flight Number--------ETA--------Destination-------Status").grid(row=1,column=0)
for i in scheduled:
c+=1
r+=1
tk.Label(master=view,text=(i,"-------",scheduled[i][0],"--------",scheduled[i][1],"--------",scheduled[i][2])).grid(row=r,column=0)
for i in cancelled:
c+=1
r+=1
tk.Label(master=view,text=(i,"-------",cancelled[i][0],"--------",cancelled[i][1],"--------",cancelled[i][2])).grid(row=r,column=0)
def stamain():#standard user control panel
def switchuserstand():
stamainsc.destroy()
login()
stamainsc=tk.Tk()
stamainsc.title("Standard User Control Panel")
tk.Button(master=stamainsc,text="View The Details Of Flights",command=view).grid(row=2,column=0)
tk.Button(master=stamainsc,text="Switch User",command=switchuserstand).grid(row=3,column=0)
tk.Button(master=stamainsc,text="Exit The Program",command=exit).grid(row=4,column=0)
tk.Label(master=stamainsc,text="").grid(row=5,column=0)
img=tk.PhotoImage(file="ActualLogo.png")
rp=tk.Label(master=stamainsc,image=img).grid(row=1,column=0)
stamainsc.mainloop()
def login():#login function
def userver():
def passver():
b=password.get()
if check==1:
if admin[a]==b:
loginsc.destroy()
admain()
reminder()
else:
a3=tk.Tk()
a3.title("Wrong Password!")
tk.Label(master=a3,text="Wrong Password! Please Try Again!").grid(row=1,column=1)
elif check==2:
if supervis[a]==b:
loginsc.destroy()
supmain()
reminder()
else:
a3=tk.Tk()
a3.title("Wrong Password!")
tk.Label(master=a3,text="Wrong Password! Please Try Again!").grid(row=1,column=1)
elif check==3:
if standard[a]==b:
loginsc.destroy()
stamain()
else:
a3=tk.Tk()
a3.title("Wrong Password!")
tk.Label(master=a3,text="Wrong Password! Please Try Again!").grid(row=1,column=1)
a=username.get()
if not(a in admin or a in supervis or a in standard):
a1=tk.Tk()
a1.title("Wrong Username!")
tk.Label(master=a1,text="Username Not Found. Please Try Again!").grid(row=1,column=1)
else:
if a in supervis:
check=2
elif a in admin:
check=1
elif a in standard:
check=3
tk.Label(master=loginsc,text="Enter Your Password").grid(row=2,column=0)
password=tk.Entry(master=loginsc,show='*')
password.grid(row=2,column=1)
a3=tk.Button(master=loginsc,text="Confirm Password",width=25,command=passver).grid(row=2,column=2)
loginsc=tk.Tk()
loginsc.title("Login")
tk.Label(master=loginsc,text="").grid(row=5,column=1)
img=tk.PhotoImage(file="download.png")
rp=tk.Label(master=loginsc,image=img).grid(row=0,column=1)
tk.Label(master=loginsc,text="Enter Your Username").grid(row=1,column=0)
username=tk.Entry(master=loginsc)
username.grid(row=1,column=1)
a22=tk.Button(master=loginsc,text="Confirm Username",width=25,command=userver).grid(row=1,column=2)
loginsc.mainloop()
login()
| b200431ba11e0aa304a05476793d614e8a715bed | [
"Markdown",
"Python"
] | 2 | Markdown | sathya050801/Flight-Management | 2b23e229a7aaa514a6c8b39371b2d5a81979be12 | 602358dfefd5d1522d3a6e5670f4ff157992da36 |
refs/heads/master | <repo_name>galinabelyaeva/javascript-logging-lab-js-intro-000<file_sep>/index.js
console.error("This is an error, but don't worry!");
console.log("Log it like it's hot. You know what I'm sayin'");
console.warn("Careful...Careful");
| 414865658d87a7b699ef594496208926e061e99d | [
"JavaScript"
] | 1 | JavaScript | galinabelyaeva/javascript-logging-lab-js-intro-000 | c0e43eff95f6e2bcad597c7023f924a209104943 | 969e86f68e4e971dd50ec25eb922f9bf6c4a8859 |
refs/heads/main | <repo_name>samuelguedesalves/backend-setup<file_sep>/src/server.ts
import 'reflect-metadata';
import './database';
import express from 'express';
const server = express();
const port = process.env.PORT || 3333;
server.listen(port, () => {
console.log(`Server is running in port: ${port}\nPress ctrl+c to stop thid process`);
});
<file_sep>/README.md
# backend-setup
backend setup, basic config
| 46fc660a6c70c1492dbd8dae195a8650401f3a30 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | samuelguedesalves/backend-setup | a43f7b911b0ccfc11c73d47a847b6721168e8600 | 2d3232e40989d9ed144b608927cbfee046f450e1 |
refs/heads/main | <file_sep><?php
use App\Http\Controllers\DataSiswaController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('nama', function () {
//return 'Nama <NAME>';
//});
Route::get('umur', function () {
$umur = 17;
return 'Saya berumur ' . $umur;
});
Route::get('alamat', function () {
return 'Rumah Saya di Jl.Sukamenak';
});
Route::get('skul', function () {
return 'Saya Bersekolah di SMK ASSALAAM BANDUNG';
});
Route::get('sekian', function () {
return 'Sekian Wassalaam';
});
//parameter wajib
Route::get('/aku/riwayat/{riwayat}', function ($riwayat) {
return $riwayat . ' anak ke 3 dari 4 bersaudara';
});
//parameter wajib
Route::get('/aku/riwayat/{nama}/{sekola}', function ($nama, $sekola) {
return 'Nama saya : ' . $nama . '<br>Saya bersekolah di ' . $sekola;
});
//parameter optional kalo tidak diisi
Route::get('/nama-saya-adalah-{nama?}', function ($nama = null) {
return 'Nama Saya Adalah : ' . $nama;
});
//parameter optional kalo di isi
Route::get('/nama-saya-adalah/{nama?}', function ($nama = 'NAMA WAJIB DI ISI!!') {
return 'Nama Saya Adalah : ' . $nama;
});
//LATIHAN
Route::get('/hitung-luas-segitiga/{alas}/{tinggi}', function ($alas, $tinggi) {
$hasil = $alas * $tinggi * 0.5;
return 'Hasil Luas Segitiga : ' . $hasil;
});
Route::get('/hitung-luas-segitiga/{alas?}/{tinggi?}', function ($alas = 1, $tinggi = 1) {
$hasil = $alas * $tinggi * 0.5;
return 'Hasil Luas Segitiga : ' . $hasil;
});
//route group
Route::group(['prefix' => 'jurusan'], function () {
Route::get('/', function () {
return "Berhasil";
});
Route::get('/kelas/{namaKelas}', function ($namaKelas) {
return $namaKelas;
});
Route::get('/wali-kelas/{namaKelas}', function ($nama) {
return $nama;
});
});
//menampilkan data class berdasarkan method
Route::get('data-siswa', [DataSiswaController::class, 'dataSiswa']);
Route::get('nama/{nama}', [DataSiswaController::class, 'nama']);
//menampilkan seluruh isi class
Route::resource('user', UserController::class);
Route::get('profile', function () {
return view('profile.index');
});
Route::get('profile/{nama}', function ($nama) {
return view('profile.detail', ['nama_user' => $nama]);
});
Route::get('album', function() {
return view('album');
});
<file_sep><?php
namespace App\Http\Controllers;
class DataSiswaController extends Controller
{
public function dataSiswa()
{
$nama = '<NAME>';
return $nama;
}
public function dataSiswi()
{
$nama = '<NAME>';
return $nama;
}
public function nama($nama)
{
return "Nama Anda Adalah : " . $nama;
}
}
| 7d32da5ec72f572ff167c28fbafa470e6492eee8 | [
"PHP"
] | 2 | PHP | kaylarahma/laravel-dasar | c7a64a47ec36fc177c0c6ed04d9a373ae4e2e449 | eec46537b68e1ac8e5327549b52a41f52a5306f5 |
refs/heads/master | <repo_name>BrandonC98/Voxel-Editor<file_sep>/Project V2/Project V2/Source/ShaderManager.h
#pragma once
#include <GL\glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <string>
#include <iostream>
#include <fstream>
//using namespace std;
class ShaderManager
{
public:
ShaderManager(const std::string& vertexShader, const std::string& fragmentShader);
~ShaderManager();
//used to define the type of shader to retrive
static enum shaderType
{
NONE = -0, VERTEX = 0, FRAGMENT = 1
};
void Bind() const;
void Unbind() const;
void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3);
void SetTranform(glm::mat4 transform);
void UnifromMat4(const std::string& name, glm::mat4 mat4);
unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader);
static std::string GetShader(shaderType typeOfShader, std::string fileName);
private:
unsigned int CompileShader(GLuint type, const std::string& source);
unsigned int id;
int GetUniformLocation(const std::string& name);
};
<file_sep>/Project V2/Project V2/Source/WavefrontFile.cpp
#include "WavefrontFile.h"
WavefrontFile::WavefrontFile(std::string fileName)
{
file.open(fileName);
}
void WavefrontFile::EndObject()
{
faceCounter += 8;
}
void WavefrontFile::Insert(std::string line)
{
//adds the line to the file
file << line;
}
void WavefrontFile::InsertFace(int v1, int v2, int v3, int v4)
{
std::ostringstream ssV1, ssV2, ssV3, ssV4;
ssV1 << v1 + faceCounter;
ssV2 << v2 + faceCounter;
ssV3 << v3 + faceCounter;
ssV4 << v4 + faceCounter;
//the f character represents the vertices index of a face. the vertices are gathered from InsertVertex()
std::string line = "f " + ssV1.str() + " " + ssV2.str() + " " + ssV3.str() + " " + ssV4.str() + "\n";
Insert(line);
}
void WavefrontFile::InsertVertex(float x, float y, float z)
{
std::ostringstream ssX, ssY, ssZ;
ssX << x;
ssY << y;
ssZ << z;
//the v Character represents vertices
std::string line = "v " + ssX.str() + " " + ssY.str() + " " + ssZ.str() + "\n";
Insert(line);
}
void WavefrontFile::InsertEmptyLine()
{
Insert("\n");
}
void WavefrontFile::Close()
{
file.close();
}
void WavefrontFile::InsertComment(std::string comment)
{
//the # symbol defines a comment in obj files
std::string line = "# " + comment + "\n";
Insert(line);
}
<file_sep>/Project V2/Project V2/Source/VoxGrid.h
#pragma once
#include "Vox.h"
#include <iostream>
class VoxGrid
{
public:
VoxGrid();
VoxGrid(int _arraySize);
~VoxGrid();
void ActivateVox(int keyX, int keyY, int KeyZ);
void DeactivateVox(int keyX, int keyY, int KeyZ);
bool IsVoxHere(int keyX, int keyY, int keyZ);
bool IsVoxColourTheSame(int keyX, int keyY, int keyZ, float r, float g, float b);
void SetVoxColour(int keyx, int keyY, int keyZ, float r, float g, float b);
int Count();
void SetAllPositions();
float GetVoxCol(int keyX,int keyY,int keyZ, int colourIndex);
bool OutOfBound(int keyX, int keyY, int KeyZ);
private:
Vox ***vGrid;
int arraySize;
};
<file_sep>/Project V2/Project V2/Source/Main.cpp
//OpenGL Related
#include <GL\glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
//c++ Related
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
//Project Related
#include "ShaderManager.h"
#include "VBuffer.h"
#include "IndexBuffer.h"
#include "Renderer.h"
#include "VertexArray.h"
#include "DeltaTime.h"
#include "Input.h"
#include "Transform.h"
#include "Camera.h"
#include "Window.h"
#include "VoxGrid.h"
#include "WavefrontFile.h"
//User interface related
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "ToolBar.h"
#include "Menu.h"
#include <GLFW\glfw3.h>
//callbacks
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void Mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
int const arraySize = 32;
int const offset = 2;
Input* input = 0;
glm::vec3 cursorPosition;
bool turnGridOn = true;
bool turnWireFrameOn = false;
bool placeVox = false;
bool removeVox = false;
bool leftClick = false;
float CurrentHight = 800;
float CurrentWidth = 1200;
bool editMode = true;
bool moveCam = false;
bool camControlMode = false;
int yCursor = 0;
ToolBar toolbar;
void GlfwSetUp()
{
/* Initialize the library */
if (glfwInit() == GL_TRUE)
{
std::cout << "GLFW Setup Successful" << std::endl;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
glDepthFunc(GL_LESS);
}
else
{
std::cout << "GLFW Setup Fail" << std::endl;
}
}
int main(void)
{
GlfwSetUp();
Window window(CurrentWidth, CurrentHight);
window.Bind();
window.SetViewPort();
if (glewInit() != GLEW_OK) std::cout << "glew not intialised" << std::endl;
//set callbacks
glfwSetFramebufferSizeCallback(window.GetWindow(), framebuffer_size_callback);
glfwSetCursorPosCallback(window.GetWindow(), mouse_callback);
glfwSetScrollCallback(window.GetWindow(), scroll_callback);
glfwSetMouseButtonCallback(window.GetWindow(), Mouse_button_callback);
glfwSetKeyCallback(window.GetWindow(), key_callback);
//glEnable(GL_DEPTH_TEST);
//define the voxels vertices
float voxVerts[] =
{
0.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f
};
//define the indices
unsigned int voxIndices[]
{
5, 4, 0, 1,
5, 0, 6, 5,
1, 2, 6, 1,
7, 6, 2, 3,
7, 2, 4, 7,
3, 0, 4, 3,
6, 7, 4, 5,
6, 4, 1, 0,
3, 2, 1, 3
};
VertexArray vertexArray;
VBuffer vertexBuffer(voxVerts, 24 * 3 * sizeof(float));
vertexArray.VertexBufferLayout(0, 3, GL_FALSE);
vertexArray.SetStride(3);
vertexArray.AddBuffer(vertexBuffer);
IndexBuffer indexBuffer(voxIndices, 36);
//get the shader files and stores them in a string
std::string vertSrc = ShaderManager::GetShader(ShaderManager::VERTEX, "TransformVert.shader");
std::string fragSrc = ShaderManager::GetShader(ShaderManager::FRAGMENT, "basFrag.shader");
ShaderManager shader(vertSrc, fragSrc);
shader.Unbind();
Renderer renderer;
glEnable(GL_DEPTH_TEST);
const float objOffset = 0.5f;
DeltaTime* dTime = DeltaTime::GetInstance();
//sets the camera position to the middle of the grid
Camera* cam = Camera::GetInstance(arraySize / 2, 4.0f, arraySize + offset , 2.5f);
input = Input::GetInstance();
cam->SetPerspective(CurrentWidth, CurrentHight);
bool firstMove = false;
//set Cursor Voxel Colour
float vCursorCol[3] = { 1, 1, 1 };
VoxGrid voxGrid(arraySize);
voxGrid.SetAllPositions();
glm::vec3 gridTranslation = glm::vec3(0, 0, 0);
//handles the voxels rgb values
float col[4] = { 1.0f,1.0f,1.0f,1.0f };
float cursorSpeed = 1000;
//turns the cursor off
glfwSetInputMode(window.GetWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
const char* glsl_version = "#version 130";
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsClassic();
ImGui_ImplGlfw_InitForOpenGL(window.GetWindow(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
Menu menu;
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window.GetWindow()))
{
//BASIC FRAME SET UP
// everything that needs to be done each frame
// should be done here before anything is rendered
// as rendering may rely on it
//sets the background colour
glClearColor(0.12, 0.12, 0.12, 1);
//clears all the opengl rendered objects in the scene
renderer.Clear();
cam->SetPerspective(CurrentWidth, CurrentHight);
dTime->UpdateTime(glfwGetTime());
//get the cursor position and converts that to world space
glm::vec3 cursorPosition = input->ScreenToWorldSpace(cam->GetLookAt(), cam->GetPerspective(), CurrentWidth, CurrentHight);
//only the x and y are used. the y will actually be used for the z axis as we use the scroll will for the y
//they are then rounded as the cursor needs to snap to and from positions
cursorPosition.x = glm::round(cursorPosition.x * cursorSpeed);
cursorPosition.y = glm::round(cursorPosition.y * cursorSpeed);
//FLOOR GRID
//draws a grid on the floor so the user
//can see where key can place voxels and if
//they are in line
//render Grid
if (turnGridOn)
{
//this always needs to be solid so if
//wireframe is on this will disable it
//during the rendering of the grid
if (turnWireFrameOn)
{
//turns wireframe off
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
}
Transform gridTransform;
//Z axis lines
for (int i = 0; i <= arraySize; i++)
{
gridTransform.Translate(i, gridTranslation.y, gridTranslation.z);
gridTransform.Scale(0.025, 0.025, arraySize);
shader.Bind();
shader.SetUniform4f("u_Colour", 1, 1, 1, 1.0);
shader.SetTranform(gridTransform.Result());
shader.UnifromMat4("view", cam->GetLookAt());
shader.UnifromMat4("projection", cam->GetPerspective());
renderer.Draw(vertexArray, indexBuffer, shader);
}
//X axis lines
for (int i = 0; i >= -arraySize; i--)
{
gridTransform.Translate(gridTranslation.x, gridTranslation.y, -i);
gridTransform.Scale(arraySize, 0.025, 0.025);
shader.Bind();
shader.SetUniform4f("u_Colour", 1, 1, 1, 1.0);
shader.SetTranform(gridTransform.Result());
shader.UnifromMat4("view", cam->GetLookAt());
shader.UnifromMat4("projection", cam->GetPerspective());
renderer.Draw(vertexArray, indexBuffer, shader);
}
if (turnWireFrameOn)
{
//turns wireframe on
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
}
}
// RENDER VOXELS
//loops through a 3 dimensional array. if the element
//is true it runs the code to draw a voxel.
//any thing that needs to be done to every voxel should be
//done in this loop
Transform vGridTransform;
Transform voxelOutlineTransform;
for (int x = 0; x < voxGrid.Count(); x++)
{
for (int y = 0; y < voxGrid.Count(); y++)
{
for (int z = 0; z < voxGrid.Count(); z++)
{
if (voxGrid.IsVoxHere(x, y, z) == true)
{
vGridTransform.Translate(x, y, z);
voxelOutlineTransform.Translate(x, y, z);
voxelOutlineTransform.Scale(1, 1, 1);
if (!turnWireFrameOn)
{
//turns wireframe on
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
//the wireframe thickeness is determined by this value
//so its increased for this small part of rendering and then
//changed back to 1 the normal thickness
glLineWidth(5.0f);
shader.Bind();
//sets the colour to black
shader.SetUniform4f("u_Colour", 0, 0, 0, 1);
shader.SetTranform(voxelOutlineTransform.Result());
shader.UnifromMat4("view", cam->GetLookAt());
shader.UnifromMat4("projection", cam->GetPerspective());
//only draws the wireframe of the voxel.
//this is done to better define where one voxel ends
//and another starts for the user
renderer.Draw(vertexArray, indexBuffer, shader);
//turns wireframe off
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
}
glLineWidth(1.0f);
//draws the actual voxel
shader.Bind();
shader.SetUniform4f("u_Colour", voxGrid.GetVoxCol(x, y, z, 0), voxGrid.GetVoxCol(x, y, z, 1), voxGrid.GetVoxCol(x, y, z, 2), 1.0);
shader.SetTranform(vGridTransform.Result());
shader.UnifromMat4("view", cam->GetLookAt());
shader.UnifromMat4("projection", cam->GetPerspective());
//draws the voxel
renderer.Draw(vertexArray, indexBuffer, shader);
}
}
}
}
//RENDER CURSOR VOXEL
//this area is for the voxel cursor
if (editMode)
{
Transform cursorTransform;
//moves the cursors object position
cursorTransform.Translate(cursorPosition.x, yCursor, cursorPosition.y);
//changes the cursor to red if out of bounds
if (!voxGrid.OutOfBound(cursorPosition.x, yCursor, cursorPosition.y))
{
vCursorCol[0] = 1;
vCursorCol[1] = 1;
vCursorCol[2] = 1;
}
else
{
vCursorCol[0] = 1;
vCursorCol[1] = 0;
vCursorCol[2] = 0;
}
shader.Bind();
//sets the cursor colour in via the shader
shader.SetUniform4f("u_Colour", vCursorCol[0], vCursorCol[1], vCursorCol[2], 1);
shader.SetTranform(cursorTransform.Result());
shader.UnifromMat4("view", cam->GetLookAt());
shader.UnifromMat4("projection", cam->GetPerspective());
//draws a voxel at the position of the cursor
//to show the users where they are and preview of what
//a voxel would look like in that position.
renderer.Draw(vertexArray, indexBuffer, shader);
if (leftClick)
{
//checks if a voxel is in the cursors current position
if (!voxGrid.IsVoxHere(cursorPosition.x, yCursor, cursorPosition.y))
{
//adds a voxel to the voxel array
voxGrid.ActivateVox(cursorPosition.x, yCursor, cursorPosition.y);
std::cout << "active vox " << "[" << cursorPosition.x << "][" << yCursor << "][" << cursorPosition.y << "]" << std::endl;
voxGrid.SetVoxColour(cursorPosition.x, yCursor, cursorPosition.y, col[0], col[1], col[2]);
}
else
{
//removes a voxel from the voxel array
voxGrid.DeactivateVox(cursorPosition.x, yCursor, cursorPosition.y);
}
leftClick = false;
}
}
//SAVE AND EXPORT
//handles the saving to obj.
//the WavefrontFile class does all the work here
//if any more file formats are add it should be
//in this section
if (toolbar.GetSaveButtonState())
{
//at the moment the file is created in the projects directory
//under the name file
WavefrontFile objFile("file.obj");
objFile.InsertComment("Obj File Created with the Voxel Editor");
//loops throw a 3 demensional arrray to check if a element needs to be rendered
for (int x = 0; x < voxGrid.Count(); x++)
{
for (int y = 0; y < voxGrid.Count(); y++)
{
for (int z = 0; z < voxGrid.Count(); z++)
{
if (voxGrid.IsVoxHere(x, y, z) == true)
{
//adds a new line to make the source file more readable
objFile.InsertEmptyLine();
objFile.InsertVertex(x + objOffset, y + objOffset, z - objOffset);
objFile.InsertVertex(x + objOffset, y - objOffset, z - objOffset);
objFile.InsertVertex(x + objOffset, y + objOffset, z + objOffset);
objFile.InsertVertex(x + objOffset, y - objOffset, z + objOffset);
objFile.InsertVertex(x - objOffset, y + objOffset, z - objOffset);
objFile.InsertVertex(x - objOffset, y - objOffset, z - objOffset);
objFile.InsertVertex(x - objOffset, y + objOffset, z + objOffset);
objFile.InsertVertex(x - objOffset, y - objOffset, z + objOffset);
objFile.InsertEmptyLine();
objFile.InsertFace(1, 5, 7, 3);
objFile.InsertFace(4, 3, 7, 8);
objFile.InsertFace(8, 7, 5, 6);
objFile.InsertFace(6, 2, 4, 8);
objFile.InsertFace(2, 1, 3, 4);
objFile.InsertFace(6, 5, 1, 2);
objFile.EndObject();
}
}
}
}
objFile.Close();
toolbar.ResetSaveButtonState();
}
//IMGUI USER INTERFACE
//UI related tasks should be placed here
//all the UI is done using ImGui
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
toolbar.Render(turnGridOn);
if (ImGui::Begin("Menu"))
{
//displays the cursors current position
ImGui::Text("X: %.0f, Y: %i, Z: %.0f", cursorPosition.x, yCursor, cursorPosition.y);
ImGui::TextColored(ImVec4(1, 1, 0, 1), "IMPORTANT NOTE: if VOXEL cursor is not visible\nmove the mouse until the coordinates\nabove are: X: 16, Y: 0, Z: 16\nAlso make sure editing mode is active\n(the cursor shouldn't be visible)");
//displays a colour picker and assigns the values to the col array
ImGui::ColorPicker3("Colour", col);
//turns wireframe on/off
ImGui::Checkbox("WireFrame Mode", &turnWireFrameOn);
if (turnWireFrameOn)
{
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
}
//basic controls
ImGui::Text("left mouse button: place/delete voxel");
ImGui::Spacing();
ImGui::Text("right mouse button: switch to cursor for UI or voxel cursor for editing");
ImGui::Spacing();
ImGui::Text("scroll wheel: move voxel cursor in the Y direction.\nuse while holding left Ctrl for zoom");
ImGui::Spacing();
ImGui::Text("hold left CTRL: move mouse to look around");
ImGui::Spacing();
ImGui::Text("Hold Left ALT: move mouse to move around the scene");
ImGui::Spacing();
//shortcut list
ImGui::Text("shortcut list:\n S key: export\n G key: turn grid on/off\n W key: turn wireframe on/off");
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
/* Swap front and back buffers */
glfwSwapBuffers(window.GetWindow());
/* Poll for and process events */
glfwPollEvents();
}
indexBuffer.~IndexBuffer();
shader.~ShaderManager();
vertexBuffer.~VBuffer();
vertexArray.~VertexArray();
window.~Window();
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
//KEYBOARD INPUT
//this section is for standard keyboard input
//close window on escape key
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
//turn camera movement on/off
if (mods == GLFW_MOD_ALT && action == GLFW_REPEAT)
{
moveCam = true;
editMode = false;
}
else
{
moveCam = false;
}
//turn camera control off/on
if (mods == GLFW_MOD_CONTROL && action == GLFW_REPEAT)
{
camControlMode = true;
editMode = false;
}
else
{
camControlMode = false;
editMode = true;
}
//SHORTCUT KEY INPUT
//for shortcut mapping
// wireframe mode shortcut
if (key == GLFW_KEY_W && action == GLFW_PRESS)
{
if (turnWireFrameOn) turnWireFrameOn = false;
else turnWireFrameOn = true;
}
// grid toggle shortcut
if (key == GLFW_KEY_G && action == GLFW_PRESS)
{
if (turnGridOn) turnGridOn = false;
else turnGridOn = true;
}
//export shortcut
if (key == GLFW_KEY_S && action == GLFW_PRESS)
{
toolbar.SetSaveButtonStateToTrue();
}
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
//ajusts the viewport to the correct size
glViewport(0, 0, width, height);
//stores the values to be updated throughtout the program
//so nothing that needs the height and width is incorrect
CurrentHight = height;
CurrentWidth = width;
}
void Mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
input = Input::GetInstance();
Camera* cam = Camera::GetInstance(0.0f, 0.0f, 9.0f, 2.5f);
//place/delete voxel
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
leftClick = true;
}
//turn edit mode on/off
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS)
{
if (editMode)
{
editMode = false;
}
else editMode = true;
if (!editMode)
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
if (editMode)
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
input = Input::GetInstance();
input->SetMousePosition(xpos, ypos);
Camera* cam = Camera::GetInstance(0.0f, 0.0f, 0.0f, 0.0f);
//moves the camera's position on the x and y axis
if (moveCam)
{
if (ypos < input->lastY) cam->MoveUp();
if (xpos < input->lastX) cam->MoveLeft();
if (ypos > input->lastY) cam->MoveDown();
if (xpos > input->lastX) cam->MoveRight();
input->lastX = xpos;
input->lastY = ypos;
}
if (camControlMode)
{
if (cam->firstMove)
{
//if its the camera's first move
//then it won't have a last position
//so it sets it to its current
input->lastX = xpos;
input->lastY = ypos;
cam->firstMove = false;
}
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// yaw/ptich
float xoffset = xpos - input->lastX;
float yoffset = input->lastY - ypos;
input->lastX = xpos;
input->lastY = ypos;
xoffset *= cam->sensitivity;
yoffset *= cam->sensitivity;
cam->Rotate(xoffset, yoffset);
}
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
//moves the cursor position up/down
if (editMode)
{
if (yoffset > 0) yCursor++;
else if (yoffset < 0) yCursor--;
}
//zooms the camera in/out
if (camControlMode)
{
Camera* cam = Camera::GetInstance(0.0f, 0.0f, 9.0f, 2.5f);
cam->Zoom(yoffset);
}
}
<file_sep>/Project V2/Project V2/Source/Window.cpp
#include "Window.h"
Window::Window(int _width, int _hight)
{
width = _width;
hight = _hight;
//make the window
window = glfwCreateWindow(width, hight, title, NULL, NULL);
if (window == NULL)
{
std::cout << "Error: window not created correctly" << std::endl;
glfwTerminate();
}
}
Window::~Window()
{
glfwDestroyWindow(window);
}
void Window::Bind()
{
glfwMakeContextCurrent(window);
//sets screen fresh to that of the monitors
glfwSwapInterval(1);
}
int Window::GetHight()
{
return hight;
}
int Window::GetWidth()
{
return width;
}
void Window::Unbind()
{
glfwMakeContextCurrent(NULL);
}
void Window::SetViewPort()
{
glViewport(0, 0, width, hight);
}
GLFWwindow* Window::GetWindow()
{
return window;
}<file_sep>/Project V2/Project V2/Source/WavefrontFile.h
#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
/*
this class creates and writes to a file.
*/
class WavefrontFile
{
public:
WavefrontFile(std::string fileName);
void InsertComment(std::string comment);
void InsertVertex(float x, float y, float z);
void InsertFace(int v1, int v2, int v3, int v4);
void EndObject();
void Close();
void InsertEmptyLine();
private:
void Insert(std::string line);
std::string fileName;
int faceCounter = 0;
std::ofstream file;
};
<file_sep>/Project V2/Project V2/Source/IndexBuffer.h
#pragma once
#include <GL\glew.h>
class IndexBuffer
{
private:
unsigned int id;
unsigned int count;
public:
IndexBuffer(const unsigned int* data, unsigned int count);
~IndexBuffer();
void Bind() const;
void Unbind()const;
inline unsigned int GetCount() const { return count; }
};
<file_sep>/Project V2/Project V2/Source/Menu.h
#pragma once
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GL\glew.h>
class Menu
{
public:
void Render(float x, int y, float z, float colour[4], bool* turnWireFrameOn);
//bool GetWireFrameState();
private:
//bool wireFrameOn = false;
};
<file_sep>/Project V2/Project V2/Source/ToolBar.cpp
#include "ToolBar.h"
void ToolBar::Render(bool& turnGridOn)
{
cam = Camera::GetInstance(0, 0, 0, 0);
//toolbar
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("Files"))
{
//export to OBJ. the S key is the shortcut for this
if (ImGui::Button("Export S"))
{
save = true;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Options"))
{
ImGui::SliderFloat("Camera Sensitivty", &cam->speed, 1.0f, 10.0f); //MAYBE DELETE
//turns the floor grid off/on
ImGui::Checkbox("Toggle Grid", &turnGridOn);
//present style for the UI
if (ImGui::Button("Style Classic")) ImGui::StyleColorsClassic();
if (ImGui::Button("Style Dark")) ImGui::StyleColorsDark();
if (ImGui::Button("Style Light")) ImGui::StyleColorsLight();
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void ToolBar::SetSaveButtonStateToTrue()
{
save = true;
}
bool ToolBar::GetSaveButtonState()
{
return save;
}
void ToolBar::ResetSaveButtonState()
{
save = false;
}
<file_sep>/Project V2/Project V2/Source/VBuffer.h
#pragma once
#include <GL\glew.h>
class VBuffer
{
private:
unsigned int id;
public:
VBuffer(const void* data, unsigned int size);
~VBuffer();
void Bind() const;
void Unbind() const;
};
<file_sep>/Project V2/Project V2/Source/Camera.cpp
#include "Camera.h"
Camera* Camera::instance = 0;
//the Camera is singleton
Camera* Camera::GetInstance(float x, float y, float z, float speed)
{
if (instance == 0)
{
instance = new Camera(x, y, z, speed);
return instance;
}
else return instance;
}
Camera::Camera(float x, float y, float z, float _speed)
{
position.x = x;
position.y = y;
position.z = z;
front = glm::vec3(0.0f, 0.0f, -1.0f);
up = glm::vec3(0.0f, 1.0f, 0.0f);
speed = _speed;
yaw = -90.0f;
pitch = 0;
direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
direction.y = sin(glm::radians(pitch));
direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
}
//rotate the camera on the spot
void Camera::Rotate(float xoffset, float yoffset)
{
yaw += xoffset;
pitch += yoffset;
if(pitch > 89.0f)
pitch = 89.0f;
if (pitch < -89.0f)
pitch = -89.0f;
direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
direction.y = sin(glm::radians(pitch));
direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
SetFront(glm::normalize(direction));
}
Camera::~Camera()
{}
void Camera::SetPerspective(float width, float height)
{
projection = glm::perspective(glm::radians(fov), width / height, 0.1f, 100.0f);
}
glm::mat4 Camera::GetPerspective()
{
return projection;
}
glm::mat4 Camera::GetLookAt()
{
glm::mat4 view = glm::lookAt(position, position + front, up);
return view;
}
float Camera::GetSpeed()
{
DeltaTime* dtime = DeltaTime::GetInstance();
float step = speed * dtime->GetDeltaTime();
return step;
}
void Camera::SetFront(glm::vec3 _front)
{
front = _front;
}
void Camera::SetSpeed(float _speed)
{
speed = _speed;
}
void Camera::MoveUp()
{
position += GetSpeed() * up;
}
void Camera::Zoom(float scrollY)
{
if (fov >= 1.0f && fov <= 45.0f) fov -= scrollY;
if (fov <= 1.0f) fov = 1.0f;
if (fov >= 45.0f) fov = 45.0f;
}
void Camera::MoveDown()
{
position -= GetSpeed() * up;
}
void Camera::MoveLeft()
{
position -= glm::normalize(glm::cross(front, up)) * GetSpeed();
}
void Camera::MoveRight()
{
position += glm::normalize(glm::cross(front, up)) * GetSpeed();
}
<file_sep>/Project V2/Project V2/Source/VertexArray.h
#pragma once
#include <GL\glew.h>
#include "VBuffer.h"
class VertexArray
{
private:
unsigned int id;
float stride;
int index;
int componentsPerVert;
bool normalised;
public:
VertexArray();
~VertexArray();
void AddBuffer(const VBuffer& vb);
void Bind() const;
void Unbind() const;
void SetStride(float size);
void VertexBufferLayout(int index, int compPerV, bool normalised);
};
<file_sep>/Project V2/Project V2/Source/ToolBar.h
#pragma once
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "Camera.h"
class ToolBar
{
public:
void Render(bool& turnGridOn);
bool GetSaveButtonState();
void ResetSaveButtonState();
void SetSaveButtonStateToTrue();
private:
bool save;
Camera* cam;
};
<file_sep>/Project V2/Project V2/Source/Camera.h
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "DeltaTime.h"
#include <iostream>
class Camera
{
public:
~Camera();
static Camera* GetInstance(float x, float y, float z, float speed);
void MoveRight();
void MoveLeft();
void MoveUp();
void MoveDown();
void SetFront(glm::vec3 _front);
void Zoom(float scrollY);
float GetSpeed();
void SetSpeed(float _speed);
void SetPerspective(float width, float height);
glm::mat4 GetPerspective();
glm::mat4 GetLookAt();
float speed;
float sensitivity = 0.05f;
bool firstMove = true;
void Rotate(float xoffset, float yoffset);
float fov = 45.0f;
private:
Camera(float x, float y, float z, float _speed);
static Camera* instance;
glm::vec3 front;
glm::vec3 up;
glm::vec3 direction;
glm::mat4 view = glm::mat4(1.0f);
float yaw;
float pitch;
glm::mat4 projection = glm::mat4(1);
glm::vec3 position;
};
<file_sep>/Project V2/Project V2/imgui.ini
[Window][Debug##Default]
Pos=12,30
Size=279,974
Collapsed=0
[Window][Dear ImGui Demo]
Pos=1302,6
Size=550,680
Collapsed=0
[Window][Hello, world!]
Pos=60,60
Size=345,180
Collapsed=0
[Window][Another Window]
Pos=60,13
Size=198,118
Collapsed=0
[Window][Menu]
Pos=38,337
Size=535,648
Collapsed=0
<file_sep>/Project V2/Project V2/Source/Window.h
#pragma once
#include <iostream>
#include <GLFW/glfw3.h>
/*
this class handles the window creation.
Bind() will make the window the current
context. this class needs GLFW to operate.
*/
class Window
{
public:
void Bind();
void Unbind();
void SetViewPort();
GLFWwindow* GetWindow();
Window(int _width, int _hight);
~Window();
int GetHight();
int GetWidth();
private:
GLFWwindow* window;
const char* title = "Voxel Editor";
int width;
int hight;
};<file_sep>/Project V2/Project V2/Source/Menu.cpp
#include "Menu.h"
void Menu::Render(float x, int y, float z, float* colour, bool* turnWireFrameOn)
{
if (ImGui::Begin("Menu"))
{
//displays the cursors current position
ImGui::Text("X: %.0f, Y: %i, Z: %.0f", x, y, z);
//displays a colour picker and assigns the values to the col array
ImGui::ColorPicker3("Colour", colour);
//turns wireframe on/off
ImGui::Checkbox("WireFrame Mode", turnWireFrameOn);
if (turnWireFrameOn)
{
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
}
ImGui::End();
}
}
<file_sep>/Project V2/Project V2/Source/Transform.h
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class Transform
{
public:
Transform();
void Translate(float x, float y, float z);
void Rotate(float angle, float xAxis, float yAxis, float zAxis);
void Scale(float xScale, float yScale, float zScale);
glm::mat4 Result();
private:
glm::mat4 trans;
glm::mat4 results;
};
<file_sep>/Project V2/Project V2/Source/Vox.cpp
#include "Vox.h"
void Vox::SetPosition(float x, float y, float z)
{
position[0] = x;
position[1] = y;
position[2] = z;
}
void Vox::SetColour(float r, float g, float b)
{
colour[0] = r;
colour[1] = g;
colour[2] = b;
}
bool Vox::IsColourTheSame(float r, float g, float b)
{
if (colour[0] == r && colour[1] == g && colour[2] == b)
return true;
else return false;
}
float Vox::GetColour(int col)
{
return colour[col];
}
<file_sep>/Project V2/Project V2/Source/Input.h
#pragma once
#include "glm/glm.hpp"
class Input
{
public:
static Input* GetInstance();
void SetMousePosition(double xPosition, double yPosition);
double GetMouseX() const;
double GetMouseY() const;
glm::vec3 ScreenToWorldSpace(glm::mat4 view, glm::mat4 projection, int screenWidth, int screenHeight);
float lastX = 1200;
float lastY = 800;
private:
Input();
static Input* instance;
double mouseX = 0;
double mouseY = 0;
float offsetX;
float offsetY;
};
<file_sep>/Project V2/Project V2/Source/Transform.cpp
#include "Transform.h"
Transform::Transform()
{
trans = glm::mat4(1.0f);
}
void Transform::Translate(float x, float y, float z)
{
glm::vec3 newPosition;
newPosition.x = x;
newPosition.y = y;
newPosition.z = z;
trans = glm::translate(trans, newPosition);
}
void Transform::Rotate(float angle, float xAxis, float yAxis, float zAxis)
{
glm::vec3 axis;
axis.x = xAxis;
axis.y = yAxis;
axis.z = zAxis;
trans = glm::rotate(trans, glm::radians(angle), axis);
}
void Transform::Scale(float xScale, float yScale, float zScale)
{
glm::vec3 scale;
scale.x = xScale;
scale.y = yScale;
scale.z = zScale;
trans = glm::scale(trans, scale);
}
glm::mat4 Transform::Result()
{
results = trans;
trans = glm::mat4(1.0f);
return results;
}<file_sep>/Project V2/Project V2/Source/VBuffer.cpp
#include "VBuffer.h"
VBuffer::VBuffer(const void* data, unsigned int size)
{
//genrate buffer
glGenBuffers(1, &id);
glBindBuffer(GL_ARRAY_BUFFER, id);
//populates the bound buffer
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
}
VBuffer::~VBuffer()
{
glDeleteBuffers(1, &id);
}
void VBuffer::Bind() const
{
//this becomes the active buffer
glBindBuffer(GL_ARRAY_BUFFER, id);
}
void VBuffer::Unbind() const
{
//this removes it from the active buffer
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
<file_sep>/Project V2/Project V2/Source/ShaderManager.cpp
#include "ShaderManager.h"
std::string ShaderManager::GetShader(shaderType typeOfShader, std::string fileName)
{
std::string shader;
std::string filepath;
switch (typeOfShader)
{
case 0:
filepath = "Resources/Shaders/Vertex/";
break;
case 1:
filepath = "Resources/Shaders/Fragment/";
break;
}
std::ifstream stream(filepath + fileName);
std::string line;
//gets each line of the shader file and stores it in the line variable that is then
//added to the shader string
while (getline(stream, line))
{
shader += line + '\n';
}
return shader;
}
ShaderManager::ShaderManager(const std::string& vertexShader, const std::string& fragmentShader)
{
id = CreateShader(vertexShader, fragmentShader);
}
ShaderManager::~ShaderManager()
{
glDeleteProgram(id);
}
void ShaderManager::Bind() const
{
glUseProgram(id);
}
void ShaderManager::Unbind() const
{
glUseProgram(0);
}
void ShaderManager::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3)
{
glUniform4f(GetUniformLocation(name), v0, v1, v2, v3);
}
void ShaderManager::SetTranform(glm::mat4 transform)
{
unsigned int transLoc = glGetUniformLocation(id, "model");
glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(transform));
}
void ShaderManager::UnifromMat4(const std::string& name, glm::mat4 mat4)
{
glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, glm::value_ptr(mat4));
}
int ShaderManager::GetUniformLocation(const std::string& name)
{
int location = glGetUniformLocation(id, name.c_str());
if (location == -1) std::cout << " Error: uniform " << name << " doesn't exist" << std::endl;
return location;
}
unsigned int ShaderManager::CompileShader(GLuint type, const std::string& source)
{
GLuint id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
//error handling
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
char* message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(id, length, &length, message);
std::cout << "Failed to compile shader!" << std::endl;
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
return id;
}
unsigned int ShaderManager::CreateShader(const std::string& vertexShader, const std::string& fragmentShader)
{
GLuint program = glCreateProgram();
GLuint vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
<file_sep>/Project V2/Project V2/Source/VoxGrid.cpp
#include "VoxGrid.h"
VoxGrid::VoxGrid()
{}
VoxGrid::VoxGrid(int _arraySize)
{
arraySize = _arraySize;
//creates 3 dimensional array
vGrid = new Vox * *[arraySize];
for (int x = 0; x < arraySize; x++)
{
vGrid[x] = new Vox * [arraySize];
for (int y = 0; y < arraySize; y++)
{
vGrid[x][y] = new Vox[arraySize];
}
}
}
void VoxGrid::SetAllPositions()
{
// sets the position for all voxel elements of the array
for (int x = 0; x < arraySize; x++)
{
for (int y = 0; y < arraySize; y++)
{
for (int z = 0; z < arraySize; z++)
{
vGrid[x][y][z].SetPosition(x, y, z);
}
}
}
}
void VoxGrid::DeactivateVox(int keyX, int keyY, int KeyZ)
{
if (!OutOfBound(keyX, keyY, KeyZ))
{
vGrid[keyX][keyY][KeyZ].SetDeactive();
}
}
float VoxGrid::GetVoxCol(int keyX, int keyY, int keyZ, int colourIndex)
{
return vGrid[keyX][keyY][keyZ].GetColour(colourIndex);
}
void VoxGrid::SetVoxColour(int keyx, int keyY, int keyZ, float r, float g, float b)
{
vGrid[keyx][keyY][keyZ].SetColour(r, g, b);
}
int VoxGrid::Count()
{
return arraySize;
}
void VoxGrid::ActivateVox(int keyX, int keyY, int keyZ)
{
if (!OutOfBound(keyX, keyY, keyZ))
{
vGrid[keyX][keyY][keyZ].SetActive();
}
else std::cout << "position out of bounds" << std::endl;
}
bool VoxGrid::IsVoxHere(int keyX, int keyY, int keyZ)
{
if(!OutOfBound(keyX, keyY, keyZ))
return vGrid[keyX][keyY][keyZ].IsVoxHere;
else std::cout << "position out of bounds" << std::endl;
}
bool VoxGrid::IsVoxColourTheSame(int keyX, int keyY, int keyZ, float r, float g, float b)
{
return vGrid[keyX][keyY][keyZ].IsColourTheSame(r, g, b);
}
bool VoxGrid::OutOfBound(int keyX, int keyY, int keyZ)
{
//checks if x,y and z are within the grid limits
if (keyX <= arraySize && keyX >= 0 && keyY <= arraySize && keyY >= 0 && keyZ <= arraySize && keyZ >= 0)
return false;
else return true;
}
VoxGrid::~VoxGrid()
{
}
<file_sep>/README.md
# Voxel Editor
Voxel based modelling software
<file_sep>/Project V2/Project V2/Source/DeltaTime.cpp
#include "DeltaTime.h"
DeltaTime* DeltaTime::instance = 0;
DeltaTime* DeltaTime::GetInstance()
{
if (instance == 0)
{
instance = new DeltaTime();
return instance;
}
else
{
return instance;
}
}
DeltaTime::DeltaTime() {};
DeltaTime::~DeltaTime()
{
delete instance;
}
void DeltaTime::UpdateTime(float time)
{
float currentFrame = time;
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
}
float DeltaTime::GetDeltaTime()
{
return deltaTime;
}<file_sep>/Project V2/Project V2/Source/Vox.h
#pragma once
class Vox
{
public:
bool IsVoxHere = false;
void SetColour(float r, float g, float b);
bool IsColourTheSame(float r, float g, float b);
float GetColour(int col);
void SetPosition(float x, float y, float z);
inline bool SetActive() { IsVoxHere = true; return IsVoxHere; };
inline bool SetDeactive() { IsVoxHere = false; return IsVoxHere; };
private:
float position[3];
float colour[3] = { 0.12f, 0.12f, 0.12f };
};
<file_sep>/Project V2/Project V2/Source/VertexArray.cpp
#include "VertexArray.h"
VertexArray::VertexArray()
{
glGenVertexArrays(1, &id);
}
VertexArray::~VertexArray()
{
glDeleteVertexArrays(1, &id);
}
void VertexArray::Bind() const
{
glBindVertexArray(id);
}
void VertexArray::Unbind() const
{
glBindVertexArray(0);
}
void VertexArray::VertexBufferLayout(int _index, int _compPerV, bool _normalised)
{
index = _index;
componentsPerVert = _compPerV;
normalised = _normalised;
}
void VertexArray::AddBuffer(const VBuffer& vb)
{
Bind();
vb.Bind();
glEnableVertexAttribArray(index);
glVertexAttribPointer(index, componentsPerVert, GL_FLOAT, normalised, stride, 0);
}
//used to distinguish where a set of data end and a new one starts
void VertexArray::SetStride(float size)
{
stride = sizeof(float)* size;
}
<file_sep>/Project V2/Project V2/Source/DeltaTime.h
#pragma once
/*
use this to get the deltaTime for smooth
movement. it's a singleton. create a instance
put UpdateDeltaTime() in the render loop and
pass it the float that contains the time.
use GetDeltaTime() to retive it.
*/
class DeltaTime
{
public:
static DeltaTime *GetInstance();
void UpdateTime(float time);
float GetDeltaTime();
~DeltaTime();
private:
DeltaTime();
static DeltaTime* instance;
float deltaTime;
float lastFrame;
};
<file_sep>/Project V2/Project V2/Source/Input.cpp
#include "Input.h"
Input* Input::instance = 0;
Input::Input() {};
Input* Input::GetInstance()
{
if (instance == 0)
{
instance = new Input();
return instance;
}
else
{
return instance;
}
}
glm::vec3 Input::ScreenToWorldSpace(glm::mat4 view, glm::mat4 projection, int screenWidth, int screenHeight)
{
//converts screen position to world space
// we get the mouse position in world space out of this
glm::mat4 mat = (view * projection);
mat = glm::inverse(mat);
glm::vec4 results;
results.x = (2.0f * ((float)(GetMouseX() - 0) / screenWidth - 0)) - 1.0f;
results.y = 1.0f - (2.0f * ((float)(GetMouseY() - 0) / (screenHeight)-0));
results.z = 2.0 * 1.0f - 1.0f;
results.w = -1.0;
glm::vec4 mouse = mat * results;
mouse.w = 1.0f / mouse.w;
mouse.x *= mouse.w;
mouse.y *= mouse.w;
mouse.z *= mouse.w;
return mouse;
}
void Input::SetMousePosition(double xPosition, double yPosition)
{
mouseX = xPosition;
mouseY = yPosition;
}
double Input::GetMouseX() const
{
return mouseX;
}
double Input::GetMouseY() const
{
return mouseY;
}
| 7382d2f574bbbc42b59c04c56e37f7de08dd854c | [
"Markdown",
"C++",
"INI"
] | 30 | C++ | BrandonC98/Voxel-Editor | 128d322a2a50831cec58b140b832af28fa85409e | 8911cbbed199ab42b4b6d7b42edd76f9364ded17 |
refs/heads/master | <repo_name>olejabiz/Pizza<file_sep>/server/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace server
{
class Program
{
static void Main(string[] args)
{
// Устанавливаем для сокета локальную конечную точку
IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
// Создаем сокет Tcp/Ip
Socket sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Назначаем сокет локальной конечной точке и слушаем входящие сокеты
try
{
sListener.Bind(ipEndPoint);
sListener.Listen(10);
// Начинаем слушать соединения
while (true)
{
Console.WriteLine("Ожидаем соединение через порт " + ipEndPoint);
// Программа приостанавливается, ожидая входящее соединение
Socket handler = sListener.Accept();
string data = null;
// Мы дождались клиента, пытающегося с нами соединиться
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
// Показываем данные на консоли
Console.Write("Полученный текст: " + data + "\n\n");
void Pepperoni()
{
Console.WriteLine("Пепперони ");
string reply = "Вес: 560г.\n Состав: Грибы шампиньоны, Моцарелла, Пепперони, Томатный пицца - соус.\n Цена: 600 руб.";
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
}
void Fourseasons()
{
Console.WriteLine("Четыре сезона ");
string reply = "Вес: 750г.\n Состав: Шампиньоны, Курица, Моцарелла, Соус барбекю, Томаты.\n Цена: 700 руб. ";
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
}
void Fourcheeses()
{
Console.WriteLine("Четыре сыра ");
string reply = "Вес: 555г.\n Состав: Моцарелла, Сливочный пицца-соус, Сыр Дор Блю, Сыр Чеддер.\n Цена: 500 руб. ";
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
}
void Margarita()
{
Console.WriteLine("Маргарита ");
string reply = "Вес: 540г.\n Состав: Моцарелла, Помидоры, Томатный пицца-соус.\n Цена: 550 руб. ";
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
}
void Gavayskaya()
{
Console.WriteLine("Гавайская ");
string reply = "Вес:455г.\n Состав: Ананас, Курица, Моцарелла, Соус сливочный.\n Цена: 450 руб. ";
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
}
switch (data)
{
case "Пепперони":
Pepperoni();
break;
case "4 сезона":
Fourseasons();
break;
case "4 сыра":
Fourcheeses();
break;
case "Маргарита":
Margarita();
break;
case "Гавайская":
Gavayskaya();
break;
}
// Отправляем ответ клиенту\
if (data.IndexOf("<TheEnd>") > -1)
{
Console.WriteLine("Сервер завершил соединение с клиентом.");
break;
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadLine();
}
}
}
}
<file_sep>/pizzaprakt/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pizzaprakt
{
public partial class Form1 : Form
{
string message = "";
public Form1()
{
InitializeComponent();
richTextBox1.Text = "Введите название пиццы, информацию о которой вы хотите получить:";
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SendMessageFromSocket(11000);
}
catch
{
}
}
void SendMessageFromSocket(int port)
{
// Буфер для входящих данных
byte[] bytes = new byte[1024];
// Соединяемся с удаленным устройством
// Устанавливаем удаленную точку для сокета
IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);
Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Соединяем сокет с удаленной точкой
sender.Connect(ipEndPoint);
this.message = richTextBox2.Text;
//fm.RTB1.Text = "Сокет соединяется с {0} "+ sender.RemoteEndPoint.ToString();
byte[] msg = Encoding.UTF8.GetBytes(message);
// Отправляем данные через сокет
int bytesSent = sender.Send(msg);
// Получаем ответ от сервера
int bytesRec = sender.Receive(bytes);
richTextBox1.Text = "\nОтвет от сервера: {0}\n\n" + Encoding.UTF8.GetString(bytes, 0, bytesRec);
//fm.RTB1.Text = "\nОтвет от сервера: {0}\n\n"+ Encoding.UTF8.GetString(bytes, 0, bytesRec);
richTextBox2.Clear();
// Используем рекурсию для неоднократного вызова SendMessageFromSocket()
/*if (message.IndexOf("<TheEnd>") == -1)
SendMessageFromSocket(port);*/
// Освобождаем сокет
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
}
} | c6849211e377481fb02e90d494ac3c85ce548ac7 | [
"C#"
] | 2 | C# | olejabiz/Pizza | b82e1ad1731e63e26ae402d8c54186d4769d6d61 | 6e1db7e0554c864c787b0a6240ca9ad39fb145c7 |
refs/heads/master | <file_sep>declare namespace cc {
interface Node { // tslint:disable-line
angelTo(point: cc.Vec2): number;
getWorldPosition(): cc.Vec2;
getAttr<T>(key: string): T;
}
interface Graphics { // tslint:disable-line
dashedLine(startPos: cc.Vec2, endPos: cc.Vec2, lineLength?: number, spaceLength?: number): void;
}
export function assert(cond: boolean, msg?: string): void;
export function hasScene(sceneName: string): boolean;
export function randf(minInclusive: number, maxInclusive: number): number;
export function takeScreenshot(): Promise<string>;
export function spriteFrameFromBase64(base64: string): Promise<SpriteFrame>;
}
interface Array<T> { // tslint:disable-line
randOne(): T;
shuffle(): T[];
uniq(): T[];
}
interface Number { // tslint:disable-line
round(decimal): number;
}
Number.prototype.round = function round(this: number, decimal: number): number {
return Math.round(this * Math.pow(10, decimal)) / Math.pow(10, decimal);
};
Array.prototype.randOne = function <T>(this: T[]): T {
return this[Math.floor(this.length * Math.random())];
};
Array.prototype.shuffle = function shuffle<T>(this: T[]): T[] {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
};
Array.prototype.uniq = function shuffle<T>(this: T[]): T[] {
return this.filter((v, i, a) => a.indexOf(v) === i);
};
cc.Node.prototype.getWorldPosition = function (this: cc.Node) {
return this.parent.convertToWorldSpaceAR(this.getPosition());
};
cc.Node.prototype.angelTo = function (this: cc.Node, point): number {
const target = point.sub(this.getWorldPosition());
const angel = Math.atan2(target.x, target.y);
return angel * 180 / Math.PI;
};
cc.Node.prototype.getAttr = function <T>(this: cc.Node, key) {
return this[key] as T;
};
cc.spriteFrameFromBase64 = (base64) => {
return new Promise<cc.SpriteFrame>((resolve, reject) => {
const img = new Image();
img.src = base64;
img.onload = () => {
const texture = new cc.Texture2D();
texture.initWithElement(img);
texture.handleLoadedTexture();
const newframe = new cc.SpriteFrame(texture);
resolve(newframe);
};
});
};
cc.takeScreenshot = () => {
return new Promise<string>((resolve, reject) => {
cc.director.on(cc.Director.EVENT_AFTER_DRAW, () => {
const base64 = cc.game.canvas.toDataURL();
cc.director.off(cc.Director.EVENT_AFTER_DRAW);
resolve(base64);
});
});
};
cc.randf = (min, max) => {
return min + Math.round(max * Math.random());
};
cc.hasScene = (name) => {
const scenes = cc.game.config.scenes;
for (const s of scenes) {
if (s.url.endsWith(name + ".fire")) {
return true;
}
}
return false;
};
if (cc.Graphics) {
cc.Graphics.prototype.dashedLine = function (
this: cc.Graphics,
startPos,
endPos,
lineLength = 10,
spaceLength = 20) {
let cursor = startPos;
let count = 0;
const direction = endPos.sub(startPos);
if (direction.mag() < 10) {
return;
}
const increment = direction.normalize();
while ((endPos.x - cursor.x) * increment.x >= 0 && (endPos.y - cursor.y) * increment.y >= 0) {
if (count % 2 === 0) {
this.moveTo(cursor.x, cursor.y);
cursor = cursor.add(increment.mul(lineLength));
} else {
this.lineTo(cursor.x, cursor.y);
cursor = cursor.add(increment.mul(spaceLength));
}
count++;
}
};
}
<file_sep>const { ccclass, property } = cc._decorator;
@ccclass
export default class Overlay extends cc.Component {
@property(cc.Label)
private text: cc.Label = null;
public closeOverlay() {
this.node.active = false;
}
public openOverlay(text: string) {
this.text.string = text;
this.node.active = true;
}
}
<file_sep>import Card from "./Card";
import { CardType, Color, Pattern } from "./CardData";
import NewCards from "./NewCards";
import Overlay from "./Overlay";
const { ccclass, property } = cc._decorator;
const PADDING = 60;
const NODE_WIDTH = 150;
export const ANIMATION_TIME = 0.25;
const MAX_HOLDING = 6;
let _instance: CardDeck = null;
@ccclass
export default class CardDeck extends cc.Component {
public get unlockedSquad() {
return this._unlockedSquad;
}
public set unlockedSquad(value) {
this.setHoldingAreaLabel();
this.placeholders.children.forEach((node, i) => {
node.children[0].active = i >= value;
});
this._unlockedSquad = value;
}
public get life(): number {
return this._life;
}
public set life(value: number) {
this.lifeLabel.string = `Life: ${value}`;
this._life = value;
}
public get opponentLife(): number {
return this._opponentLife;
}
public set opponentLife(value: number) {
this.opponentLifeLabel.string = `Opponent's Life: ${value}`;
this._opponentLife = value;
}
public static getInstance(): CardDeck {
if (_instance === null) {
throw new Error("Placeholders is null, likely due to onLoad execution order");
}
return _instance;
}
public newCardPanelOpen: boolean = false;
@property(cc.Node)
public readonly dragToRemove: cc.Node = null;
public turnCount: number = 0;
@property(cc.Node)
private nextTurn: cc.Node = null;
@property(NewCards)
private newCards: NewCards = null;
private _unlockedSquad: number = 0;
private _life: number = 100;
private _opponentLife: number = 100;
@property(cc.Prefab)
private cardPrefab: cc.Prefab = null;
@property(cc.Node)
private placeholders: cc.Node = null;
@property(cc.Node)
private holdingNode: cc.Node = null;
@property(cc.Node)
private squadNode: cc.Node = null;
@property(cc.Node)
private squadNodeClone: cc.Node = null;
@property(cc.Node)
private opponentSquadNode: cc.Node = null;
@property(cc.Label)
private holdingAreaLabel: cc.Label = null;
@property(cc.Label)
private lifeLabel: cc.Label = null;
@property(cc.Label)
private opponentLifeLabel: cc.Label = null;
public moveToSquad(c: Card): boolean {
if (this.squadNode.childrenCount >= this._unlockedSquad) {
return false;
}
c.node.position = this.squadNode.convertToNodeSpaceAR(c.node.parent.convertToWorldSpaceAR(c.node.position));
c.node.parent = this.squadNode;
this.rearrangeCards();
return true;
}
public sell(c: Card): boolean {
c.node.parent = this.node;
c.node.destroy();
this.life += Math.pow(3, c.level - 1);
this.rearrangeCards();
return true;
}
public toggleNextTurn(showNextTurn) {
this.nextTurn.active = showNextTurn;
this.dragToRemove.active = !showNextTurn;
}
public moveToHolding(c: Card): boolean {
if (this.holdingNode.childrenCount >= MAX_HOLDING) {
return false;
}
c.node.position = this.holdingNode.convertToNodeSpaceAR(c.node.parent.convertToWorldSpaceAR(c.node.position));
c.node.parent = this.holdingNode;
this.rearrangeCards();
return true;
}
public addToHolding(c: Card): boolean {
if (this.holdingNode.childrenCount >= MAX_HOLDING) {
alert("Holding area is full");
return false;
}
if (this.life <= 2) {
alert("You don't have enough lives");
return;
}
this.life -= 2;
c.node.position = this.holdingNode.convertToNodeSpaceAR(c.node.parent.convertToWorldSpaceAR(c.node.position));
c.node.parent = this.holdingNode;
c.isNewCard = false;
this.rearrangeCards();
return true;
}
public doNextTurn() {
if (this.squadNode.childrenCount < this.unlockedSquad) {
alert("Your have empty battle card slots, drag more cards from holding area");
return;
}
this.turnCount++;
this.opponentLife -= cc.randf(Math.floor(this.opponentLife * 0.05), Math.floor(this.opponentLife * 0.15));
const opponentSquad = [];
for (let i = 0; i < Math.min(2 + this.turnCount, 8); i++) {
opponentSquad.push(new CardType(
Color[Object.keys(Color).randOne()],
Pattern[Object.keys(Pattern).randOne()],
));
}
// Build opponent squad
const opponentFreq: { [k: string]: Card[] } = {};
this.opponentSquadNode.removeAllChildren();
opponentSquad.forEach((card, i) => {
const node = cc.instantiate(this.cardPrefab);
const c = node.getComponent(Card);
c.build(card);
c.isOpponentCard = true;
node.parent = this.opponentSquadNode;
node.x = this.getCardX(opponentSquad.length, i);
if (opponentFreq[c.card.color]) {
opponentFreq[c.card.color].push(c);
} else {
opponentFreq[c.card.color] = [c];
}
if (opponentFreq[c.card.pattern]) {
opponentFreq[c.card.pattern].push(c);
} else {
opponentFreq[c.card.pattern] = [c];
}
});
// Clone my own squad
const freq: { [k: string]: Card[] } = {};
this.squadNodeClone.removeAllChildren();
this.squadNode.children.forEach((cloneFrom) => {
const node = cc.instantiate(this.cardPrefab);
const c = node.getComponent(Card);
const ccc = cloneFrom.getComponent(Card);
c.build(ccc.card, ccc.level);
node.parent = this.squadNodeClone;
node.position = cloneFrom.position;
if (freq[c.card.color]) {
freq[c.card.color].push(c);
} else {
freq[c.card.color] = [c];
}
if (freq[c.card.pattern]) {
freq[c.card.pattern].push(c);
} else {
freq[c.card.pattern] = [c];
}
});
Object.keys(freq).forEach((k) => {
if (freq[k].length >= 3) {
freq[k].forEach((c) => {
if (c.level >= 4) {
return;
}
c.level++;
c.playUpgradeAnimation(0);
});
}
});
Object.keys(opponentFreq).forEach((k) => {
if (opponentFreq[k].length >= 3) {
opponentFreq[k].forEach((c) => {
if (c.level >= 4) {
return;
}
c.level++;
c.playUpgradeAnimation(0);
});
}
});
this.opponentSquadNode.parent.active = true;
this.squadNode.active = false;
const myCards = this.squadNodeClone.children.map((c) => c.getComponent(Card));
const opponentCards = this.opponentSquadNode.children.map((c) => c.getComponent(Card));
const callback = () => {
if (myCards.length <= 0 || opponentCards.length <= 0) {
this.unschedule(callback);
const myScore = myCards.reduce((prev, current) => prev += current.level, 0);
const opponentScore = opponentCards.reduce((prev, current) => prev += current.level, 0);
const diff = 2 * (myScore - opponentScore);
this.opponentSquadNode.parent.active = false;
this.squadNodeClone.removeAllChildren();
this.squadNode.active = true;
if (diff > 0) {
alert(`You have killed opponent ${Math.abs(diff)} lives`);
this.opponentLife -= diff;
} else if (diff < 0) {
alert(`You have lost ${Math.abs(diff)} lives`);
this.life += diff;
} else {
alert("It's a tie!");
}
this.scheduleOnce(() => {
if (this.opponentLife <= 0) {
alert("You have won!");
cc.director.loadScene("Main");
return;
}
if (this.life <= 0) {
alert("You have lost!");
cc.director.loadScene("Main");
return;
}
this.newCards.openPanel({ freeReroll: true });
}, 0.5);
return;
}
const o = opponentCards[0];
const m = myCards[0];
m.node.runAction(cc.sequence(
cc.moveTo(
ANIMATION_TIME,
m.node.parent.convertToNodeSpaceAR(o.node.getWorldPosition()).sub(cc.v2(0, 50)),
).easing(cc.easeInOut(3)),
cc.moveTo(
ANIMATION_TIME,
m.node.position,
).easing(cc.easeInOut(3)),
cc.callFunc(() => {
const d = Math.min(m.level, o.level);
m.level -= d;
o.level -= d;
if (m.level <= 0) {
myCards.shift();
}
if (o.level <= 0) {
opponentCards.shift();
}
}),
));
};
this.schedule(callback, ANIMATION_TIME * 3, cc.macro.REPEAT_FOREVER);
}
public mergeCards() {
let isDirty = true;
while (isDirty) {
isDirty = false;
const freq: { [k: string]: Card[] } = {};
this.squadNode.children.concat(this.holdingNode.children).forEach((n) => {
const c = n.getComponent(Card);
if (freq[c.card.color + c.card.pattern + c.level]) {
freq[c.card.color + c.card.pattern + c.level].push(c);
} else {
freq[c.card.color + c.card.pattern + c.level] = [c];
}
});
Object.keys(freq).forEach((k) => {
if (freq[k].length >= 3 && freq[k][0].level < 4) {
freq[k][0].level++;
freq[k][0].playUpgradeAnimation();
freq[k][1].node.parent = this.node;
freq[k][1].node.destroy();
freq[k][2].node.parent = this.node;
freq[k][2].node.destroy();
isDirty = true;
}
});
}
this.rearrangeCards();
}
public turnInProgress(): boolean {
return this.opponentSquadNode.parent.active;
}
protected onLoad() {
_instance = this;
}
protected start() {
this.unlockedSquad = 3;
this.life = 100;
this.opponentLife = 100;
}
private setHoldingAreaLabel() {
this.holdingAreaLabel.string = `Holding Area ${this.holdingNode.childrenCount}/${MAX_HOLDING}`;
}
private rearrangeCards() {
this.rearrangeSquad();
this.rearrangeHolding();
}
private rearrangeHolding() {
this.setHoldingAreaLabel();
this.holdingNode.children.forEach((card, i) => {
card.stopAllActions();
card.scale = 1;
card.runAction(cc.moveTo(ANIMATION_TIME, this.getCardX(this.holdingNode.childrenCount, i), 0));
});
}
private rearrangeSquad() {
this.squadNode.children.forEach((card, i) => {
card.stopAllActions();
card.scale = 1;
card.runAction(cc.moveTo(ANIMATION_TIME, this.placeholders.children[i].position));
});
}
private getCardX(total: number, index: number) {
const w = cc.winSize.width - PADDING;
if (total === 1) {
return NODE_WIDTH / 2 + PADDING / 2;
}
const dist = (w - total * NODE_WIDTH) / (total - 1);
return PADDING / 2 + (dist + NODE_WIDTH) * index + NODE_WIDTH / 2;
}
}
<file_sep>import Card from "./Card";
import { CardType, Color, Pattern } from "./CardData";
import CardDeck from "./CardDeck";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Placeholders extends cc.Component {
protected start() {
const cd = CardDeck.getInstance();
this.node.children.forEach((c, i) => {
c.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventTouch) => {
if (i >= cd.unlockedSquad) {
const calc = Math.pow(2, i - 1) - CardDeck.getInstance().turnCount;
const cost = Math.max(2, calc);
if (cd.life <= cost) {
alert("You don't have enough lives");
return;
}
if (confirm(`Unlock this slot with ${cost} lives?`)) {
cd.unlockedSquad++;
cd.life -= cost;
}
}
});
});
}
}
<file_sep>export class CardType {
public readonly color: Color;
public readonly pattern: Pattern;
constructor(color: Color, pattern: Pattern) {
this.color = color;
this.pattern = pattern;
}
}
export enum Color {
Red = "#ff7675",
Blue = "#0984e3",
Black = "#2d3436",
Green = "#00b894",
}
export enum Pattern {
Gold = "Gold",
Wood = "Wood",
Water = "Water",
Fire = "Fire",
Earth = "Earth",
}
<file_sep>import { CardType } from "./CardData";
import CardDeck, { ANIMATION_TIME } from "./CardDeck";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Card extends cc.Component {
public get level(): number {
return this._level;
}
public set level(value: number) {
this._level = value;
this.level1.active = this._level >= 1;
this.level2.active = this._level >= 2;
this.level3.active = this._level >= 3;
this.level4.active = this._level >= 4;
}
public card: CardType = null;
public isNewCard: boolean = false;
public isOpponentCard: boolean = false;
public rearrangeAction: cc.Action;
@property(cc.Node)
private level1: cc.Node = null;
@property(cc.Node)
private level2: cc.Node = null;
@property(cc.Node)
private level3: cc.Node = null;
@property(cc.Node)
private level4: cc.Node = null;
@property(cc.Sprite)
private pattern: cc.Sprite = null;
@property(cc.Node)
private tileFrame: cc.Node = null;
private previousPosition: cc.Vec2 = null;
private _level: number;
public playUpgradeAnimation(delay: number = ANIMATION_TIME) {
this.scheduleOnce(() => {
this.node.runAction(cc.sequence(
cc.scaleTo(0.25, 1.1),
cc.scaleTo(0.25, 1),
cc.scaleTo(0.25, 1.1),
cc.scaleTo(0.25, 1),
cc.scaleTo(0.25, 1.1),
cc.scaleTo(0.25, 1),
));
}, delay);
}
public build(card: CardType, level = 1) {
this.card = card;
const color = cc.color().fromHEX(this.card.color);
// Pattern
const url = `characters/${card.pattern.replace(" ", "-")}`;
cc.loader.loadRes(url, cc.SpriteFrame, (err, spriteFrame) => {
this.pattern.spriteFrame = spriteFrame;
this.pattern.node.color = color;
});
// Level
this.level = level;
this.level4.color = color;
this.level3.color = color;
this.level2.color = color;
this.level1.color = color;
this.tileFrame.color = color;
}
protected start() {
this.node.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventTouch) => {
if (this.isOpponentCard || CardDeck.getInstance().turnInProgress()) {
return;
}
if (this.isNewCard) {
if (!CardDeck.getInstance().newCardPanelOpen) {
return;
}
CardDeck.getInstance().addToHolding(this);
} else {
if (CardDeck.getInstance().newCardPanelOpen) {
return;
}
CardDeck.getInstance().toggleNextTurn(false);
this.previousPosition = this.node.position;
}
});
this.node.on(cc.Node.EventType.TOUCH_MOVE, (event: cc.Event.EventTouch) => {
if (CardDeck.getInstance().newCardPanelOpen || this.isNewCard ||
this.isOpponentCard || CardDeck.getInstance().turnInProgress()) {
return;
}
this.node.position = this.node.parent.convertToNodeSpaceAR(event.getLocation());
});
this.node.on(cc.Node.EventType.TOUCH_END, (event: cc.Event.EventTouch) => {
if (CardDeck.getInstance().newCardPanelOpen || this.isNewCard ||
this.isOpponentCard || CardDeck.getInstance().turnInProgress()) {
return;
}
CardDeck.getInstance().toggleNextTurn(true);
const dtr = CardDeck.getInstance().dragToRemove;
const removeMinY = this.node.parent.convertToNodeSpaceAR(dtr.getWorldPosition()).y - dtr.height / 2;
if (this.node.position.y > removeMinY) {
CardDeck.getInstance().sell(this);
} else if (this.node.position.y > this.previousPosition.y) {
if (!CardDeck.getInstance().moveToSquad(this)) {
this.node.position = this.previousPosition;
}
} else {
if (!CardDeck.getInstance().moveToHolding(this)) {
this.node.position = this.previousPosition;
}
}
});
}
}
<file_sep>import Card from "./Card";
import { CardType, Color, Pattern } from "./CardData";
import CardDeck from "./CardDeck";
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewCards extends cc.Component {
@property(cc.Node)
private panel: cc.Node = null;
@property(cc.Node)
private placeholders: cc.Node = null;
@property(cc.Node)
private cards: cc.Node = null;
@property(cc.Prefab)
private cardPrefab: cc.Prefab = null;
public closePanel() {
CardDeck.getInstance().newCardPanelOpen = false;
this.panel.active = false;
CardDeck.getInstance().mergeCards();
}
public openPanel({ freeReroll = false }) {
if (freeReroll) {
this.reroll({ free: freeReroll });
}
CardDeck.getInstance().newCardPanelOpen = true;
this.panel.active = true;
}
protected start() {
this.openPanel({ freeReroll: true });
}
private reroll({ free = false }) {
if (!free) {
if (CardDeck.getInstance().life <= 2) {
alert("You don't have enough lives");
return;
}
CardDeck.getInstance().life -= 2;
}
this.cards.removeAllChildren();
this.placeholders.children.forEach((p) => {
const node = cc.instantiate(this.cardPrefab);
const c = node.getComponent(Card);
c.build(new CardType(Color[Object.keys(Color).randOne()], Pattern[Object.keys(Pattern).randOne()]));
node.parent = this.cards;
node.position = p.position;
c.isNewCard = true;
});
}
}
| 125b45e9cce094e81400638ba602dca617d84c55 | [
"TypeScript"
] | 7 | TypeScript | insraq/LD44 | 4a66cb1c28ba65b65617cc2986b24257d3b687ea | 16342bbd1680a7862dfa0d1ee4c7acea795c0040 |
refs/heads/main | <repo_name>VictoriaAnufrieva/Form<file_sep>/Form/js/script.js
const valid_fields = {
f_name: false,
l_name: false,
email: false,
password: <PASSWORD>,
password_conf: <PASSWORD>,
code: true,
phone: false,
country: true,
city: true,
// zip: false,
}
const keys_valid_fields = [
'f_name',
'l_name'
]
let create_new_account = document.querySelector('.button')
// console.log(create_new_account)
create_new_account.onclick= function(){
let valid = true
for(let key in valid_fields){
// console.log(valid_fields[key])
if(!valid_fields[key]){
console.log(valid_fields[key])
valid = false
break
}
} //END LOOP
if(valid){
console.log("ok")
}
else{
console.log("error")
}
} // END FUNCTION
const text = document.querySelectorAll('.any_text');
// console.log(text)
for(let i=0; i<text.length; i++){
// console.log(i)
// console.log(text[i])
text[i].onchange =function(){
if(/^\D+$/.test(this.value)){
console.log('Good');
this.classList.add('valid')
this.classList.remove('error')
valid_fields[keys_valid_fields[i]]=true
} else{
this.classList.add('error')
this.classList.remove('valid')
valid_fields[keys_valid_fields[i]]=false
}
}
}
const emailInput = document.querySelector('.email');
emailInput.onchange = function(){
if(/.{3,}@[a-z]{1,10}\.[a-z]{2,4}/.test(emailInput.value)){
emailInput.classList.add('valid')
emailInput.classList.remove('error')
valid_fields.email=true
}else {
console.log('Error');
emailInput.classList.add('error')
emailInput.classList.remove('valid')
valid_fields.email=false
}
}
const pass1 = document.querySelector('.password');
const pass2 = document.querySelector('.password_confirm');
const form_alert = document.querySelector('.form_alert')
pass1.oninput = function(){
if(/^(?=.*\d)(?=.*[a-z ]).{8,}$/.test(pass1.value)){
pass1.classList.add('valid')
pass1.classList.remove('error')
valid_fields.password=true
form_alert.style.display='none'
} else {
pass1.classList.add('error')
pass1.classList.remove('valid')
valid_fields.password=false
form_alert.style.display='block'
}
}
pass2.oninput = function(){
if(pass1.value === pass2.value){
pass2.classList.add('valid')
pass2.classList.remove('error')
valid_fields.password_conf=true
} else {
pass2.classList.add('error')
pass2.classList.remove('valid')
valid_fields.password_conf=false
}
}
let select = document.querySelector("select")
const arr = ['+954','+987','+944','+943','+916'];
for(let i=0; i<arr.length; i++){
let option = document.createElement('option')
option.innerHTML=arr[i]
// console.dir(option)
select.append(option)
}
let phone = document.querySelector(".phone")
console.log(phone)
phone.oninput=function(){
setTimeout(() => {
if(/^\d{1} [0-9]{8}$/.test(this.value)){
console.log('Good');
this.classList.add('valid')
this.classList.remove('error')
valid_fields.phone=true
} else{
this.classList.add('error')
this.classList.remove('valid')
valid_fields.phone=false
}
}, 100);
}
$('.phone').mask('0 00000000',{clearIfNotMatch:true});
const address=document.querySelector('.address')
address.oninput=function(){
if(/^\S{5,30}$/.test(this.value)){
console.log('Good');
this.classList.add('valid')
this.classList.remove('error')
} else{
this.classList.add('error')
this.classList.remove('valid')
}
}
const zip_code=document.querySelector('.zip_code')
zip_code.oninput=function(){
if(/^\d{3}-[0-9]{3}$/.test(this.value)){
console.log('Good');
this.classList.add('valid')
this.classList.remove('error')
valid_fields.zip=true
} else{
this.classList.add('error')
this.classList.remove('valid')
valid_fields.zip=false
}
}
$('.zip_code').mask('000-000');
const country = [
{
name:'Latvia',
cities: ['Dobele', 'Jelgava', 'Ogre','Riga', 'Talsi']
},
{
name:'Lebanon',
cities:['Beirut', 'Byblos', 'Sidon', 'Tripoli', 'Tyre']
},
{
name:'Liberia',
cities:['Bopolu', 'Ganda', 'Monrovia', 'Totota', 'Zwedru']
},
{
name:'Libya',
cities:['Awbari', 'Benghazi', 'Misrata', 'Sirte', 'Zilten']
},
{
name:'Liechtenstein',
cities: ['Balzers', 'Bazora', 'Eschen', 'Triesen', 'Vaduz']
}
] // End array_country
function select_cities(index){
const city = document.querySelector('.choose_city');
console.dir(city)
console.log(city.innerHTML)
city.innerHTML=''
for(let i=0; i<country[index].cities.length; i++){
let option = document.createElement('option')
option.innerHTML=country[index].cities[i]
// console.log(option)
city.append(option)
}
}
let choose_country = document.querySelector('.choose_country');
select_cities(0)
choose_country.onchange=function(){
for (let i=0; i<country.length; i++){
if(choose_country.value==country[i].name){
// console.log(country[i].color)
choose_country.style.background=country[i].color
select_cities(i)
} //ENd if
} //ENd loop
} //ENd function
for (let i=0; i<country.length; i++){
// console.log(country[i])
let option = document.createElement('option')
option.innerHTML=country[i].name
// console.dir(option)
choose_country.append(option)
}
| ad40c2c6bb5c5ad0288064666cab339df5c2e975 | [
"JavaScript"
] | 1 | JavaScript | VictoriaAnufrieva/Form | e7456219855d4a6c187c6321befa8c80493b9622 | e1c4590f30c1dd29ea2e05bde17aecb5a26e92b2 |
refs/heads/master | <repo_name>aveselovalova/micro-frontend<file_sep>/packages/container/webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ModuleFederationPlugin } = require("webpack").container;
const path = require("path");
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
});
const moduleFederationPlugin = new ModuleFederationPlugin({
name: "container",
remotes: {
module: "moduleApp@http://localhost:8081/remoteEntry.js",
},
shared: ["react", "react-dom"],
});
module.exports = {
entry: "./src/index",
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 8080,
},
output: {
publicPath: "http://localhost:8080/",
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
// to avoid: Uncaught Error: Shared module is not available for eager consumption
test: /bootstrap\.tsx$/,
loader: "bundle-loader",
options: {
lazy: true,
},
},
{
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader'
},
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]'
},
}
}
]
},
],
},
plugins: [moduleFederationPlugin, htmlPlugin],
};
<file_sep>/packages/container/src/components/App/module.d.ts
/// <reference types="react" />
declare module "module" {
const App: React.ComponentType;
export default App;
}
<file_sep>/README.md
# Micro-Frontend (ModuleFederationPlugin)
### Avaliable scripts:
* bootstrap -- install packages dependencies;
* start -- run packages in development mode;
* build -- build packages;
### Possible errors:
**Uncaught Error: Shared module is not available for eager consumption**
Solution:
* Change the entry point of the application:
```
import bootstrap from "./bootstrap";
bootstrap(() => {});
```
* Move an old entry point code into bootstrap.tsx
```
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from "./components/App/App";
ReactDOM.render(<App />, document.getElementById("root"));
```
* add __bundle-loader__;
```
{
test: /bootstrap\.js$/,
loader: "bundle-loader",
options: {
lazy: true,
},
}
```
| aeb0e5a268adea9c85d6529e9de8050d9cdc291f | [
"JavaScript",
"TypeScript",
"Markdown"
] | 3 | JavaScript | aveselovalova/micro-frontend | 3b7b883b7d8c6f0b39ea2a15bfcf913f319751ed | 81c010fffe83ffafa9dbfc2afe04ddbfb5fe6570 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dip;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
*
* @author 41819
*/
public class DIP {
public int[] Resize(Image img){
//height<530,width<680 [width,height]
int height=530;
int width=680;
int [] size=new int[2];
if((img.getHeight()>height&&img.getWidth()<width)||(img.getHeight()/height>=img.getWidth()/width)){
size[1]=height;
double w=img.getWidth()*height/img.getHeight();
size[0]=(int)w;
}
else if(img.getHeight()<height&&img.getWidth()>width||(img.getHeight()/height<img.getWidth()/width)){
size[0]=width;
double h=img.getHeight()*width/img.getWidth();
size[1]=(int)h;
}
return size;
}
public WritableImage RGB2Gray(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage gray_img=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = gray_img.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
color = color.grayscale();
pixelWriterGray.setColor(i, j, color);
}
return gray_img;
}
public WritableImage RGB2BGR(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriterGray.setColor(i, j, Color.color(color.getBlue(), color.getGreen(), color.getRed()));
}
return img1;
}
public WritableImage RGB2GBR(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriterGray.setColor(i, j, Color.color(color.getGreen(), color.getBlue(), color.getRed()));
}
return img1;
}
public WritableImage RGB2RBG(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriterGray.setColor(i, j, Color.color(color.getRed(), color.getBlue(), color.getGreen()));
}
return img1;
}
public WritableImage RGB2BRG(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriterGray.setColor(i, j, Color.color(color.getBlue(), color.getRed(), color.getGreen()));
}
return img1;
}
public WritableImage RGB2GRB(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriterGray.setColor(i, j, Color.color(color.getGreen(), color.getRed(), color.getBlue()));
}
return img1;
}
private double[] RGB2HSV_pixel(double r,double g,double b){
double[] color=new double[3];
double Cmax=(r>g?r:g)>b?(r>g?r:g):b;
double Cmin=(r<g?r:g)<b?(r<g?r:g):b;
double delta=Cmax-Cmin;
double H=0,S=0,V=0;
V=Cmax;
if(Cmax==0)
S=0;
else
S=delta/Cmax;
if(delta==0)
H=0;
else if(Cmax==r&&g>=b)
H=60*((g-b)/delta);
else if(Cmax==r&&g<b)
H=60*(((g-b)/delta)+6);
else if(Cmax==g)
H=60*((b-r)/delta+2);
else if(Cmax==b)
H=60*((r-g)/delta+4);
color[0]=H;
color[1]=S;
color[2]=V;
return color;
}
public WritableImage RGB2HSV(WritableImage img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
double r=0;
double g=0;
double b=0;
double[] c=RGB2HSV_pixel(r,g,b);
WritableImage hsv_img=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterHSV = hsv_img.getPixelWriter();
//ColorAdjust colorAdjust = new ColorAdjust();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
r=color.getRed();
g=color.getGreen();
b=color.getBlue();
c=RGB2HSV_pixel(r,g,b);
pixelWriterHSV.setColor(i, j, Color.rgb((int)(c[0]*255/360),(int)(c[1]*255),(int)(c[2]*255)));
}
return hsv_img;
}
public WritableImage RGB2RGB(Image img){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage gray_img=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriter = gray_img.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
Color color=pixelReader.getColor(i,j);
pixelWriter.setColor(i, j, color);
}
return gray_img;
}
/*
*mode=0:RGB
*mode=1:Gray
*mode=2:
*/
public void Img_View(WritableImage img,ImageView imageView){
// ImageView imageView=new ImageView();
imageView.setImage(img);//height<530,width<440
int[] img_size=Resize(img);
imageView.setFitHeight(img_size[1]);
imageView.setFitWidth(img_size[0]);
}
private float[][] Reverse(float[][] kernel){
int width=kernel[0].length;
int height=kernel.length;
for(int i=0;i<height/2;i++)
for(int j=0;j<width;j++){
float t=kernel[i][j];
kernel[i][j]=kernel[height-i-1][width-j-1];
kernel[height-i-1][width-j-1]=t;
}
for(int j=0;j<width/2;j++){
float t=kernel[height/2][j];
kernel[height/2][j]=kernel[height/2][width-j-1];
kernel[height/2][width-j-1]=t;
}
return kernel;
}
private Color Set_color(float r,float g,float b,float gray,int mode){
Color color=Color.color(0,0,0);
r=(r<=1?r:1);
r=(r>=0?r:0);
g=(g<=1?g:1);
g=(g>=0?g:0);
b=(b<=1?b:1);
b=(b>=0?b:0);
gray=(gray<=1?gray:1);
gray=(gray>=0?gray:0);
if(mode==0){
color=Color.color(r, g, b);
}
else if(mode==1)
color=Color.gray(gray);
return color;
}
public WritableImage convolution(WritableImage img,float[][] kernel,int mode){
kernel=Reverse(kernel);
int width=kernel[0].length;
int height=kernel.length;
float r=0,g=0,b=0,gray=0;
WritableImage img1=new WritableImage((int)img.getWidth(),(int)img.getHeight());
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriter = img1.getPixelWriter();
for(int i=0;i<(int)img.getWidth();i++)
for(int j=0;j<(int)img.getHeight();j++){
if(i<(int)(width/2)){//left
if(j<(int)(height/2)){//left-top
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else if(j>img.getHeight()-height/2-1){//left-buttom
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else{
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=0;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
}
else if(i>img.getWidth()-width/2-1){//right
if(j<(int)(height/2)){//right-top
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else if(j>img.getHeight()-height/2-1){//right-buttom
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else{
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=0;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
}
else{
if(j<(int)(height/2)){//top
for(int x=0;x<width;x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else if(j>img.getHeight()-height/2-1){
for(int x=0;x<width;x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i, j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
else{
for(int x=0;x<width;x++)
for(int y=0;y<height;y++){
if(mode==0){
r+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray+=kernel[x][y]*pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
}
pixelWriter.setColor(i,j,Set_color(r,g,b,gray,mode));
r=g=b=gray=0;
}
}
}
return img1;
}
private Color Get_median_color(double[] r,double[] g,double[] b,double[] gray,int index,int mode){
Color color=Color.rgb(0,0,0);
if(mode==0){
Arrays.sort(r);
Arrays.sort(g);
Arrays.sort(b);
color=Color.color(r[index], g[index], b[index]);
}
else if(mode==1){
Arrays.sort(gray);
color=Color.gray(gray[index]);
}
return color;
}
public WritableImage Median(WritableImage img,int size,int mode){
int width=size;
int height=size;
double[] r=new double[width*height],g=new double[width*height],b=new double[width*height],gray=new double[width*height];
int index=0;
WritableImage img1=new WritableImage((int)img.getWidth(),(int)img.getHeight());
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriter = img1.getPixelWriter();
for(int i=0;i<(int)img.getWidth();i++)
for(int j=0;j<(int)img.getHeight();j++){
if(i<(int)(width/2)){//left
if(j<(int)(height/2)){//left-top
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else if(j>img.getHeight()-height/2-1){//left-buttom
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else{
for(int x=(int)(width/2)-i;x<width;x++)
for(int y=0;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
}
else if(i>img.getWidth()-width/2-1){//right
if(j<(int)(height/2)){//right-top
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else if(j>img.getHeight()-height/2-1){//right-buttom
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else{
for(int x=0;x<(int)width/2-i+img.getWidth();x++)
for(int y=0;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
}
else{
if(j<(int)(height/2)){//top
for(int x=0;x<width;x++)
for(int y=(int)(height/2)-j;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else if(j>img.getHeight()-height/2-1){
for(int x=0;x<width;x++)
for(int y=0;y<(int)height/2-j+img.getHeight();y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
else{
for(int x=0;x<width;x++)
for(int y=0;y<height;y++){
if(mode==0){
r[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
g[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getGreen();
b[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getBlue();
}
else if(mode==1){
gray[index]=pixelReader.getColor(i-width/2+x,j-height/2+y).getRed();
}
index++;
}
pixelWriter.setColor(i,j,Get_median_color(r,g,b,gray,(int)width*height/2,mode));
r=new double[width*height];
g=new double[width*height];
b=new double[width*height];
gray=new double[width*height];
index=0;
}
}
}
return img1;
}
public WritableImage image_process(WritableImage img,int option){
WritableImage img1=new WritableImage((int)img.getWidth(),(int)img.getHeight());
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<(int)img.getWidth();i++)
for(int j=0;j<(int)img.getHeight();j++){
Color color=pixelReader.getColor(i,j);
switch(option){
case 0: color=color.invert();
pixelWriterGray.setColor(i, j, color);
break;
case 1: color=color.brighter();
pixelWriterGray.setColor(i, j, color);
break;
case 2: color=color.darker();
pixelWriterGray.setColor(i, j, color);
break;
case 3: color=color.saturate();
pixelWriterGray.setColor(i, j, color);
break;
case 4: color=color.desaturate();
pixelWriterGray.setColor(i, j, color);
break;
}
}
return img1;
}
public WritableImage Binary (WritableImage img,double threshold){
int width = (int) img.getWidth();
int height = (int) img.getHeight();
WritableImage img1=new WritableImage(width,height);
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriterGray = img1.getPixelWriter();
for(int i=0;i<width;i++)
for(int j=0;j<height;j++){
double color=pixelReader.getColor(i,j).getRed();
color=color>threshold?1:0;
pixelWriterGray.setColor(i, j, Color.gray(color));
}
return img1;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dip;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/**
*
* @author 41819
*/
public class Filter extends Application {
setPane addpane=new setPane();
@Override
public void start(Stage primaryStage) {
VBox vbox=addpane.addVBoxPane();
StackPane root = new StackPane();
//root.getChildren().add(btn);
root.getChildren().add(vbox);
Scene scene = new Scene(root, 830, 600);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){
@Override
public void handle(WindowEvent event) {
Platform.exit();
}
});
primaryStage.setResizable(false);
primaryStage.setTitle("Filter");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
<file_sep># Image-Convolution-Calculator
A Java image convolution calculator
## Feature
- [x] Image Color Channel Transform
- [x] Image Filter
- [x] Image Convolution
- [x] Common Operator
## Demo

| b76af1abf669d4a64bf0923e759ed372ce77acd4 | [
"Markdown",
"Java"
] | 3 | Java | Chaphlagical/Image-Convolution-Calculator | 0e2bea27d83d0574b4b9375294b54fd774b08773 | ecba475d40baade2d9a0ef3087bb29faa7bad723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.