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/main
|
<repo_name>tarundeepV/APICall<file_sep>/test.py
import requests
response = requests.get('http://127.0.0.1:5000/app/api/courses?id=1')
print(response.status_code)
print(response.json())
<file_sep>/API.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
courses = [
{
'courseID': 1,
'courseName': 'python programming'
},
{
'courseID': 2,
'courseName': 'data science'
},
{
'courseID': 3,
'courseName': 'web dev'
},
{
'courseID': 4,
'courseName': 'nlp'
},
]
@app.route('/')
def index():
return render_template('index.html')
@app.route('/app/api/courses/all')
def show():
return jsonify(courses)
@app.route('/app/api/courses', methods=['GET'])
def id():
if 'id' in request.args:
id = int(request.args['id'])
else:
return "unknown request"
result = []
for course in courses:
if course['courseID'] == id:
result.append(course)
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
|
b66caf8a507008a33ee8e20352f31c797668911e
|
[
"Python"
] | 2
|
Python
|
tarundeepV/APICall
|
a20be3c0a7f2052387d590562c4d8e15a54ba7db
|
89f4ef69f41c0f85d2fefbdfaf8586ca6819fb72
|
refs/heads/master
|
<file_sep>var str_age_min = "Um bei progettiamo.ch mitzumachen, muss man mindestens 18 Jahre alt sein."
var str_obl_filed = "Bitte überprüfe die Pflichtfelder"
var str_account_created = "Konto erfolgreich angelegt. Um das Konto zu aktivieren, wurde eine Bestätigungs-E-Mail an die angegebene E-Mail-Adresse gesendet"
var str_email_exist = "Die E-Mail-Adresse wurde bereits für ein anderes Konto verwendet"
var str_email_noexist = "E-Mail-Adresse nicht vorhanden"
var str_email_registered = "E-Mail-Adresse bereits registriert"
var str_email_unvalid = "Die angegebene Adresse ist ungültig."
var str_email_modified = "E-Mail-Adresse geändert."
var str_email_recovery = "E-Mail-Adresse zur Wiederherstellung erstellt."
var str_generic_error = "Ein Fehler ist aufgetreten, bitte versuche es erneut."
var str_login_error = "Um diese Aktion durchzuführen, musst du dich LOGIN"
var str_add_replica = "Schreibe hier deine Antwort"
var str_pubblica ="Veröffentlichen"
var str_reset_pass = "<PASSWORD>"
var str_new_pass_sent = "Eine E-Mail mit einem neuen Passwort wurde an deine Adresse geschickt."
var str_subscription_done = "Anmeldung gespeichert"
var str_verify_code = "Überprüfe den Verifizierungscode"
var str_logfb_not = "Facebook-Login nicht vollendet."
var str_logfb_noexist = "Dein Facebook-Konto ist nicht mit einem progettiamo.ch-Konto verbunden.<br/>Wir bitten dich, den Vorgang zur Kontoerstellung mit derselben E-Mail-Adresse durchzuführen, die du auf Facebook verwendest.<br/>Du wirst nun zum Formular für die Kontoerstellung umgeleitet."
var str_unsubscription_done = "Adresse aus dem Newsletter-Verteiler gelöscht"
var str_confirmemail_sent = "Es wurde eine Bestätigungsanfrage an deine E-Mail-Adresse gesendet"
var str_data_saving = "Deine Daten wurden gespeichert ...<br/>Die Seite wird nun neu geladen"
var str_pass_min ="Das neue Passwort muss folgende Anforderungen erfüllen: mindestens 6 Zeichen lang, eine Ziffer, einen Grossbuchstaben, keine Leerzeichen"
var str_pass_modified ="Das Passwort wurde geändert"
var str_pass_conf_err = "Bestätigung des neuen Passworts fehlgeschlagen"
var str_pass_err = "Das aktuelle Passwort ist falsch"
var str_par_del = "Absatz löschen?"
var str_no_elment ="Inhalt nicht verfügbar"
var str_promise_sending = "Zusage wird getätigt ..."
var str_promise_sent = "Deine Finanzierungszusage in der Höhe von Fr. <b>#</b> wurde registriert.<br/><br/>Du erhältst eine Bestätigung an deine E-Mail-Adresse.<br/><br/>Herzlichen Dank für deine Projektunterstützung."
var str_promise_conf = "Bestätigung Zusagen von"
var str_promise_pre = "Um deine Finanzierungszusage zu tätigen, musst du dich zuerst einloggen.<br/>Falls du dich noch nicht eingeloggt hast oder dein Konto noch erstellen musst, klicke auf Bestätigen, so wirst du mit der Internetseite verbunden und kehrst dann direkt wieder an diesen Punkt zurück."
var str_promise_conf_access = "Einloggen um zu bestätigen"
var str_annulla ="Abbrechen"
var str_conferma ="Bestätigen"
var str_del_news ="Update löschen?"
var str_file_upload_ext="Wähle eine Datei im png- oder jpg-Format"
var str_maxupload="Maximal erlaubte Dateigrösse"
var str_upload_ended="Upload beendet"
var str_date_fromat="tt.mm.jjjj"
var str_f_telefono="telefon"
var str_chiudi_gallery="Gallery schliessen"<file_sep><?php
ini_set("memory_limit","99M");
ini_set("max_execution_time","1200");
ini_set("max_input_time","1200");
ini_set("upload_max_filesize","12M");
ini_set("post_max_size","14M");
$checkrefer = $_SERVER['HTTP_REFERER'];
$pos = strrpos($checkrefer, "actions/project_");
if ($pos === false ) {
$pos = strrpos($checkrefer, "/profilo");
}
$pos=1;
if ($pos > 0 ) {
$tabdest = $_POST ['tabdest'];
$fileprefix = $_SERVER['HTTP_HOST'];
$fileprefix = str_replace("www","",$fileprefix);
$fileprefix = str_replace("preview","",$fileprefix);
$fileprefix = str_replace(":","",$fileprefix);
$fileprefix = str_replace("localhost","progettiamo.ch",$fileprefix);
$fileprefix = str_replace("lavb.ch","progettiamo.ch",$fileprefix);
$fileprefix = str_replace("test.","",$fileprefix);
$fileprefix .= date("mdYHis");
$percorso = "../../database/images/";
if ($tabdest == "fails" || $tabdest == "products" || $tabdest == "fieldF") {
$percorso = "../../database/files/";
}
if ($tabdest == "registeredusers" || $tabdest == "p_projects" || $tabdest == "p_pictures" || $tabdest == "p_description") {
$percorso = "../../database/projects/";
}
$totfiless="";
$totsizess="";
$totfile=0;
$x=0;
while(list($key,$value) = each($_FILES["files"]["name"]))
{
if(!empty($value)){
$filename = $value;
$origExt = substr($filename, strrpos($filename,"."));
$safe_filename=$fileprefix ."_".$x.$origExt;
$gSize=$_FILES["files"]["size"][$key];
copy($_FILES["files"]["tmp_name"][$key], $percorso . $safe_filename);
$totfile++;
$x++;
$totfiless .= "," . $safe_filename."#".$gSize."#".$filename ;
$totsizess .= "," . $gSize;
}
}
$totfiless = substr($totfiless, 1);
$totsizess = substr($totsizess, 1);
$totfiles = explode(",",$totfiless);
$totsizes = explode(",",$totsizes);
$filesrefs="";
if (strlen($totfiless)>0) {
$getResults="";
for ($x=0; $x<count($totfiles); $x++)
{
$getFile=explode('#',$totfiles[$x]);
$getResults.=',{"name":"'.$getFile[2].'","size":"'.$getFile[1].'","url":"'.$getFile[0].'","thumbnail_url":"","delete_url":"","delete_type":"DELETE"}';
}
$getResults = '['.substr($getResults, 1).']';
header("Content-Type: text/plain");
echo $getResults;
}
}
?><file_sep>var str_age_min = "Per partecipare a progettiamo.ch occorre aver compiuto 18 anni."
var str_obl_filed = "Verificare i campi obbligatori"
var str_account_created = "Account creato con successo, per attivare l\'account è stata inviata una mail di verifica all\'indirizzo email specificato"
var str_email_exist = "L\'indirizzo e-mail è già associato ad un altro account"
var str_email_noexist = "Indirizzo e-mail non presente"
var str_email_registered = "Indirizzo e-mail già registrato"
var str_email_unvalid = "L\'indirizzo specificato non è valido."
var str_email_modified = "Indirizzo e-mail modificato."
var str_email_recovery = "Indirizzo e-mail di recupero impostato."
var str_generic_error = "Si è verificato un errore, si prega di riprovare."
var str_login_error = "Per eseguire questa azione dovete eseguire il LOGIN"
var str_add_replica = "Scrivi qui la tua replica"
var str_pubblica ="pubblica"
var str_reset_pass = "<PASSWORD>"
var str_new_pass_sent = "Una mail con la nuova password è stata inviata al vostro indirizzo."
var str_subscription_done = "Iscrizione registrata"
var str_verify_code = "Verificare il codice di controllo"
var str_logfb_not = "Login Facebook non completato."
var str_logfb_noexist = "Il vostro account Facebook non è collegato con un account progettiamo.ch.<br/>Vi preghiamo di eseguire la procedura di creazione account con l\'indirizzo email che utilizzate su Facebook.<br/>Verrete ora ridirezionati al form per la creazione account."
var str_unsubscription_done = "Indirizzo rimosso dalla newsletter"
var str_confirmemail_sent = "È stata inviata una richiesta di conferma al suo indirizzo e-mail"
var str_data_saving = "i dati sono stati salvati ...<br/>La pagina verrà ora ricaricata"
var str_pass_min ="La nuova password deve avere una lunghezza minima di 6 caratteri, contenere un numero e una lettera maiuscola e non contenere spazi"
var str_pass_modified ="La password è stata modificata"
var str_pass_conf_err = "Conferma nuova password errata"
var str_pass_err = "Password attuale errata"
var str_par_del = "Eliminare il paragrafo?"
var str_no_elment ="Contenuto non disponibile"
var str_promise_sending = "Invio promessa in corso ..."
var str_promise_sent = "La sua promessa di finanziamento di Fr. <b>#</b> è stata registrata.<br/><br/>Riceverà una conferma al suo indirizzo e-mail.<br/><br/>Grazie per il vostro sostegno al progetto."
var str_promise_conf = "Confermare la promessa di"
var str_promise_pre = 'Per poter effettuare la tua promessa di finanziamento devi aver effettuato il login.<br/>Se non hai ancora effettuato il login o devi creare il tuo account, premendo su "Conferma" potrai agevolmente collegarti al sito e ritornare direttamente a questo punto'
var str_promise_conf_access = "Accedi per confermare"
var str_annulla ="Annulla"
var str_conferma ="Conferma"
var str_del_news ="Eliminare l\'aggiornamento?"
var str_file_upload_ext="Scegliere un file in formato png o jpg"
var str_maxupload="Dimensione massima consentita per il file"
var str_upload_ended="Upload terminato"
var str_date_fromat="gg.mm.aaaa"
var str_f_telefono="telefono"
var str_chiudi_gallery="chiudi gallery"<file_sep>var str_age_min = "To be a member of progettiamo.ch, you must be at least 18 years old"
var str_obl_filed = "Check mandatory fields"
var str_account_created = "Account is successfully created, to activate the account, a verification email has been sent to the specified email address"
var str_email_exist = "The email address is already associated with another account"
var str_email_noexist = "Email address is missing"
var str_email_registered = "Email address is already registered"
var str_email_unvalid = "The specified email address is invalid."
var str_email_modified = "Email address is changed."
var str_email_recovery = "Recovery email address is configured"
var str_generic_error = "If an error occurred, please try again."
var str_login_error = "To perform this action, you must LOGIN"
var str_add_replica = "Write your reply here"
var str_pubblica ="publish"
var str_reset_pass = "<PASSWORD>"
var str_new_pass_sent = "An email containing the new password has been sent to your address."
var str_subscription_done = "Inscription is registered!"
var str_verify_code = "Check the control code"
var str_logfb_not = "Login Facebook is not completed."
var str_logfb_noexist = "Your Facebook account is not linked to an account on progettiamo.ch.<br/>Please perform the account creation procedure with the email address you use on Facebook.<br/>You will now be redirected to a form for account creation."
var str_unsubscription_done = "Address is removed from the newsletter"
var str_confirmemail_sent = "A confirmation request has been sent to your email address"
var str_data_saving = "the data have been saved ...<br/>The page will now be reloaded "
var str_pass_min ="The new password must contain at least 6 characters without spaces, must include a number and an uppercase letter"
var str_pass_modified ="The password has been changed"
var str_pass_conf_err = "Confirmation: new password is incorrect"
var str_pass_err = "Current password is incorrect"
var str_par_del = "Delete the paragraph?"
var str_no_elment ="Content is not available"
var str_promise_sending = "Sending the promise is in progress..."
var str_promise_sent = "Your promise of funding Fr. <b>#</b> has been registered.<br/><br/>You will receive a confirmation at your email address<br/><br/>Thank you for supporting this project."
var str_promise_conf = "Confirm the promise of"
var str_promise_pre = "To be able to make your promise of funding, you must be logged in.<br/>If you have not yet logged in or you must create your account, by clicking on Confirm, you will be able to easily connect to the site and return directly to this point"
var str_promise_conf_access = "Login to confirm"
var str_annulla ="Cancel"
var str_conferma ="Confirm"
var str_del_news ="Delete the news?"
var str_file_upload_ext="Choose a png or jpg file"
var str_maxupload="Maximum allowable size for the file"
var str_upload_ended="Upload is finished"
var str_date_fromat="dd.mm.yyyy"
var str_f_telefono="phone"
var str_chiudi_gallery="close gallery"<file_sep>//MENU
var menu1 = "Config";
var menu2 = "Contents";
var menu3 = "Recycle Bin";
var menu4 = "Users";
var menu5 = "dsm Users";
var menu6 = "NetWorking";
var menu7 = "Languages";
var menu8 = "PreView";
var menu9 = "Exit";
var menu10 = "Attachments";
var menu11 = "Images";
var menu12 = "Contact Box";
var menu13 = "Admin Password";
//FRIENDS
var friends_txt_input_error = "Nome o TITOLO non Corretti";
var friends_txt_max_friend = "Hai raggiunto il numero massimo di Amici Fixed";
var friends_txt_attach_image = "Allegare un file di tipo Immagine";
var friends_txt_max_size = "La dimensione del file supera 1 MB";
var maxFriends = 2;
//CONTENTS
var txt1 = "Admin Contents";
var txt2 ="You are managing the";
var txt2a ="version";
var txt3="Published";
var txt3a="Not published";
var txt4="Manage different Version";
var txt5 ="Create Main Section";
var txt6="Edit Main Sections Order";
var txt6a="subPages order";
var txt6b="SET SECTION PRIORITY";
//USERS
var txt7="Registered Users";
var txt7a="Protected Pages";
var txt8="Users";
var txt9 = "Create a new user";
var txt9_1 = "Create a new Progettiamo Friend";
var txt10="Disable all Users";
var txt11="Enable all Users";
var txt12="E-Mail";
var txt13="Active";
var txt14="Prot. Pages";
var txt15="Networking Groups";
var txt16="File Sharing Group";
//BIN
var txt17="Empty Recycle Bin";
var txt17a="No files found in your recycle Bin";
var txt18="Re-Publish";
//DSM USER
var txt19="Create new DsM User";
var txt19a = "Admin dsm User";
var txt20 = "Create new";
var txt20a = "Active User";
var txt20b = "Firstname";
var txt20c = "Name";
var txt20d = "Password";
var txt20e = "Administrator dSm Users";
var txt20f = "Administrator Subscribed Users";
var txt20g = "Administrator Networking";
var txt20h = "Administrator Languages";
var txt20i = "Administrator Config";
var txt20l = "Administrator Contents";
var txt20m = "Allow admin contents";
var txt20n = "Restrict to sections";
var txt20o = "No restrictions";
var txt20p = "Restrict to language";
//NETWORKING
var txt21 = "Themes";
var txt22 = "Add a new Theme";
var txt22a = "No theme was found";
var txt22b = "opened by ";
var txt23 = "on";
var txt24 = "Add a user to this group";
var txt25 = "select";
var txt26 = "Write permission";
var txt27 = "insert";
var txt28 = "Subscribed Users";
var txt29 = "Last Login";
var txt30 = "Edit Profile";
var txt31 = "Delete user";
var txt32 = "Uploaded files";
var txt33 = "Add new file";
var txt34 = "Theme";
var txt35 = "Date";
var txt36 = "Title";
var txt37 = "Description";
var txt38 = "User";
var txt39 = "Change";
var txt40 = "Delete";
var txt40a = "Insert";
var txt40b = "Insert";
var txt41 = "Download";
var txt42 = "Activate Languages";
var txt43 = "Language";
var txt44 = "Active";
var txt45 = "Publish";
var txt46 = "Main Language";
var back1 = "BACK";
var save1 = "SAVE";
var unde1 = "Not defined";
var pass1 = "<PASSWORD>";
var fname1 = "Firstname";
var name1 = "Name";
//EDIT PAGE
var txt47="Page Title";
var txt47a="Language";
var txt48="Created on";
var txt48a="Attributes";
var txt49="This page is";
var txt50="Hide title";
var txt51="News Section";
var txt51a="Protected page";
var txt51b="Networking Login";
var txt51c="Click on EDIT TEXT icon to add Text";
var txt51d="Hide in menu";
var txt51e="None";
var txt52="Edit Text";
var txt52a="Main section image";
var txt53="Define publishing position";
var txt54="Click on the "Over page"-Name to delete the reference";
var txt55="Set as subpage of";
var txt56="set";
var txt57="Attachment";
var txt58="New file";
var txt59="Attached Documents";
//ADD ATTACHMENT
var txt60="Title / Name";
var txt61="Select Document";
var txt62="CANCEL";
var txt63="UPLOAD";
//DELETING
var txt64="Are you sure to delete this page?";
var txt64a="Are you sure to delete this image?";
var txt64b="Are you sure to delete this file?";
var txt64c="Are you sure to move this object by this folder?";
var txt64d="DELETE REFERENCE TO SECTION";
var txt65="CONFIRM";
var txt65a="DELETE";
var txt65b="EDIT";
var txt66="YES";
var txt67="NO";
//ADD INTERNAL LINK
var txt68="Link to a page";
var txt69="Link to a file";
<file_sep>var str_age_min = "Pour faire partie de progettiamo.ch, vous devez avoir au moins 18 ans."
var str_obl_filed = "Vérifiez les champs obligatoires"
var str_account_created = "Compte est créé avec succès, pour activer le compte, un e-mail de vérification a été envoyé à l'adresse e-mail indiquée"
var str_email_exist = "L'adresse e-mail est déjà associée à un autre compte"
var str_email_noexist = "Adresse e-mail introuvable"
var str_email_registered = "Adresse e-mail est déjà enregistrée"
var str_email_unvalid = "L'adresse indiquée est invalide."
var str_email_modified = "Adresse e-mail modifiée."
var str_email_recovery = "Adresse e-mail de récupération est configurée."
var str_generic_error = "Si une erreur s'est produite , veuillez réessayer."
var str_login_error = "Pour effectuer cette action, vous devez établir une LOGIN"
var str_add_replica = "Écrivez votre réponse ici"
var str_pubblica ="Publiez"
var str_reset_pass = "<PASSWORD> de passe"
var str_new_pass_sent = "Un email avec le nouveau mot de passe a été envoyé à votre adresse."
var str_subscription_done = "Inscription enregistrée"
var str_verify_code = "Vérifiez le code de contrôle"
var str_logfb_not = "Login via Facebook n’est pas terminée."
var str_logfb_noexist = "Votre compte Facebook n’est pas lié à un compte sur progettiamo.ch. <br/> Veuillez effectuer la procédure de création de compte avec l'adresse e-mail que vous utilisez sur Facebook. <br/> Vous serez maintenant redirigé vers le formulaire de création de compte."
var str_unsubscription_done = "Adresse retirée de la newsletter"
var str_confirmemail_sent = "Une demande de confirmation a été envoyée à votre adresse e-mail"
var str_data_saving = "iLes données ont été sauvegardées…<br/> La page sera maintenant rechargée."
var str_pass_min ="Le nouveau mot de passe doit contenir au moins 6 caractères sans espaces, doit contenir un chiffre et une lettre majuscule"
var str_pass_modified ="Le mot de passe a été modifié"
var str_pass_conf_err = "Confirmation: nouveau mot de passe incorrect"
var str_pass_err = "Mot de passe actuel incorrect"
var str_par_del = "Supprimer le paragraphe?"
var str_no_elment ="Contenu n’est pas disponible"
var str_promise_sending = "Envoi de la promesse en cours ..."
var str_promise_sent = "Votre promesse de financement de Fr. <b>#</b> a été enregistrée. <br/><br/> Vous recevrez une confirmation à votre adresse e-mail. <br/><br/> Merci d’avoir soutenu le projet."
var str_promise_conf = "Confirmez la promesse de"
var str_promise_pre = "Pour pouvoir faire votre promesse de financement, vous devez avoir établi une connexion. <br/> Si vous n’avez pas encore établi une connexion ou vous devez créer votre compte, en cliquant sur Confirmez, vous pourrez aisément vous connecter au site et retourner directement à ce point"
var str_promise_conf_access = "Connectez pour confirmer"
var str_annulla ="Annullez"
var str_conferma ="Confirmation"
var str_del_news ="Supprimer la mise à jour?"
var str_file_upload_ext="Choisissez un fichier png ou jpg"
var str_maxupload="Taille de fichier maximale autorisée"
var str_upload_ended="Chargement terminé"
var str_date_fromat="jj.mm.aaaa"
var str_f_telefono="téléphone"
var str_chiudi_gallery="fermez la gallerie"<file_sep>
makeComment = function(refmsg,refproject,mode) {
gtval=$('textarea.addComment').val()
if ($('textarea.addComment').hasClass('changed') && gtval.length>3) {
gtval=gtval.replace(/(?:\r\n|\r|\n)/g, '<br />');
$.ajax({
type: "POST",
url: "/project/addComments.asp?txtval="+gtval+"&load="+refmsg+"&refproject="+refproject+"&mode="+mode+"&ssid=" + Math.floor((Math.random()*111111)+1),
dataType: 'html',
timeout: 6000,
error : function(msg) {
$('<p style="color:#ff0000;clear:both">'+str_generic_error+'</p>').appendTo($('div.comments div.blog:last'))
},
success : function(msg) {
if (msg=="NOTLOGGED")
{
$('<p style="color:#ff0000;clear:both">'+str_login_error+'</p>').appendTo($('div.comments div.blog:last'))
} else {
viewComments(refmsg,refproject)
}
}});
}
}
makeReplica = function(replicaObj,refmsg,refproject,mode) {
$('div.addreplica').remove()
$('input.replica').parent().css('height','25px')
$('input.replica').parent().css('margin-bottom','30px')
$('input.replica').css('display','inline')
$('<div class="addreplica" style="float:right; width:90%; margin-top:-25px;"><textarea class="addComment" style="height:70px" onfocus="if (!$(this).hasClass(\'changed\')) {$(this).val(\'\');$(this).addClass(\'changed\')}">'+str_add_replica+'</textarea><input type="button" class="bt" onclick="makeComment('+refmsg+','+refproject+','+mode+')" value="'+str_pubblica+'" style="float:right; margin-top:-4px; margin-right:-1px;"/></div>').appendTo(replicaObj.parent())
replicaObj.css('display','none')
replicaObj.parent().css('height','65px')
replicaObj.parent().css('margin-bottom','65px')
}
viewComments = function(refmsg,refproject) {
$('body.progetti div.pDesc').eq(5).removeClass("active")
$('body.progetti div.comments').remove()
$('<div class="pDesc comments"></div>').appendTo($('div.pCenter'))
$.ajax({
type: "GET",
url: "/project/getComments.asp?load="+refmsg+"&refproject="+refproject+"&ssid=" + Math.floor((Math.random()*111111)+1),
timeout: 6000,
error : function(msg) {
$('body.progetti div.comments').html('<p>'+str_generic_error+'</p>')
$('body.progetti div.comments').css('display','inline')
},
success : function(msg) {
msg = msg.replace(/</g, '<');
msg = msg.replace(/>/g, '>');
msg = msg.replace(/&/g, '&');
$('body.progetti div.comments').html(msg)
$('body.progetti div.comments').css('display','inline')
if ($('div.blogcontainer').size()>0)
{
minH=($('div.blogcontainer').innerHeight()+$('div.blogcontainer').position().top+$('div.comments').position().top+330)
if ($('body.progetti div.pText').height()<minH) $('body.progetti div.pText').css('min-height',minH+"px")
}
setTimeout(function() { $('html,body').animate({scrollTop: $('body.progetti div.comments').offset().top-220},500)},200)
}});
}
getEdit = function(dest,refProject,lobj) {
$('div.pText').css('height','100px')
$('div.pContainer').css('height','100px')
$("div.myprojectsFrame iframe").css("opacity","0.0")
$("html, body").animate({scrollTop: '160px'},200)
$("body.progetti div.pButton").not(lobj).css("color","#fff")
$("body.progetti div.pButton").not(lobj).each(function() {
$(this).find('img').attr('src',$(this).find('img').attr("longdesc"))
})
$("body.progetti div.pButton").removeClass("active, actfin")
$("body.progetti div.edit").not('.fin').addClass("a"+$('#maincat').html())
lobj.not('.fin').css("color",$('#maincolor').html())
if (lobj.hasClass("fin")) {
lobj.addClass("actfin")
lobj.css("color","#292f3a")
}
lobj.removeClass("a"+$('#maincat').html())
lobj.addClass("active")
altImg=lobj.find('img').attr('rel')
lobj.find('img').attr('src',altImg)
$("div.myprojectsFrame iframe").attr("src","/project/project_make_"+dest+".asp?load="+refProject)
}
init_projectPage = function() {
$('body.progetti a.gImg').find('img').eq(0).hover(function() {$(this).attr('src','/images/thumb_picture.png')}, function() {$(this).attr('src','/images/vuoto.gif')})
$('body.progetti div.pButton').not('.edit').click(function() {
actObj=$(this)
var index = $("body.progetti div.pButton").index(this);
$('body.progetti div.comments').remove()
$('div.fancyLavb-container').remove();
$('.btclgl').remove();
$('div.fancyLavb-dots').remove()
$("body.progetti div.pButton").not(actObj).css("color","#fff")
$("body.progetti div.pButton").not(actObj).each(function() {
$(this).find('img').attr('src',$(this).find('img').attr("longdesc"))
})
$("body.progetti div.pButton").removeClass("active")
$("body.progetti div.pButton").removeClass("actfin")
$("body.progetti div.pButton").not('.fin').addClass("a"+$('#maincat').html())
actObj.not('.fin').css("color",$('#maincolor').html())
if (actObj.hasClass("fin")) {
actObj.addClass("actfin")
actObj.css("color","#292f3a")
}
actObj.removeClass("a"+$('#maincat').html())
actObj.addClass("active")
$('body.progetti div.pLeft div.anchor').remove()
addancres=$('body.progetti div.pDesc').eq(index).find('div.anchor').html()
$('<div class="anchor">'+addancres+'</div>').appendTo($('body.progetti div.pLeft'))
altImg=actObj.find('img').attr('rel')
actObj.find('img').attr('src',altImg)
$('body.progetti div.pDesc').removeClass("active")
divTarget=$('body.progetti div.pDesc').eq(index)
divTarget.addClass("active")
divTarget.find('div.mm').stop().fadeIn()
if (divTarget.html().indexOf("#$login$#")!=-1)
{
gtDest=$('meta[property="og:url"]').attr('content')
if (gtDest.indexOf("/donate/")==-1) $('meta[property="og:url"]').attr('content',gtDest+"/donate/")
getLogin()
return;
}
resizeProject(divTarget)
});
$('body.progetti div.pDesc div.mm').each(function() {
$(this).find('a.gImg').eq(0).css('display','inline')
})
for (xv=0; xv<$('body.progetti div.pDesc img.vImg').size(); xv++)
{
videoImg=$('body.progetti div.pDesc img.vImg').eq(xv)
videoSrc=videoImg.attr("rel");
getVideoImg(videoImg,videoSrc)
}
if ($('body').hasClass('progetti')) {
doSharing();
eval($('a.firstAction').attr('href'))
}
$('a.imgG').fancybox({
openEffect : 'fade',
closeEffect : 'none',
nextEffect : 'fade',
prevEffect : 'none',
autoDimensions: false,
autoSize: false,
maxHeight: '75%',
maxWidth: '80%',
type: 'image',
autoResize: true,
padding:0,
beforeLoad : function(){
var url= $(this.element).attr("data-href");
this.href = url
},
helpers : {
overlay : {
css : {
'background' : 'rgba(255, 255, 255, 0.8)'
}}
}});
}
resizeProject = function(actobj) {
hmin1=actobj.innerHeight()+230
hmin2=$('body.progetti div.pRight').innerHeight()+200
hmin3=(actobj.find('div.mm').size()*390/2)+170
hMin=Math.max(hmin1,hmin2,hmin3)
$('body.progetti div.pText').css('min-height',hMin+'px')
}
var xv=1
getVideoImg = function (videoImg, videoSrc) {
videoSrc = videoImg.attr("rel");
console.log(videoSrc);
if (videoSrc.length > 0) {
videoImg.hoverIntent(function () { $(this).attr('src', '/images/thumb_video.png') }, function () { $(this).attr('src', '/images/vuoto.gif') });
videoImg.click(function () { videoOpen($(this)) })
videoId = videoSrc;
if (videoId.indexOf('/') != -1) videoId = videoId.substring(videoSrc.lastIndexOf("/") + 1)
if (videoId.indexOf('?') != -1) videoId = videoId.substring(0, videoId.indexOf("?"))
if (videoId.indexOf('&') != -1) videoId = videoId.substring(0, videoId.indexOf("&"))
console.log(videoId);
videoImg.attr("id", videoId);
if (videoSrc.indexOf('vimeo.com') != -1) {
//loadVimeoThumb(videoId,xv*500)
loadVimeoThumb(videoImg, xv * 500)
}
if (videoSrc.indexOf('youtu') != -1) {
videoImg.css('background-image', 'url(http://img.youtube.com/vi/' + videoId + '/hqdefault.jpg)');
}
}
}
setDonate = function() {
$('#formDonate').submit(function(e) {
e.preventDefault();
gtVal=parseFloat($('#donation_value').val())
gtProject=$('#refProject').val()
gtProjectName=$('#refProjectName').val()
minVal=parseFloat($('#minval').val())
if (gtVal>0 && gtVal>=minVal)
{
$('.fDonate').remove()
$('.fDImg').remove()
$('.donationMaker').html(str_promise_sending);
gtUrl="/setDonation.asp?load=" + gtProject + "&val=" + gtVal + "&projectname="+gtProjectName+"&ssid=" + Math.floor((Math.random()*111111)+1)
$.ajax({
url: gtUrl,
error: function(msg){
$('.donationMaker').html('<p>'+str_generic_error+'</p>')
},
success: function(data){
if (data=='DONE')
{
msgadd = str_promise_sent.replace('#',gtVal)
$('.donationMaker').html('<p>' + msgadd + '</p>')
setTimeout(function() { document.location=""+$('meta[property="og:url"]').attr('content'); },4000)
}
if (data=='LOGIN') {
gtDest=$('meta[property="og:url"]').attr('content')
if (gtDest.indexOf("/donate/")==-1) $('meta[property="og:url"]').attr('content',gtDest+"/donate/")
getLogin()
}
}
});
}
})
}
confirmDonation = function (userlogged) {
vVal = $('p.mmake input.sDonate').val();
$('input.fDonate').attr('onfocus', 'this.blur()')
$('.donationMaker p.cmake').remove();
$('.donationMaker p.premake').css('display', 'inline-block');
$('.donationMaker input.sDonate').css('display', 'none');
str_promise_tmp = '';
str_button_confirm = '<input type="button" class="sDonate" style="width:154px;display:inline-block;" value="' + str_annulla +
'" onclick="noDonation()"/> <input type="button" class="sDonate" style="display:inline-block; width:154px" value="' + str_conferma +
'" onclick="$(\'#formDonate\').submit()"/>';
if (userlogged == 0) {
str_promise_tmp = str_promise_pre;
gtDest = $('meta[property="og:url"]').attr('content')
if (gtDest.indexOf("/donate/") == -1) $('meta[property="og:url"]').attr('content', gtDest + "/donate/")
str_button_confirm = '<a class="btn" style=" background: url(/images/btn_big_clear.png) left top no-repeat;clear:both;width:290px" href="#" onclick="$(\'#formDonate\').submit()">' + str_promise_conf_access + '</a>';
}
$('<p class="cmake cmakef">' + str_promise_conf + ' <b>' + $('input.fDonate').val() + '</b> Fr.?</p><p class="cmake" style="clear:both;font-size:12px; margin:10px 0px">' +
str_promise_tmp + '</p><p class="cmake cmakef"><br/>' + str_button_confirm + '<br/><br/></p>').appendTo($('.donationMaker'))
resizeProject($('div.pDesc').eq(4))
}
noDonation=function() {
$('.donationMaker p.cmake').remove()
$('.donationMaker p.mmake').css('display','inline-block')
$('input.fDonate').attr('onfocus','void(0)')
$('body.progetti img.fDImg').removeClass('fDImgActive')
$('.donationMaker').css('display','inline-block')
$('.donationMaker p.premake').css('display','none')
resizeProject($('div.pDesc').eq(4))
}
setDonation = function (inp, mode, userlogged) {
$('body.progetti input.fDonate').removeClass('fActive')
$('body.progetti img.fDImg').removeClass('fDImgActive')
inVal = inp.val();
regexp1 = /[^0-9\.\'\-\,]+/g
if (regexp1.test(inVal)) {
inVal = inVal.replace(regexp1, '');
inVal = inVal.replace(/,/g, '.');
inp.val(inVal)
}
inVal = inVal.replace(/,/g, '.');
inVal = inVal.replace(/\'/g, '');
inVal = inVal.replace(/.-/g, '.00');
inVal = parseFloat(inVal)
$('#donation_value').val(inVal)
$('p.mmake input.sDonate').val($('input.sDonate').attr('rel') + " Fr. " + inVal)
$('body.progetti img.fDImg').addClass('fDImgActive')
$('.donationMaker').fadeIn(300, function () {
confirmDonation(userlogged)
})
resizeProject($('div.pDesc').eq(4))
}
filterMM = function(mode,obj) {
$('div.fancyLavb-container').remove();
$('.btclgl').remove(); $('div.fancyLavb-dots').remove()
$('div.pDesc div.mm').not('.'+mode).css('display','none')
$('div.pDesc div.'+mode).stop().fadeIn(200)
$('body.progetti div.pLeft div.anchor a').removeClass('active')
$(obj).addClass('active')
}
toAnchor = function(ancre) {
$('html, body').animate({scrollTop: $('a[name="'+ancre+'"]').offset().top-50},800)
goToAnchor=$('a[name="'+ancre+'"]').position().top+45;
maxTop=$('body.progetti div.pCenter').innerHeight()-190-$('body.progetti div.pLeft div.anchor a').last().position().top
if (goToAnchor>maxTop) goToAnchor=maxTop;
$('body.progetti div.pLeft div.anchor').animate({marginTop: goToAnchor },600)
$('body.progetti div.pLeft div.anchor a').removeClass('active')
$('body.progetti div.pLeft #'+ancre).addClass('active')
}
addtoFavorites = function (pref) {
var data1 = {
project: pref
};
$.ajax({
type: "POST",
url: "/actions/favorite.asp",
data: data1,
timeout: 6000,
success : function(msg) {
document.location=""+$('meta[property="og:url"]').attr('content')
}});
}
doSharing = function () {
if ($('#facebook').size() > 0) {
shareUrl = $('meta[property="og:url"]').attr('content')
$('#eml').click(function () {
document.location = 'mailto:<EMAIL>?subject=Progettiamo.ch&body=' + shareUrl
})
$('#googleplus').click(function () {
gUrl = 'https://plus.google.com/share?url=' + encodeURIComponent(shareUrl)
window.open(gUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
})
$('#pinterest').click(function () {
shareImage = $('meta[property="og:image"]').attr('content')
shareDesc = $('meta[property="og:title"]').attr('content')
gUrl = 'http://www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(shareUrl) + "&media=" + encodeURIComponent(shareImage) + "&description=" + encodeURIComponent(shareDesc)
window.open(gUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
})
$('#facebook').sharrre({
share: {
facebook: true
},
template: '<a class="box" href="#"><div class="share"><span></span></div></a>',
url: shareUrl,
action:'like',
enableHover: false,
enableTracking: true,
click: function (api, options) {
api.simulateClick();
api.openPopup('facebook');
//alert('popup open');
}
});
$('#twitter').sharrre({
share: {
twitter: true
},
template: '<a class="box" href="#"><div class="share"><span></span></div></a>',
url: shareUrl,
enableHover: false,
enableTracking: true,
click: function (api, options) {
api.simulateClick();
api.openPopup('twitter');
}
});
}
}
$.fn.fancyLavb = function () {
that = $(this)
that.click(function(e) {
e.preventDefault();
mainPar=$(this).parent();
var actThumbs=""
mainPar.find(that).each(function(){
gthref=$(this).attr("href")
gttitle=$(this).attr("longdesc")
actThumbs+="|"+gthref+'$$'+gttitle
})
mainPar.parent().find('div').css('display','none')
$('.btclgl').remove()
$('div.fancyLavb-dots').remove()
var actPageThumbs=0;
$('<div class="fancyLavb-container"></div>').prependTo(mainPar.parent())
actThumbs=actThumbs.split('|')
$('<div class="fancyLavb-thumbs"><div></div></div>').prependTo($('div.fancyLavb-container'))
if (actThumbs.length<3) $('div.fancyLavb-thumbs').css('display','none')
if (actThumbs.length>5)
$('<div class="fancyLavb-dots"></div>').appendTo(mainPar.parent())
{
pageThumbs=Math.ceil((actThumbs.length-1)/4)
for (y=1; y<=pageThumbs; y++)
{
$('<a><img/></a>').appendTo($('div.fancyLavb-dots'));
}
$('div.fancyLavb-dots a img').attr('src','/images/vuoto.gif')
$('div.fancyLavb-dots a').click(function() {
gtaInd=$(this).index('div.fancyLavb-dots a')
$('div.fancyLavb-dots a').removeClass('active')
$(this).addClass('active')
actPageThumbs=gtaInd
sizeleft=$('div.fancyLavb-thumbs').width()
newleft=sizeleft*gtaInd*-1
$('div.fancyLavb-thumbs > div').animate({left: newleft},800)
})
$('div.fancyLavb-dots a').eq(0).addClass('active')
}
$('<input type="button" class="bt btclgl" value="'+str_chiudi_gallery+'" style="margin:40px 0px 0px 42.5%" onclick="$(\'div.pButton\').eq(2).trigger(\'click\'); $(\'.btclgl\').remove(); $(\'div.fancyLavb-dots\').remove()"/>').appendTo(mainPar.parent())
for (x=1; x<actThumbs.length; x++)
{
gtT=actThumbs[x].split('$$')
$('<img src="/images/vuoto.gif" style="background-image:url('+gtT[0]+')" data-href="'+gtT[0]+'" longdesc="'+gtT[1]+'"/>').appendTo($('div.fancyLavb-thumbs > div'))
}
var actTumb=0; thumbSize=$('div.fancyLavb-thumbs > div img').size()
if (thumbSize>1) {
$('<div class="arrow back" rel="-1"></div>').prependTo($('div.fancyLavb-container'))
$('<div class="arrow next" rel="+1"></div>').prependTo($('div.fancyLavb-container'))
}
if (actThumbs.length>4 && $('div.fancyLavb-thumbs > div').innerWidth()>$('div.fancyLavb-thumbs').width()) {
$('<div class="arrow1 back1" rel="-"></div>').appendTo($('div.fancyLavb-container'))
$('<div class="arrow1 next1" rel="+"></div>').appendTo($('div.fancyLavb-container'))
}
$('div.fancyLavb-container > div.arrow1').click(function() {
gtmode=$(this).attr('rel')
newPageThumbs=eval(actPageThumbs+gtmode+"1")
if (newPageThumbs<0 || newPageThumbs>=pageThumbs) return
$('div.fancyLavb-dots a').eq(newPageThumbs).trigger('click')
})
$('div.fancyLavb-container > div.arrow').click(function() {
gtmode=$(this).attr('rel')
newimg=eval(actTumb+gtmode);
if (newimg<0) newimg=thumbSize-1;
if (newimg==thumbSize) newimg=0;
newimgPage=Math.ceil(newimg/4+0.1)-1
$('div.fancyLavb-dots a').eq(newimgPage).trigger('click')
$('div.fancyLavb-thumbs > div img').eq(newimg).trigger('click')
})
$('div.fancyLavb-thumbs > div img').hover(function() {$(this).attr('src','/images/over_thumb.png')}, function() {$(this).attr('src','/images/vuoto.gif')})
$('div.fancyLavb-thumbs > div img').click(function() {
thumb=$(this);
gtIndex=thumb.index('div.fancyLavb-thumbs > div img')
actTumb=gtIndex;
newload=$('<div class="fancyLavb-image"></div>').prependTo($('div.fancyLavb-container'))
tTitle=thumb.attr('longdesc')
if (tTitle.length>0) tTitle="<p>"+tTitle+"</p>"
$('<div class="fancyLavb-title"><div class="fancyLavb-titleBg"></div><div class="fancyLavb-titleTx"><span>'+(gtIndex+1) + "/"+ thumbSize+'</span>'+ tTitle+'</div></div>').appendTo($('div.fancyLavb-image'))
$('<img/>').load(function() {
$('div.fancyLavb-image').not(newload).fadeOut()
newload.css('background-image','url('+this.src+')')
newload.fadeIn()
})
.attr('src',thumb.attr('data-href'))
})
$('html, body').animate({scrollTop: $('div.fancyLavb-container').offset().top-200},400)
$('div.fancyLavb-thumbs > div img').eq(0).trigger('click')
})
}
delNews = function(bref) {
gtref=$('#edRef').val()
if (confirm(str_del_news)) {
var data1 = {
load: gtref,
refb: bref
};
$.ajax({
type: "POST",
url: "/actions/del_news.asp",
data: data1,
timeout: 6000,
success : function() {
document.location=""+document.location.href;
}});
}
}
editNews = function(gload) {
gtref=$('#edRef').val()
viewFormAdd(gload)
}
viewFormAdd=function(gload) {
$('input.bt').parent().fadeOut(100);
gtref=$('#edRef').val()
if (gload==0) gload="";
$('div.myprojectsFrame iframe').attr('src','/actions/project_update.asp?load='+gtref+'&edref='+gload+'&ssid=' + Math.floor((Math.random()*111111)+1));
$('.myprojectsFrame').fadeIn(100, function() {
resizeProject($('div.pDesc').eq(5))
$("html, body").animate({scrollTop: $('.myprojectsFrame').offset().top -100 },200)
});
}
closeFormAdd=function() {
$('input.bt').parent().fadeIn(100);
$('.myprojectsFrame').fadeOut(150, function() {
resizeProject($('div.pDesc').eq(5))
});
}<file_sep>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI;
using System.Data;
using System.Data.OleDb;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using main;
using System.Text;
public partial class ADMIN_ProjectPromotersExcelDownload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String load = Request["load"];
String mode = Request["mode"];
string connectionString = "";
string dbpath = Server.MapPath("/");
//dbpath=Mid(dbpath,1,Instrrev(dbpath,"\")-1)
//checklast=Mid(dbpath,Instrrev(dbpath,"\")+1)
//If checklast="admin" Then
//dbpath=Mid(dbpath,1,Instrrev(dbpath,"\")-1)
//checklast=Mid(dbpath,Instrrev(dbpath,"\")+1)
//End if
//If checklast="web" Or checklast="public_html" Or checklast="admin" Then dbpath=Mid(dbpath,1,Instrrev(dbpath,"\")-1)
//'If checklast="web" Or checklast="public_html" Or checklast="progettiamo" Or checklast="admin" Then dbpath=Mid(dbpath,1,Instrrev(dbpath,"\")-1)
dbpath = dbpath.Substring(0, dbpath.LastIndexOf("\\"));
dbpath = dbpath.Substring(0, dbpath.LastIndexOf("\\"));
dbpath = dbpath + "\\database\\";
string dbname = "dsm_progettiamo.v1.mdb";
main.rc4encrypt rc4 = new rc4encrypt();
rc4.Password = "<PASSWORD>";
dbpath = dbpath + dbname;
DataTable dt = null;
String SQL = "SELECT * FROM p_projects WHERE ID=" + load;
string filename = "";
int adm_area = Session["adm_area"] == null ? 0 : (int)Session["adm_area"];
if (adm_area > 0)
{
SQL = "SELECT * FROM p_projects WHERE ID=" + load + " AND CO_p_area=" + Session["adm_area"];
}
try
{
connectionString = @"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + dbpath + "';";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (OleDbCommand command = new OleDbCommand(SQL, con))
using (OleDbDataReader reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Columns.Add("Ente/Società", typeof(String));
dt.Columns.Add("Cognome", typeof(String));
dt.Columns.Add("Nome", typeof(String));
dt.Columns.Add("Fr.", typeof(String));
dt.Columns.Add("Email", typeof(String));
dt.Columns.Add("Tel.", typeof(String));
dt.Columns.Add("Cap", typeof(String));
dt.Columns.Add("Luogo", typeof(String));
dt.Columns.Add("Indirizzo", typeof(String));
dt.Columns.Add("Data", typeof(String));
while (reader.Read())
{
filename = reader["TA_nome"].ToString();
SQL = "SELECT DISTINCT ID FROM (SELECT ID FROM QU_projects_promises WHERE CO_p_projects=" + load + " ORDER BY DT_data)";
using (OleDbCommand com2 = new OleDbCommand(SQL, con))
{
using (OleDbDataReader rec1 = com2.ExecuteReader())
{
string refu = "";
while (rec1.Read())
{
refu = rec1["ID"].ToString();
SQL = "SELECT SUM(IN_promessa) as promesso,MAX(DT_data) as lastdata FROM QU_projects_promises WHERE CO_p_projects=" + load + " AND ID=" + refu;
using (OleDbCommand com3 = new OleDbCommand(SQL, con))
{
using (OleDbDataReader rec2 = com3.ExecuteReader())
{
while (rec2.Read())
{
string promesso = rec2["promesso"].ToString();
string lastdata = rec2["lastdata"].ToString();
SQL = "SELECT * FROM registeredusers WHERE ID=" + refu;
using (OleDbCommand com4 = new OleDbCommand(SQL, con))
using (OleDbDataReader rec3 = com4.ExecuteReader())
{
while (rec3.Read())
{
string email = rec3["TA_email"].ToString();
//EnDecrypt.CryptedText = email;
//EnDecrypt.Decrypt();
//email = System.Web.HttpUtility.UrlDecode(email);
//rc4.URLDecode(email);
//throw new Exception(rc4.URLDecode(email));
if (!String.IsNullOrEmpty(email)){
rc4.PlainText = email;
email = rc4.EnDeCrypt(2);
}
string telefono = rec3["TA_telefono"].ToString();
//EnDecrypt.CryptedText = telefono;
//EnDecrypt.Decrypt();
if (!String.IsNullOrEmpty(telefono))
{
rc4.PlainText = telefono;
telefono = rc4.EnDeCrypt(2);
}
dt.Rows.Add(rec3["TA_ente"], DecodeFromUtf8((String)rec3["TA_cognome"]), DecodeFromUtf8((String)rec3["TA_nome"]), promesso, email, telefono, rec3["TA_cap"], rec3["TA_citta"], rec3["TA_indirizzo"], lastdata);
}
}
}
}
}
}
}
}
}
}
}
}
catch (Exception ex)
{
Response.Write(dbpath + "<br/>" + ex.Message + "<br/>" + ex.StackTrace);
Response.End();
return;
}
downloadExcel(filename, dt, mode);
}
public static string HexStrToStr(string hexStr)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexStr.Length; i += 2)
{
int n = Convert.ToInt32(hexStr.Substring(i, 2), 16);
sb.Append(Convert.ToChar(n));
}
return sb.ToString();
}
private static string ConvertFromUTF8(string s)
{
if (String.IsNullOrEmpty(s)) return s;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(s);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
return iso.GetString(isoBytes);
}
private static string DecodeFromUtf8(string s)
{
string utf8_String = s;
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
return Encoding.UTF8.GetString(bytes);
}
public void downloadExcel(String filename, DataTable dt, String extension)
{
filename = HttpUtility.UrlEncode(filename);
IWorkbook workbook;
ICellStyle headerCellStyle;
if (extension == "xlsx")
{
workbook = new XSSFWorkbook();
}
else if (extension == "xls")
{
workbook = new HSSFWorkbook();
}
else
{
throw new Exception("This format is not supported");
}
ISheet sheet1 = workbook.CreateSheet("Sostenitori");
//make a header row
IRow row1 = sheet1.CreateRow(0);
IFont boldFont = (IFont)workbook.CreateFont();
boldFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
headerCellStyle = workbook.CreateCellStyle();
headerCellStyle.SetFont(boldFont);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.CellStyle = headerCellStyle;
String columnName = dt.Columns[j].ToString();
cell.SetCellValue(columnName);
}
//loops through data
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
String columnName = dt.Columns[j].ToString();
cell.SetCellValue(dt.Rows[i][columnName].ToString());
}
}
using (MemoryStream exportData = new MemoryStream())
{
Response.Clear();
workbook.Write(exportData);
filename = string.Format("attachment;filename=sostenitori_{0}_{1}", filename, DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString());
if (extension == "xlsx") //xlsx file format
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", filename + ".xlsx" );
Response.BinaryWrite(exportData.ToArray());
}
else if (extension == "xls") //xls file format
{
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", filename + ".xls");
Response.BinaryWrite(exportData.GetBuffer());
}
Response.End();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PayPal.Api;
using System.Net;
public partial class actions_PayPal_SDK : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get a reference to the config
Dictionary<string,string> config = ConfigManager.Instance.GetProperties();
// Use OAuthTokenCredential to request an access token from PayPal
String accessToken = new OAuthTokenCredential(config).GetAccessToken();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.DefaultConnectionLimit = 9999;
APIContext apiContext = new APIContext(accessToken);
// Initialize the apiContext's configuration with the default configuration for this application.
apiContext.Config = ConfigManager.Instance.GetProperties();
// Define any custom configuration settings for calls that will use this object.
apiContext.Config["connectionTimeout"] = "1000"; // Quick timeout for testing purposes
// Define any HTTP headers to be used in HTTP requests made with this APIContext object
if (apiContext.HTTPHeaders == null)
{
apiContext.HTTPHeaders = new Dictionary<string, string>();
}
apiContext.HTTPHeaders["some-header-name"] = "some-value";
}
}<file_sep>//MENU
var menu1 = "Config";
var menu2 = "Inhalte ";
var menu3 = "Papierkorb";
var menu4 = "Benutzer";
var menu5 = "dsmBenutzer";
var menu6 = "Austauschplattform";
var menu7 = "Sprachen";
var menu8 = "Vorschau";
var menu9 = "Exit";
var menu10 = "Dokumente";
var menu11 = "Bilder";
var menu12 = "Kontakt Box";
var menu13 = "Admin Passwort";
//FRIENDS
var friends_txt_input_error = "Nome o TITOLO non Corretti";
var friends_txt_max_friend = "Hai raggiunto il numero massimo di Amici Fixed";
var friends_txt_attach_image = "Allegare un file di tipo Immagine";
var friends_txt_max_size = "La dimensione del file supera 1 MB";
var maxFriends = 2;
//CONTENTS
var txt1 = "Admin-Inhalte";
var txt2 ="Sie befinden sich in der";
var txt2a ="Version";
var txt3="Publiziert";
var txt3a="Nicht Publiziert";
var txt4="Andere Sprachversion bearbeiten";
var txt5 ="Neuen Hauptmenüpunkt hinzufügen";
var txt6="Reihenfolge der Menüpunkte bestimmen";
var txt6a="Untermenue ord.";
var txt6b="MENUEREIHENFOLGE SETZEN / ÄNDERN";
//USERS
var txt7="Benutzerverwaltung";
var txt7a="Geschützte Seiten";
var txt8="Benutzer";
var txt9 = "Neuen Benutzer hinzufuegen";
var txt9_1="Create a new Progettiamo Friend";
var txt10="Alle Benutzer deaktivieren";
var txt11="Alle Benutzer aktivieren";
var txt12="E-mail";
var txt13="Aktiv";
var txt14=txt7a;
var txt15="Netzwerkgruppe";
var txt16="Dokumententauschgruppe";
//BIN
var txt17="Papierkorb leeren";
var txt17a="Es befinden sich keine Dokumente in Ihrem Papierkorb";
var txt18="publizieren";
//DSM USER
var txt19="Neuen dSm Benutzer hinzufügen";
var txt19a = "Admin dsm Benutzer";
var txt20 = "Neu hinzufuegen";
var txt20a = "Aktiver Benutzer";
var txt20b = "Vorname";
var txt20c = "Name";
var txt20d = "Passwort";
var txt20e = "Administrator dSm Benutzer";
var txt20f = "Administrator der angemeldeten Benutzer";
var txt20g = "Administrator Dokumentenplattform";
var txt20h = "Administrator Sprachen";
var txt20i = "Administrator Config";
var txt20l = "Administrator Inhalte";
var txt20m = "Darf Inhalte bearbeiten";
var txt20n = "Beschränkt auf";
var txt20o = "Keine Einschränkungen";
var txt20p = "Sprachen Beschränkt auf";
//NETWORKING
var txt21 = "Themen";
var txt22 = "Neues Thema hinzufügen";
var txt22a = "Keine Thema gefünden";
var txt22b = "eröffnet von ";
var txt23 = "am";
var txt24 = "Dieser Gruppe einen Benutzer zuordnen";
var txt25 = "auswählen";
var txt26 = "Schreibrecht";
var txt27 = "hinzufuegen";
var txt28 = "Eingeschriebene Benutzer";
var txt29 = "Letztes Login";
var txt30 = "Profil editieren";
var txt31 = "Benutzer entfernen";
var txt32 = "Erneuerte Dokumente";
var txt33 = "Dokumente einfügen";
var txt34 = "Thema";
var txt35 = "Datum";
var txt36 = "Titel";
var txt37 = "Beschrieb";
var txt38 = "Benutzer";
var txt39 = "Ändern";
var txt40 = "Löschen";
var txt40a = "Einfügen";
var txt40b = "Einfuegen";
var txt41 = "Download";
var txt42 = "Sprachen aktivieren";
var txt43 = "Sprachen";
var txt44 = "Aktivieren";
var txt45 = "Publiziert";
var txt46 = "Hauptsprache";
var back1 = "ZURUECK";
var save1 = "SPEICHERN";
var unde1 = "Nicht definiert";
var pass1 = "<PASSWORD>";
var fname1 = "Vorname";
var name1 = "Name";
//EDIT PAGE
var txt47="Seitentitel";
var txt47a="Sprache";
var txt48="Erstellt am";
var txt48a="Attribut";
var txt49="Diese Seite ist";
var txt50="Titel verstecken";
var txt51="Newsteil";
var txt51a="Geschützte Seiten";
var txt51b="Austauschplattform Login";
var txt51c="Klicken Sie rechts auf "Text bearbeiten", um einen Text einzufügen.";
var txt51d="Unsichtbar im Menü";
var txt51e="Kein Bild vorhanden";
var txt51f="E_Commerce Section";
var txt52="Text bearbeiten";
var txt52a="Hauptmenüpunkt Bilder";
var txt53="Publikationsposition definieren";
var txt54="Auf den "Over page"-Namen klicken, um die Referenz zu löschen";
var txt55="Als Unterseite von";
var txt56="setzen";
var txt57="Anlage einfügen";
var txt58="NEUE ANLAGE";
var txt59="Angefüge Dokumente";
//ADD ATTACHMENT
var txt60="Titel / Name";
var txt61="Dokument auswählen";
var txt62="ABBRECHEN";
var txt63="HOCHLADEN";
//DELETING
var txt64="Sind Sie sicher, dass Sie diese Seite löschen wollen?";
var txt64a="Wollen Sie dieses Bild wirklich löschen?";
var txt64b="Wollen Sie dieses Dokument wirlich löschen?";
var txt64c="Wollen Sie diese Seite wirklich von diesem Ordner entfernen?";
var txt64d="Verknuepfung entfernen";
var txt65="LOESCHEN";
var txt65a="LOESCHEN";
var txt65b="EDITIEREN";
var txt66="JA";
var txt67="NEIN";
//ADD INTERNAL LINK
var txt68="Link zu einer Seite";
var txt69="Link zu einem Anhang";
|
8daa7680640035a49da3c2ab72017ddf7a2ee906
|
[
"JavaScript",
"C#",
"PHP"
] | 10
|
JavaScript
|
ivus84/progettiamo_ch
|
1df8d8e1de5d6afcc6eef2bfc382c08790dc49f8
|
8c8e7461e583f7aa045e493db3dde1002c11862b
|
refs/heads/master
|
<file_sep>Python user management utility
<file_sep>import uuid
import json
from thirdparty.ua_parser import user_agent_parser
from django.core.exceptions import MultipleObjectsReturned
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import HttpResponse, Http404
from armutils.jsonresponse import JsonResponses
from serverapp.api.models import User, Device, DeviceSession
class ApiMessageList(object):
def __init__(self):
self.msgs = []
def add(self, code, msg):
self.msgs.append({'code':code, 'msg':msg})
def get(self):
return self.msgs
class ApiBase(object):
OK = 200
BADREQ = 400
UNAUTH = 403
SERVERR = 500
ERRCODE_UNKNOWN_METHOD = -10
ERRCODE_INVALID_SESSION = -20
ERRCODE_SESSION_INTEGRITY = -30
ERRCODE_UNKNOWN_DEVICE = -40
ERRCODE_MISSING_TOKEN = -50
ERRCODE_ALREADY_LOGGED_IN = -60
ERRCODE_AUTH_FAILED = -70
ERRCODE_MISSING_FIELDS = -80
ERRCODE_SESSION_NOT_FOUND = -90
ERRCODE_DEVICE_INTEGRITY = -100
ERRCODE_FIELD_ERR = -120
ERRCODE_NO_UNASS_CLIENT = -130
KEY_SESS = 'sess'
KEY_USERNAME = 'u'
KEY_PASSWORD = 'p'
KEY_DEV_ID = 'd'
KEY_SECTOKEN = 'sectoken'
KEY_ACT_LIST = 'acts'
@classmethod
def create_msglist(cls, code=None, msg=None):
msglist = ApiMessageList()
if code and msg:
msglist.add(code, msg)
return msglist
@classmethod
def create_field_errors(cls, field_err_msglist):
msglist = cls.create_msglist()
for msg in field_err_msglist:
msglist.add(ApiBase.ERRCODE_FIELD_ERR, msg)
return msglist
@classmethod
def resp(cls, status, msglist=None, **otherargs):
r = {'status': status}
if msglist:
r['msgs'] = msglist
for key, val in otherargs.items():
r[key] = val
return r
@classmethod
def gen_sectoken(cls):
sectoken = uuid.uuid4()
return sectoken.get_hex()
@classmethod
def validate_required(cls, inputdata, req_keylist):
notfound = []
for key in req_keylist:
if key not in inputdata:
notfound.append(key)
return notfound
@classmethod
def create_device(cls, request, user, dev_uid):
user_agent_str = request.META['HTTP_USER_AGENT']
result_dict = user_agent_parser.Parse(user_agent_str)
ua_os = result_dict['os']['family']
major = result_dict['os']['major']
minor = result_dict['os']['minor']
if major and minor:
ua_osver = "%s.%s"%(major, minor)
else:
ua_osver = 'n/a'
device = Device(user=user, device_unique_id=dev_uid, os=ua_os, os_version=ua_osver, user_agent=user_agent_str)
device.save()
return device
# Returns tuple of (status code, response json, structured input)
# If status code is not OK, response json is present and structured input is None
# Otherwise, response json is None and structured input is present
@classmethod
def initialize(cls, request, requires_auth=True):
inputdata = {}
if request.method == 'POST':
# Post data should always be json
inputdata = json.loads(request.raw_post_data)
elif request.method == 'GET':
inputdata = request.REQUEST
else:
msglist = cls.create_msglist(cls.ERRCODE_UNKNOWN_METHOD, "Invalid rest method.")
return (cls.SERVERR, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
# Check auth
if requires_auth:
# Look for required params for checking auth in input data
sectoken = None
dev_uid = None
if cls.KEY_SECTOKEN in inputdata:
sectoken = inputdata[cls.KEY_SECTOKEN]
if cls.KEY_DEV_ID in inputdata:
dev_uid = inputdata[cls.KEY_DEV_ID]
if sectoken and dev_uid:
# Try to find the device
try:
device = Device.objects.get(device_unique_id=dev_uid)
# Try to find the existing session
try:
dev_sess = DeviceSession.objects.get(device=device, security_token=sectoken)
inputdata[cls.KEY_SESS] = dev_sess
except DeviceSession.DoesNotExist, dee:
logging.info("Could not find session for dev_uid=[%s] and sectoken=[%s]"%(dev_uid, sectoken))
msglist = cls.create_msglist(cls.ERRCODE_INVALID_SESSION, "Invalid session")
return (cls.UNAUTH, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
except MultipleObjectsReturned, me:
logging.error("Found multiple sessions for dev_uid=[%s] and sectoken=[%s]. This is bad-ditty-bad-bad. Fuck."%(dev_uid, sectoken))
msglist = cls.create_msglist(cls.ERRCODE_SESSION_INTEGRITY, "Internal server error validating your session. Please logout and log back in.")
return (cls.SERVERR, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
except Device.DoesNotExist, ee:
logging.warn("Problem finding device for dev_uid=[%s]"%dev_uid)
msglist = cls.create_msglist(cls.ERRCODE_UNKNOWN_DEVICE, "Could not find session for specified device.")
return (cls.BADREQ, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
except MultipleObjectsReturned, devmor:
logging.error("Found multiple devices for dev_uid=[%s]. This is bad-ditty-bad-bad. Fuck."%(dev_uid))
msglist = cls.create_msglist(cls.ERRCODE_DEVICE_INTEGRITY, "Internal server error validating your session. Please logout and log back in.")
return (cls.SERVERR, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
else:
logging.warn("Missing sectoken and/or dev_uid. Cannot attempt to validate session.")
msglist = cls.create_msglist(cls.ERRCODE_MISSING_TOKEN, "Invalid login.")
return (cls.BADREQ, JsonResponses.as_is(cls.resp(0, msglist=msglist.get())), None)
return (cls.OK, None, inputdata)<file_sep>#!/usr/bin/env python
import sys
from django.core.management import setup_environ
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
setup_environ(settings)
if __name__ == "__main__":
if len(sys.argv) > 1:
mod = sys.argv[1]
try:
mod_obj = __import__("cardea.standalone.%s"%mod, fromlist=["cardea.standalone"])
except ImportError, e:
sys.stderr.write("Cannot find standalone module [%s].\n"%mod)
sys.exit(1)<file_sep>Common elements of all the customizable Django directory layouts, including useful css and javascript libs,
common Django template components for web development (login, logout, register user, admin console, display table templates and views, url layout for both website and webservices, components for making ajax calls from web pages easily, etc.)
<file_sep> {% if table.data %}
{% for row in table.data %}
{% include table.row_template %}
{% endfor %}
{% else %}
<tr>
<td colspan={{table.columns}}>{{table.empty_text}}</td>
</tr>
{% endif %}
<file_sep># Django settings for cardea project.
import os
import sys
from cardea.metaconfig import Metaconfig
DEPLOY_ROOT='/var/cardea'
SECRETS_FILE='.secrets'
CONTRIB_LIBS_DIR=os.path.join(os.getcwd(), 'src', 'contrib', 'libs')
sys.path.append(CONTRIB_LIBS_DIR)
Metaconfig.load(DEPLOY_ROOT, SECRETS_FILE)
BROKER_URL = Metaconfig.get('CLOUDAMQP_URL')
ENV = Metaconfig.get('CARDEA_ENV')
#DEBUG = True
#TEMPLATE_DEBUG = DEBUG
FE_TESTING = Metaconfig.get('FE_TESTING')
ADMINS = (
# ('<NAME>', '<EMAIL>'),
)
#os.environ['DJANGO_SETTINGS_MODULE'] = 'cardeahome.settings'
MANAGERS = ADMINS
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'cardea', # Or path to database file if using sqlite3.
# 'USER': 'cardearw', # Not used with sqlite3.
# 'PASSWORD': '<PASSWORD>', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Los_Angeles'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_TZ = False
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'src/cardeahome/staticfiles'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'src/cardeahome/static',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '<KEY>'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
# 'hirefire.contrib.django.middleware.HireFireMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_hosts.middleware.HostsMiddleware',
)
#HIREFIRE_PROCS = ['cardea.service.task.procs.WorkerProc']
#HIREFIRE_TOKEN = os.environ.get('HIREFIRE_TOKEN')
ROOT_URLCONF = 'urls'
ROOT_HOSTCONF = 'hosts'
DEFAULT_HOST = 'www'
FIXTURE_DIRS = (
'src/cardeahome/cardea/account'
)
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'src/cardeahome/templates'
)
BASE_INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_hosts',
'cardea.api',
'cardea.pub',
'cardea.cadmin',
'cardea.account',
'cardea.keydb',
'cardea.product',
'cardea.recalls',
'cardea.safety',
'cardea.service',
'cardea.sources',
'cardea.standalone'
]
CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True
import djcelery
djcelery.setup_loader()
DEBUG = False
CELERY_IMPORTS = (
'cardea.service.task.definitions'
)
BROKER_POOL_LIMIT = 1
CELERYD_CONCURRENCY = 1
BASE_INSTALLED_APPS.append('djcelery')
INSTALLED_APPS = tuple(BASE_INSTALLED_APPS)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'super_verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s $(asctime)s %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
},
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'stream': sys.stdout
},
'log_file':{
'level':'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/var/log/cardea.log',
'maxBytes': '16777216', # 16megabytes
'formatter': 'verbose'
},
'parse_log_file':{
'level':'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/var/log/cardea-parse.log',
'maxBytes': '16777216', # 16megabytes
'formatter': 'verbose'
},
'notifications_log_file':{
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/var/log/cardea-notifications.log',
'maxBytes': '16777216', # 16megabytes
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['console','log_file'],
'level': 'DEBUG',
'propagate': True,
'filters': []
},
'parse': {
'handlers': ['console', 'parse_log_file'],
'level': 'DEBUG',
'propagate': True,
'filters': []
},
'notifications': {
'handlers': ['console', 'notifications_log_file'],
'level': 'INFO',
'propagate': True,
'filters': []
},
'django.request': {
'handlers': ['log_file'],
'level': 'DEBUG',
'propagate': True,
'filters': []
},
}
}
import os
import sys
import urlparse
# 'dev' is strictly for running Django runserver
if ENV == 'dev' or ENV == 'stage':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cardea',
'USER': 'cardearw',
'PASSWORD': '<PASSWORD>',
'HOST': 'localhost'
}
}
# 'stage' is for running via foreman
# 'prod' is running in Heroku
elif ENV == 'prod':
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config(default=Metaconfig.get('DATABASE_URL'))}<file_sep>class TableGen(object):
TABLE_META = {}
@classmethod
def get_table_meta(cls, tname, user, sfilter):
if tname in cls.TABLE_META:
return cls.TABLE_META[tname]['metafunc'](user, sfilter)
else:
return None
@classmethod
def get_table_page(cls, tname, user, sfilter, page):
pg = cls.get_table_meta(tname, user, sfilter)
if page <= pg.num_pages:
curr_page = pg.page(page)
page_objs = curr_page.object_list
results = map(lambda x: cls.TABLE_META[tname]['datafunc'](x), page_objs)
else:
results = []
return results
@classmethod
def get_table_data(cls, tname, user, sfilter, page):
if tname in cls.TABLE_META:
return {
'data': cls.get_table_page(tname, user, sfilter, page),
'row_template': cls.TABLE_META[tname]['template'],
'columns': cls.TABLE_META[tname]['cols'],
'empty_text': cls.TABLE_META[tname]['empty_text']
}
else:
return None
@classmethod
def register_datasource(cls, name, stuff):
cls.TABLE_META[name] = stuff
@classmethod
def get_page_num_list(cls, page, pages):
# Meta-page size
m = 10
x = page
t = pages
spn = (x - x%m)
if spn == x and spn > 1:
spn = x - m + 1
else:
spn = spn + 1
epn = spn + m - 1
pre_start = spn - 1
post_end = epn + 1
last_page = min(epn, pages)
page_list = []
if pages > 1:
if spn > 1:
page_index = pre_start
page_list.append({'text': '<<', 'page': page_index, 'selected': False})
for i in range(spn, last_page+1):
page_index = i
selected = (page == page_index)
page_list.append({'text': page_index, 'page': page_index, 'selected': selected})
if last_page < pages:
page_index = post_end
page_list.append({'text': '>>', 'page': page_index, 'selected': False})
else:
page_list.append({'text': '1', 'page': 1, 'selected': True})
return page_list
<file_sep>import re
import logging
from datetime import datetime
# Key must be present in object
class RequiredConstraint(object):
@classmethod
def check(cls, obj, keyname):
if keyname in obj:
return (True, None)
else:
logging.error("[%s] is a required field."%keyname)
return (False, "[%s] is a required field."%keyname)
# Value must be non-empty
class NotEmptyConstraint(object):
@classmethod
def check(cls, obj, keyname):
if keyname in obj:
if str(obj[keyname]):
return (True, None)
else:
logging.error("Value for field [%s] must not be empty."%keyname)
return (False, "Value for field [%s] must not be empty."%keyname)
else:
return (True, None)
class MinLengthConstraint(object):
def __init__(self, minlen):
self.minlen = minlen
def check(self, obj, keyname):
if keyname in obj and str(obj[keyname]):
if len(str(obj[keyname])) >= self.minlen:
return (True, None)
else:
return (False, "Value for field is below the minimum length of %s"%self.minlen)
else:
return (True, None)
class MaxLengthConstraint(object):
def __init__(self, maxlen):
self.maxlen = maxlen
def check(self, obj, keyname):
if keyname in obj and str(obj[keyname]):
if len(str(obj[keyname])) <= self.maxlen:
return (True, None)
else:
return (False, "Value for field exceeds the maximum length of %s"%self.maxlen)
else:
return (True, None)
class EnumConstraint(object):
def __init__(self, *valuelist):
self.valuelist = valuelist
def check(self, obj, keyname):
if keyname in obj and str(obj[keyname]):
val = str(obj[keyname])
if val in self.valuelist:
return (True, None)
else:
return (False, "Field [%s] with value [%s] is not in list of acceptable values: %s"%(keyname, val, self.valuelist))
else:
return (True, None)
class AttributeDef(object):
def __init__(self, typename, keyname):
self.typename = typename
self.keyname = keyname
self.constraint_cls_list = []
def add_constraint(self, c):
self.constraint_cls_list.append(c)
def check_constraints(self, obj):
final_status = True
msgs = []
for c in self.constraint_cls_list:
(status, msg) = c.check(obj, self.keyname)
final_status = status and final_status
if msg:
msgs.append(msg)
return (final_status, msgs)
class DataNormalizer(object):
TYPES = {}
def __init__(self):
self.attrdefs = {}
def add_attr_def(self, varname, keyname, typename, *constraints):
setattr(self, varname, keyname)
self.attrdefs[keyname] = AttributeDef(typename, keyname)
for c in constraints:
self.attrdefs[keyname].add_constraint(c)
def blank_fill(self):
retval = {}
for attr in self.attrdefs.values():
retval[attr.keyname] = None
return retval
# Return (normed_dict, None) only if all attributes check out
# otherwise return (False, err_msg)
def normalize(self, obj):
normed_dict = self.blank_fill()
final_status = True
msglist = []
if type(obj) == dict:
# Check constraints
for attrdef in self.attrdefs.values():
(status, msgs) = attrdef.check_constraints(obj)
final_status = status and final_status
if msgs:
msglist.extend(msgs)
for key, val in obj.items():
if key in self.attrdefs:
attr = self.attrdefs[key]
if attr.typename in DataNormalizer.TYPES:
typefunc = DataNormalizer.TYPES[attr.typename]
(attr_status, normed_val) = typefunc(val)
final_status = attr_status and final_status
if attr_status:
normed_dict[key] = normed_val
else:
final_status = False
logging.error("Could not convert attribute [%s] with value [%s] to type [%s]"%(key, val, attr.typename))
msglist.append("Could not convert attribute [%s] with value [%s] to type [%s]"%(key, val, attr.typename))
else:
final_status = False
logging.error("Cannot find type definition for attribute [%s] with typename=[%s]"%(key, attr.typename))
msglist.append("Cannot find type definition for attribute [%s] with typename=[%s]"%(key, attr.typename))
else:
final_status = False
logging.error("Key [%s] not defined in this DataNormalizer instance"%key)
msglist.append("Key [%s] not defined in this DataNormalizer instance"%key)
else:
logging.error("DataNormalizer instance can only normalize a dictionary")
msglist.append("DataNormalizer instance can only normalize a dictionary")
final_status = False
return (final_status, normed_dict, msglist)
# Built-in normalization funcs
# nfunc(value) : (status, normed-value)
# At some point, might need to have this encode to ascii or utf8
@classmethod
def norm_str(cls, value):
cleaned = str(value).strip()
return (True, cleaned)
@classmethod
def norm_int(cls, value):
cleaned = str(value).strip()
return (True, int(value))
@classmethod
def norm_float(cls, value):
cleaned = str(value).strip()
try:
normed = float(cleaned)
return (True, normed)
except ValueError, ve:
return (False, None)
@classmethod
def norm_datetime(cls, value):
cleaned = str(value).strip()
pat = re.compile("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} UTC")
if pat.match(cleaned):
try:
normed = datetime.strptime(cleaned, "%Y-%m-%dT%H:%M:%S %Z")
return (True, normed)
except ValueError, ve:
return (False, None)
else:
return (False, None)
@classmethod
def norm_bool(cls, value):
cleaned = int(value)
if cleaned == 1:
return (True, True)
elif cleaned == 0:
return (True, False)
else:
return (False, None)
@classmethod
def norm_email(cls, value):
cleaned = str(value).strip()
pat = re.compile("[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
if pat.match(cleaned):
return (True, cleaned)
else:
return (False, None)
@classmethod
def norm_str_list(cls, value):
cleaned = str(value).strip()
str_list = filter(lambda d: len(d) > 0, reduce(lambda b, c: b + c, map(lambda a: re.split('\s+', a), re.split(',', cleaned))))
return (True, list(set(str_list)))
# Map typenames to validation functions
@classmethod
def register_type(cls, typename, normfunc):
cls.TYPES[typename] = normfunc<file_sep>For managing sensitive configs, like passwords, secret api keys, etc.
<file_sep>class DataChoice(object):
CHOICE_PREFIX = 'CHOICE'
LABEL_PREFIX = 'LABEL'
def __init__(self):
self.choice_dict = {}
self.label_dict = {}
cindex = 0
lindex = 0
for attr in dir(self):
if attr.startswith(DataChoice.CHOICE_PREFIX):
attrval = getattr(self, attr)
self.choice_dict[cindex] = attrval
cindex += 1
if attr.startswith(DataChoice.LABEL_PREFIX):
attrval = getattr(self, attr)
self.label_dict[lindex] = attrval
lindex += 1
self.inv_choice_dict = dict((v,k) for k, v in self.choice_dict.iteritems())
choices = []
for key, val in self.choice_dict.items():
choices.append((key, val))
self.choices = tuple(choices)
@classmethod
def get_code(cls, key):
inst = cls()
if key in inst.inv_choice_dict:
return inst.inv_choice_dict[key]
else:
return None
@classmethod
def get_key(cls, code):
inst = cls()
if code in inst.choice_dict:
return inst.choice_dict[code]
else:
return None
@classmethod
def get_label(cls, code):
inst = cls()
if code in inst.label_dict:
return inst.label_dict[code]
else:
return None
@classmethod
def choices(cls):
inst = cls()
return inst.choices
@classmethod
def keys(cls):
inst = cls()
return inst.choice_dict.values()<file_sep>from django.conf import settings
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
('^$', views.home),
('^admin/', include('cardea.cadmin.urls')),
('^account/', include('cardea.account.urls')),
('^pub/', include('cardea.pub.urls')),
# ('^test/', include('cardea.test.urls')),
# url(r'^django-admin/', include(admin.site.urls)),
(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT})
)<file_sep>A mailing system to easily send email. The django-common module includes a thin wrapper
around this to allow sending emails formatted using django templates
<file_sep>Customizable Django directory layout with scripts for deploying to an AWS instance, a settings.py for pointing to a real db,
scripts for running gunicorn_django server and celeryd, templates for a crontab, etc.
<file_sep>Customizable Django directory layout with settings.py specifically designed to work with Heroku,
scripts for updating various Heroku configs and deploying to Heroku
<file_sep>A general purpose notification system. The django-common module includes a thin wrapper
around this for formatting notifications using django templates
<file_sep>Customizable Django directory layout with additional required libs for running django-nonrel and customized settings.py
to work in a Google App Engine environment
<file_sep>import json
class JsonResponses(object):
@classmethod
def response(cls, resp_struct):
return json.dumps(resp_struct)
@classmethod
def server_error(cls, msg):
return cls.response({'code': 1,
'msg': 'There was an internal server error. Please contact the system administrator for assistance.'})
@classmethod
def already_logged_in(cls, user):
return cls.response({'code':10,
'msg': "You are already logged in as %s. Please log out to create a new account."%(user.username)})
@classmethod
def required_field_missing(cls, field):
return cls.response({'code':20,
'msg': "A value for the field [%s] is required but not present in your request."%field})
@classmethod
def invalid_argument_value(cls, field, value):
return cls.response({'code':30,
'msg': "You have provided an invalid value (%s) for the [%s] field."%(value, field)})
@classmethod
def account_exists(cls, user):
return cls.response(
{
'code': 40,
'msg': "An account already exists for the user %s"%user
}
)
@classmethod
def invalid_login(cls):
return cls.response(
{
'code': 50,
'msg': "Invalid username or password. Please try again."
}
)
@classmethod
def page_not_authorized(cls):
return cls.response(
{
'code': 60,
'msg': 'You must be logged in to access that page.'
}
)
@classmethod
def ajax_not_authorized(cls):
return cls.response(
{
'code': 70,
'msg': 'You must be logged in to access that api.'
}
)
@classmethod
def oauth_get_url_response(cls, url):
return cls.response(
{
'code': 0,
'msg': 'Url to authorize access to account',
'url': url
}
)
@classmethod
def oauth_request_response(cls, request_token, request_auth_url):
return cls.response(
{
'code': 80,
'rt': request_token,
'rau': request_auth_url
}
)
@classmethod
def as_is(cls, data):
return cls.response(data)
@classmethod
def one_object(cls, obj_data):
return cls.response(
{
'code': 5,
'data': obj_data
}
)
@classmethod
def object_created(cls, obj_name, obj_data):
return cls.response(
{
'code': 0,
'msg': "%s created successfully"%obj_name,
'data': obj_data
}
)
@classmethod
def object_count(cls, count):
return cls.response(
{
'code': 1,
'count': count
}
)
@classmethod
def object_list(cls, olist):
return cls.response(
{
'code': 2,
'list':olist
}
)
@classmethod
def ok(cls, msg=''):
return cls.response(
{
'code': 0,
'msg': msg
}
)
@classmethod
def fail(cls, msg):
return cls.response(
{
'code': 90,
'msg': msg
}
)<file_sep>django==1.4
gunicorn==0.16.1
cython==0.18
MySQL-python==1.2.4
https://github.com/SiteSupport/gevent/archive/1.0rc2.tar.gz
PyCascade==1.0
oauth==1.0.1
simplejson==3.1.3
chardet==2.1.1
python-dateutil==1.5
DateUtils==0.6.5
django-celery==3.0.11
pycrypto
BeautifulSoup==3.2.1
bottlenose==0.4.2
simples3
PyYAML==3.10
dj-database-url==0.2.0<file_sep>Tools for implementing OAuth to access third-party apis
<file_sep>starwarp-web
============
NOTICE: Work in progress - probably not very useful just yet.
Web tools for my consulting firm.
Share and Enjoy!
<file_sep>from django.shortcuts import render_to_response, redirect
from django.shortcuts import get_object_or_404, render
from django.shortcuts import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
import cardea.app
import logging
import hashlib
def home(request):
if request.user.is_authenticated():
if request.user.is_superuser:
return redirect('/admin')
else:
return redirect('/account')
else:
return redirect('/pub')<file_sep>package ws is a webservices lib for dealing with parsing and formatting json data into real objects
and returning web responses formatted nicely.
<file_sep>Config management using yaml
|
0e1df26065837dbe642b5c1ef641a28f96bda925
|
[
"Markdown",
"Python",
"Text",
"HTML"
] | 23
|
Markdown
|
jacksonofalltrades/starwarp-web
|
e57e5d85a41f9b7b17359130183f18d3ef517748
|
8d37ac32d7126242e41e47b5213173d07c601174
|
refs/heads/master
|
<file_sep>import java.awt.*;
public class Ball
{
private int r=0, alpha=255;
private double x,y,dx,dy=0.0;
private double red,green,blue;
private Color col, target;
public Ball()
{
x=20;
y=20;
r=10;
dx=6*Math.random()-3;
dy=6*Math.random()-3;
col= Color.blue;
red=col.getRed();
green=col.getGreen();
blue=col.getBlue();
}
public Ball(double x, double y, int r, Color c)
{
this.x=x;
this.y=y;
this.r=r;
dx=6*Math.random()-3;
dy=6*Math.random()-3;
col=c;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getdx()
{
return dx;
}
public double getdy()
{
return dy;
}
public void setAlpha(int a)
{
alpha=a;
}
private void move(int mx, int my, Color target)
{
x+=dx;
y+=dy;
if(x >= mx - r) //hits the right edge
{
x=mx - r;
dx = dx * -1;
}
else if(x<r)
{
x=r;
dx*=-1;
}
if(y>=my-r)
{
y=my-r;
dy*=-1;
}
else if(y<r)
{
y=r;
dy*=-1;
}
int tr=target.getRed();
int tg=target.getGreen();
int tb=target.getBlue();
double dr=tr-red;
double dg=tg-green;
double db=tb-blue;
red+=dr/100;
green+=dg/100;
blue+=db/100;
col=new Color((int)(red),(int)(green),(int)(blue), alpha);
}
public void draw(Graphics myBuffer, int mx, int my, Color target, boolean b)
{
myBuffer.setColor(col);
myBuffer.fillOval((int)x-r/2,(int)y-r/2,r,r);
if(b) move(mx, my, target);
}
}
|
dd1b0a05faa659bdfd23ea3b26708e73e93bcf98
|
[
"Java"
] | 1
|
Java
|
amgodman/Website
|
9d5cc51ffd974b02eec686672979f5dcee7e0a3c
|
9a813378e72a06e073dbd4db54509195010df13e
|
refs/heads/master
|
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import d3 from 'd3';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Mesh extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
meshClass: 'react-d3-map-core__mesh',
onMouseOver: (d) => {},
onMouseOut: (d) => {}
}
static propTypes = {
data: PropTypes.object.isRequired,
geoPath: PropTypes.func.isRequired,
meshClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkMesh(dom) {
const {
data,
meshClass,
geoPath,
onMouseOut,
onMouseOver,
onClick,
id
} = this.props;
var mesh = d3.select(dom);
mesh
.datum(data)
.attr('class', `${meshClass} mesh`)
.attr("d", geoPath)
.style('fill', 'none')
.style('stroke', '#CCC')
.style('stroke-width', '.5px')
if(id)
mesh.attr('id', id);
if(onMouseOver)
mesh.on("mouseover", function (d, i) {return onMouseOver(this, d, id);})
if(onMouseOut)
mesh.on("mouseout", function (d, i) {return onMouseOut(this, d, id);} )
if(onClick)
mesh.on("click", function (d, i) {return onClick(this, d, id);})
return mesh;
}
render () {
var meshGroup = ReactFauxDOM.createElement('path');
var chart = this._mkMesh(meshGroup)
return chart.node().toReact();
}
}
<file_sep>
var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Point = require('../../lib/index').Point;
var Marker = require('../../lib/index').Marker;
var Popup = require('../../lib/index').Popup;
var Tile = require('../../lib/index').Tile;
var Polygon = require('../../lib/index').Polygon;
var ZoomControl = require('../../lib/index').ZoomControl;
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
var tileFunc = require('../../lib/index').tileFunc;
// Example
(function() {
var ChartPopup = React.createClass({
getInitialState: function() {
var height= this.props.height;
var width = this.props.width;
var projeciton= this.props.projection;
var translate= this.props.translate;
var center = this.props.center;
var scale = this.props.scale;
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
center: center
});
var tiles = tileFunc({
scale: proj.scale() * 2 * Math.PI,
translate: proj([0, 0]),
size: ([width, height])
});
return {
zoomTranslate: null,
scale: scale,
times: 1,
tiles: tiles,
proj: proj,
tileScale: tiles.scale,
tileTranslate: tiles.translate
}
},
onZoom: function(zoomScale, zoomTranslate) {
var times = this.state.times;
// tiles only translate and scale
// don't change tiles
var height= this.props.height;
var width = this.props.width;
var projeciton= this.props.projection;
var translate= this.props.translate;
var center = this.props.center;
var proj = projectionFunc({
projection: projection,
scale: (zoomScale / 2 / Math.PI) * times,
translate: zoomTranslate,
center: center
});
var tiles = tileFunc({
scale: proj.scale() * 2 * Math.PI,
translate: proj([0, 0]),
size: ([width, height])
});
this.setState({
scale: zoomScale * times,
zoomTranslate: zoomTranslate,
proj: proj,
tiles: tiles,
tileScale: tiles.scale,
tileTranslate: tiles.translate
})
},
zoomIn: function() {
var times = this.state.times;
this.setState({
times: times * 2,
scale: this.state.scale * 2
})
},
zoomOut: function() {
var times = this.state.times;
this.setState({
times: times / 2,
scale: this.state.scale / 2
})
},
render: function() {
var zoomTranslate = this.state.zoomTranslate;
var tiles = this.state.tiles;
var tileScale= this.state.tileScale;
var tileTranslate = this.state.tileTranslate;
var scale = this.state.scale;
var proj = this.state.proj;
var width = this.props.width;
var height= this.props.height;
var center = this.props.center;
var translate = this.props.translate;
var projection = this.props.projection;
var pointRadius= this.props.pointRadius
var uk = require('json!../data/uk.json');
var uk_points = topojson.feature(uk, uk.objects.places).features;
// data should be a MultiLineString
var onZoom = this.onZoom;
var zoomIn = this.zoomIn;
var zoomOut = this.zoomOut;
var style = {position: 'relative'}
var onLoad = function(that, d, i) {
console.log(that);
}
return (
<div style={style}>
<Chart
width= {width}
height= {height}
projection = {proj}
center= {center}
onZoom= {onZoom}
>
<Tile
tiles= {tiles}
scale= {tileScale}
translate= {tileTranslate}
onLoad= {onLoad}
/>
<ZoomShape
width= {width}
height= {height}
scale= {scale}
center= {center}
translate= {translate}
projection= {projection}
pointRadius= {pointRadius}
zoomTranslate= {zoomTranslate}
proj= {proj}
/>
</Chart>
<ZoomControl
zoomInClick= {zoomIn}
zoomOutClick= {zoomOut}
/>
</div>
)
}
})
var ZoomShape = React.createClass({
render() {
var pointRadius= this.props.pointRadius;
var proj = this.props.proj;
var geo = geoPath(proj, {
pointRadius: pointRadius
});
var uk = require('json!../data/uk.json');
var data = topojson.feature(uk, uk.objects.places);
var land = topojson.feature(uk, uk.objects.subunits);
var x = function(d) { return +proj(d.geometry.coordinates)[0]; }
var y = function(d) { return +proj(d.geometry.coordinates)[1]; }
var points = data.features.map(function(d, i) {
return (
<g key={i}>
<Point
key= {i}
data= {d}
geoPath= {geo}
{...this.props}
/>
<MarkerGroup
key= {i.i}
data= {d}
x= {+proj(d.geometry.coordinates)[0]}
y= {+proj(d.geometry.coordinates)[1]}
{...this.props}
/>
</g>
)
}.bind(this))
return (
<g>
{points}
</g>
)
}
})
var MarkerGroup = React.createClass({
getInitialState: function() {
return {
showPopup: false
}
},
onClick: function() {
this.setState({
showPopup: !this.state.showPopup
})
},
render: function() {
var data = this.props.data;
var x = this.props.x;
var y = this.props.y;
var showPopup= this.state.showPopup;
var popup;
var onClick = this.onClick;
var content = "Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 33 KB of JS, it has all the mapping features most developers ever need.";
if(showPopup) {
popup = (
<Popup
x= {x}
y= {y - 50}
contentPopup={content}
closeClick= {onClick}
/>
)
}
return (
<g>
<Marker
data= {data}
x= {x}
y= {y}
onClick= {onClick}
/>
{popup}
</g>
)
}
})
var width = 960;
var height = 1160;
var center = [-5, 55.4]
var translate = [width / 2, height / 2];
var projection = 'mercator';
var pointRadius = 2;
var scale = 1200 * 5;
ReactDOM.render(
<ChartPopup
width= {width}
height= {height}
center= {center}
translate= {translate}
projection= {projection}
pointRadius= {pointRadius}
scale= {scale}
/>
, document.getElementById('blank-zoom')
)
})()
<file_sep>"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var Chart = require('../../lib/index').Chart;
var Mesh = require('../../lib/index').Mesh;
var topojson = require('topojson');
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
// Example
// http://bl.ocks.org/mbostock/3757132
(function() {
var width = 960,
height = 1160;
var title = "test chart lib"
var topodata = require('json!../data/world-50m.json');
// data should be a MultiLineString
var data = topojson.mesh(topodata, topodata.objects.countries, function(a, b) { return a !== b; });
var scale = (width + 1) / 2 / Math.PI;
var translate = [width / 2, height / 2];
var precision = .1;
var projection = 'mercator';
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
precision: precision
});
var geo = geoPath(proj);
ReactDOM.render(
<Chart
title= {title}
width= {width}
height= {height}
>
<Mesh
width= {width}
height= {height}
data= {data}
geoPath= {geo}
/>
</Chart>
, document.getElementById('blank-mesh')
)
})()
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes,
} from 'react';
import {
default as ReactFauxDOM
} from 'react-faux-dom';
import d3 from 'd3';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Voronoi extends Component {
constructor(props) {
super(props);
}
static defaultProps = {
onMouseOver: (d) => {},
onMouseOut: (d) => {}
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkVoronoi (dom) {
const {
x,
y,
width,
height,
data,
onMouseOut,
onMouseOver
} = this.props;
var voronoiInit = d3.geom.voronoi()
.x(x)
.y(y)
.clipExtent([
[0, 0],
[width, height]
])
voronoiInit(data)
.forEach((d) => { d.point.cell = d; });
var voronoiChart = d3.select(dom);
var voronoiPath = voronoiChart.selectAll('path')
.data(data)
.enter().append('path')
.attr("d", (d) => {return d.cell ? "M" + d.cell.join("L") + "Z" : null; })
.datum((d) => {return d; })
.on("mouseover", function (d, i) {return onMouseOver(this, d, i);})
.on("mouseout", function (d, i) {return onMouseOut(this, d, i);} )
.style('fill', 'none')
.style('pointer-events', 'all')
.each(function(d) {
var dom = d3.select(this)
if(d.style) {
for(var key in d.style) {
dom.style(key, d.style[key]);
}
}
})
return voronoiChart;
}
render() {
var voronoiPath = ReactFauxDOM.createElement('g');
voronoiPath.setAttribute("class", "react-d3-core-map__voronoi_utils")
var voronoi = this._mkVoronoi(voronoiPath);
return voronoi.node().toReact();
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import {
default as ReactDOM
} from 'react-dom'
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import {
default as Queue
} from 'queue-async';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
import {
default as ReactCSSTransitionGroup
} from 'react-addons-css-transition-group';
export default class VectorTile extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
vectorTileClass: 'react-d3-map-core__vectorTile',
layers: 'all'
}
static propTypes = {
vectorTiles: PropTypes.array.isRequired,
vectorTileClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
componentDidMount() {
var tilesGroup = ReactDOM.findDOMNode(this.refs.vectorTilesGroup)
this._mkVectorTile(tilesGroup);
}
// componentDidUpdate() {
// var tilesGroup = ReactDOM.findDOMNode(this.refs.vectorTilesGroup)
// this._mkVectorTile(tilesGroup);
// }
_mkVectorTile(dom) {
const {
vectorTiles,
vectorTileClass,
onMouseOut,
onMouseOver,
layers,
geoPath
} = this.props;
var vectorTileDom = d3.select(dom);
Queue()
.defer(d3.json, "http://vector.mapzen.com/osm/" + layers + "/" + vectorTiles[2] + "/" + vectorTiles[0] + "/" + vectorTiles[1] + ".json?api_key=vector-tiles-_dA3ANY")
.await((error, json) => {
if(json.features) {
var path = vectorTileDom.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("key", (d, i) => {return i;})
.attr("class", (d) => { return d.properties.kind; })
.attr("d", geoPath);
if(onMouseOut)
path.on("mouseover", (d, i) => {return onMouseOver(this, d, i);})
if(onMouseOver)
path.on("mouseout", (d, i) => {return onMouseOut(this, d, i);} )
}else {
for(var key in json) {
var path = vectorTileDom.selectAll("path")
.data(json[key].features)
.enter().append("path")
.attr("key", (d, i) => {return i;})
.attr("class", (d) => { return d.properties.kind; })
.attr("d", geoPath);
if(onMouseOut)
path.on("mouseover", (d, i) => {return onMouseOver(this, d, i);})
if(onMouseOver)
path.on("mouseout", (d, i) => {return onMouseOut(this, d, i);} )
}
}
});
}
render () {
return (
<g
ref = "vectorTilesGroup"
className = "tile"
>
</g>
);
}
}
<file_sep>
"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import d3 from 'd3';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class PointText extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
pointTextClass: 'react-d3-map-core__pointText',
dy: '.35em',
onMouseOver: (d) => {},
onMouseOut: (d) => {}
}
static propTypes = {
data: PropTypes.object.isRequired,
projection: PropTypes.func.isRequired,
pointTextClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkPointText(dom) {
const {
data,
pointTextClass,
text,
x,
dy,
textAnchor,
projection,
onMouseOut,
onMouseOver
} = this.props;
var pointText = d3.select(dom);
pointText
.datum(data)
.attr('class', `${pointTextClass} pointText`)
.attr("transform", (d) => { return 'translate(' + projection(d.geometry.coordinates) + ')'})
.attr("dy", dy)
.attr("x", x)
.style("text-anchor", textAnchor)
.text(text)
.on("mouseover", function (d, i) {return onMouseOver(this, d, i);})
.on("mouseout", function (d, i) {return onMouseOut(this, d, i);} )
return pointText;
}
render () {
var pointTextGroup = ReactFauxDOM.createElement('text');
var chart = this._mkPointText(pointTextGroup)
return chart.node().toReact();
}
}
<file_sep>"use strict";
export default {
width: 960,
height: 500
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes,
} from 'react';
import d3 from 'd3';
import {
default as CommonProps,
} from '../commonProps';
import {
default as ReactDOM
} from 'react-dom'
export default class ChartSvg extends Component {
constructor(props) {
super (props);
}
static defaultProps = Object.assign(CommonProps, {
svgClassName: 'react-d3-map-core__container_svg',
scaleExtent: [1 << 12, 1 << 28]
})
static propTypes = {
id: PropTypes.string,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
svgClassName: PropTypes.string.isRequired
}
componentDidMount() {
var {
width,
height,
scaleExtent,
projection,
onZoom,
onZoomStart,
onZoomEnd,
center
} = this.props;
var tau = 2 * Math.PI;
// implement zoom if xscale and y scale is set!
if(projection && onZoom) {
var center = projection(center);
var zoom = d3.behavior.zoom()
.scale(projection.scale() * tau)
.translate([width - center[0], height - center[1]])
if(scaleExtent)
zoom.scaleExtent([scaleExtent[0] * tau, scaleExtent[1] * tau]);
if(onZoom)
zoom.on("zoom", () => { onZoom.call(this, zoom.scale(), zoom.translate()) });
if(onZoomStart)
zoom.on("zoomstart", () => { onZoomStart.call(this, zoom.scale(), zoom.translate()) });
if(onZoomEnd)
zoom.on("zoomend", () => { onZoomEnd.call(this, zoom.scale(), zoom.translate()) });
d3.select(ReactDOM.findDOMNode(this.refs.svgContainer))
.call(zoom);
}
}
render() {
const {
height,
width,
svgClassName,
id,
children
} = this.props;
return (
<svg
height = {height}
width = {width}
className = {svgClassName}
ref = "svgContainer"
>
<g>
{children}
</g>
</svg>
)
}
}
<file_sep>"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Polygon = require('../../lib/index').Polygon;
var tileFunc = require('../../lib/index').tileFunc;
var geoPath = require('../../lib/index').geoPath;
var projectionFunc = require('../../lib/index').projection;
var VectorTile = require('../../lib/index').VectorTile;
// Example
(function() {
var width = 960,
height = 960
var css = require('./css/vectortile.css')
var scale = (1 << 21);
var translate = [width / 2, height / 2];
var center = [-100.4183, 57.7750];
var projection = 'mercator';
var proj = projectionFunc({
projection: projection,
scale: scale / 2 / Math.PI,
translate: translate,
center: center
});
var geo = geoPath(proj);
var tiles = tileFunc({
scale: proj.scale() * 2 * Math.PI,
translate: proj([0, 0]),
size: ([width, height])
})
var tiles = tiles.map((d, i) => {
return (
<VectorTile
key= {i}
vectorTiles= {d}
layers= 'all'
geoPath= {geo}
/>
)
})
ReactDOM.render(
<Chart
width= {width}
height= {height}
>
{tiles}
</Chart>
, document.getElementById('blank-vectortile')
)
})()
<file_sep>"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Point = require('../../lib/index').Point;
var Voronoi = require('../../lib/index').Voronoi;
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
// Example
(function() {
var width = 960,
height = 1160,
margins = {top: 20, right: 50, bottom: 20, left: 50};
var title = "test chart lib"
var uk = require('json!../data/uk.json');
var uk_points = topojson.feature(uk, uk.objects.places).features;
// data should be a MultiLineString
var data = topojson.feature(uk, uk.objects.places);
var scale = 1200 * 5;
var parallels = [50, 60]
var rotate = [4.4, 0]
var center = [0, 55.4]
var translate = [width / 2, height / 2];
var projection = 'albers';
var pointRadius = 2;
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
parallels: parallels,
rotate: rotate,
center: center
});
var geo = geoPath(proj, {
pointRadius: pointRadius
});
var x = function(d) { return +proj(d.geometry.coordinates)[0]; }
var y = function(d) { return +proj(d.geometry.coordinates)[1]; }
var onMouseOut = function(dom, d, i) {console.log(d, i);}
var onMouseOver = function(dom, d, i) {console.log(d, i);}
data.features = data.features.map(function(d) {
d.style = {
'fill': 'green'
};
return d;
})
var points = data.features.map(function(d, i) {
return (
<Point
key= {i}
data= {d}
geoPath= {geo}
/>
)
})
ReactDOM.render(
<Chart
title= {title}
width= {width}
height= {height}
margins= {margins}
>
<Voronoi
data= {data.features}
geoPath= {geo}
x= {x}
y= {y}
width= {width}
height= {height}
onMouseOut= {onMouseOut}
onMouseOver= {onMouseOver}
/>
{points}
</Chart>
, document.getElementById('blank-voronoi')
)
})()
<file_sep>"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Point = require('../../lib/index').Point;
var PointText = require('../../lib/index').PointText;
var Marker = require('../../lib/index').Marker;
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
// Example
(function() {
var width = 960,
height = 1160,
margins = {top: 20, right: 50, bottom: 20, left: 50};
var title = "test chart lib"
var uk = require('json!../data/uk.json');
var uk_points = topojson.feature(uk, uk.objects.places).features;
// data should be a MultiLineString
var data = topojson.feature(uk, uk.objects.places);
var scale = 1200 * 5;
var parallels = [50, 60]
var rotate = [4.4, 0]
var center = [0, 55.4]
var translate = [width / 2, height / 2];
var projection = 'albers';
var pointRadius = 2;
var text = function(d) { return d.properties.name; };
var x = function(d) { return d.geometry.coordinates[0] > -1 ? 6 : -6; }
var textAnchor = function(d) { return d.geometry.coordinates[0] > -1 ? "start" : "end"; }
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
parallels: parallels,
rotate: rotate,
center: center
});
var geo = geoPath(proj, {
pointRadius: pointRadius
});
var pointText = uk_points.map(function(d, i) {
return (
<PointText
key={i.text}
data={d}
projection= {proj}
text={text}
x={x}
textAnchor= {textAnchor}
/>
)
})
var points = data.features.map(function(d, i) {
return (
<g>
<Point
key= {i}
data= {d}
geoPath= {geo}
/>
<Marker
key= {i.i}
data= {d}
x= {+proj(d.geometry.coordinates)[0]}
y= {+proj(d.geometry.coordinates)[1]}
/>
</g>
)
})
ReactDOM.render(
<Chart
title= {title}
width= {width}
height= {height}
margins= {margins}
>
{points}
{pointText}
</Chart>
, document.getElementById('blank-point')
)
})()
<file_sep>// http://bl.ocks.org/mbostock/8ca036b3505121279daf
<file_sep>var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Sphere = require('../../lib/index').Sphere;
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
var Arc = require('../../lib/index').Arc;
// Example
// http://bl.ocks.org/mbostock/3757132
(function() {
var width = 960,
height = 720;
var title = "test chart lib"
var topodata = require('json!../data/world-50m.json');
// data should be a MultiLineString
var dataCountries = topojson.mesh(topodata, topodata.objects.countries, function(a, b) { return a !== b; });
var dataLand = topojson.feature(topodata, topodata.objects.land);
var css = require('./css/arc.css');
var scale = height / 2.1;
var translate = [width / 2, height / 2];
var clipAngle = 90;
var precision = .5;
var projection = 'orthographic';
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
clipAngle: clipAngle,
precision: precision
});
var geo = geoPath(proj);
var places = {
HNL: [(-157 - 55 / 60 - 21 / 3600), (21 + 19 / 60 + 07 / 3600)],
HKG: [(113 + 54 / 60 + 53 / 3600), (22 + 18 / 60 + 32 / 3600)],
SVO: [(37 + 24 / 60 + 53 / 3600), (55 + 58 / 60 + 22 / 3600)],
HAV: [(-82 - 24 / 60 - 33 / 3600), (22 + 59 / 60 + 21 / 3600)],
CCS: [(-66 - 59 / 60 - 26 / 3600), (10 + 36 / 60 + 11 / 3600)],
UIO: [(-78 - 21 / 60 - 31 / 3600), (0 + 06 / 60 + 48 / 3600)]
};
var route = {
type: "LineString",
coordinates: [
places.HNL,
places.HKG,
places.SVO,
places.HAV,
places.CCS,
places.UIO
]
};
var arc = (
<Arc
data= {route}
geoPath= {geo}
/>
)
ReactDOM.render(
<Chart
title= {title}
width= {width}
height= {height}
>
<Sphere
geoPath= {geo}
/>
{arc}
</Chart>
, document.getElementById('blank-sphere')
)
})()
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import d3 from 'd3';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Marker extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
markerClass: 'react-d3-map-core__marker'
}
static propTypes = {
data: PropTypes.object.isRequired,
markerClass: PropTypes.string,
onMouseOver: (d) => {},
onMouseOut: (d) => {},
onClick: (d) => {}
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkMarker(dom) {
const {
data,
markerClass,
x,
y,
onMouseOut,
onMouseOver,
onClick,
id
} = this.props;
var marker = d3.select(dom);
marker.append('image')
.datum(data)
.attr('class', `${markerClass} marker`)
.attr("xlinkHref", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAGmklEQVRYw7VXeUyTZxjvNnfELFuyIzOabermMZEeQC/OclkO49CpOHXOLJl/CAURuYbQi3KLgEhbrhZ1aDwmaoGqKII6odATmH/scDFbdC7LvFqOCc+e95s2VG50X/LLm/f4/Z7neY/ne18aANCmAr5E/xZf1uDOkTcGcWR6hl9247tT5U7Y6SNvWsKT63P58qbfeLJG8M5qcgTknrvvrdDbsT7Ml+tv82X6vVxJE33aRmgSyYtcWVMqX97Yv2JvW39UhRE2<KEY>)
.attr("x", x - (25 / 2))
.attr("y", y - (41))
.attr("height", 41)
.attr("width", 25)
marker.append('image')
.datum(data)
.attr('class', `${markerClass} marker-shadow`)
.attr("xlinkHref", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAC5ElEQVRYw+2YW4/TMBCF45S0S<KEY>
.attr("x", x - (25 / 2))
.attr("y", y - (41))
.attr("height", 41)
.attr("width", 41)
if(id)
marker.attr('id', id);
if(onMouseOver)
marker.on("mouseover", function (d, i) {return onMouseOver(this, data, x, y, i);})
if(onMouseOver)
marker.on("mouseout", function (d, i) {return onMouseOut(this, data, x, y, i);} )
if(onClick)
marker.on("click", function(d, i) { return onClick(this, data, x, y, i); })
return marker;
}
render () {
var markerGroup = ReactFauxDOM.createElement('g');
var chart = this._mkMarker(markerGroup)
return chart.node().toReact();
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes,
} from 'react';
export default class Tooltip extends Component {
constructor (props) {
super(props);
}
static defaultProps = {
gravity: 's',
dist: 10
}
_mkContent() {
const {
contentTooltip
} = this.props;
var cv = Object.keys(contentTooltip).map((d, i) => {
var trStyle = {
display: 'table-row',
backgroundImage: 'linear-gradient(#FFF, #EEE)',
padding: '3px',
height: '30px'
}
var tdStyle = {
display: 'table-cell',
padding: '3px',
verticalAlign: 'middle',
whiteSpace: 'normal',
border: '1px solid #D3D3D3',
maxWidth: '250px'
}
var tdHeadStyle = {
display: 'table-cell',
padding: '3px',
verticalAlign: 'middle',
whiteSpace: 'normal',
border: '1px solid #D3D3D3',
backgroundColor: '#555',
color: '#FFF',
textTransform: 'capitalize'
}
return (
<div className= "tooltip_tr" style={trStyle} key={i}>
<div className= "tooltip_td" style={tdHeadStyle} key={i}>
{d}
</div>
<div className= "tooltip_td" style={tdStyle} key={i.i}>
{contentTooltip[d].toString()}
</div>
</div>
)
})
return cv;
}
render() {
const {
xTooltip,
yTooltip,
contentTooltip,
dist
} = this.props;
var style = {
left: xTooltip? xTooltip + dist: -100,
top: yTooltip? yTooltip + dist: -100,
position: 'fixed'
}
if(contentTooltip) {
var cvContent = this._mkContent();
}
var tableStyle = {
display: 'table',
borderStyle: 'solid',
borderWidth: '1px',
boxSizing: 'border-box'
};
return (
<div
style= {style}
className= "react-d3-map-core__tooltip_utils"
ref= "tooltip"
>
<div className= "tooltip_table" style={tableStyle}>
{cvContent}
</div>
</div>
)
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import d3 from 'd3';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Arc extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
arcClass: 'react-d3-map-core__arc',
onMouseOver: (d) => {},
onMouseOut: (d) => {}
}
static propTypes = {
data: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]),
geoPath: PropTypes.func.isRequired,
arcClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkArc(dom) {
const {
data,
arcClass,
geoPath,
onMouseOut,
onMouseOver
} = this.props;
var arc = d3.select(dom);
// TODO: two points should transform to arc.
arc
.datum(data)
.attr('class', `${arcClass} arc`)
.attr("d", geoPath)
.on("mouseover", function (d, i) {return onMouseOver(this, d, i);})
.on("mouseout", function (d, i) {return onMouseOut(this, d, i);} )
return arc;
}
render () {
var arcGroup = ReactFauxDOM.createElement('path');
var chart = this._mkArc(arcGroup)
return chart.node().toReact();
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import d3 from 'd3';
import {
graticule
} from './utils/graticule';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Graticule extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
graticuleClass: 'react-d3-map-core__graticule'
}
static propTypes = {
geoPath: PropTypes.func.isRequired,
graticuleClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkGraticule(dom) {
const {
graticuleClass,
geoPath,
onMouseOut,
onMouseOver
} = this.props;
var grati = d3.select(dom)
grati
.datum(graticule(this.props))
.attr('class', `${graticuleClass} graticule`)
.attr('d', geoPath)
.style('fill', 'none')
.style('stroke', '#777')
.style('stroke-opacity', .5)
.style('stroke-width', '.5px')
if(onMouseOut)
grati.on("mouseover", function (d, i) {return onMouseOver(this, d, i);})
if(onMouseOver)
grati.on("mouseout", function (d, i) {return onMouseOut(this, d, i);} )
return grati;
}
render () {
var graticuleGroup = ReactFauxDOM.createElement('path');
var chart = this._mkGraticule(graticuleGroup);
return chart.node().toReact();
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import d3 from 'd3';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Polygon extends Component {
constructor(props) {
super (props);
}
static defaultProps = {
polygonClass: 'react-d3-map-core__polygon'
}
static propTypes = {
data: PropTypes.object.isRequired,
geoPath: PropTypes.func.isRequired,
polygonClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkPolygon(dom) {
const {
id,
data,
polygonClass,
geoPath,
onMouseOut,
onMouseOver,
onClick
} = this.props;
var polygon = d3.select(dom);
polygon
.datum(data)
.attr('class', `${polygonClass} polygon`)
.attr("d", geoPath);
if(id)
polygon.attr('id', id);
if(onMouseOver)
polygon.on("mouseover", function (d, i) {return onMouseOver(this, d, id);});
if(onMouseOut)
polygon.on("mouseout", function (d, i) {return onMouseOut(this, d, id);} );
if(onClick)
polygon.on("click", function (d, i) {return onClick(this, d, id);});
return polygon;
}
render () {
var poly = ReactFauxDOM.createElement('path');
var chart = this._mkPolygon(poly);
return chart.node().toReact();
}
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes
} from 'react';
import d3 from 'd3';
import {
default as ReactFauxDOM,
} from 'react-faux-dom';
import {
isTooltipUpdate
} from './utils/tooltipUpdate';
export default class Circle extends Component {
constructor(props) {
super(props);
}
static defaultProps = {
centroidClass: 'react-d3-map-core__centroid',
dy: '.35em',
onMouseOver: (d) => {},
onMouseOut: (d) => {}
}
static propTypes = {
data: PropTypes.object.isRequired,
geoPath: PropTypes.func.isRequired,
circleClass: PropTypes.string
}
shouldComponentUpdate(nextProps, nextState) {
return !isTooltipUpdate(nextProps, nextState, this);
}
_mkCircle(dom) {
const {
data,
circleClass,
geoPath,
r,
x,
y,
onMouseOut,
onMouseOver
} = this.props;
var circle = d3.select(dom);
circle
.datum(data)
.attr('class', `${circleClass} bubble`)
.attr("transform", (d) => { return `translate(${x}, ${y})`})
.attr("r", r)
.on("mouseover", function (d, i) {return onMouseOver(this, d, i);})
.on("mouseout", function (d, i) {return onMouseOut(this, d, i);})
return circle;
}
render() {
var circle = ReactFauxDOM.createElement('circle');
var chart = this._mkCircle(circle)
return chart.node().toReact();
}
}
<file_sep>"use strict";
import d3 from 'd3';
export function graticule(props) {
var graticule = d3.geo.graticule();
return graticule;
}
<file_sep>"use strict";
import {
default as React,
Component,
PropTypes,
} from 'react';
export default class Popup extends Component {
constructor (props) {
super(props);
}
static defaultProps = {
dist: 10,
width: 200
}
componentDidMount() {
this._updateHeight();
}
componentDidUpdate() {
this._updateHeight();
}
_updateHeight() {
const {
y
} = this.props;
var contentDOM = this.refs.popupContentWrapper;
var contentForeign = this.refs.popupContentForeignObject;
var closeForeign = this.refs.popupCloseBtnForeignObject;
contentForeign.setAttribute('y', y - contentDOM.clientHeight);
closeForeign.setAttribute('y', y - contentDOM.clientHeight + 5);
}
_mkContent() {
const {
contentPopup
} = this.props;
var popupContentStyle= {
backgroundColor: '#FFF',
margin: '13px 19px',
lineHeight: 1.4
}
return (
<div className="popup_content" style= {popupContentStyle}>
{contentPopup}
</div>
)
}
render() {
const {
x,
y,
contentPopup,
width,
closeClick,
id
} = this.props;
if(contentPopup) {
var cvContent = this._mkContent();
}
var popupGroupStyle = {
position: 'relative'
}
var closeStyle = {
padding: '4px 4px 0 0',
textAlign: 'center',
width: '18px',
height: '14px',
font: '16px/14px Tahoma, Verdana, sans-serif',
color: '#c3c3c3',
textDecoration: 'none',
fontWeight: 'bold',
background: 'transparent',
cursor: 'pointer'
}
var popupStyle = {
boxShadow: '0 3px 14px rgba(0,0,0,0.4)',
padding: '1px',
textAlign: 'center',
borderRadius: '12px',
backgroundColor: '#FFF',
width: 'auto'
};
var tipContainerStyle= {
margin: '0 auto',
width: '20px',
height: '20px'
}
var tipStyle= {
width: '17px',
padding: '1px'
}
return (
<g
className= "react-d3-map-core__popup_utils"
ref= "popup"
>
<foreignObject
ref="popupContentForeignObject"
x= {x - 23}
y= {y - 50}
width= {width}
height= {"100%"}
>
<div className= "react-d3-map-core__popup__content-wrapper" style={popupStyle} ref="popupContentWrapper">
{cvContent}
</div>
</foreignObject>
<foreignObject
ref="popupCloseBtnForeignObject"
x= {x - 20}
y= {y - 50}
width= {100}
height= {100}
>
<span className="react-d3-map-core__popup__close-button" onClick={closeClick} style={closeStyle} >×</span>
</foreignObject>
<foreignObject
x= {x - 7}
y= {y - 2}
width= {100}
height= {100}
>
<img className="react-d3-map-core__popup__tip" style= {tipStyle} src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAeCAYAAABuUU38AAAACXBIWXMAABYlAAAWJQFJUiTwAAAMK2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjarVd3VFN5t923JKGEXgSkhN4E6UWkd0FAOoyFkAQIhBBCgordcRgFxy4WrOioiKOOBZCxIOpgGwR7H9RBZWQcLNhQ+f4I4Izfe3+8td5vrZu1784+5+xz1l133QNoeHAlEhGpCRSKZdLEyB<KEY>"/>
</foreignObject>
</g>
)
}
}
<file_sep>"use strict";
import d3 from 'd3';
import {
default as tile
} from '../library/d3.geo.tile.js';
export function tileFunc (props) {
const {
scale,
translate,
size,
zoomDelta
} = props;
var tileFunc;
tileFunc = tile()
if(scale) tileFunc.scale(scale);
if(translate) tileFunc.translate(translate);
if(size) tileFunc.size(size);
if(zoomDelta) tileFunc.zoomDelta(zoomDelta);
return tileFunc();
}
<file_sep>"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var topojson = require('topojson');
var Chart = require('../../lib/index').Chart;
var Point = require('../../lib/index').Point;
var Popup = require('../../lib/index').Popup;
var Marker = require('../../lib/index').Marker;
var Popup = require('../../lib/index').Popup;
var Tile = require('../../lib/index').Tile;
var projectionFunc = require('../../lib/index').projection;
var geoPath = require('../../lib/index').geoPath;
var tileFunc = require('../../lib/index').tileFunc;
// Example
(function() {
var ChartPopup = React.createClass({
getInitialState: function() {
return {
xPopup: null,
yPopup: null,
contentPopup: null
}
},
onClick: function(dom, d, x, y) {
this.setState({
xPopup: x,
yPopup: y,
contentPopup: d.properties.name
})
},
_onMouseOut: function(dom, d, i) {
this.setState({
xPopup: null,
yPopup: null,
contentPopup: null
})
},
render: function() {
var width = 960,
height = 1160;
var uk = require('json!../data/uk.json');
var uk_points = topojson.feature(uk, uk.objects.places).features;
// data should be a MultiLineString
var data = topojson.feature(uk, uk.objects.places);
var scale = 1200 * 5;
var rotate = [4.4, 0]
var center = [0, 55.4]
var translate = [width / 2, height / 2];
var projection = 'mercator';
var pointRadius = 2;
var proj = projectionFunc({
projection: projection,
scale: scale,
translate: translate,
rotate: rotate,
center: center
});
var geo = geoPath(proj, {
pointRadius: pointRadius
});
var tiles = tileFunc({
scale: proj.scale() * 2 * Math.PI,
translate: proj([0, 0]),
size: ([width, height])
})
var x = function(d) { return +proj(d.geometry.coordinates)[0]; }
var y = function(d) { return +proj(d.geometry.coordinates)[1]; }
var onClick = this.onClick;
var points = data.features.map(function(d, i) {
return (
<g>
<Point
key= {i}
data= {d}
geoPath= {geo}
{...this.state}
/>
<Marker
key= {i.i}
data= {d}
x= {+proj(d.geometry.coordinates)[0]}
y= {+proj(d.geometry.coordinates)[1]}
onClick= {onClick}
/>
</g>
)
}.bind(this))
var popup = (<Popup
{...this.state}
/>);
return (
<div>
<Chart
width= {width}
height= {height}
{...this.state}
>
<Tile
tiles= {tiles}
/>
{points}
</Chart>
{popup}
</div>
)
}
})
ReactDOM.render(
<ChartPopup />
, document.getElementById('blank-popup')
)
})()
|
224b5e2b691f7d9af885bcbd1d52e963d257aff8
|
[
"JavaScript"
] | 23
|
JavaScript
|
jklinson/react-d3-map-core
|
e16a0b2dba102a4695499852c057f3cd7c2ed4a4
|
ab9479fe7f3d43c97172ad3b64dedd21aaceac4b
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
# ---------------------------------------------------------------
# This script uses the airsensors.py module to readout the bme280
# and senseair S8 sensor. The acquired data is saved to the user-
# defined database.
# ---------------------------------------------------------------
# Note: Please make sure that you have the airsensors.py in the
# same folder as this script.
import psycopg2
from psycopg2 import sql
from datetime import datetime
import time
from airsensors import sensors
class airqualityDB(object):
def __init__(self, dbname, table):
# Connecting to the Database
try:
self.conn = psycopg2.connect(database=dbname)
print("Connected to database")
except:
print("Could not connect to database")
self.cur = self.conn.cursor()
# Connecting to the desired Table
self.table = table
try:
self.cur.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier(self.table)))
print("Connected to table")
except:
print("Connection to table could not be established")
def add(self, date, temperature, humidity, co2):
# Addition of the new measurment to the Database
query = sql.SQL("""
INSERT INTO
{}
VALUES
(%s, %s, %s, %s)
""").format(sql.Identifier(self.table))
values = [date, temperature, humidity, co2]
self.cur.execute(query, values)
self.conn.commit()
print("{} Measurment has been added".format(self.cur.rowcount))
def show(self):
#Displaying the data
self.cur.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier(self.table)))
results = self.cur.fetchall()
for result in results:
print(result)
def close(self):
#closing the connection
self.conn.close()
if __name__=="__main__":
s=sensors()
db = airqualityDB("airquality", "avenue")
# change -> to a while loop and make the python script autostart
m=5
t_sleep = 1
for i in range(0, m):
# Measuring Co2, temperature and humidity
co2, temperature, humidity = s.read()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("{}/{}, {} {} ppm, {}°C, {}%".format(i+1, m, now, co2, temperature, humidity))
# Writing the Data into the Dataframe
db.add(now, temperature, humidity, co2)
# waiting until next measurment
time.sleep(t_sleep)
# Displaying all values
db.show()
# Displaying the
db.close()
<file_sep># Introduction
__Question:__
Do we really need to sleep with an open Window for better air quality ??
Is it not enough to open the window shortly to let some fresh air in and close it
afterwards before going to bed ?
__Background:__
Sleep quality is a highly researched topic and it has been shown that multiple factors
influence sleep quality such as drugs (Caffeine, Alcohol and Nicotine), noise and light.<sup>[1]</sup>
Another external factor which affects sleep quality is air quality. It has been shown that
the most potent respiratory stimuli is Carbon dioxid.<sup>[2,3,__4__]</sup>
__Aim:__
In order to analyse air quality in various conditions (closed doors, closed windows ...)
a Rasberry Pi 2 is combined with a CO<sub>2</sub>-Sensor (the Senseair S8 )
and a Temperature/Humidity/Pressure sensor (the Bme280).
This Project is a collaboration with <NAME>.
__References:__
[1] http://healthysleep.med.harvard.edu/healthy/
[2] <NAME>. "CO2, brainstem chemoreceptors and breathing." Progress in neurobiology 59.4 (1999): 299-331.
[3] <NAME>. "Respiratory and circulatory control during sleep." Journal of Experimental Biology 100.1 (1982): 223-244.
[4] Krimsky, <NAME>., and <NAME>. "Physiology of breathing and respiratory control during sleep." Seminars
in respiratory and critical care medicine. Vol. 26. No. 01. Copyright© 2005 by Thieme Medical Publishers, Inc., 333 Seventh
Avenue, New York, NY 10001, USA., 2005.
# Methods
## Setup Rasberry Pi 2:
<file_sep>#!/usr/bin/python
# ---------------------------------------------------------------
# This Python Script reads out bme280 and senseair s8 sensors on
# the Rasberry Pi3 for a (by User-defined) time. Once the data is
# collected, it is written to a .tab file and a Plot is generated.
# This script was written by <NAME> and <NAME>.
# ---------------------------------------------------------------
#
# In order to install pandas on linux systems:
# sudo apt-get install python3-pandas
# activate the interfaces for the sensors
#
# Temp-Sensor:
# sudo raspi-config
# -> Interfacing Options:
# ->activate i2c
#
# Co2-Sensor:
# sudo raspi-config
# -> Interfacing Options:
# ->activate serial
# -> "No" when it asks if you want a login shell over serial
# -> "Yes" when asked if you want hte hardware enabled
# -> "yes" to reboot
import time
import serial
import smbus
import numpy as np # only for the np.Nan (float; vs: None = object)
from ctypes import c_short
#from ctypes import c_byte
#from ctypes import c_ubyte
#from datetime import datetime
class bme280(object):
"""
This class allows to readout temperature, humidity and
pressure from the sensor bme280:
https://www.bosch-sensortec.com/bst/products/all_products/bme280
This class was generated based on a scirpt by <NAME>.
https://www.raspberrypi-spy.co.uk/
"""
def __init__(self):
self.DEVICE = 0x76 # Default device I2C address
self.bus = smbus.SMBus(1) # Rev 2 Pi, Pi 2 & Pi 3 uses bus 1
# Rev 1 Pi uses bus 0
try:
self.read()
print("Bme280 initialized")
except:
print("Bme280 not connected")
def getShort(self, data, index):
# return two bytes from data as a signed 16-bit value
return c_short((data[index+1] << 8) + data[index]).value
def getUShort(self, data, index):
# return two bytes from data as an unsigned 16-bit value
return (data[index+1] << 8) + data[index]
def getChar(self, data,index):
# return one byte from data as a signed char
result = data[index]
if result > 127:
result -= 256
return result
def getUChar(self, data,index):
# return one byte from data as an unsigned char
result = data[index] & 0xFF
return result
def readID(self):
# Chip ID Register Address
REG_ID = 0xD0
(chip_id, chip_version) = self.bus.read_i2c_block_data(self.DEVICE, REG_ID, 2)
return (chip_id, chip_version)
def read(self):
"""
This method returns temperature, pressure and humidity
returns: (float, float, float)
"""
# Register Addresses
REG_DATA = 0xF7
REG_CONTROL = 0xF4
REG_CONFIG = 0xF5
REG_CONTROL_HUM = 0xF2
REG_HUM_MSB = 0xFD
REG_HUM_LSB = 0xFE
# Oversample setting - page 27
OVERSAMPLE_TEMP = 2
OVERSAMPLE_PRES = 2
MODE = 1
# Oversample setting for humidity register - page 26
OVERSAMPLE_HUM = 2
self.bus.write_byte_data(self.DEVICE, REG_CONTROL_HUM, OVERSAMPLE_HUM)
control = OVERSAMPLE_TEMP<<5 | OVERSAMPLE_PRES<<2 | MODE
self.bus.write_byte_data(self.DEVICE, REG_CONTROL, control)
# Read blocks of calibration data from EEPROM
# See Page 22 data sheet
cal1 = self.bus.read_i2c_block_data(self.DEVICE, 0x88, 24)
cal2 = self.bus.read_i2c_block_data(self.DEVICE, 0xA1, 1)
cal3 = self.bus.read_i2c_block_data(self.DEVICE, 0xE1, 7)
# Convert byte data to word values
dig_T1 = self.getUShort(cal1, 0)
dig_T2 = self.getShort(cal1, 2)
dig_T3 = self.getShort(cal1, 4)
dig_P1 = self.getUShort(cal1, 6)
dig_P2 = self.getShort(cal1, 8)
dig_P3 = self.getShort(cal1, 10)
dig_P4 = self.getShort(cal1, 12)
dig_P5 = self.getShort(cal1, 14)
dig_P6 = self.getShort(cal1, 16)
dig_P7 = self.getShort(cal1, 18)
dig_P8 = self.getShort(cal1, 20)
dig_P9 = self.getShort(cal1, 22)
dig_H1 = self.getUChar(cal2, 0)
dig_H2 = self.getShort(cal3, 0)
dig_H3 = self.getUChar(cal3, 2)
dig_H4 = self.getChar(cal3, 3)
dig_H4 = (dig_H4 << 24) >> 20
dig_H4 = dig_H4 | (self.getChar(cal3, 4) & 0x0F)
dig_H5 = self.getChar(cal3, 5)
dig_H5 = (dig_H5 << 24) >> 20
dig_H5 = dig_H5 | (self.getUChar(cal3, 4) >> 4 & 0x0F)
dig_H6 = self.getChar(cal3, 6)
# Wait in ms (Datasheet Appendix B: Measurement time and current calculation)
wait_time = 1.25 + (2.3 * OVERSAMPLE_TEMP) + ((2.3 * OVERSAMPLE_PRES) + 0.575) + ((2.3 * OVERSAMPLE_HUM)+0.575)
time.sleep(wait_time/1000) # Wait the required time
# Read temperature/pressure/humidity
data = self.bus.read_i2c_block_data(self.DEVICE, REG_DATA, 8)
pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
hum_raw = (data[6] << 8) | data[7]
#Refine temperature
var1 = ((((temp_raw>>3)-(dig_T1<<1)))*(dig_T2)) >> 11
var2 = (((((temp_raw>>4) - (dig_T1)) * ((temp_raw>>4) - (dig_T1))) >> 12) * (dig_T3)) >> 14
t_fine = var1+var2
temperature = float(((t_fine * 5) + 128) >> 8);
# Refine pressure and adjust for temperature
var1 = t_fine / 2.0 - 64000.0
var2 = var1 * var1 * dig_P6 / 32768.0
var2 = var2 + var1 * dig_P5 * 2.0
var2 = var2 / 4.0 + dig_P4 * 65536.0
var1 = (dig_P3 * var1 * var1 / 524288.0 + dig_P2 * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * dig_P1
if var1 == 0:
pressure=0
else:
pressure = 1048576.0 - pres_raw
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = dig_P9 * pressure * pressure / 2147483648.0
var2 = pressure * dig_P8 / 32768.0
pressure = pressure + (var1 + var2 + dig_P7) / 16.0
# Refine humidity
humidity = t_fine - 76800.0
humidity = (hum_raw - (dig_H4 * 64.0 + dig_H5 / 16384.0 * humidity)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * humidity * (1.0 + dig_H3 / 67108864.0 * humidity)))
humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0)
if humidity > 100:
humidity = 100
elif humidity < 0:
humidity = 0
return temperature/100.0,pressure/100.0,humidity
class senseair(object):
"""
Class for Co2 sensor "senseair s8". It allows to readout the Co2 concentration.
Link ----
"""
def __init__(self):
self.ser = serial.Serial("/dev/ttyS0",baudrate =9600,timeout = 0.5)
try:
self.read()
print("Senseair S8 initialized")
except:
print("Senseair S8 not connected")
def read(self):
"""
This method returns the Co2 concentration in ppm
returns float
"""
self.ser.flushInput()
self.ser.write(b"\xFE\x44\x00\x08\x02\x9F\x25")
resp = self.ser.read(7)
high = resp[3]
low = resp[4]
co2 = (high*256) + low
return co2
class sensors(object):
def __init__(self):
#Initializing bme280
self.bme = bme280()
#Initializing sensair s8
self.senseair_s8 = senseair()
def read(self):
"""
Reads out both sensors. If no values are received, the values are set to None.
Returns Co2, Temperature and humidity
returns: (float, float, float)
"""
try:
co2=self.senseair_s8.read()
except:
co2 = np.nan
try:
temperature,pressure,humidity = self.bme.read()
humidity = round(humidity, 2)
except:
temperature, pressure, humidity = (np.nan, np.nan, np.nan)
return (co2, temperature, humidity)
if __name__=="__main__":
s=sensors()
co2, temperature, humidity = s.read()
print("{} ppm, {}°C, {}%".format(co2, temperature, humidity))
#now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#print("{} {} ppm, {}°C, {}%".format(now, co2, temperature, humidity))
<file_sep>#!/usr/bin/python3
# ---------------------------------------------------------------
# This Python Script reads out bme280 and senseair s8 sensors on
# the Rasberry Pi3 for a (by User-defined) time. Once the data is
# collected, it is written to a .tab file and a Plot is generated.
# This script was written by <NAME> and <NAME>.
# Note: Please make sure that you have the airsensors.py in the
# same folder as this script.
# ---------------------------------------------------------------
import os
import numpy as np # only for np.Nan values
import pandas as pd
import time
from datetime import datetime
from airsensors import sensors
import matplotlib.pyplot as plt
def setting_up_dataframe(columns):
"""
Sets up a dataframe with a timestamp index and the defined columns.
columns= List
"""
df = pd.DataFrame(columns=columns, index=pd.to_datetime([]))
return df
def harryplotter(df, outfilename):
"""
Plots the collected data.
df = pd.Dataframe
outfilename = filepath and Name
"""
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
f0 = df.iloc[:, 0].plot(ax=axes[0, 0])
f0.set_title("Temperature")
f0.set_xlabel("Time")
f0.set_ylabel("C")
f1 = df.iloc[:, 1].plot(ax=axes[0, 1])
f1.set_title("Humidity")
f1.set_xlabel("Time")
f1.set_ylabel("Humidity")
f2 = df.iloc[:, 2].plot(ax=axes[1, 0])
f2.set_title("Co2 concentration")
f2.set_xlabel("Time")
f2.set_ylabel("Co2 in ppm")
f3 = df.iloc[:, 0:3].plot(ax=axes[1, 1], logy=True)
f3.set_title("All measurments")
f3.set_xlabel("Time")
plt.tight_layout()
plt.savefig("{}_plots.pdf".format(outfilename))
def run_analysis():
# Settings:
try:
z = int(input("For how many minutes do you want to take the measurements? (in min, only int)\n>"))
except ValueError:
z = int(input("Please insert an integer!\n For how many minutes do you want to measure\n>"))
# The time intervall between each measurments
t_sleep = 1
m = int(z * 60 / t_sleep)
# Establishing the current folder:
directory = os.path.dirname(os.path.realpath(__file__))
# Defining name of the destination folder
dest = os.path.join(directory, "Measurments")
# Testing if destination folder exists - if not create
if not os.path.exists(dest):
os.mkdir(dest)
# Defining the outfilename
outfilename = os.path.join(dest, datetime.now().strftime("%Y_%m_%d-%H_%M_%S_Measurments"))
# setting up the Dataframe:
df = setting_up_dataframe(["temperature", "humidity", "Co2(ppm)"])
# Initializing sensors
s=sensors()
for i in range(0, m):
# Measuring Co2, temperature and humidity
co2, temperature, humidity = s.read()
# Writing the Data into the Dataframe
df.loc[pd.Timestamp('now').strftime("%Y-%m-%d %H:%M:%S")] = [temperature, humidity, co2]
#df.loc[pd.Timestamp('now')] = [temperature, humidity, co2]
# Producing a nice print statement:
print(df.iloc[:,:])
now = pd.Timestamp('now').strftime("%Y-%m-%d %H:%M:%S")
print("{}/{}, {} {} ppm, {}°C, {}%".format(i+1, m, now, co2, temperature, humidity))
# waiting until next measurment
time.sleep(t_sleep)
# writing the dataframe to an excel file
df.to_csv(outfilename + ".tab", sep='\t')
# plotting the data and saving
harryplotter(df, outfilename)
if __name__=="__main__":
# Let's run analysis
run_analysis()
|
1afa38e00ad72ee37da36ef66ba10d75f4425c93
|
[
"Markdown",
"Python"
] | 4
|
Python
|
EtienneEs/Co2-sensor
|
848529e5964f37848b87fb50ebbbeaf143fd947a
|
89ac9aa047e38ed8df34c75df39529f39275860f
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# Just a few tools
# These aren't strictly plot-related functions, but will be useful for user
# in the context of making plots.
#------------------------------------------------------------------------------#
import time
import numpy as np
from numbers import Number
from functools import wraps
from inspect import cleandoc
try:
from icecream import ic
except ImportError: # graceful fallback if IceCream isn't installed.
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
#------------------------------------------------------------------------------#
# Decorators
#------------------------------------------------------------------------------#
def docstring_fix(child):
"""
Decorator function for appending documentation from overridden method
onto the overriding method docstring.
Adapted from: https://stackoverflow.com/a/8101598/4970632
"""
for name,chfunc in vars(child).items(): # returns __dict__ object
if not callable(chfunc): # better! see: https://stackoverflow.com/a/624939/4970632
# if not isinstance(chfunc, FunctionType):
continue
for parent in getattr(child, '__bases__', ()):
parfunc = getattr(parent, name, None)
if not getattr(parfunc, '__doc__', None):
continue
if not getattr(chfunc, '__doc__', None):
chfunc.__doc__ = '' # in case it's None
cmessage = f'Full name: {parfunc.__qualname__}()'
pmessage = f'Parent method (documentation below): {chfunc.__qualname__}()'
chfunc.__doc__ = f'\n{cmessage}\n{cleandoc(chfunc.__doc__)}\n{pmessage}\n{cleandoc(parfunc.__doc__)}'
break # only do this for the first parent class
return child
def fancy_decorator(decorator):
"""
Normally to make a decorator that accepts arguments, you have to create
3 nested function definitions. This abstracts that away -- if you decorate
your decorator-function declaration with this, the decorator will now accept arguments.
See: https://stackoverflow.com/a/1594484/4970632
"""
@wraps(decorator)
def decorator_maker(*args, **kwargs):
def decorator_wrapper(func):
return decorator(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
def timer(func):
"""
A decorator that prints the time a function takes to execute.
See: https://stackoverflow.com/a/1594484/4970632
"""
@wraps(func)
def decorator(*args, **kwargs):
t = time.clock()
print(f'{func.__name__}()')
res = func(*args, **kwargs)
print(f'{func.__name__}() time: {time.clock()-t}s')
return res
return decorator
def logger(func):
"""
A decorator that logs the activity of the script (it actually just prints it,
but it could be logging!)
See: https://stackoverflow.com/a/1594484/4970632
"""
@wraps(func)
def decorator(*args, **kwargs):
res = func(*args, **kwargs)
print(f'{func.__name__} called with: {args} {kwargs}')
return res
return decorator
def counter(func):
"""
A decorator that counts and prints the number of times a function
has been executed.
See: https://stackoverflow.com/a/1594484/4970632
"""
@wraps(func)
def decorator(*args, **kwargs):
# decorator.count += 1
t = time.clock()
res = func(*args, **kwargs)
decorator.time += (time.clock() - t)
decorator.count += 1
print(f'{func.__name__} cumulative time: {decorator.time}s ({decorator.count} calls)')
# print(f'{func.__name__} has been used: {decorator.count}x')
return res
decorator.time = 0
decorator.count = 0 # initialize
return decorator
#------------------------------------------------------------------------------#
# Helper stuff
#------------------------------------------------------------------------------#
_fill = (lambda x,y: x if x is not None else y)
class _dot_dict(dict):
"""
Simple class for accessing elements with dot notation.
See: https://stackoverflow.com/a/23689767/4970632
"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def isnumber(item):
"""
Just test if number.
See: https://stackoverflow.com/questions/4187185/how-can-i-check-if-my-python-object-is-a-number
Note: Numpy numbers have __getitem__ attribute! So cannot test this.
Why is this done? So they can be converted to ND singleton numpy arrays
easily with number[None,None,...].
"""
return isinstance(item, Number)
def isvector(item):
"""
Just test if is iterable, but not a string (we almost never mean this).
"""
# return hasattr(item, '__iter__') and not isinstance(item, str)
return np.iterable(item) and not isinstance(item, str)
#------------------------------------------------------------------------------#
# Accessible for user
#------------------------------------------------------------------------------#
def arange(min_, *args):
"""
Duplicate behavior of np.arange, except with inclusive endpoints; dtype is
controlled very carefully, so should be 'most precise' among min/max/step args.
Input:
stop
start, stop, [step]
Just like np.arange!
Output:
The array sequence.
"""
# Optional arguments just like np.arange
if len(args)==0:
max_ = min_
min_ = 0 # this re-assignes the NAME "min_" to 0
step = 1
elif len(args)==1:
max_ = args[0]
step = 1
elif len(args)==2:
max_ = args[0]
step = args[1]
else:
raise ValueError('Function takes from one to three arguments.')
# All input is integer? Get new "max"
if min_//1==min_ and max_//1==max_ and step//1==step:
min_, max_, step = np.int64(min_), np.int64(max_), np.int64(step)
max_ += 1
# Input is float or mixed; cast all to float64, then get new "max"
else:
# Get the next FLOATING POINT, in direction of the second argument
# Forget this; round-off errors from continually adding step to min mess this up
# max_ = np.nextafter(max_, np.finfo(np.dtype(np.float64)).max)
min_, max_, step = np.float64(min_), np.float64(max_), np.float64(step)
max_ += step/2
return np.arange(min_, max_, step)
def edges(values, axis=-1):
"""
Get approximate edge values along arbitrary axis.
"""
# First permute
values = np.array(values)
values = np.swapaxes(values, axis, -1)
# Next operate
flip = False
if values[...,1]<values[...,0]:
flip = True
values = np.flip(values, axis=-1)
values = np.concatenate((
values[...,:1] - (values[...,1]-values[...,0])/2,
(values[...,1:] + values[...,:-1])/2,
values[...,-1:] + (values[...,-1]-values[...,-2])/2,
), axis=-1)
if flip:
values = np.flip(values, axis=-1)
# Permute back and return
values = np.swapaxes(values, axis, -1)
return values
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# Note colormaps are *callable*, will just deliver the corresponding color, easy.
# Notes on different colorspaces:
# * HCL is perfectly perceptually uniform, always. But some colors in the
# range [0,360], [0,100], [0,100] are impossible.
# * HSL fixes this by, for *every hue and luminance*, designating 100 as
# the maximum *possible* valid chroma. This makes it suitable for
# single hue colormaps.
# * HPL fixes this by, for *every luminance*, designating 100 as
# the *minimum* max chroma across *every hue for that luminance*. This
# makes it more suitable for multi-hue colormaps.
#------------------------------------------------------------------------------#
# Notes on 'channel-wise alpha':
# * Colormaps generated from HCL space (and cmOcean ones) are indeed perfectly
# perceptually uniform, but this still looks bad sometimes -- usually we
# *want* to focus on the *extremes*, so want to weight colors more heavily
# on the brighters/whiter part of the map! That's what the ColdHot map does,
# it's what most of the ColorBrewer maps do, and it's what ColorWizard does.
# * By default extremes are stored at end of *lookup table*, not as
# separate RGBA values (so look under cmap._lut, indexes cmap._i_over and
# cmap._i_under). You can verify that your cmap is using most extreme values
# by comparing high-resolution one to low-resolution one.
#------------------------------------------------------------------------------#
# Potential bottleneck, loading all this stuff?
# NO. Try using @timer on register functions, turns out worst is colormap
# one at 0.1 seconds. Just happens to be a big package, takes a bit to compile
# to bytecode (done every time module changed) then import.
#------------------------------------------------------------------------------#
# Here's some useful info on colorspaces
# https://en.wikipedia.org/wiki/HSL_and_HSV
# http://www.hclwizard.org/color-scheme/
# http://www.hsluv.org/comparison/ compares lch, hsluv (scaled lch), and hpluv (truncated lch)
# Info on the CIE conventions
# https://en.wikipedia.org/wiki/CIE_1931_color_space
# https://en.wikipedia.org/wiki/CIELUV
# https://en.wikipedia.org/wiki/CIELAB_color_space
# And some useful tools for creating colormaps and cycles
# https://nrlmry.navy.mil/TC.html
# http://help.mail.colostate.edu/tt_o365_imap.aspx
# http://schumacher.atmos.colostate.edu/resources/archivewx.php
# https://coolors.co/
# http://tristen.ca/hcl-picker/#/hlc/12/0.99/C6F67D/0B2026
# http://gka.github.io/palettes/#diverging|c0=darkred,deeppink,lightyellow|c1=lightyellow,lightgreen,teal|steps=13|bez0=1|bez1=1|coL0=1|coL1=1
# https://flowingdata.com/tag/color/
# http://tools.medialab.sciences-po.fr/iwanthue/index.php
# https://learntocodewith.me/posts/color-palette-tools/
#------------------------------------------------------------------------------
import os
import re
import numpy as np
import numpy.ma as ma
import matplotlib.colors as mcolors
import matplotlib.cm as mcm
from matplotlib import rcParams
from cycler import cycler
from glob import glob
from . import colormath
from . import utils
from .utils import _fill, ic
_data = f'{os.path.dirname(__file__)}' # or parent, but that makes pip install distribution hard
# Define some new palettes
# Note the default listed colormaps
_cycles_cmap = ['Set1', 'Set2', 'Set3', 'Set4', 'Set5']
_cycles_list = {
# default matplotlib v2
'default': ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],
# copied from stylesheets; stylesheets just add color themese from every possible tool, not already present as a colormap
'538': ['#008fd5', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#810f7c'],
'ggplot': ['#E24A33', '#348ABD', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8'],
# the default seaborn ones (excluded deep/muted/bright because thought they were unappealing)
'colorblind': ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#F0E442', '#56B4E9'],
'colorblind10': ["#0173B2", "#DE8F05", "#029E73", "#D55E00", "#CC78BC", "#CA9161", "#FBAFE4", "#949494", "#ECE133", "#56B4E9"], # versions with more colors
# from the website
'flatui': ["#3498db", "#e74c3c", "#95a5a6", "#34495e", "#2ecc71", "#9b59b6"],
# created with online tools; add to this
# see: http://tools.medialab.sciences-po.fr/iwanthue/index.php
'cinematic': [(51,92,103), (158,42,43), (255,243,176), (224,159,62), (84,11,14)],
'cool': ["#6C464F", "#9E768F", "#9FA4C4", "#B3CDD1", "#C7F0BD"],
'sugar': ["#007EA7", "#B4654A", "#80CED7", "#B3CDD1", "#003249"],
'vibrant': ["#007EA7", "#D81159", "#B3CDD1", "#FFBC42", "#0496FF"],
'office': ["#252323", "#70798C", "#DAD2BC", "#F5F1ED", "#A99985"],
'industrial': ["#38302E", "#6F6866", "#788585", "#BABF95", "#CCDAD1"],
'tropical': ["#0D3B66", "#F95738", "#F4D35E", "#FAF0CA", "#EE964B"],
'intersection': ["#2B4162", "#FA9F42", "#E0E0E2", "#A21817", "#0B6E4F"],
'field': ["#23395B", "#D81E5B", "#FFFD98", "#B9E3C6", "#59C9A5"],
}
# Color stuff
# Keep major color names, and combinations of those names
_distinct_colors_space = 'hsl' # register colors distinct in this space?
_distinct_colors_threshold = 0.07
_distinct_colors_exceptions = [
'white', 'black', 'gray', 'red', 'pink', 'grape',
'sky blue',
'violet', 'indigo', 'blue',
'coral', 'tomato red', 'crimson',
'cyan', 'teal', 'green', 'lime', 'yellow', 'orange',
'red orange', 'yellow orange', 'yellow green', 'blue green',
'blue violet', 'red violet',
]
_space_aliases = {
'rgb': 'rgb',
'hsv': 'hsv',
'hpl': 'hpl',
'hpluv': 'hpl',
'hsl': 'hsl',
'hsluv': 'hsl',
'hcl': 'hcl',
'lch': 'hcl',
}
# Names of builtin colormaps
_cmap_categories = { # initialize as empty lists
# We keep these ones
'Matplotlib Originals':
['viridis', 'plasma', 'inferno', 'magma', 'twilight', 'twilight_shifted'],
'ProPlot Sequential':
[ 'Glacial',
'Bog',
# 'Wood',
'Lake', 'Sea', 'Verdant', 'Forest',
'Blood',
'Fire', 'Golden', 'Sunrise', 'Sunset',
],
# 'Vibrant'], # empty at first, fill automatically
'ProPlot Diverging':
['ColdHot', 'NegPos', 'DryWet', 'Water'],
'cmOcean Sequential':
['Gray', 'Oxy', 'Thermal', 'Haline', 'Ice', 'Dense',
'Deep', 'Algae', 'Tempo', 'Speed', 'Matter', 'Turbid',
'Amp', 'Solar', 'Phase', 'Phase_shifted'],
'cmOcean Diverging':
['Balance', 'Curl', 'Delta'],
# 'OpenColors':
# ['OpenGray', 'OpenRed', 'OpenPink', 'OpenGrape', 'OpenViolet', 'OpenIndigo',
# 'OpenBlue', 'OpenCyan', 'OpenTeal', 'OpenGreen', 'OpenLime',
# 'OpenYellow', 'OpenOrange'],
'ColorBrewer2.0 Sequential':
# ['Greys',
['Grays',
'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'],
'ColorBrewer2.0 Diverging':
['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral'],
'Other':
['cubehelix', 'bwr'],
# ['cubehelix', 'rainbow', 'bwr'],
# These ones will be deleted
'Alt Sequential':
sorted(['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'coolwarm', 'seismic', # diverging ones
'afmhot', 'gist_heat', 'copper']),
'Alt Rainbow':
sorted(['multi', 'cubehelix', 'cividis']),
'Alt Diverging':
sorted(['coolwarm', 'bwr', 'seismic']),
'Miscellaneous':
sorted(['flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'brg', 'hsv', 'hot', 'rainbow',
'gist_rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])}
# Categories to ignore/*delete* from dictionary because they suck donkey balls
_cmap_categories_delete = ['Alt Diverging', 'Alt Sequential', 'Alt Rainbow', 'Miscellaneous']
# Default number of colors
_N_hires = 256
#------------------------------------------------------------------------------#
# More generalized utility for retrieving colors
#------------------------------------------------------------------------------#
def get_space(space):
"""
Verify requested colorspace is valid.
"""
space = _space_aliases.get(space, None)
if space is None:
raise ValueError(f'Unknown colorspace "{space}".')
return space
def to_rgb(color, space='rgb'):
"""
Generalization of mcolors.to_rgb to translate color tuple
from any colorspace to rgb. Also will convert color strings to tuple.
"""
# First the RGB input
# NOTE: Need isinstance here because strings stored in numpy arrays
# are actually subclasses thereof!
if isinstance(color, str):
try:
color = mcolors.to_rgb(color) # ensure is valid color
except Exception:
raise ValueError(f'Invalid RGBA argument {color}. Registered colors are: {", ".join(mcolors._colors_full_map.keys())}.')
elif space=='rgb':
color = color[:3] # trim alpha
if any(c>1 for c in color):
color = [c/255 for c in color] # scale to within 0-1
# Next the perceptually uniform versions
elif space=='hsv':
color = colormath.hsl_to_rgb(*color)
elif space=='hpl':
color = colormath.hpluv_to_rgb(*color)
elif space=='hsl':
color = colormath.hsluv_to_rgb(*color)
elif space=='hcl':
color = colormath.hcl_to_rgb(*color)
elif space=='rgb':
color = color[:3] # trim alpha
if any(c>1 for c in color):
color = [c/255 for c in color] # scale to within 0-1
else:
raise ValueError('Invalid RGB value.')
return color
def to_xyz(color, space):
"""
Inverse of above, translate to some colorspace.
"""
# Run tuple conversions
# NOTE: Don't pass color tuple, because we may want to permit out-of-bounds RGB values to invert conversion
if isinstance(color, str):
color = mcolors.to_rgb(color) # convert string
else:
color = color[:3]
if space=='hsv':
color = colormath.rgb_to_hsl(*color) # rgb_to_hsv would also work
elif space=='hpl':
color = colormath.rgb_to_hpluv(*color)
elif space=='hsl':
color = colormath.rgb_to_hsluv(*color)
elif space=='hcl':
color = colormath.rgb_to_hcl(*color)
elif space=='rgb':
color = color # do nothing
else:
raise ValueError(f'Invalid colorspace {space}.')
return color
def add_alpha(color):
"""
Ensures presence of alpha channel.
"""
if not utils.isvector(color):
raise ValueError('Input must be color tuple.')
if len(color)==3:
color = [*color, 1.0]
elif len(color)==4:
color = [*color] # copy, and put into list
else:
raise ValueError(f'Tuple length must be 3 or 4, got {len(color)}.')
return color
def get_channel_value(color, channel, space='hsl'):
"""
Gets hue, saturation, or luminance channel value from registered
string color name.
Arguments
---------
color :
scalar numeric ranging from 0-1, or string color name, optionally
with offset specified as '+x' or '-x' at the end of the string for
arbitrary float x.
channel :
channel number or name (e.g., 0, 1, 2, 'h', 's', 'l')
"""
# Interpret channel
channel_idxs = {'hue': 0, 'saturation': 1, 'chroma': 1, 'luminance': 2,
'alpha': 3, 'h': 0, 's': 1, 'c': 1, 'l': 2}
channel = channel_idxs.get(channel, channel)
if callable(color) or utils.isnumber(color):
return color
if channel not in (0,1,2):
raise ValueError('Channel must be in [0,1,2].')
# Interpret string or RGB tuple
offset = 0
if isinstance(color, str):
regex = '([-+]\S*)$' # user can optionally offset from color; don't filter to just numbers, want to raise our own error if user messes up
match = re.search(regex, color)
if match:
try:
offset = float(match.group(0))
except ValueError:
raise ValueError(f'Invalid channel identifier "{color}".')
color = color[:match.start()]
return offset + to_xyz(to_rgb(color, 'rgb'), space)[channel]
#------------------------------------------------------------------------------#
# Generalized colormap/cycle constructors
#------------------------------------------------------------------------------#
def colormap(*args, extend='both',
left=None, right=None, x=None, # optionally truncate color range by these indices
ratios=1, reverse=False,
gamma=None, gamma1=None, gamma2=None,
name=None, register=False, save=False, N=None, **kwargs):
"""
Convenience function for generating colormaps in a variety of ways.
The 'extend' property will be used to resample LinearSegmentedColormap
if we don't intend to use both out-of-bounds colors; otherwise we lose
the strongest colors at either end of the colormap.
You can still use extend='neither' in colormap() call with extend='both'
in contour or colorbar call, just means that colors at ends of the main
region will be same as out-of-bounds colors.
Notes on Resampling
-------------------
From answer: see https://stackoverflow.com/q/48613920/4970632
This resampling method is awful! All it does is reduce the
lookup table size -- what ends up happening under the hood is matplotlib
tries to *evenly* draw N-1 ('min'/'max') or N-2 ('neither') colors from
a lookup table with N colors, which means it simply *skips over* 1 or
2 colors in the middle of the lookup table, which will cause visual jumps!
Segment data is completely divorced from the number of levels; can
have many high-res segments with colormap N very small.
"""
# Turns out pcolormesh makes QuadMesh, which itself is a Collection,
# which itself gets colors when calling draw() using update_scalarmappable(),
# which itself uses to_rgba() to get facecolors, which itself is an inherited
# ScalarMappable method that simply calls the colormap with numbers. Anyway
# the issue *has* to be with pcolor, because when giving pcolor an actual
# instance, no longer does that thing where final levels equal extensions.
# Since collection API does nothing to underlying data or cmap, must be
# something done by pcolormesh function.
_N = N or _N_hires
_cmaps = []
name = name or 'custom' # must have name, mcolors utilities expect this
if len(args)==0:
args = [rcParams['image.cmap']] # use default
for cmap in args:
# Retrieve Colormap instance
# Also make sure you reset the lookup table (get_cmap does this
# by calling _resample).
if not cmap:
cmap = rcParams['image.cmap']
if isinstance(cmap,str) and cmap in mcm.cmap_d:
cmap = mcm.cmap_d[cmap]
if isinstance(cmap, mcolors.LinearSegmentedColormap):
cmap = cmap._resample(_N)
if isinstance(cmap, mcolors.Colormap):
# Allow gamma override, otherwise do nothing
if isinstance(cmap, PerceptuallyUniformColormap):
if gamma and not gamma1 and not gamma2:
gamma1 = gamma2 = gamma
if gamma1 or gamma2:
segmentdata = cmap._segmentdata.copy()
if gamma1:
segmentdata['gamma1'] = gamma1
if gamma2:
segmentdata['gamma2'] = gamma2
cmap = type(cmap)(cmap.name, segmentdata, space=cmap.space, mask=cmap.mask)
elif isinstance(cmap, mcolors.LinearSegmentedColormap):
if gamma:
cmap._gamma = gamma
cmap._init()
elif isinstance(cmap, dict):
# Dictionary of hue/sat/luminance values or 2-tuples representing linear transition
save = cmap.pop('save', save)
name = cmap.pop('name', name)
for key in cmap:
if key in kwargs:
print(f'Warning: Got duplicate keys "{key}" in cmap dictionary ({cmap[key]}) and in keyword args ({kwargs[key]}). Using first one.')
kw = kwargs.update
cmap = PerceptuallyUniformColormap.from_hsl(name, N=_N, **{**kwargs, **cmap})
elif not isinstance(cmap, str):
# List of colors
cmap = mcolors.ListedColormap(cmap, name=name, **kwargs)
else:
# Monochrome colormap based from input color (i.e. single hue)
regex = '([0-9].)$'
match = re.search(regex, cmap) # declare options with _[flags]
cmap = re.sub(regex, '', cmap) # remove options
fade = kwargs.pop('fade',90) if not match else match.group(1) # default fade to 90 luminance
# Build colormap
cmap = to_rgb(cmap) # to ensure is hex code/registered color
cmap = monochrome_cmap(cmap, fade, name=name, N=_N, **kwargs)
_cmaps += [cmap]
# Now merge the result of this arbitrary user input
# Since we are merging cmaps, potentially *many* color transitions; use big number by default
if len(_cmaps)>1:
N_merge = _N*len(_cmaps)
cmap = merge_cmaps(*_cmaps, name=name, ratios=ratios, N=N_merge)
# Reverse
if reverse:
cmap = cmap.reversed()
# Optionally clip edges or resample map.
try:
left, right = x
except TypeError:
pass
if isinstance(cmap, mcolors.ListedColormap):
slicer = None
if left is not None or right is not None:
slicer = slice(left,right)
elif N is not None:
slicer = slice(None,N)
# Just sample indices for listed maps
if slicer:
slicer = slice(left,right)
try:
cmap = mcolors.ListedColormap(cmap.colors[slicer])
except Exception:
raise ValueError(f'Invalid indices {slicer} for listed colormap.')
elif left is not None or right is not None:
# Trickier for segment data maps
# First get segmentdata and parse input
kw = {}
olddata = cmap._segmentdata
newdata = {}
if left is None:
left = 0
if right is None:
right = 1
if hasattr(cmap, 'space'):
kw['space'] = cmap.space
# Next resample the segmentdata arrays
for key,xyy in olddata.items():
if key in ('gamma1', 'gamma2'):
newdata[key] = xyy
continue
xyy = np.array(xyy)
x = xyy[:,0]
xleft, = np.where(x>left)
xright, = np.where(x<right)
if len(xleft)==0:
raise ValueError(f'Invalid x minimum {left}.')
if len(xright)==0:
raise ValueError(f'Invalid x maximum {right}.')
l, r = xleft[0], xright[-1]
newxyy = xyy[l:r+1,:].copy()
if l>0:
xl = xyy[l-1,1:] + (left - x[l-1])*(xyy[l,1:] - xyy[l-1,1:])/(x[l] - x[l-1])
newxyy = np.concatenate(([[left, *xl]], newxyy), axis=0)
if r<len(x)-1:
xr = xyy[r,1:] + (right - x[r])*(xyy[r+1,1:] - xyy[r,1:])/(x[r+1] - x[r])
newxyy = np.concatenate((newxyy, [[right, *xr]]), axis=0)
newxyy[:,0] = (newxyy[:,0] - left)/(right - left)
newdata[key] = newxyy
# And finally rebuild map
cmap = type(cmap)(cmap.name, newdata, **kw)
if isinstance(cmap, mcolors.LinearSegmentedColormap) and N is not None:
# Perform a crude resampling of the data, i.e. just generate a
# low-resolution lookup table instead
# NOTE: All this does is create a new colormap with *attribute* N levels,
# for which '_lut' attribute has not been generated yet.
offset = {'neither':-1, 'max':0, 'min':0, 'both':1}
if extend not in offset:
raise ValueError(f'Unknown extend option {extend}.')
cmap = cmap._resample(N - offset[extend]) # see mcm.get_cmap source
# Optionally register a colormap
if name and register:
print(name, 'Registering')
if name.lower() in [cat_cmap.lower() for cat,cat_cmaps in _cmap_categories.items()
for cat_cmap in cat_cmaps if 'ProPlot' not in cat]:
print(f'Warning: Overwriting existing colormap "{name}".')
# raise ValueError(f'Builtin colormap "{name}" already exists. Choose a different name.')
elif name in mcm.cmap_d:
pass # no warning necessary
# print(f'Warning: Overwriting existing colormap "{name}".')
mcm.cmap_d[name] = cmap
mcm.cmap_d[name+'_r'] = cmap.reversed()
if re.search('[A-Z]',name):
mcm.cmap_d[name.lower()] = cmap
mcm.cmap_d[name.lower()+'_r'] = cmap.reversed()
# print(f'Registered name {name}.') # not necessary
# Optionally save colormap to disk
if name and save:
# Save segment data directly
basename = f'{cmap.name}.npy'
filename = f'{_data}/cmaps/{basename}'
np.save(filename, dict(cmap._segmentdata, space=cmap.space))
print(f'Saved colormap to "{basename}".')
# Save list of hex colors
# basename = f'{cmap.name}.hex'
# with open(filename, 'w') as h: # overwrites if exists; otherwise us 'a'
# h.write(','.join(mcolors.to_hex(cmap(i)) for i in np.linspace(0,1,cmap.N)))
return cmap
def colors(*args, vmin=0, vmax=1, **kwargs):
"""
Convenience function to draw colors from arbitrary ListedColormap or
LinearSegmentedColormap.
In the latter case, we will draw samples from that colormap by (default)
drawing from Use vmin/vmax to scale your samples.
"""
samples = 10
# Two modes:
# 1) User inputs some number of samples; 99% of time, use this
# to get samples from a LinearSegmentedColormap
# draw colors.
if utils.isnumber(args[-1]) or utils.isvector(args[-1]):
args, samples = args[:-1], args[-1]
# 2) User inputs a simple list; 99% of time, use this
# to build up a simple ListedColormap.
elif len(args)>1:
args = [args] # presumably send a list of colors
cmap = colormap(*args, **kwargs) # the cmap object itself
if isinstance(cmap, mcolors.ListedColormap):
# Just get the colors
colors = cmap.colors
elif isinstance(cmap, mcolors.LinearSegmentedColormap): # or subclass
# Employ ***more flexible*** version of get_cmap() method, which does this:
# LinearSegmentedColormap(self.name, self._segmentdata, lutsize)
if utils.isnumber(samples):
# samples = np.linspace(0, 1-1/nsample, nsample) # from 'centers'
samples = np.linspace(0, 1, samples) # from edge to edge
elif utils.isvector(samples):
samples = np.array(samples)
else:
raise ValueError(f'Invalid samples "{samples}". If you\'re building '
'a colormap on-the-fly, input must be [*args, '
'samples] where *args are passed to the colormap() constructor '
'and "samples" is either the number of samples desired '
'or a vector of colormap samples within [0,1].')
colors = cmap((samples-vmin)/(vmax-vmin))
else:
raise ValueError(f'Colormap returned weird object type: {type(cmap)}.')
return colors
def cycle(*args, **kwargs):
"""
Simple alias.
"""
return colors(*args, **kwargs)
class PerceptuallyUniformColormap(mcolors.LinearSegmentedColormap):
"""
Generate LinearSegmentedColormap in perceptually uniform colorspace --
i.e. either HSLuv, HCL, or HPLuv. Adds handy feature where *channel
value for string-name color is looked up*.
Example
-------
dict(hue = [[0, 'red', 'red'], [1, 'blue', 'blue']],
saturation = [[0, 1, 1], [1, 1, 1]],
luminance = [[0, 1, 1], [1, 0.2, 0.2]])
"""
def __init__(self, name, segmentdata,
space='hsl', gamma=None, gamma1=None, gamma2=None,
mask=False, **kwargs):
"""
Initialize with dictionary of values. Note that hues should lie in
range [0,360], saturation/luminance in range [0,100].
Arguments
---------
mask :
Whether to mask out-of-range colors as black, or just clip
the RGB values (distinct from colormap clipping the extremes).
gamma1 :
Raise the line used to transition from a low chroma value (x=0)
to a higher chroma value (x=1) by this power, like HCLWizard.
gamma2 :
Raise the line used to transition from a high luminance value (x=0)
to a lower luminance value (x=1) by this power, like HCLWizard.
Why change the direction of transition depending on which value is
bigger? Because makes it much easier to e.g. weight the center of
a diverging colormap.
"""
# Attributes
# NOTE: Don't allow power scaling for hue because that would be weird.
# Idea is want to allow skewing so dark/saturated colors are
# more isolated/have greater intensity.
# NOTE: We add gammas to the segmentdata dictionary so it can be
# pickled into .npy file
space = get_space(space)
if 'gamma' in kwargs:
raise ValueError('Standard gamma scaling disabled. Use gamma1 or gamma2 instead.')
gamma1 = _fill(gamma, gamma1)
gamma2 = _fill(gamma, gamma2)
segmentdata['gamma1'] = _fill(gamma1, _fill(segmentdata.get('gamma1', None), 1.0))
segmentdata['gamma2'] = _fill(gamma2, _fill(segmentdata.get('gamma2', None), 1.0))
self.space = space
self.mask = mask
# First sanitize the segmentdata by converting color strings to their
# corresponding channel values
keys = {*segmentdata.keys()}
target = {'hue', 'saturation', 'luminance', 'gamma1', 'gamma2'}
if keys != target and keys != {*target, 'alpha'}:
raise ValueError(f'Invalid segmentdata dictionary with keys {keys}.')
for key,array in segmentdata.items():
# Allow specification of channels using registered string color names
if 'gamma' in key:
continue
if callable(array):
continue
for i,xyy in enumerate(array):
xyy = list(xyy) # make copy!
for j,y in enumerate(xyy[1:]): # modify the y values
xyy[j+1] = get_channel_value(y, key, space)
segmentdata[key][i] = xyy
# Initialize
# NOTE: Our gamma1 and gamma2 scaling is just fancy per-channel
# gamma scaling, so disable the standard version.
super().__init__(name, segmentdata, gamma=1.0, **kwargs)
def reversed(self, name=None):
"""
Reverse colormap.
"""
if name is None:
name = self.name + '_r'
def factory(dat):
def func_r(x):
return dat(1.0 - x)
return func_r
data_r = {}
for key,xyy in self._segmentdata.items():
if key in ('gamma1', 'gamma2', 'space'):
if 'gamma' in key: # optional per-segment gamma
xyy = np.atleast_1d(xyy)[::-1]
data_r[key] = xyy
continue
elif callable(xyy):
data_r[key] = factory(xyy)
else:
data_r[key] = [[1.0 - x, y1, y0] for x, y0, y1 in reversed(xyy)]
return PerceptuallyUniformColormap(name, data_r, space=self.space)
def _init(self):
"""
As with LinearSegmentedColormap, but convert each value
in the lookup table from 'input' to RGB.
"""
# First generate the lookup table
channels = ('hue','saturation','luminance')
reverse = (False, False, True) # gamma weights *low chroma* and *high luminance*
gammas = (1.0, self._segmentdata['gamma1'], self._segmentdata['gamma2'])
self._lut_hsl = np.ones((self.N+3, 4), float) # fill
for i,(channel,gamma,reverse) in enumerate(zip(channels, gammas, reverse)):
self._lut_hsl[:-3,i] = make_mapping_array(self.N, self._segmentdata[channel], channel, gamma, reverse)
if 'alpha' in self._segmentdata:
self._lut_hsl[:-3,3] = make_mapping_array(self.N, self._segmentdata['alpha'], 'alpha')
self._lut_hsl[:-3,0] %= 360
# self._lut_hsl[:-3,0] %= 359 # wrong
# Make hues circular, set extremes (i.e. copy HSL values)
self._lut = self._lut_hsl.copy() # preserve this, might want to check it out
self._set_extremes() # generally just used end values in segmentdata
self._isinit = True
# Now convert values to RGBA, and clip colors
for i in range(self.N+3):
self._lut[i,:3] = to_rgb(self._lut[i,:3], self.space)
self._lut[:,:3] = clip_colors(self._lut[:,:3], self.mask)
def _resample(self, N):
"""
Return a new color map with *N* entries.
"""
self.N = N # that easy
self._i_under = self.N
self._i_over = self.N + 1
self._i_bad = self.N + 2
self._init()
return self
@staticmethod
def from_hsl(name,
# h=0, s=99, l=[99, 20], c=None, a=None,
h=0, s=100, l=[100, 20], c=None, a=None,
hue=None, saturation=None, luminance=None, chroma=None, alpha=None,
ratios=None, reverse=False, **kwargs):
"""
Make linear segmented colormap by specifying channel values.
"""
# Build dictionary, easy peasy
h = _fill(hue, h)
s = _fill(chroma, _fill(c, _fill(saturation, s)))
l = _fill(luminance, l)
a = _fill(alpha, _fill(a, 1.0))
cs = ['hue', 'saturation', 'luminance', 'alpha']
channels = [h, s, l, a]
cdict = {}
for c,channel in zip(cs,channels):
cdict[c] = make_segmentdata_array(channel, ratios, reverse, **kwargs)
cmap = PerceptuallyUniformColormap(name, cdict, **kwargs)
return cmap
@staticmethod
def from_list(name, color_list,
ratios=None, reverse=False,
**kwargs):
"""
Make linear segmented colormap from list of color tuples. The values
in a tuple can be strings, in which case that corresponding color-name
channel value is deduced.
Optional
--------
ratios : simple way to specify x-coordinates for listed color
transitions -- bigger number is slower transition, smaller
number is faster transition.
space : colorspace of hue-saturation-luminance style input
color tuples.
"""
# Dictionary
cdict = {}
channels = [*zip(*color_list)]
if len(channels) not in (3,4):
raise ValueError(f'Bad color list: {color_list}')
cs = ['hue', 'saturation', 'luminance']
if len(channels)==4:
cs += ['alpha']
else:
cdict['alpha'] = 1.0 # dummy function that always returns 1.0
# Build data arrays
for c,channel in zip(cs,channels):
cdict[c] = make_segmentdata_array(channel, ratios, reverse, **kwargs)
cmap = PerceptuallyUniformColormap(name, cdict, **kwargs)
return cmap
def make_segmentdata_array(values, ratios=None, reverse=False, **kwargs):
"""
Construct a list of linear segments for an individual channel.
This was made so that user can input e.g. a callable function for
one channel, but request linear interpolation for another one.
"""
# Handle function handles
if callable(values):
if reverse:
values = lambda x: values(1-x)
return values # just return the callable
values = np.atleast_1d(values)
if len(values)==1:
value = values[0]
return [(0, value, value), (1, value, value)] # just return a constant transition
# Get x coordinates
if not np.iterable(values):
raise TypeError('Colors must be iterable.')
if ratios is not None:
xvals = np.atleast_1d(ratios) # could be ratios=1, i.e. dummy
if len(xvals) != len(values) - 1:
raise ValueError(f'Got {len(values)} values, but {len(ratios)} ratios.')
xvals = np.concatenate(([0], np.cumsum(xvals)))
xvals = xvals/np.max(xvals) # normalize to 0-1
else:
xvals = np.linspace(0,1,len(values))
# Build vector
array = []
slicer = slice(None,None,-1) if reverse else slice(None)
for x,value in zip(xvals,values[slicer]):
array.append((x, value, value))
return array
def make_mapping_array(N, data, channel, gamma=1.0, reverse=False):
"""
Mostly a copy of matplotlib version, with a few modifications:
* Disable clipping, allow the 0-360, 0-100, 0-100 HSL values.
* Allow circular hue gradations along 0-360.
* Allow weighting each transition by going from:
c = c1 + x*(c2 - c1)
for x in range [0-1], to
c = c1 + (x**gamma)*(c2 - c1)
"""
# Optionally allow for ***callable*** instead of linearly interpolating
# between line segments
gammas = np.atleast_1d(gamma)
if (gammas < 0.01).any() or (gammas > 10).any():
raise ValueError('Gamma can only be in range [0.01,10].')
if callable(data):
if len(gammas)>1:
raise ValueError('Only one gamma allowed for functional segmentdata.')
x = np.linspace(0, 1, N)**gamma
lut = np.array(data(x), dtype=float)
return lut
# Get array
try:
data = np.array(data)
except Exception:
raise TypeError('Data must be convertible to an array.')
shape = data.shape
if len(shape) != 2 or shape[1] != 3:
raise ValueError('Data must be nx3 format.')
if len(gammas)!=1 and len(gammas)!=shape[0]-1:
raise ValueError(f'Need {shape[0]-1} gammas for {shape[0]}-level mapping array, but got {len(gamma)}.')
if len(gammas)==1:
gammas = np.repeat(gammas, shape[:1])
# Get indices
x = data[:, 0]
y0 = data[:, 1]
y1 = data[:, 2]
if x[0] != 0.0 or x[-1] != 1.0:
raise ValueError('Data mapping points must start with x=0 and end with x=1.')
if (np.diff(x) < 0).any():
raise ValueError('Data mapping points must have x in increasing order.')
x = x*(N - 1)
# Get distances from the segmentdata entry to the *left* for each requested
# level, excluding ends at (0,1), which must exactly match segmentdata ends
xq = (N - 1)*np.linspace(0, 1, N)
ind = np.searchsorted(x, xq)[1:-1] # where xq[i] must be inserted so it is larger than x[ind[i]-1] but smaller than x[ind[i]]
distance = (xq[1:-1] - x[ind - 1])/(x[ind] - x[ind - 1])
# Scale distances in each segment by input gamma
# The ui are starting-points, the ci are counts from that point
# over which segment applies (i.e. where to apply the gamma)
_, uind, cind = np.unique(ind, return_index=True, return_counts=True)
for i,(ui,ci) in enumerate(zip(uind,cind)): # i will range from 0 to N-2
# Test if 1
gamma = gammas[ind[ui]-1] # the relevant segment is to *left* of this number
if gamma==1:
continue
# By default, weight toward a *lower* channel value (i.e. bigger
# exponent implies more colors at lower value)
# Again, the relevant 'segment' is to the *left* of index returned by searchsorted
ir = False
if ci>1: # i.e. more than 1 color in this 'segment'
ir = ((y0[ind[ui]] - y1[ind[ui]-1]) < 0) # by default want to weight toward a *lower* channel value
if reverse:
ir = (not ir)
if ir:
distance[ui:ui + ci] = 1 - (1 - distance[ui:ui + ci])**gamma
else:
distance[ui:ui + ci] **= gamma
# Perform successive linear interpolations all rolled up into one equation
lut = np.zeros((N,), float)
lut[1:-1] = distance*(y0[ind] - y1[ind - 1]) + y1[ind - 1]
lut[0] = y1[0]
lut[-1] = y0[-1]
return lut
#------------------------------------------------------------------------------#
# Colormap constructors
#------------------------------------------------------------------------------#
def merge_cmaps(*_cmaps, name='merged', N=512, ratios=1, **kwargs):
"""
Merge arbitrary colormaps.
Arguments
---------
_cmaps :
List of colormap strings or instances for merging.
name :
Name of output colormap.
N :
Number of lookup table colors desired for output colormap.
Notes
-----
* Old method had us simply calling the colormap with arrays of fractions.
This was sloppy, because it just samples locations on the lookup table and
will therefore degrade the original, smooth, functional transitions.
* Better method is to combine the _segmentdata arrays and simply scale
the x coordinates in each (x,y1,y2) channel-tuple according to the ratios.
* In the case of ListedColormaps, we just combine the colors.
"""
# Initial
if len(_cmaps)<=1:
raise ValueError('Need two or more input cmaps.')
ratios = ratios or 1
if utils.isnumber(ratios):
ratios = [1]*len(_cmaps)
# Combine the colors
_cmaps = [colormap(cmap, N=None, **kwargs) for cmap in _cmaps] # set N=None to disable resamping
if all(isinstance(cmap, mcolors.ListedColormap) for cmap in _cmaps):
if not np.all(ratios==1):
raise ValueError(f'Cannot assign different ratios when mering ListedColormaps.')
colors = [color for cmap in _cmaps for color in cmap.colors]
cmap = mcolors.ListedColormap(colors, name=name, N=len(colors))
# Accurate methods for cmaps with continuous/functional transitions
elif all(isinstance(cmap,mcolors.LinearSegmentedColormap) for cmap in _cmaps):
# Combine the actual segmentdata
kinds = {type(cmap) for cmap in _cmaps}
if len(kinds)>1:
raise ValueError(f'Got mixed colormap types.')
kind = kinds.pop() # colormap kind
keys = {key for cmap in _cmaps for key in cmap._segmentdata.keys()}
ratios = np.array(ratios)/np.sum(ratios) # so if 4 cmaps, will be 1/4
x0 = np.concatenate([[0], np.cumsum(ratios)])
xw = x0[1:] - x0[:-1]
# Combine the segmentdata, and use the y1/y2 slots at merge points
# so the transition is immediate (can never interpolate between end
# colors on the two colormaps)
segmentdata = {}
for key in keys:
# Combine scalar values
if key in ('gamma1', 'gamma2'):
if key not in segmentdata:
segmentdata[key] = []
for cmap in _cmaps:
segmentdata[key] += [cmap._segmentdata[key]]
continue
# Combine xyy data
datas = []
test = [callable(cmap._segmentdata[key]) for cmap in _cmaps]
if not all(test) and any(test):
raise ValueError('Mixed callable and non-callable colormap values.')
if all(test): # expand range from x-to-w to 0-1
for x,w,cmap in zip(x0[:-1], xw, _cmaps):
data = lambda x: data((x - x0)/w) # WARNING: untested!
datas.append(data)
def data(x):
idx, = np.where(x<x0)
if idx.size==0:
i = 0
elif idx.size==x0.size:
i = x0.size-2
else:
i = idx[-1]
return datas[i](x)
else:
for x,w,cmap in zip(x0[:-1], xw, _cmaps):
data = np.array(cmap._segmentdata[key])
data[:,0] = x + w*data[:,0]
datas.append(data)
for i in range(len(datas)-1):
datas[i][-1,2] = datas[i+1][0,2]
datas[i+1] = datas[i+1][1:,:]
data = np.concatenate(datas, axis=0)
data[:,0] = data[:,0]/data[:,0].max(axis=0) # scale to make maximum exactly 1 (avoid floating point errors)
segmentdata[key] = data
# Create object
kwargs = {}
if kind is PerceptuallyUniformColormap:
spaces = {cmap.space for cmap in _cmaps}
if len(spaces)>1:
raise ValueError(f'Trying to merge colormaps with different HSL spaces {repr(spaces)}.')
kwargs.update({'space':spaces.pop()})
cmap = kind(name, segmentdata, N=N, **kwargs)
else:
raise ValueError('All colormaps should be of the same type (Listed or LinearSegmented).')
return cmap
def monochrome_cmap(color, fade, reverse=False, space='hsl', name='monochrome', **kwargs):
"""
Make a sequential colormap that blends from color to near-white.
Arguments
---------
color :
Build colormap by varying the luminance of some RGB color while
keeping its saturation and hue constant.
Optional
--------
reverse : (False)
Optionally reverse colormap.
space : ('hsl')
Colorspace in which we vary luminance.
"""
# Get colorspace
space = get_space(space)
h, s, l = to_xyz(to_rgb(color), space)
if utils.isnumber(fade): # allow just specifying the luminance channel
# fade = np.clip(fade, 0, 99)
fade = np.clip(fade, 0, 100)
fade = to_rgb((h, 0, fade), space=space)
_, fs, fl = to_xyz(to_rgb(fade), space)
fs = s # consider changing this?
index = slice(None,None,-1) if reverse else slice(None)
return PerceptuallyUniformColormap.from_hsl(name, h, [s,fs][index], [l,fl][index], space=space, **kwargs)
def clip_colors(colors, mask=True, gray=0.2, verbose=False):
"""
Arguments
---------
colors :
List of length-3 RGB color tuples.
mask : (bool)
Whether to mask out (set to some dark gray color) or clip (limit
range of each channel to [0,1]) out-of-range RGB channels.
Notes
-----
Could use np.clip (matplotlib.colors uses this under the hood) but want
to display messages, and anyway premature efficiency is the root of all
evil, we're manipulating like 1000 colors max here, it's no big deal.
"""
message = 'Invalid' if mask else 'Clipped'
colors = np.array(colors) # easier
under = (colors<0)
over = (colors>1)
if mask:
colors[(under | over)] = gray
else:
colors[under] = 0
colors[over] = 1
if verbose:
for i,name in enumerate('rgb'):
if under[:,i].any():
print(f'Warning: {message} "{name}" channel (<0).')
if over[:,i].any():
print(f'Warning: {message} "{name}" channel (>1).')
return colors
# return colors.tolist() # so it is *hashable*, can be cached (wrote this because had weird error, was unrelated)
#------------------------------------------------------------------------------#
# Cycle helper functions
#------------------------------------------------------------------------------#
def set_cycle(cmap, samples=None, rename=False):
"""
Set the color cycler.
Arguments
---------
cmap :
Name of colormap or colormap instance from which we draw list of colors.
samples :
Array of values from 0-1 or number indicating number of evenly spaced
samples from 0-1 from which to draw colormap colors. Will be ignored
if the colormap is a ListedColormap (interpolation not possible).
"""
_colors = colors(cmap, samples)
cyl = cycler('color', _colors)
rcParams['axes.prop_cycle'] = cyl
rcParams['patch.facecolor'] = _colors[0]
if rename:
rename_colors(cmap)
def rename_colors(cycle='colorblind'):
"""
Calling this will change how shorthand codes like "b" or "g"
are interpreted by matplotlib in subsequent plots.
Arguments
---------
cycle : {deep, muted, pastel, dark, bright, colorblind}
Named seaborn palette to use as the source of colors.
"""
seaborn_cycles = ['colorblind', 'deep', 'muted', 'bright']
if cycle=='reset':
colors = [(0.0, 0.0, 1.0), (0.0, .50, 0.0), (1.0, 0.0, 0.0), (.75, .75, 0.0),
(.75, .75, 0.0), (0.0, .75, .75), (0.0, 0.0, 0.0)]
elif cycle in seaborn_cycles:
colors = cycles[cycle] + [(0.1, 0.1, 0.1)]
else:
raise ValueError(f'Cannot set colors with color cycle {cycle}.')
for code, color in zip('bgrmyck', colors):
rgb = mcolors.colorConverter.to_rgb(color)
mcolors.colorConverter.colors[code] = rgb
mcolors.colorConverter.cache[code] = rgb
#------------------------------------------------------------------------------
# Normalization classes for mapping data to colors (i.e. colormaps)
# WARNING: Many methods in ColorBarBase tests for class membership, crucially
# including _process_values(), which if it doesn't detect BoundaryNorm will
# end up trying to infer boundaries from inverse() method
#------------------------------------------------------------------------------
def norm(norm_i, levels=None, norm=None, **kwargs):
"""
Return arbitrary normalizer.
"""
if isinstance(norm_i, mcolors.Normalize):
pass
elif norm_i is None:
norm_i = None
elif norm_i is None:
norm_i = mcolors.Normalize() # default is just linear from 0 to 1
elif type(norm_i) is not str: # dictionary lookup
raise ValueError(f'Unknown norm "{norm_i}".')
if isinstance(norm_i, str):
if norm_i not in normalizers:
raise ValueError(f'Unknown normalizer "{norm_i}". Options are {", ".join(normalizers.keys())}.')
norm_i = normalizers[norm_i]
if norm_i in (BinNorm, LinearSegmentedNorm):
kwargs.update({'levels':levels, 'norm':norm})
norm_i = norm_i(**kwargs)
return norm_i
class LinearSegmentedNorm(mcolors.Normalize):
"""
Description
-----------
As in BoundaryNorm case, but instead we linearly *interpolate* colors
between the provided boundary levels. Exactly analagous to the method
in LinearSegmentedColormap: perform linear interpolations between
successive monotonic, but arbitrarily spaced, points.
"""
def __init__(self, levels, norm=None, clip=False, **kwargs):
# Test
levels = np.atleast_1d(levels)
if levels.size<=1:
raise ValueError('Need at least two levels.')
elif ((levels[1:]-levels[:-1])<=0).any():
raise ValueError(f'Levels {levels} passed to LinearSegmentedNorm must be monotonically increasing.')
super().__init__(np.nanmin(levels), np.nanmax(levels), clip) # second level superclass
# Add some properties
if not norm: # e.g. a logarithmic transform
norm = (lambda x: x)
norm.inverse = (lambda x: x)
self._x = levels # alias for boundaries
self._x_norm = norm(levels)
self._y = np.linspace(0, 1, levels.size)
self._norm = norm
def __call__(self, xq, clip=None):
# Follow example of make_mapping_array for efficient, vectorized
# linear interpolation across multiple segments
# NOTE: normal test puts values at a[i] if a[i-1] < v <= a[i]; for
# left-most data, satisfy a[0] <= v <= a[1]
# NOTE: searchsorted gives where xq[i] must be inserted so it is larger
# than x[ind[i]-1] but smaller than x[ind[i]]
x = self._x_norm # from arbitrarily spaced monotonic levels
y = self._y # to linear range 0-1
xq = self._norm(np.atleast_1d(xq))
ind = np.searchsorted(x, xq)
ind[ind==0] = 1
ind[ind==len(x)] = len(x) - 1 # actually want to go to left of that
distance = (xq - x[ind - 1])/(x[ind] - x[ind - 1])
yq = distance*(y[ind] - y[ind - 1]) + y[ind - 1]
return ma.masked_array(yq, np.isnan(xq))
def inverse(self, yq):
# Performs inverse operation of __call__
x = self._x_norm
y = self._y
yq = np.atleast_1d(yq)
ind = np.searchsorted(y, yq)
ind[ind==0] = 1
ind[ind==len(x)] = len(x) - 1
distance = (yq - y[ind - 1])/(y[ind] - y[ind - 1])
xq = distance*(x[ind] - x[ind - 1]) + x[ind - 1]
return ma.masked_array(self._norm.inverse(xq), np.isnan(yq))
class BinNorm(mcolors.BoundaryNorm):
"""
Simple normalizer that *interpolates* from an RGB array at point
(level_idx/num_levels) along the array, instead of choosing color
from (transform(level_value)-transform(vmin))/(transform(vmax)-transform(vmin))
where transform can be linear, logarithmic, etc.
Note
----
If you are using a diverging colormap with extend='max/min', the center
will get messed up. But that is very strange usage anyway... so please
just don't do that :)
Todo
----
Allow this to accept transforms too, which will help prevent level edges
from being skewed toward left or right in case of logarithmic/exponential data.
Example
-------
Your levels edges are weirdly spaced [-1000, 100, 0, 100, 1000] or
even [0, 10, 12, 20, 22], but center "colors" are always at colormap
coordinates [.2, .4, .6, .8] no matter the spacing; levels just must be monotonic.
"""
def __init__(self, levels, norm=None, centers=False, clip=False, extend=None, **kwargs):
# Declare boundaries, vmin, vmax in True coordinates
# NOTE: Idea is that we bin data into len(levels) discrete x-coordinates,
# and optionally make out-of-bounds colors the same or different
# NOTE: Don't need to call parent __init__, this is own implementation
# Do need it to subclass BoundaryNorm, so ColorbarBase will detect it
# See BoundaryNorm: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py
extend = extend or 'both'
levels = np.atleast_1d(levels)
if levels.size<=1:
raise ValueError('Need at least two levels.')
elif ((levels[1:]-levels[:-1])<=0).any():
raise ValueError(f'Levels {levels} passed to Normalize() must be monotonically increasing.')
if extend not in ('both','min','max','neither'):
raise ValueError(f'Unknown extend option "{extend}". Choose from "min", "max", "both", "neither".')
if centers:
levels = utils.edges(levels)
N = len(levels)
# Determine y-bin *centers* desired
# NOTE: Length of bin centers should be N + 1
norm = norm or (lambda x: x) # e.g. a logarithmic transform
offset = {'both':2, 'min':1, 'max':1, 'neither':0}
resample = {'both':range(N+1), 'neither':[0, *range(N-1), N-2],
'min':[*range(N), N-1], 'max':[0, *range(N)]}
self._norm = norm
self._x = norm(levels)
self._y_bins = np.linspace(0, 1, N + offset[extend] - 1)[resample[extend]]
# Add builtin properties
self.boundaries = levels # alias read by other functions
self.vmin = levels[0]
self.vmax = levels[-1]
self.clip = clip
self.N = N
def __call__(self, xq, clip=None):
# Follow example of LinearSegmentedNorm, but perform no interpolation,
# just use searchsorted to bin the data.
# NOTE: The bins vector includes out-of-bounds negative (searchsorted
# index 0) and out-of-bounds positive (searchsorted index N+1) values
x = self._x
xq = self._norm(np.atleast_1d(xq))
yq = self._y_bins[np.searchsorted(x, xq)] # which x-bin does each point in xq belong to?
return ma.masked_array(yq, np.isnan(xq))
def inverse(self, yq):
# Not possible
raise ValueError('BinNorm is not invertible.')
class StretchNorm(mcolors.Normalize):
"""
Normalizers that 'stretches' and 'compresses' either side of a colormap
about some midpoint, proceeding exponentially (exp>0) or logarithmically
(exp<0) down the linear colormap from the center point.
Notes
-----
* Default midpoint is vmin, i.e. we just stretch to the right. For diverging
colormaps, use midpoint 0.5.
* Need to update this. Should features be incorporated with
LinearSegmentedNorm? Should user just use exponential gradation
functions in the segmentdata instead of using a special normalizer?
"""
def __init__(self, exp=0, midpoint=None, vmin=None, vmax=None, clip=None):
# Bigger numbers are too one-sided
if abs(exp) > 10:
raise ValueError('Warping scale must be between -10 and 10.')
super().__init__(vmin, vmax, clip)
self._midpoint = midpoint
self._exp = exp
def _warp(x, exp, exp_max=4):
# Returns indices stretched so neutral/low values are sampled more heavily
if exp > 0:
invert = True
else:
invert, exp = False, -exp
exp = exp*(exp_max/10)
# Apply function; approaches x=1 as a-->Inf, x=x as a-->0
if invert: x = 1-x
value = (x-1+(np.exp(x)-x)**exp)/(np.e-1)**exp
if invert:
value = 1-value # flip on y-axis
return value
def __call__(self, value, clip=None):
# Get middle point in 0-1 coords, and value
midpoint = self._midpoint or self.vmin
midpoint_scaled = (midpoint - self.vmin)/(self.vmax - self.vmin)
value_scaled = (value - self.vmin)/(self.vmax - self.vmin)
try: iter(value_scaled)
except TypeError:
value_scaled = np.arange(value_scaled)
value_cmap = ma.empty(value_scaled.size)
# Get values, accounting for midpoints
for i,v in enumerate(value_scaled):
v = np.clip(v, 0, 1)
if v>=midpoint_scaled:
block_width = 1 - midpoint_scaled
value_cmap[i] = (midpoint_scaled +
block_width*self._warp((v - midpoint_scaled)/block_width, self._exp)
)
else:
block_width = midpoint_scaled
value_cmap[i] = (midpoint_scaled -
block_width*self._warp((midpoint_scaled - v)/block_width, self._exp)
)
return value_cmap
#------------------------------------------------------------------------------#
# Register new colormaps; must come before registering the color cycles
# * If leave 'name' empty in register_cmap, name will be taken from the
# Colormap instance. So do that.
# * Note that **calls to cmap instance do not interpolate values**; this is only
# done by specifying levels in contourf call, specifying lut in get_cmap,
# and using LinearSegmentedColormap.from_list with some N.
# * The cmap object itself only **picks colors closest to the "correct" one
# in a "lookup table**; using lut in get_cmap interpolates lookup table.
# See LinearSegmentedColormap doc: https://matplotlib.org/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html#matplotlib.colors.LinearSegmentedColormap
# * If you want to always disable interpolation, use ListedColormap. This type
# of colormap instance will choose nearest-neighbors when using get_cmap, levels, etc.
#------------------------------------------------------------------------------#
def register_colors(nmax=np.inf, verbose=False):
"""
Register new color names. Will only read first n of these
colors, since XKCD library is massive (they should be sorted by popularity
so later ones are no loss).
Notes
-----
* The 'threshold' arg denotes how separated each channel of the HCL converted
colors must be.
* This seems like it would be slow, but takes on average 0.03 seconds on
my macbook, so it's fine.
"""
# First ***reset*** the colors dictionary
# Why? We want to add XKCD colors *sorted by popularity* from file, along
# with crayons dictionary; having registered colors named 'xkcd:color' is
# annoying and not useful
scale = (360, 100, 100)
translate = {'b': 'blue', 'g': 'green', 'r': 'red', 'c': 'cyan',
'm': 'magenta', 'y': 'yellow', 'k': 'black', 'w': 'white'}
base1 = mcolors.BASE_COLORS # one-character names
base2 = {translate[key]:value for key,value in base1.items()} # full names
mcolors._colors_full_map.clear() # clean out!
mcolors._colors_full_map.cache.clear() # clean out!
mcolors._colors_full_map.update(base1)
mcolors._colors_full_map.update(base2)
# First register colors and get their HSL values
names = []
hcls = np.empty((0,3))
for file in glob(f'{_data}/colors/*.txt'):
# Read data
category, _ = os.path.splitext(os.path.basename(file))
data = np.genfromtxt(file, delimiter='\t', dtype=str, comments='%', usecols=(0,1)).tolist()
ncolors = min(len(data),nmax-1)
# Add categories
colors_unfiltered[category] = {}
colors_filtered[category] = {} # just initialize this one
# Sanitize names and add to dictionary
hcl = np.empty((ncolors,3))
for i,(name,color) in enumerate(data): # is list of name, color tuples
if i>=nmax: # e.g. for xkcd colors
break
hcl[i,:] = to_xyz(color, space=_distinct_colors_space)
name = re.sub('/', ' ', name)
name = re.sub("'s", '', name)
name = re.sub('grey', 'gray', name)
name = re.sub('pinky', 'pink', name)
name = re.sub('greeny', 'green', name)
names.append((category, name))
colors_unfiltered[category][name] = color
# Concatenate HCL arrays
hcls = np.concatenate((hcls, hcl), axis=0)
# Remove colors that are 'too similar' by rounding to the nearest n units
# WARNING: unique axis argument requires numpy version >=1.13
# WARNING: evidently it is ***impossible*** to actually delete colors
# from the custom_colors dictionary (perhaps due to quirk of autoreload,
# perhaps by some more fundamental python thing), so we instead must create
# *completely separate* dictionary and add colors from there
hcls = hcls/np.array(scale)
hcls = np.round(hcls/_distinct_colors_threshold).astype(np.int64)
_, index, counts = np.unique(hcls, return_index=True, return_counts=True, axis=0) # get unique rows
deleted = 0
counts = counts.sum()
exceptions_regex = '^(' + '|'.join(_distinct_colors_exceptions) + ')[0-9]?$'
# Add colors to filtered colors
for i,(category,name) in enumerate(names):
if not re.match(exceptions_regex, name) and i not in index:
deleted += 1
else:
colors_filtered[category][name] = colors_unfiltered[category][name]
for category,dictionary in colors_filtered.items():
mcolors._colors_full_map.update(dictionary)
if verbose:
print(f'Started with {len(names)} colors, removed {deleted} insufficiently distinct colors.')
def register_cmaps():
"""
Register colormaps and cycles in the cmaps directory.
Note all of those methods simply modify the dictionary mcm.cmap_d.
"""
# Simple test to see if this has already been run
if 'Greys' not in mcm.cmap_d:
return
# First read from file
for file in glob(f'{_data}/cmaps/*'):
# Read table of RGB values
if not re.search('.(rgb|hex|npy)$', file):
continue
name = os.path.basename(file)[:-4]
# Comment this out to overwrite existing ones
# if name in mcm.cmap_d: # don't want to re-register every time
# continue
if re.search('.rgb$', file):
try: cmap = np.loadtxt(file, delimiter=',') # simple
except:
print(f'Failed to load {os.path.basename(file)}.')
continue
if (cmap>1).any():
cmap = cmap/255
# Read list of hex strings
elif re.search('.hex$', file):
cmap = [*open(file)] # just a single line
if len(cmap)==0:
continue # file is empty
cmap = cmap[0].strip().split(',') # csv hex strings
cmap = np.array([mcolors.to_rgb(c) for c in cmap]) # from list of tuples
# Directly read segmentdata of hex strings
# Will ensure that HSL colormaps have the 'space' entry
else:
segmentdata = np.load(file).item() # unpack 0-D array
if 'space' in segmentdata:
space = segmentdata.pop('space')
cmap = PerceptuallyUniformColormap(name, segmentdata, space=space, N=_N_hires)
else:
cmap = mcolors.LinearSegmentedColormap(name, segmentdata, N=_N_hires)
# Register as ListedColormap or LinearSegmentedColormap
if isinstance(cmap, mcolors.Colormap): # i.e. we did not load segmentdata directly
cmap_r = cmap.reversed()
else:
N = len(cmap) # simple as that; number of rows of colors
cmap = mcolors.LinearSegmentedColormap.from_list(name, cmap, N) # using static method is way easier
cmap_r = cmap.reversed() # default name is name+'_r'
cmaps.add(name)
# Register maps (this is just what register_cmap does)
mcm.cmap_d[cmap.name] = cmap
mcm.cmap_d[cmap_r.name] = cmap_r
# Fix the builtin rainbow colormaps by switching from Listed to
# LinearSegmented -- don't know why matplotlib shifts with these as
# discrete maps by default, dumb.
for name in _cmap_categories['Matplotlib Originals']: # initialize as empty lists
cmap = mcm.cmap_d.get(name,None)
if cmap and isinstance(cmap, mcolors.ListedColormap):
mcm.cmap_d[name] = mcolors.LinearSegmentedColormap.from_list(name, cmap.colors)
# Swap the order of divering colorbrewer maps, direction of color changes
# is opposite from intuition (red to blue, pink to green, etc.)
names = []
if 'RdBu' in mcm.cmap_d: # only do this once! we modified the content of ColorBrewer Diverging
for name in _cmap_categories['ColorBrewer2.0 Diverging']:
# Reverse map and name
# e.g. RdBu --> BuRd, RdYlBu --> BuYlRd
# Note default name PuOr is literally backwards...
cmap = mcm.cmap_d.get(name, None)
cmap_r = mcm.cmap_d.get(name + '_r', None)
if cmap:
if name not in ('Spectral','PuOr','BrBG'):
del mcm.cmap_d[name]
del mcm.cmap_d[name + '_r']
name = re.sub('^(..)(..)?(..)$', r'\3\2\1', name)
mcm.cmap_d[name] = cmap_r
mcm.cmap_d[name + '_r'] = cmap
names += [name]
_cmap_categories['ColorBrewer2.0 Diverging'] = names
# Add shifted versions of cyclic colormaps, and prevent same colors on ends
for name in ['twilight', 'Phase']:
cmap = mcm.cmap_d.get(name, None)
if cmap and isinstance(cmap, mcolors.LinearSegmentedColormap):
data = cmap._segmentdata
data_shift = data.copy()
for key,array in data.items():
array = np.array(array)
# Drop an end color
array = array[1:,:]
array_shift = array.copy()
array_shift[:,0] -= 0.5
array_shift[:,0] %= 1
array_shift = array_shift[array_shift[:,0].argsort(),:]
# Normalize x-range
array[:,0] -= array[:,0].min()
array[:,0] /= array[:,0].max()
data[key] = array
array_shift[:,0] -= array_shift[:,0].min()
array_shift[:,0] /= array_shift[:,0].max()
data_shift[key] = array_shift
# Register shifted version and original
mcm.cmap_d[name] = mcolors.LinearSegmentedColormap(name, data, cmap.N)
mcm.cmap_d[name + '_shifted'] = mcolors.LinearSegmentedColormap(name + '_shifted', data_shift, cmap.N)
# Convert names
mcm.cmap_d['Grays'] = mcm.cmap_d.pop('Greys')
mcm.cmap_d['Grays_r'] = mcm.cmap_d.pop('Greys_r')
# Add OpenColor colormaps
# Actually nah, not enough gradation for these
# for color in ['gray', 'red', 'pink', 'grape', 'violet', 'indigo', 'blue', 'cyan',
# 'teal', 'green', 'lime', 'yellow', 'orange']:
# color_list = [to_rgb(color + str(i)) for i in range(10)]
# name = 'Open' + color.title()
# mcm.cmap_d[name] = mcolors.LinearSegmentedColormap.from_list(name, color_list)
# Delete ugly ones
for category in _cmap_categories_delete:
for name in _cmap_categories:
mcm.cmap_d.pop(name, None)
# Register names so that they can be invoked ***without capitalization***
# This always bugged me! Note cannot change dictionary during iteration.
ignorecase = {}
ignore = [category for categories in _cmap_categories_delete for category in categories]
for name,cmap in mcm.cmap_d.items():
if name in ignore:
mcm.cmap_d.pop(name, None)
elif re.search('[A-Z]',name):
ignorecase[name.lower()] = cmap
mcm.cmap_d.update(ignorecase)
for key in ignorecase.keys():
_cmaps_lower.add(key)
def register_cycles():
"""
Register cycles defined right here by dictionaries.
"""
# Simply register them as ListedColormaps
# TODO: Consider adding support for loading cycles on disk
for name,colors in _cycles_list.items():
mcm.cmap_d[name] = mcolors.ListedColormap([to_rgb(color) for color in colors])
mcm.cmap_d[f'{name}_r'] = mcolors.ListedColormap([to_rgb(color) for color in colors[::-1]])
cycles.add(name)
# Remove some redundant ones
mcm.cmap_d.pop('tab10', None)
mcm.cmap_d.pop('tab20', None)
mcm.cmap_d.pop('Paired', None)
mcm.cmap_d.pop('Pastel1', None)
mcm.cmap_d.pop('Pastel2', None)
mcm.cmap_d.pop('Dark2', None)
if 'Accent' in mcm.cmap_d:
mcm.cmap_d.pop('Set1', None)
mcm.cmap_d['Set1'] = mcm.cmap_d.pop('Accent')
cycles.add('Accent')
if 'tab20b' in mcm.cmap_d:
mcm.cmap_d['Set4'] = mcm.cmap_d.pop('tab20b')
cycles.add('Set4')
if 'tab20c' in mcm.cmap_d:
mcm.cmap_d['Set5'] = mcm.cmap_d.pop('tab20c')
cycles.add('Set5')
# Register stuff when this module is imported
# The 'cycles' are simply listed colormaps, and the 'cmaps' are the smoothly
# varying LinearSegmentedColormap instances or subclasses thereof
cmaps = set() # track downloaded colormaps; user can then check this list
cycles = set() # same, but track cycles
colors_filtered = {} # limit to 'sufficiently unique' color names
colors_unfiltered = {} # downloaded colors categorized by filename
_cmaps_lower = set() # lower-case keys added to dictionary, that we will ignore
register_colors() # must be done first, so we can register OpenColor cmaps
register_cmaps()
register_cycles()
# Finally our dictionary of normalizers
# Includes some custom classes, so has to go at end
normalizers = {
'none': mcolors.NoNorm,
'null': mcolors.NoNorm,
'step': BinNorm,
'bins': BinNorm,
'bin': BinNorm,
'segmented': LinearSegmentedNorm,
'boundary': mcolors.BoundaryNorm,
'log': mcolors.LogNorm,
'linear': mcolors.Normalize,
'power': mcolors.PowerNorm,
'symlog': mcolors.SymLogNorm,
}
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# This makes package locally importable, as long as
# this directory is on PYTHONPATH.
#------------------------------------------------------------------------------#
from .proplot import *
<file_sep>These fonts were added from the default site-packages distribution generally found in
```
<base>/lib/python3.6/site-packages/matplotlib//mpl-data/fonts/ttf
```
and from some default included with the MacOS distribution. The files in this folder are intended to populate the mpl-data folder on matplotlib installed for any server. Use the "fontsetup" command to do so; this shell script will delete the existing font caches.
<file_sep>#!/usr/bin/env python3
import re
import numpy as np
# import io
# from contextlib import redirect_stdout
# Local modules, projection sand formatters and stuff
from .rcmod import rc
from .gridspec import _gridspec_kwargs, FlexibleGridSpec
from . import base
from .utils import _fill, ic
from functools import wraps
# Have to do this for a couple things
import matplotlib.pyplot as plt
#------------------------------------------------------------------------------#
# Miscellaneous helper functions
#------------------------------------------------------------------------------#
def figure(*args, **kwargs):
"""
Simple alias for 'subplots', perhaps more intuitive.
"""
return subplots(*args, **kwargs)
def close():
"""
Close all figures 'open' in memory. This does not delete images printed
in an ipython notebook; those are rendered versions of the abstract figure objects.
"""
plt.close('all') # easy peasy
def show():
"""
Show all figures.
"""
plt.show()
#-------------------------------------------------------------------------------
# Primary plotting function; must be used to create figure/axes if user wants
# to use the other features
#-------------------------------------------------------------------------------
class axes_list(list):
"""
Magical clas that iterates through each axes and calls respective
method on each one. Returns a list of each return value.
"""
def __repr__(self):
# Make clear that this is no ordinary list
return 'axes_list(' + super().__repr__() + ')'
def __getitem__(self, key):
# Return an axes_list version of the slice, or just the axes
axs = list.__getitem__(self, key)
if isinstance(key,slice): # i.e. returns a list
axs = axes_list(axs)
return axs
def __getattr__(self, attr):
# Stealthily return dummy function that actually iterates
# through each attribute here
values = [getattr(ax, attr, None) for ax in self]
if None in values:
raise AttributeError(f"'{type(self[0])}' object has no method '{attr}'.")
elif all(callable(value) for value in values):
@wraps(values[0])
def iterator(*args, **kwargs):
ret = []
for ax in self:
res = getattr(ax, attr)(*args, **kwargs)
if res is not None:
ret += [res]
return None if not ret else ret[0] if len(ret)==1 else ret
return iterator
elif all(not callable(value) for value in values):
return values[0] if len(values)==1 else values # just return the attribute list
else:
raise AttributeError('Mixed methods found.')
def subplots(array=None, ncols=1, nrows=1, rowmajor=True, # allow calling with subplots(array)
emptycols=[], emptyrows=[], # obsolete?
tight=None, auto_adjust=True,
# tight=True, adjust=False,
rcreset=True, silent=True, # arguments for figure instantiation
span=None, # bulk apply to x/y axes
share=None, # bulk apply to x/y axes
spanx=1, spany=1, # custom setting, optionally share axis labels for axes with same xmin/ymin extents
sharex=3, sharey=3, # for sharing x/y axis limits/scales/locators for axes with matching GridSpec extents, and making ticklabels/labels invisible
innerpanels={}, innercolorbars={}, innerpanels_kw={},
basemap=False, proj={}, projection={}, proj_kw={}, projection_kw={},
**kwargs): # for projections; can be 'basemap' or 'cartopy'
"""
Summary
-------
Special creation of subplots grids, allowing for arbitrarily overlapping
axes objects. Will return figure handle and axes objects.
Details
-------
* Easiest way to create subplots is with nrows=1 and ncols=1. If you want extra space
between a row or column, specify the row/column number that you want to be 'empty' with
emptyrows=row/emptycolumn=column, and adjust wratios/hratios for the desired width of that space.
* For more complicated plots, can pass e.g. array=[[1,2,3,4],[0,5,5,0]] to create a grid
of 4 plots on the top, single plot spanning the middle 2-columns on the bottom, and empty
spaces where the 0 appears.
* Use bottompanel/bottompanels to make several or multiple panels on the bottom
that can be populated with multiple colorbars/legend; bottompanels=True will
just make one 'space' for every column, and bottompanels=[1,1,2] for example will
make a panel spanning the first two columns, then a single panel for the final column.
This will add a bottompanel attribute to the figure; can index that attribute if there
are multiple places for colorbars/legend.
* Initialize cartopy plots with package='basemap' or package='cartopy'. Can control which plots
we want to be maps with maps=True (everything) or maps=[numbers] (the specified subplot numbers).
Notes
-----
* Matplotlib set_aspect option seems to behave strangely on some plots (trend-plots from
SST paper); for this reason we override the fix_aspect option provided by basemap and
just draw figure with appropriate aspect ratio to begin with. Otherwise get weird
differently-shaped subplots that seem to make no sense.
* Shared axes will generally end up with the same axis limits/scaling/majorlocators/minorlocators;
the sharex and sharey detection algorithm really is just to get instructions to make the
ticklabels/axis labels invisible for certain axes.
Todo
----
* Generalize axes sharing for right y-axes and top x-axes. Enable a secondary
axes sharing mode where we *disable ticklabels and labels*, but *do not
use the builtin sharex/sharey API*, suitable for complex map projections.
* For spanning axes labels, right now only detect **x labels on bottom**
and **ylabels on top**; generalize for all subplot edges.
* Figure size should be constrained by the dimensions of the axes, not vice
versa; might make things easier.
"""
# Check
sharex = _fill(share, sharex)
sharey = _fill(share, sharey)
spanx = _fill(span, spanx)
spany = _fill(span, spany)
if int(sharex) not in range(4) or int(sharey) not in range(4):
raise ValueError('Axis sharing options sharex/sharey can be 0 (no sharing), 1 (sharing, but keep all tick labels), and 2 (sharing, but only keep one set of tick labels).')
# Helper functions
translate = lambda p: {'bottom':'b', 'top':'t', 'right':'r', 'left':'l'}.get(p, p)
auto_adjust = _fill(tight, auto_adjust)
def axes_dict(value, kw=False):
# First build up dictionary
# Accepts:
# 1) 'string' or {1:'string1', (2,3):'string2'}
if not kw:
if not isinstance(value, dict):
value = {range(1,num_axes+1): value}
# 2) {'prop':value} or {1:{'prop':value1}, (2,3):{'prop':value2}}
else:
nested = [isinstance(value,dict) for value in value.values()]
if not any(nested): # any([]) == False
value = {range(1,num_axes+1): value.copy()}
elif not all(nested):
raise ValueError('Wut.')
# Then unfurl wherever keys contain multiple axes numbers
kw_out = {}
for nums,item in value.items():
nums = np.atleast_1d(nums)
for num in nums.flat:
if not kw:
kw_out[num-1] = item
else:
kw_out[num-1] = item.copy()
# Verify numbers
if {*range(num_axes)} != {*kw_out.keys()}:
raise ValueError(f'Have {num_axes} axes, but {value} has properties for axes {", ".join(str(i+1) for i in sorted(kw_out.keys()))}.')
return kw_out
# Array setup
if array is None:
array = np.arange(1,nrows*ncols+1)[...,None]
order = 'C' if rowmajor else 'F' # for column major, use Fortran ordering
array = array.reshape((nrows, ncols), order=order) # numpy is row-major, remember
array = np.array(array) # enforce array type
if array.ndim==1:
array = array[None,:] if rowmajor else array[:,None] # interpret as single row or column
# Empty rows/columns feature
array[array==None] = 0 # use zero for placeholder; otherwise have issues
if emptycols:
emptycols = np.atleast_1d(emptycols)
for col in emptycols.flat:
array[:,col-1] = 0
if emptyrows:
emptyrows = np.atleast_1d(emptyrows)
for row in emptyrows.flat:
array[row-1,:] = 0
# Enforce rule
nums = np.unique(array[array!=0])
num_axes = len(nums)
if tuple(nums.flat) != tuple(range(1,num_axes+1)):
raise ValueError('Axes numbers must span integers 1 to num_axes (i.e. cannot skip over numbers).')
nrows = array.shape[0]
ncols = array.shape[1]
# Get basemap.Basemap or cartopy.CRS instances for map, and override aspec tratio
# NOTE: Previously went to some pains (mainly for basemap, something in the
# initialization deals with this) to only draw one projection. This is hard
# to generalize when want different projections/kwargs, so abandon
basemap = axes_dict(basemap, False) # package used for projection
proj = axes_dict(projection or proj or 'xy', False) # name of projection; by default use base.XYAxes
proj_kw = axes_dict(projection_kw or proj_kw, True) # stores cartopy/basemap arguments
axes_kw = {num:{} for num in range(num_axes)} # stores add_subplot arguments
for num,name in proj.items():
# Builtin matplotlib polar axes, just use my overridden version
if name=='polar':
axes_kw[num]['projection'] = 'newpolar'
if num==1:
kwargs.update(aspect=1)
# The default, my XYAxes projection
elif name=='xy':
axes_kw[num]['projection'] = 'xy'
# Custom Basemap and Cartopy axes
elif name:
package = 'basemap' if basemap[num] else 'cartopy'
instance, aspect = base.map_projection_factory(package, name, **proj_kw[num])
axes_kw[num].update({'projection':package, 'map_projection':instance})
if not silent:
print(f'Forcing aspect ratio: {aspect:.3g}')
if num==0:
kwargs.update(aspect=aspect)
else:
raise ValueError('All projection names should be declared. Wut.')
# Create dictionary of panel toggles and settings
# Input can be string e.g. 'rl' or dictionary e.g. {(1,2,3):'r', 4:'l'}
# NOTE: Internally we convert array references to 0-base here
# Add kwargs and the 'which' arguments
# Optionally change the default panel widths for 'colorbar' panels
if not isinstance(innercolorbars, (dict, str)):
raise ValueError('Must pass string of panel sides or dictionary mapping axes numbers to sides.')
if not isinstance(innerpanels, (dict, str)):
raise ValueError('Must pass string of panel sides or dictionary mapping axes numbers to sides.')
innerpanels = axes_dict(innerpanels or '', False)
innercolorbars = axes_dict(innercolorbars or '', False)
innerpanels_kw = axes_dict(innerpanels_kw, True)
for kw in innerpanels_kw.values():
kw['whichpanels'] = ''
for num,which in innerpanels.items():
innerpanels_kw[num]['whichpanels'] += translate(which)
for num,which in innercolorbars.items():
which = translate(which)
if which:
innerpanels_kw[num]['whichpanels'] += which
if re.search('[bt]', which):
kwargs['hspace'] = _fill(kwargs.get('hspace',None), rc['gridspec.xlab'])
innerpanels_kw[num]['sharex_panels'] = False
innerpanels_kw[num]['hwidth'] = _fill(innerpanels_kw[num].get('hwidth', None), rc['gridspec.cbar'])
innerpanels_kw[num]['hspace'] = _fill(innerpanels_kw[num].get('hspace', None), rc['gridspec.xlab'])
if re.search('[lr]', which):
kwargs['wspace'] = _fill(kwargs.get('wspace',None), rc['gridspec.ylab'])
innerpanels_kw[num]['sharey_panels'] = False
innerpanels_kw[num]['wwidth'] = _fill(innerpanels_kw[num].get('wwidth', None), rc['gridspec.cbar'])
if 'l' in which and 'r' in which:
default = (rc['gridspec.ylab'], rc['gridspec.nolab'])
elif 'l' in which:
default = rc['gridspec.ylab']
else:
default = rc['gridspec.nolab']
innerpanels_kw[num]['wspace'] = _fill(innerpanels_kw[num].get('wspace', None), default)
# Create gridspec for outer plotting regions (divides 'main area' from side panels)
figsize, offset, subplots_kw, gridspec_kw = _gridspec_kwargs(nrows, ncols, **kwargs)
row_offset, col_offset = offset
gs = FlexibleGridSpec(**gridspec_kw)
fig = plt.figure(figsize=figsize, auto_adjust=auto_adjust, rcreset=rcreset,
gridspec=gs, subplots_kw=subplots_kw,
FigureClass=base.Figure,
)
#--------------------------------------------------------------------------
# Manage shared axes/axes with spanning labels
#--------------------------------------------------------------------------
# Get some axes properties
# Note that these locations should be **sorted** by axes id
axes_ids = [np.where(array==i) for i in np.unique(array) if i>0] # 0 stands for empty
yrange = row_offset + np.array([[xy[0].min(), xy[0].max()+1] for xy in axes_ids]) # yrange is shared columns
xrange = col_offset + np.array([[xy[1].min(), xy[1].max()+1] for xy in axes_ids])
# asdfas
# xmin = np.array([xy[0].min() for xy in axes_ids]) # unused
# ymax = np.array([xy[1].max() for xy in axes_ids])
# Shared axes: generate list of base axes-dependent axes pairs
# That is, find where the minimum-maximum gridspec extent in 'x' for a
# given axes matches the minimum-maximum gridspec extent for a base axes
xgroups_base, xgroups_sorted, xgroups, grouped = [], [], [], []
if sharex:
for i in range(num_axes): # axes now have pseudo-numbers from 0 to num_axes-1
matches = (xrange[i,:]==xrange).all(axis=1) # *broadcasting rules apply here*
matching_axes = np.where(matches)[0] # gives ID number of matching_axes, from 0 to num_axes-1
if i not in grouped and matching_axes.size>1:
# Find all axes that have the same gridspec 'x' extents
xgroups += [matching_axes]
# Get bottom-most axis with shared x; should be single number
# xgroups_base += [matching_axes[np.argmax(yrange[matching_axes,1])]]
xgroups_base += [matching_axes[np.argmax(yrange[matching_axes,1])]]
# Sorted group
xgroups_sorted += [matching_axes[np.argsort(yrange[matching_axes,1])[::-1]]] # bottom-most axes is first
grouped += [*matching_axes] # bookkeeping; record ids that have been grouped already
ygroups_base, ygroups_sorted, ygroups, grouped = [], [], [], []
if sharey:
for i in range(num_axes):
matches = (yrange[i,:]==yrange).all(axis=1) # *broadcasting rules apply here*
matching_axes = np.where(matches)[0]
if i not in grouped and matching_axes.size>1:
ygroups += [matching_axes]
ygroups_base += [matching_axes[np.argmin(xrange[matching_axes,0])]] # left-most axis with shared y, for matching_axes
ygroups_sorted += [matching_axes[np.argsort(xrange[matching_axes,0])]] # left-most axis is first
grouped += [*matching_axes] # bookkeeping; record ids that have been grouped already
#--------------------------------------------------------------------------
# Draw axes
# TODO: Need to configure to automatically determine 'base' axes based on
# what has already been drawn. Not critical but would be nice.
# TODO: Need to do something similar for the spanning axes. Also will
# allow label to be set on any of the axes, but when this happens, will
# set the label on the 'base' spanning axes.
#--------------------------------------------------------------------------
# Base axes; to be shared with other axes as ._sharex, ._sharey attributes
axs = num_axes*[None] # list of axes
allgroups_base = []
if sharex:
allgroups_base += xgroups_base
if sharey:
allgroups_base += ygroups_base
for i in allgroups_base:
ax_kw = axes_kw[i]
if axs[i] is not None: # already created
continue
if innerpanels_kw[i]['whichpanels']: # non-empty
axs[i] = fig.panel_factory(gs[slice(*yrange[i,:]), slice(*xrange[i,:])],
spanx=spanx, spany=spany,
number=i+1, **ax_kw, **innerpanels_kw[i]) # main axes handle
else:
axs[i] = fig.add_subplot(gs[slice(*yrange[i,:]), slice(*xrange[i,:])],
spanx=spanx, spany=spany,
number=i+1, **ax_kw) # main axes can be a cartopy projection
# Dependent axes
for i in range(num_axes):
# Detect if we want to share this axis with another. If so, get that
# axes. Also do some error checking
sharex_ax, sharey_ax = None, None # by default, don't share with other axes objects
ax_kw = axes_kw[i]
if sharex:
igroup = np.where([i in g for g in xgroups])[0]
if igroup.size==1:
sharex_ax = axs[xgroups_base[igroup[0]]]
if sharex_ax is None:
raise ValueError('Something went wrong; shared x axes was not already drawn.')
if sharey:
igroup = np.where([i in g for g in ygroups])[0] # np.where works on lists
if igroup.size==1:
sharey_ax = axs[ygroups_base[igroup[0]]]
if sharey_ax is None:
raise ValueError('Something went wrong; shared x axes was not already drawn.')
# Draw axes, and add to list
if axs[i] is not None:
# Axes is a *base* and has already been drawn, but might still
# have shared axes (e.g. is bottom-axes of three-column plot
# and we want it to share the leftmost y-axis)
if sharex_ax is not None and axs[i] is not sharex_ax:
axs[i]._sharex_setup(sharex_ax, sharex)
if sharey_ax is not None and axs[i] is not sharey_ax:
axs[i]._sharey_setup(sharey_ax, sharey)
else:
# Virgin axes; these are not an x base or a y base
if innerpanels_kw[i]['whichpanels']: # non-empty
axs[i] = fig.panel_factory(gs[slice(*yrange[i,:]), slice(*xrange[i,:])],
number=i+1, spanx=spanx, spany=spany,
sharex_level=sharex, sharey_level=sharey,
sharex=sharex_ax, sharey=sharey_ax, **ax_kw, **innerpanels_kw[i])
else:
axs[i] = fig.add_subplot(gs[slice(*yrange[i,:]), slice(*xrange[i,:])],
number=i+1, spanx=spanx, spany=spany,
sharex_level=sharex, sharey_level=sharey,
sharex=sharex_ax, sharey=sharey_ax, **ax_kw) # main axes can be a cartopy projection
# Check that axes don't belong to multiple groups
# This should be impossible unless my code is completely wrong...
for ax in axs:
for name,groups in zip(('sharex', 'sharey'), (xgroups, ygroups)):
if sum(ax in group for group in xgroups)>1:
raise ValueError(f'Something went wrong; axis {i:d} belongs to multiple {name} groups.')
#--------------------------------------------------------------------------#
# Create panel axes
#--------------------------------------------------------------------------#
def _paneladd(name, panels):
if not panels:
return
axsp = []
side = re.sub('^(.*)panel$', r'\1', name)
for n in np.unique(panels).flat:
offset = row_offset if side in ('left','right') else col_offset
idx, = np.where(panels==n)
idx = slice(offset + min(idx), offset + max(idx) + 1)
if side=='right':
subspec = gs[idx,-1]
elif side=='left':
subspec = gs[idx,0]
elif side=='bottom':
subspec = gs[-1,idx]
axp = fig.add_subplot(subspec, panel_side=side, invisible=True, projection='panel')
axsp += [axp]
setattr(fig, name, axes_list(axsp))
_paneladd('bottompanel', subplots_kw.bottompanels)
_paneladd('rightpanel', subplots_kw.rightpanels)
_paneladd('leftpanel', subplots_kw.leftpanels)
#--------------------------------------------------------------------------
# Return results
# Will square singleton arrays
#--------------------------------------------------------------------------
if not silent:
print('Figure setup complete.')
# if len(axs)==1:
# axs = axs[0]
# return fig, axs
return fig, axes_list(axs)
<file_sep>#!/usr/bin/env python3
"""
Script that simply lists the availble system fonts.
Add to this.
"""
import os
import re
import shutil
from glob import glob
from matplotlib import matplotlib_fname
from matplotlib import get_cachedir
import matplotlib.font_manager as mfonts
# from subprocess import Popen, PIPE
#------------------------------------------------------------------------------
# List the current font names, original version; works on Linux but not Mac,
# because can't find mac system fonts?
#------------------------------------------------------------------------------#
# List the system font names, smarter version
# See: https://github.com/olgabot/sciencemeetproductivity.tumblr.com/blob/master/posts/2012/11/how-to-set-helvetica-as-the-default-sans-serif-font-in.md
# Also see: https://olgabotvinnik.com/blog/2012-11-15-how-to-set-helvetica-as-the-default-sans-serif-font-in/
# Also see: https://stackoverflow.com/questions/18821795/how-can-i-get-list-of-font-familyor-name-of-font-in-matplotlib
_dir_data = re.sub('/matplotlibrc$', '', matplotlib_fname())
fonts_mpl_files = sorted(glob(f"{_dir_data}/fonts/ttf/*.[ot]tf"))
fonts_os_files = sorted(mfonts.findSystemFonts(fontpaths=None, fontext='ttf')) # even with that fontext, will include otf! weird
fonts_os, fonts_mpl = set(), set()
for _file in fonts_os_files:
try:
fonts_os.add(mfonts.FontProperties(fname=_file).get_name())
except Exception as err:
pass # fails sometimes
for _file in fonts_mpl_files:
try:
fonts_mpl.add(mfonts.FontProperties(fname=_file).get_name())
except Exception as err:
pass # fails sometimes
fonts = {*fonts_os, *fonts_mpl}
# Missing fonts (add to this list whenever user requests one)
_missing_fonts = []
#------------------------------------------------------------------------------#
# Function that sets up any .ttf fonts contained in the <fonts> directory to
# be detected by matplotlib, regardless of the OS.
# See: https://olgabotvinnik.com/blog/2012-11-15-how-to-set-helvetica-as-the-default-sans-serif-font-in/
# Best fonts for dyslexia: http://dyslexiahelp.umich.edu/sites/default/files/good_fonts_for_dyslexia_study.pdf
#------------------------------------------------------------------------------#
# ***Notes on getting ttf files on Mac****
# /System/Library/Font *OR* /Library/Fonts
# * The .otf files work in addition to .ttf files; you can verify this by
# looking at plot.fonts_files_os (results of findSystemFonts command) --
# the list will include a bunch of .otf files.
# * Some system fonts are .dfont which are unreadable to matplotlib; use
# fondu (download with Homebrew) to break down.
# * Sometimes fondu created .bdf files, not .ttf; use https://github.com/Tblue/mkttf
# Requires FontForge and PoTrace
# * Install new fonts with: "brew cask install font-<name-of-font>" after using
# "brew tap caskroom/fonts" to initialize; these will appear in ~/Library/Fonts.
# * For some conversion tools, run "pip install fonttools". Documentation
# is here: https://github.com/fonttools/fonttools
#------------------------------------------------------------------------------#
# ***Notes on default files packaged in font directory.
# * Location will be something like: /lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
# * 'STIX' fonts allow different LaTeX-like math modes e.g. blackboard bold
# and caligraphy; see: https://matplotlib.org/gallery/text_labels_and_annotations/stix_fonts_demo.html
# * The 'cm'-prefix fonts seem to provide additional mathematical symbols
# like integrals, and italized math-mode fonts.
# * We also have 'pdfcorefonts' in this directory, but I think since these
# are afm matplotlib cannot use them? Don't know.
#------------------------------------------------------------------------------#
def install_fonts():
"""
Install matplotlib fonts from ttf files located in the 'fonts' directory.
May require restarting iPython session. Note font cache will be deleted
in this process, which could cause delays.
"""
# See: https://stackoverflow.com/a/2502883/4970632
# Just print strings because in notebooks will get printed
# to terminal; see: https://stackoverflow.com/q/38616077/4970632
# _font_script = f'{os.path.dirname(__file__)}/fontscript.sh'
# p = Popen(_font_script, stdout=PIPE, shell=False)
# out, err = p.communicate()
# print(out.decode('utf-8').strip()) # strip trailing newline
# New method, just do this in python
dir_source = f'{os.path.dirname(__file__)}/fonts' # should be in same place as scripts
dir_dest = f'{_dir_data}/fonts/ttf'
# print(f'Transfering .ttf and .otf files from {dir_source} to {dir_dest}.')
for file in glob(f'{dir_source}/*.[ot]tf'):
if not os.path.exists(f'{dir_dest}/{os.path.basename(file)}'):
print(f'Adding font "{os.path.basename(file)}".')
shutil.copy(file, dir_dest)
# Delete cache
dir_cache = get_cachedir()
for file in glob(f'{dir_cache}/*.cache') + glob(f'{dir_cache}/font*'):
if not os.path.isdir(file): # don't dump the tex.cache folder... because dunno why
os.remove(file)
print(f'Deleted font cache {file}.')
# Message
print('Fonts have been installed and font cache has been emptied. Please restart your iPython session.')
<file_sep>#!/usr/bin/env python3
"""
Define various axis scales, locators, and formatters. Also define normalizers
generally used for colormap scaling. Below is rough overview of API.
General Notes:
* Want to try to avoid **using the Formatter to scale/transform values, and
passing the locator an array of scaled/transformed values**. Makes more sense
to instead define separate **axis transforms**, then can use locators and
formatters like normal, as they were intended to be used. This way, if e.g.
matching frequency-axis with wavelength-axis, just conver the **axis limits**
so they match, then you're good.
Scales:
* These are complicated. See: https://matplotlib.org/_modules/matplotlib/scale.html#ScaleBase
Use existing ones as inspiration -- e.g. InverseScale modeled after LogScale.
* Way to think of these is that *every single value you see on an axes first
gets secretly converted through some equation*, e.g. logarithm, and plotted
linearly in that transformation space.
* Methods include:
- get_transform(), which should return an mtransforms.Transform instance
- set_default_locators_and_formatters(), which should return
default locators and formatters
- limit_range_for_scale(), which can be used to raise errors/clip
stuff not within that range. From Mercator example: unlike the
autoscaling provided by the tick locators, this range limiting will
always be adhered to, whether the axis range is set manually,
determined automatically or changed through panning and zooming.
* Also, have to be 'registered' unlike locators and formatters, which
can be passed to the 'set' methods. Or maybe not?
Transforms:
* These are complicted. See: https://matplotlib.org/_modules/matplotlib/transforms.html#Transform
* Attributes:
- input_dims, output_dims, is_separable, and has_inverse; the dims are because
transforms can be N-D, but for *scales* are always 1, 1. Note is_separable is
true if transform is separable in x/y dimensions.
* Methods:
- transform(): transforms N-D coordinates, given M x N array of values. Can also
just declare transform_affine or transform_non_affine.
- inverted(): if has_inverse True, performs inverse transform.
Locators:
* These are complicated. See: https://matplotlib.org/_modules/matplotlib/ticker.html#Locator
* Special:
- __init__() not defined on base class but *must* be defined for subclass.
* Methods include:
- tick_values(), which accepts vmin/vmax and returns values of located ticks
- __call__(), which can return data limits, view limits, or
other stuff; not sure how this works or when it's invoked.
- view_limits(), which changes the *view* limits from default vmin, vmax
to prevent singularities (uses mtransforms.nonsingular method; for
more info on this see: https://matplotlib.org/_modules/matplotlib/transforms.html#nonsingular)
* Methods that usually can be left alone:
- raise_if_exceeds(), which just tests if ticks exceed MAXTICKS number
- autoscale(), which calls the internal locator 'view_limits' with
result of axis.get_view_interval()
- pan() and zoom() for interactive purposes
Formatters:
* Easy to construct: just build with FuncFormatter a function that accepts
the number and a 'position', which maybe is used for offset or something
but almost always don't touch it, leave it default.
Normalizers:
* Generally these are used for colormaps, easy to construct: require
only an __init__ method and a __call__ method.
* The init method takes vmin, vmax, and clip, and can define custom
attributes. The call method just returns a *masked array* to handle NaNs,
and call transforms data from physical units to *normalized* units
from 0-1, representing position in colormap.
"""
#------------------------------------------------------------------------------#
# Imports
#------------------------------------------------------------------------------#
import re
from . import utils
from .utils import ic
from fractions import Fraction
from types import FunctionType
import numpy as np
import numpy.ma as ma
import matplotlib.dates as mdates
import matplotlib.colors as mcolors
import matplotlib.ticker as mticker
import matplotlib.scale as mscale
import matplotlib.transforms as mtransforms
#------------------------------------------------------------------------------#
# Tick scales
#------------------------------------------------------------------------------#
scales = ['linear','log','symlog','logit', # builtin
'pressure', 'height',
'exp','sine','mercator','inverse'] # custom
def scale(scale, **kwargs):
"""
Generate arbitrary scale object.
"""
args = []
if utils.isvector(scale):
scale, args = scale[0], scale[1:]
if scale in scales and not args:
pass # already registered
elif scale=='cutoff':
scale = CutoffScaleFactory(*args, **kwargs)
elif scale in ('exp', 'height', 'pressure'): # note here args is non-zero
if scale=='height':
if len(args)!=1:
raise ValueError('Only one non-keyword arg allowed.')
args = [*args, True]
if scale=='pressure':
if len(args)!=1:
raise ValueError('Only one non-keyword arg allowed.')
args = [*args, False]
scale = ExpScaleFactory(*args, **kwargs)
else:
raise ValueError(f'Unknown scale {scale}.')
return scale
class ExpTransform(mtransforms.Transform):
# Create transform object
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, scale, minpos):
mtransforms.Transform.__init__(self)
self.minpos = minpos
self.scale = scale
def transform(self, a):
a = np.array(a)
aa = a.copy()
return np.exp(self.scale*aa)
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return InvertedExpTransform(self.scale, self.minpos)
class InvertedExpTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, scale, minpos):
mtransforms.Transform.__init__(self)
self.minpos = minpos
self.scale = scale
def transform(self, a):
a = np.array(a)
aa = a.copy()
aa[a<=self.minpos] = self.minpos
aa = np.log(aa)/self.scale
return aa # natural log here
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return ExpTransform(self.scale, self.minpos)
def ExpScaleFactory(scale, to_exp=True, name='exp'):
"""
Exponential scale, useful for plotting height and pressure e.g.
"""
scale_name = name # must make a copy
# scale = 1 # TODO: Shouldn't the scale not matter?
# scale = -1.0 # this seems to prevent ticks from going off edge
class ExpScale(mscale.ScaleBase):
name = scale_name # assigns as attribute
# Declare name
def __init__(self, axis, minpos=1e-300, **kwargs):
# Initialize
mscale.ScaleBase.__init__(self)
self.minpos = minpos
def limit_range_for_scale(self, vmin, vmax, minpos):
# Prevent conversion from inverting axis scale, which
# happens when scale is less than zero
# 99% of time this is want user will want I think
if scale<0:
vmax, vmin = vmin, vmax
if not np.isfinite(minpos):
minpos = 1e-300
return (minpos if vmin <= 0 else vmin,
minpos if vmax <= 0 else vmax)
def set_default_locators_and_formatters(self, axis):
# Consider changing this
axis.set_smart_bounds(True) # may prevent ticks from extending off sides
axis.set_major_formatter(formatter('custom'))
axis.set_minor_formatter(formatter('null'))
def get_transform(self):
# Either sub into e(scale*z), the default, or invert
# the exponential
if to_exp:
return ExpTransform(scale, self.minpos)
else:
return InvertedExpTransform(scale, self.minpos)
# Register and return
mscale.register_scale(ExpScale)
# print(f'Registered scale "{scale_name}".')
return scale_name
def CutoffScaleFactory(scale, lower, upper=None, name='cutoff'):
"""
Constructer for scale with custom cutoffs. Three options here:
1. Put a 'cliff' between two numbers (default).
2. Accelerate the scale gradient between two numbers (scale>1).
3. Deccelerate the scale gradient between two numbers (scale<1). So
scale is fast on edges but slow in middle.
Todo:
* Alongside this, create method for drawing those cutoff diagonal marks
with white space between.
See: https://stackoverflow.com/a/5669301/4970632 for multi-axis solution
and for this class-based solution. Note the space between 1-9 in Paul's answer
is because actual cutoffs were 0.1 away (and tick locs are 0.2 apart).
"""
scale_name = name # have to copy to different name
if scale<0:
raise ValueError('Scale must be a positive float.')
if upper is None:
if scale==np.inf:
raise ValueError('For infinite scale (i.e. discrete cutoff), need both lower and upper bounds.')
class CutoffScale(mscale.ScaleBase):
# Declare name
name = scale_name
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
self.name = scale_name
def get_transform(self):
return self.CutoffTransform()
def set_default_locators_and_formatters(self, axis):
axis.set_major_formatter(formatter('custom'))
axis.set_minor_formatter(formatter('null'))
axis.set_smart_bounds(True) # may prevent ticks from extending off sides
class CutoffTransform(mtransforms.Transform):
# Create transform object
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self):
mtransforms.Transform.__init__(self)
def transform(self, a):
a = np.array(a) # very numpy array
aa = a.copy()
if upper is None: # just scale between 2 segments
m = (a > lower)
aa[m] = a[m] - (a[m] - lower)*(1 - 1/scale)
elif lower is None:
m = (a < upper)
aa[m] = a[m] - (upper - a[m])*(1 - 1/scale)
else:
m1 = (a > lower)
m2 = (a > upper)
m3 = (a > lower) & (a < upper)
if scale==np.inf:
aa[m1] = a[m1] - (upper - lower)
aa[m3] = lower
else:
aa[m2] = a[m2] - (upper - lower)*(1 - 1/scale)
aa[m3] = a[m3] - (a[m3] - lower)*(1 - 1/scale)
return aa
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return CutoffScale.InvertedCutoffTransform()
class InvertedCutoffTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self):
mtransforms.Transform.__init__(self)
def transform(self, a):
a = np.array(a)
aa = a.copy()
if upper is None:
m = (a > lower)
aa[m] = a[m] + (a[m] - lower)*(1 - 1/scale)
elif lower is None:
m = (a < upper)
aa[m] = a[m] + (upper - a[m])*(1 - 1/scale)
else:
n = (upper-lower)*(1 - 1/scale)
m1 = (a > lower)
m2 = (a > upper - n)
m3 = (a > lower) & (a < (upper - n))
if scale==np.inf:
aa[m1] = a[m1] + (upper - lower)
else:
aa[m2] = a[m2] + n
aa[m3] = a[m3] + (a[m3] - lower)*(1 - 1/scale)
return aa
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return CutoffScale.CutoffTransform()
# Register and return
mscale.register_scale(CutoffScale)
# print(f'Registered scale "{scale_name}".')
return scale_name
class MercatorLatitudeScale(mscale.ScaleBase):
"""
See: https://matplotlib.org/examples/api/custom_scale_example.html
The scale function:
ln(tan(y) + sec(y))
The inverse scale function:
atan(sinh(y))
Applies user-defined threshold below +/-90 degrees above and below which nothing
will be plotted. See: http://en.wikipedia.org/wiki/Mercator_projection
Mercator can actually be useful in some scientific contexts; one of Libby's
papers uses it I think.
"""
name = 'mercator'
def __init__(self, axis, *, thresh=85.0, **kwargs):
# Initialize
mscale.ScaleBase.__init__(self)
if thresh >= 90.0:
raise ValueError('Threshold "thresh" must be <=90.')
self.thresh = thresh
def get_transform(self):
# Return special transform object
return self.MercatorLatitudeTransform(self.thresh)
def limit_range_for_scale(self, vmin, vmax, minpos):
# *Hard* limit on axis boundaries
return max(vmin, -self.thresh), min(vmax, self.thresh)
def set_default_locators_and_formatters(self, axis):
# Apply these
axis.set_smart_bounds(True)
axis.set_major_locator(Locator(20)) # every 20 degrees
axis.set_major_formatter(formatter('deg'))
axis.set_minor_formatter(formatter('null'))
class MercatorLatitudeTransform(mtransforms.Transform):
# Default attributes
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, thresh):
# Initialize, declare attribute
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
# For M N-dimensional transform, transform MxN into result
# So numbers stay the same, but data will then be linear in the
# result of the math below.
a = np.radians(a) # convert to radians
m = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)
# m[m.mask] = np.nan
# a[m.mask] = np.nan
if m.mask.any():
return ma.log(np.abs(ma.tan(m) + 1.0 / ma.cos(m)))
else:
return np.log(np.abs(np.tan(a) + 1.0 / np.cos(a)))
def inverted(self):
# Just call inverse transform class
return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(self.thresh)
class InvertedMercatorLatitudeTransform(mtransforms.Transform):
# As above, but for the inverse transform
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
# m = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)
return np.degrees(np.arctan2(1, np.sinh(a))) # always assume in first/fourth quadrant, i.e. go from -pi/2 to pi/2
def inverted(self):
return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh)
class SineLatitudeScale(mscale.ScaleBase):
"""
The scale function:
sin(rad(y))
The inverse scale function:
deg(arcsin(y))
"""
name = 'sine'
def __init__(self, axis, **kwargs):
# Initialize
mscale.ScaleBase.__init__(self)
def get_transform(self):
# Return special transform object
return self.SineLatitudeTransform()
def limit_range_for_scale(self, vmin, vmax, minpos):
# *Hard* limit on axis boundaries
return vmin, vmax
# return max(vmin, -90), min(vmax, 90)
def set_default_locators_and_formatters(self, axis):
# Apply these
axis.set_smart_bounds(True)
axis.set_major_locator(locator(20)) # every 20 degrees
axis.set_major_formatter(formatter('deg'))
axis.set_minor_formatter(formatter('null'))
class SineLatitudeTransform(mtransforms.Transform):
# Default attributes
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self):
# Initialize, declare attribute
mtransforms.Transform.__init__(self)
def transform_non_affine(self, a):
# Transformation
with np.errstate(invalid='ignore'): # NaNs will always be False
m = (a >= -90) & (a <= 90)
if not m.all():
aa = ma.masked_where(~m, a)
return ma.sin(np.deg2rad(aa))
else:
return np.sin(np.deg2rad(a))
def inverted(self):
# Just call inverse transform class
return SineLatitudeScale.InvertedSineLatitudeTransform()
class InvertedSineLatitudeTransform(mtransforms.Transform):
# As above, but for the inverse transform
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self):
mtransforms.Transform.__init__(self)
def transform_non_affine(self, a):
# Clipping, instead of setting invalid
# NOTE: Using ma.arcsin below caused super weird errors, dun do that
aa = a.copy()
return np.rad2deg(np.arcsin(aa))
def inverted(self):
return MercatorLatitudeScale.SineLatitudeTransform()
class InverseScale(mscale.ScaleBase):
"""
Similar to LogScale, but this scales to be linear in *inverse* of x. Very
useful e.g. to plot wavelengths on twin axis with wavenumbers.
Important note:
Unlike log-scale, we can't just warp the space between
the axis limits -- have to actually change axis limits. This scale will
invert and swap the limits you provide. Weird! But works great!
"""
# Declare name
name = 'inverse'
def __init__(self, axis, minpos=1e-2, **kwargs):
# Initialize (note thresh is always needed)
mscale.ScaleBase.__init__(self)
self.minpos = minpos
def get_transform(self):
# Return transform class
return self.InverseTransform(self.minpos)
def limit_range_for_scale(self, vmin, vmax, minpos):
# *Hard* limit on axis boundaries
if not np.isfinite(minpos):
minpos = 1e-300
return (minpos if vmin <= 0 else vmin,
minpos if vmax <= 0 else vmax)
def set_default_locators_and_formatters(self, axis):
# TODO: fix minor locator issue
# NOTE: log formatter can ignore certain major ticks! why is that?
axis.set_smart_bounds(True) # may prevent ticks from extending off sides
axis.set_major_locator(mticker.LogLocator(base=10, subs=[1, 2, 5]))
axis.set_minor_locator(mticker.LogLocator(base=10, subs='auto'))
axis.set_major_formatter(formatter('custom'))
axis.set_minor_formatter(formatter('null'))
# axis.set_major_formatter(mticker.LogFormatter())
class InverseTransform(mtransforms.Transform):
# Create transform object
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, minpos):
mtransforms.Transform.__init__(self)
self.minpos = minpos
def transform(self, a):
a = np.array(a)
aa = a.copy()
aa[a<=0] = self.minpos
# aa[a<=0] = np.nan # minpos
return 1.0/aa
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return InverseScale.InvertedInverseTransform(self.minpos)
class InvertedInverseTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, minpos):
mtransforms.Transform.__init__(self)
self.minpos = minpos
def transform(self, a):
a = np.array(a)
aa = a.copy()
aa[a<=0] = self.minpos
# aa[a<=0] = np.nan # messes up automatic ylim setting
return 1.0/aa
def transform_non_affine(self, a):
return self.transform(a)
def inverted(self):
return InverseScale.InverseTransform(self.minpos)
# Register hard-coded scale names, so user can set_xscale and set_yscale with strings
mscale.register_scale(InverseScale)
mscale.register_scale(SineLatitudeScale)
mscale.register_scale(MercatorLatitudeScale)
ExpScaleFactory(-1.0/7, False, 'pressure') # scale pressure so it matches a height axis
ExpScaleFactory(-1.0/7, True, 'height') # scale height so it matches a pressure axis
#------------------------------------------------------------------------------#
# Helper functions for instantiating arbitrary Locator and Formatter classes
# When calling these functions, the format() method should automatically
# detect presence of date axis by testing if unit converter is on axis is
# DateConverter instance
# See: https://matplotlib.org/api/units_api.html
# And: https://matplotlib.org/api/dates_api.html
# Also see: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axis.py
# The axis_date() method just sets the converter to the date one
#------------------------------------------------------------------------------#
def locator(loc, *args, minor=False, time=False, **kwargs):
"""
Construct a locator object.
Argument:
Can be number (specify multiples along which ticks
are drawn), list (tick these positions), or string for dictionary
lookup of possible locators.
Optional:
time: whether we want 'datetime' locators
kwargs: passed to locator when instantiated
Note: Default Locator includes 'nbins' option to subsample
the points passed so that no more than 'nbins' ticks are selected.
"""
# Do nothing, and return None if locator is None
if isinstance(loc, mticker.Locator):
return loc
# Decipher user input
if loc is None:
if time:
loc = mticker.AutoDateLocator(*args, **kwargs)
elif minor:
loc = mticker.AutoMinorLocator(*args, **kwargs)
else:
loc = mticker.AutoLocator(*args, **kwargs)
elif type(loc) is str: # dictionary lookup
if loc=='logminor':
loc = 'log'
kwargs.update({'subs':np.arange(0,10)})
elif loc not in locators:
raise ValueError(f'Unknown locator "{loc}". Options are {", ".join(locators.keys())}.')
loc = locators[loc](*args, **kwargs)
elif utils.isnumber(loc): # scalar variable
loc = mticker.MultipleLocator(loc, *args, **kwargs)
else:
loc = mticker.FixedLocator(np.sort(loc), *args, **kwargs) # not necessary
return loc
def formatter(form, *args, time=False, tickrange=None, **kwargs):
"""
As above, auto-interpret user input.
Includes option for %-formatting of numbers and dates, passing a list of strings
for explicitly overwriting the text.
Argument:
can be number (specify max precision of output), list (set
the strings on integers of axis), string (for .format() or percent
formatting), string for dictionary lookup of possible
formatters, Formatter instance, or function.
Optional:
time: whether we want 'datetime' formatters
kwargs: passed to locator when instantiated
"""
# Already have a formatter object
if isinstance(form, mticker.Formatter): # formatter object
return form
if utils.isvector(form) and form[0]=='frac':
args.append(form[1]) # the number
form = form[0]
# Interpret user input
if form is None: # by default use my special super cool formatter, better than original
if time:
form = mdates.AutoDateFormatter(*args, **kwargs)
else:
form = CustomFormatter(*args, tickrange=tickrange, **kwargs)
elif isinstance(form, FunctionType):
form = mticker.FuncFormatter(form, *args, **kwargs)
elif type(form) is str: # assumption is list of strings
if '{x}' in form:
form = mticker.StrMethodFormatter(form, *args, **kwargs) # new-style .format() form
elif '%' in form:
if time:
form = mdates.DateFormatter(form, *args, **kwargs) # %-style, dates
else:
form = mticker.FormatStrFormatter(form, *args, **kwargs) # %-style, numbers
else:
if form not in formatters:
raise ValueError(f'Unknown formatter "{form}". Options are {", ".join(formatters.keys())}.')
if form in ['deg','deglon','deglat','lon','lat']:
kwargs.update({'deg':('deg' in form)})
form = formatters[form](*args, **kwargs)
elif utils.isnumber(form): # interpret scalar number as *precision*
form = CustomFormatter(form, *args, tickrange=tickrange, **kwargs)
else:
form = mticker.FixedFormatter(form) # list of strings on the major ticks, wherever they may be
return form
#-------------------------------------------------------------------------------
# Formatting classes for mapping numbers (axis ticks) to formatted strings
# Create pseudo-class functions that actually return auto-generated formatting
# classes by passing function references to Funcformatter
#-------------------------------------------------------------------------------
# First the default formatter
def CustomFormatter(precision=2, tickrange=[-np.inf, np.inf]):
"""
Format as a number, with N sigfigs, and trimming trailing zeros.
Recall, must pass function in terms of n (number) and loc.
Arguments:
precision: max number of digits after decimal place (default 3)
tickrange: range [min,max] in which we draw tick labels (allows removing
tick labels but keeping ticks in certain region; default [-np.inf,np.inf])
For minus sign scaling, see: https://tex.stackexchange.com/a/79158/73149
"""
# Format definition
if tickrange is None:
tickrange = [-np.inf, np.inf]
elif utils.isnumber(tickrange): # use e.g. -1 for no ticks
tickrange = [-tickrange, tickrange]
def f(value, location):
# Exit if not in tickrange
eps = abs(value)/1000
if (value+eps)<tickrange[0] or (value-eps)>tickrange[1]:
return '' # avoid some ticks
# Return special string
# * Note *cannot* use 'g' because 'g' precision operator specifies count of
# significant digits, not places after decimal place.
# * There is no format that specifies digits after decimal place AND trims trailing zeros.
string = f'{{{0}:.{precision:d}f}}'.format(value) # f-string compiled, then format run
if '.' in string: # g-style trimming
string = string.rstrip('0').rstrip('.')
if string=='-0': # special case
string = '0'
if value>0 and string=='0':
# raise RuntimeError('Tried to round tick position label to zero. Add precision or use an exponential formatter.')
print('Warning: Tried to round tick position label to zero. Add precision or use an exponential formatter.')
# Use unicode minus instead of ASCII hyphen (which is default)
string = re.sub('-', '−', string) # pure unicode minus
# string = re.sub('-', '${-}$', string) # latex version
# string = re.sub('-', u'\u002d', string) # unicode hyphen minus, looks same as hyphen
# string = re.sub('-', r'\scalebox{0.75}[1.0]{$-$}', string)
return string
# And create object
return mticker.FuncFormatter(f)
#------------------------------------------------------------------------------#
# Formatting with prefixes
#------------------------------------------------------------------------------#
def PrefixSuffixFormatter(*args, prefix=None, suffix=None, **kwargs):
"""
Arbitrary prefix and suffix in front of values.
"""
prefix = prefix or ''
suffix = suffix or ''
def f(value, location):
# Finally use default formatter
func = CustomFormatter(*args, **kwargs)
return prefix + func(value, location) + suffix
# And create object
return mticker.FuncFormatter(f)
def MoneyFormatter(*args, **kwargs):
"""
Arbitrary prefix and suffix in front of values.
"""
# And create object
return PrefixSuffixFormatter(*args, prefix='$', **kwargs)
#------------------------------------------------------------------------------#
# Formatters for dealing with one axis in geographic coordinates
#------------------------------------------------------------------------------#
def CoordinateFormatter(*args, cardinal=None, deg=True, **kwargs):
"""
Generalized function for making LatFormatter and LonFormatter.
Requires only which string to use for points left/right of zero (e.g. W/E, S/N).
"""
def f(value, location):
# Optional degree symbol
suffix = ''
if deg:
suffix = '\N{DEGREE SIGN}' # Unicode lookup by name
# Apply suffix if not on equator/prime meridian
if isinstance(cardinal,str):
if value<0:
value *= -1
suffix += cardinal[0]
elif value>0:
suffix += cardinal[1]
# Finally use default formatter
func = CustomFormatter(*args, **kwargs)
return func(value, location) + suffix
# And create object
return mticker.FuncFormatter(f)
def LatFormatter(*args, **kwargs):
"""
Just calls CoordinateFormatter. Note the strings are only used if
we set cardinal=True, otherwise just prints negative/positive degrees.
"""
return CoordinateFormatter(*args, cardinal='SN', **kwargs)
def LonFormatter(*args, **kwargs):
"""
Just calls CoordinateFormatter. Note the strings are only used if
we set cardinal=True, otherwise just prints negative/positive degrees.
"""
return CoordinateFormatter(*args, cardinal='WE', **kwargs)
#------------------------------------------------------------------------------#
# Formatters with fractions
#------------------------------------------------------------------------------#
def FracFormatter(symbol, number):
"""
Format as fractions, multiples of some value, e.g. a physical constant.
"""
def f(n, loc): # must accept location argument
frac = Fraction(n/number).limit_denominator()
if n==0: # zero
string = '0'
elif frac.denominator==1: # denominator is one
if frac.numerator==1:
string = f'${symbol}$'
elif frac.numerator==-1:
string = f'${{-}}{symbol:s}$'
else:
string = f'${frac.numerator:d}{symbol:s}$'
elif frac.numerator==1: # numerator is +/-1
string = f'${symbol:s}/{frac.denominator:d}$'
elif frac.numerator==-1:
string = f'${{-}}{symbol:s}/{frac.denominator:d}$'
else: # and again make sure we use unicode minus!
string = f'${frac.numerator:d}{symbol:s}/{frac.denominator:d}$'
# string = re.sub('-', '−', string) # minus will be converted to unicode version since it's inside LaTeX math
return string
# And create FuncFormatter class
return mticker.FuncFormatter(f)
def PiFormatter():
"""
Return FracFormatter, where the number is np.pi and
symbol is $\pi$.
"""
return FracFormatter(r'\pi', np.pi)
def eFormatter():
"""
Return FracFormatter, where the number is np.exp(1) and
symbol is $e$.
"""
return FracFormatter('e', np.exp(1))
# Declare dictionaries
# Includes some custom classes, so has to go at end
locators = {
'none': mticker.NullLocator,
'null': mticker.NullLocator,
'log': mticker.LogLocator,
'maxn': mticker.MaxNLocator,
'linear': mticker.LinearLocator,
'log': mticker.LogLocator,
'multiple': mticker.MultipleLocator,
'fixed': mticker.FixedLocator,
'index': mticker.IndexLocator,
'symmetric': mticker.SymmetricalLogLocator,
'logit': mticker.LogitLocator,
'minor': mticker.AutoMinorLocator,
'microsecond': mdates.MicrosecondLocator,
'second': mdates.SecondLocator,
'minute': mdates.MinuteLocator,
'hour': mdates.HourLocator,
'day': mdates.DayLocator,
'weekday': mdates.WeekdayLocator,
'month': mdates.MonthLocator,
'year': mdates.YearLocator,
}
formatters = { # note default LogFormatter uses ugly e+00 notation
'none': mticker.NullFormatter,
'null': mticker.NullFormatter,
'strmethod': mticker.StrMethodFormatter,
'formatstr': mticker.FormatStrFormatter,
'scalar': mticker.ScalarFormatter,
'log': mticker.LogFormatterSciNotation,
'eng': mticker.LogFormatterMathtext,
'sci': mticker.LogFormatterSciNotation,
'logit': mticker.LogitFormatter,
'eng': mticker.EngFormatter,
'percent': mticker.PercentFormatter,
'index': mticker.IndexFormatter,
'default': CustomFormatter,
'custom': CustomFormatter,
'proplot': CustomFormatter,
'$': MoneyFormatter,
'pi': PiFormatter,
'e': eFormatter,
'deg': CoordinateFormatter,
'lat': LatFormatter,
'lon': LonFormatter,
'deglat': LatFormatter,
'deglon': LonFormatter,
}
<file_sep>#!/usr/bin/env python3
import numpy as np
import matplotlib.gridspec as mgridspec
import re
from .rcmod import rc
from .utils import _dot_dict, _fill, ic
# Conversions
def _units(value, error=True):
# Flexible units!
# See: http://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align#lets-talk-about-font-size-first
if not isinstance(value, str):
return value # assume int/float is in inches
unit_dict = {
'em': rc['small']/72.0,
'ex': 0.5*rc['large']/72.0, # more or less; see URL
'lh': 1.2*rc['small']/72.0, # line height units (default spacing is 1.2 em squares)
'lem': rc['small']/72.0, # for large text
'lex': 0.5*rc['large']/72.0,
'llh': 1.2*rc['large']/72.0,
'cm': 0.3937,
'mm': 0.03937,
'pt': 1/72.0,
'in': 1.0, # already in inches
}
regex = re.match('^(.*)(' + '|'.join(unit_dict.keys()) + ')$', value)
if not regex:
if error:
raise ValueError(f'Invalid size spec {value}.')
else:
return value
num, unit = regex.groups()
try:
num = float(num)
except ValueError:
if error:
raise ValueError(f'Invalid size spec {value}.')
else:
return value
return num*unit_dict[unit] # e.g. cm / (in / cm)
# Custom settings for various journals
# Add to this throughout your career, or as standards change
# PNAS info: http://www.pnas.org/page/authors/submission
# AMS info: https://www.ametsoc.org/ams/index.cfm/publications/authors/journal-and-bams-authors/figure-information-for-authors/
# AGU info: https://publications.agu.org/author-resource-center/figures-faq/
def journal_size(journal):
# Determine automatically
table = {
'pnas1': '8.7cm',
'pnas2': '11.4cm',
'pnas3': '17.8cm',
'ams1': 3.2,
'ams2': 4.5,
'ams3': 5.5,
'ams4': 6.5,
'agu1': ('95mm', '115mm'),
'agu2': ('190mm', '115mm'),
'agu3': ('95mm', '230mm'),
'agu4': ('190mm', '230mm'),
}
value = table.get(journal, None)
if value is None:
raise ValueError(f'Unknown journal figure size specifier "{journal}". ' +
'Current options are: ' + ', '.join(table.keys()))
# Return width, and optionally also the height
width, height = None, None
try:
width, height = value
except TypeError:
width = value
return width, height
# Function for processing input and generating necessary keyword args
def _gridspec_kwargs(nrows, ncols, rowmajor=True,
aspect=1, figsize=None, # for controlling aspect ratio, default is control for width
width=None, height=None, axwidth=None, axheight=None, journal=None,
hspace=None, wspace=None, hratios=None, wratios=None, # spacing between axes, in inches (hspace should be bigger, allowed room for title)
left=None, bottom=None, right=None, top=None, # spaces around edge of main plotting area, in inches
bwidth=None, bspace=None, rwidth=None, rspace=None, lwidth=None, lspace=None, # default to no space between panels
bottompanel=False, bottompanels=False, # bottompanelrows=1, # optionally draw extra rows
rightpanel=False, rightpanels=False, # rightpanelcols=1,
leftpanel=False, leftpanels=False, # leftpanelcols=1,
bottomcolorbar=False, bottomcolorbars=False, bottomlegend=False, bottomlegends=False, # convenient aliases that change default features
rightcolorbar=False, rightcolorbars=False, rightlegend=False, rightlegends=False,
leftcolorbar=False, leftcolorbars=False, leftlegend=False, leftlegends=False
):
# Handle the convenience feature for specifying the desired width/spacing
# for panels as that suitable for a colorbar or legend
# NOTE: Ugly but this is mostly boilerplate, shouln't change much
def _panelprops(panel, panels, colorbar, colorbars, legend, legends, width, space):
if colorbar or colorbars:
width = _fill(width, rc['gridspec.cbar'])
space = _fill(space, rc['gridspec.xlab'])
panel, panels = colorbar, colorbars
elif legend or legends:
width = _fill(width, rc['gridspec.legend'])
space = _fill(space, 0)
panel, panels = legend, legends
return panel, panels, width, space
rightpanel, rightpanels, rwidth, rspace, = _panelprops(
rightpanel, rightpanels, rightcolorbar, rightcolorbars,
rightlegend, rightlegends, rwidth, rspace)
leftpanel, leftpanels, lwidth, lspace = _panelprops(
leftpanel, leftpanels, leftcolorbar, leftcolorbars,
leftlegend, leftlegends, lwidth, lspace)
bottompanel, bottompanels, bwidth, bspace = _panelprops(
bottompanel, bottompanels, bottomcolorbar, bottomcolorbars,
bottomlegend, bottomlegends, bwidth, bspace)
# Handle the convenience feature for generating one panel per row/column
# and one single panel for all rows/columns
def _parse(panel, panels, nmax):
if panel: # one spanning panel
panels = [1]*nmax
elif panels not in (None,False): # can't test truthiness, want user to be allowed to pass numpy vector!
try:
panels = list(panels)
except TypeError:
panels = [*range(nmax)] # pass True to make panel for each column
return panels
bottompanels = _parse(bottompanel, bottompanels, ncols)
rightpanels = _parse(rightpanel, rightpanels, nrows)
leftpanels = _parse(leftpanel, leftpanels, nrows)
# Apply the general defaults
# Need to do this after number of rows/columns figured out
wratios = np.atleast_1d(_fill(wratios, 1))
hratios = np.atleast_1d(_fill(hratios, 1))
hspace = np.atleast_1d(_fill(hspace, rc['gridspec.title']))
wspace = np.atleast_1d(_fill(wspace, rc['gridspec.inner']))
if len(wratios)==1:
wratios = np.repeat(wratios, (ncols,))
if len(hratios)==1:
hratios = np.repeat(hratios, (nrows,))
if len(wspace)==1:
wspace = np.repeat(wspace, (ncols-1,))
if len(hspace)==1:
hspace = np.repeat(hspace, (nrows-1,))
left = _units(_fill(left, rc['gridspec.ylab']))
bottom = _units(_fill(bottom, rc['gridspec.xlab']))
right = _units(_fill(right, rc['gridspec.nolab']))
top = _units(_fill(top, rc['gridspec.title']))
bwidth = _units(_fill(bwidth, rc['gridspec.cbar']))
rwidth = _units(_fill(rwidth, rc['gridspec.cbar']))
lwidth = _units(_fill(lwidth, rc['gridspec.cbar']))
bspace = _units(_fill(bspace, rc['gridspec.xlab']))
rspace = _units(_fill(rspace, rc['gridspec.ylab']))
lspace = _units(_fill(lspace, rc['gridspec.ylab']))
# Determine figure size
if journal:
if width or height or axwidth or axheight or figsize:
raise ValueError('Argument conflict: Specify only a journal size, or the figure dimensions, not both.')
width, height = journal_size(journal) # if user passed width=<string>, will use that journal size
if not figsize:
figsize = (width, height)
width, height = figsize
width = _units(width, error=False)
height = _units(height, error=False)
# If width and height are not fixed, determine necessary width/height to
# preserve the aspect ratio of specified plot
auto_both = (width is None and height is None)
auto_width = (width is None and height is not None)
auto_height = (height is None and width is not None)
auto_neither = (width is not None and height is not None)
bpanel_space = bwidth + bspace if bottompanels else 0
rpanel_space = rwidth + rspace if rightpanels else 0
lpanel_space = lwidth + lspace if leftpanels else 0
try:
aspect = aspect[0]/aspect[1]
except (IndexError,TypeError):
pass # do nothing
aspect_fixed = aspect/(wratios[0]/np.mean(wratios)) # e.g. if 2 columns, 5:1 width ratio, change the 'average' aspect ratio
aspect_fixed = aspect*(hratios[0]/np.mean(hratios))
# Determine average axes widths/heights
# Default behavior: axes average 2.0 inches wide
if auto_width or auto_neither:
axheight_ave = (height - top - bottom - sum(hspace) - bpanel_space)/nrows
if auto_height or auto_neither:
axwidth_ave = (width - left - right - sum(wspace) - rpanel_space - lpanel_space)/ncols
if auto_both: # get stuff directly from axes
if axwidth is None and axheight is None:
axwidth = 2.0
if axheight is not None:
height = axheight*nrows + top + bottom + sum(hspace) + bpanel_space
auto_width = True
axheight_ave = axheight
if axwidth is not None:
width = axwidth*ncols + left + right + sum(wspace) + rpanel_space + lpanel_space
auto_height = True
axwidth_ave = axwidth
if axwidth is not None and axheight is not None:
auto_width = auto_height = False
figsize = (width, height) # again
# Fix height and top-left axes aspect ratio
if auto_width:
axwidth_ave = axheight_ave*aspect_fixed
width = axwidth_ave*ncols + left + right + sum(wspace) + rpanel_space + lpanel_space
# Fix width and top-left axes aspect ratio
if auto_height:
axheight_ave = axwidth_ave/aspect_fixed
height = axheight_ave*nrows + top + bottom + sum(hspace) + bpanel_space
# Check
if axwidth_ave<0:
raise ValueError(f"Not enough room for axes (would have width {axwidth_ave}). Increase width, or reduce spacings 'left', 'right', or 'wspace'.")
if axheight_ave<0:
raise ValueError(f"Not enough room for axes (would have height {axheight_ave}). Increase height, or reduce spacings 'top', 'bottom', or 'hspace'.")
# Necessary arguments to reconstruct this grid
# Can follow some of the pre-processing
subplots_kw = _dot_dict(nrows=nrows, ncols=ncols,
figsize=figsize, aspect=aspect,
hspace=hspace, wspace=wspace,
hratios=hratios, wratios=wratios,
bottompanels=bottompanels, leftpanels=leftpanels, rightpanels=rightpanels,
left=left, bottom=bottom, right=right, top=top,
bwidth=bwidth, bspace=bspace, rwidth=rwidth, rspace=rspace, lwidth=lwidth, lspace=lspace,
)
# Make sure the 'ratios' and 'spaces' are in physical units (we cast the
# former to physical units), easier then to add stuff as below
wspace = wspace.tolist()
hspace = hspace.tolist()
wratios = (ncols*axwidth_ave*(wratios/sum(wratios))).tolist()
hratios = (nrows*axheight_ave*(hratios/sum(hratios))).tolist()
# Now add the outer panel considerations (idea is we have panels whose
# widths/heights are *in inches*, and only allow the main subplots and
# figure widhts/heights to warp to preserve aspect ratio)
nrows += int(bool(bottompanels))
ncols += int(bool(rightpanels)) + int(bool(leftpanels))
if bottompanels: # the 'bottom' space actually goes between subplots and panel
hratios = hratios + [bwidth] # easy
hspace = hspace + [bottom]
bottom = bspace
if leftpanels:
wratios = [lwidth] + wratios
wspace = [left] + wspace
left = lspace
if rightpanels:
wratios = wratios + [rwidth]
wspace = wspace + [right]
right = rspace
# Scale stuff that gridspec needs to be scaled
# Scale the boundaries for gridspec
# NOTE: We *no longer* scale wspace/hspace because we expect it to
# be in same scale as axes ratios, much easier that way and no drawback really
bottom = bottom/height
left = left/width
top = 1-top/height
right = 1-right/width
# Create gridspec for outer plotting regions (divides 'main area' from side panels)
offset = (0, 1 if leftpanels else 0)
figsize = (width, height)
gridspec_kw = dict(
nrows = nrows,
ncols = ncols,
left = left,
bottom = bottom,
right = right, # unique spacing considerations
top = top, # so far no panels allowed here
wspace = wspace,
hspace = hspace,
width_ratios = wratios,
height_ratios = hratios,
) # set wspace/hspace to match the top/bottom spaces
return figsize, offset, subplots_kw, gridspec_kw
# Generate custom GridSpec classes that override the GridSpecBase
# __setitem__ method and the 'base' __init__ method
def flexible_gridspec_factory(base):
class _GridSpec(base):
"""
Generalization of builtin matplotlib GridSpec that allows for
subplots with *arbitrary spacing*. Accomplishes this by designating certain
rows and columns as *empty*.
Further accepts all spacing arguments in *inches*.
This allows for user-specified extra spacing, and for automatic adjustment
of spacing depending on whether labels or ticklabels are overlapping. Will
be added to figure class as auto_adjust() method or something.
"""
def __init__(self, nrows, ncols, **kwargs):
# Add these as attributes; want _spaces_as_ratios to be
# self-contained, so it can be invoked on already instantiated
# gridspec (see 'update')
self._nrows_visible = nrows
self._ncols_visible = ncols
self._nrows = nrows*2-1
self._ncols = ncols*2-1
wratios, hratios, kwargs = self._spaces_as_ratios(**kwargs)
return super().__init__(self._nrows, self._ncols,
hspace=0, wspace=0, # we implement these as invisible rows/columns
width_ratios=wratios,
height_ratios=hratios,
**kwargs,
)
def __getitem__(self, key):
# Magic obfuscation that renders rows and columns designated as
# 'spaces' invisible. Note: key is tuple if multiple indices requested.
def _normalize(key, size):
if isinstance(key, slice):
start, stop, _ = key.indices(size)
if stop > start:
return start, stop - 1
else:
if key < 0:
key += size
if 0 <= key < size:
return key, key
raise IndexError(f"Invalid index: {key} with size {size}.")
# SubplotSpec initialization figures out the row/column
# geometry of these two numbers automatically
nrows, ncols = self._nrows, self._ncols
nrows_visible, ncols_visible = self._nrows_visible, self._ncols_visible
if isinstance(key, tuple):
try:
k1, k2 = key
except ValueError:
raise ValueError('Unrecognized subplot spec "{key}".')
num1, num2 = np.ravel_multi_index(
[_normalize(k1, nrows_visible), _normalize(k2, ncols_visible)],
(nrows, ncols),
)
else:
num1, num2 = _normalize(key, nrows_visible * ncols_visible)
# When you move to a new column that skips a 'hspace' and when you
# move to a new row that skips a 'wspace' -- so, just multiply
# the scalar indices by 2!
def _adjust(n):
if n<0:
return 2*(n+1) - 1 # want -1 to stay -1, -2 becomes -3, etc.
else:
return n*2
num1, num2 = _adjust(num1), _adjust(num2)
return mgridspec.SubplotSpec(self, num1, num2)
def _spaces_as_ratios(self,
hspace=None, wspace=None, # spacing between axes
hratios=None, wratios=None,
height_ratios=None, width_ratios=None,
**kwargs):
# Parse flexible input
nrows = self._nrows_visible
ncols = self._ncols_visible
hratios = _fill(height_ratios, hratios)
wratios = _fill(width_ratios, wratios)
hratios = np.atleast_1d(_fill(hratios, 1))
wratios = np.atleast_1d(_fill(wratios, 1))
hspace = np.atleast_1d(_fill(hspace, np.mean(hratios)*0.10)) # this is relative to axes
wspace = np.atleast_1d(_fill(wspace, np.mean(wratios)*0.10))
if len(wspace)==1:
wspace = np.repeat(wspace, (ncols-1,)) # note: may be length 0
if len(hspace)==1:
hspace = np.repeat(hspace, (nrows-1,))
if len(wratios)==1:
wratios = np.repeat(wratios, (ncols,))
if len(hratios)==1:
hratios = np.repeat(hratios, (nrows,))
# Verify input ratios and spacings
# Translate height/width spacings, implement as extra columns/rows
if len(hratios) != nrows:
raise ValueError(f'Got {nrows} rows, but {len(hratios)} hratios.')
if len(wratios) != ncols:
raise ValueError(f'Got {ncols} columns, but {len(wratios)} wratios.')
if ncols>1 and len(wspace) != ncols-1:
raise ValueError(f'Require {ncols-1} width spacings for {ncols} columns, got {len(wspace)}.')
if nrows>1 and len(hspace) != nrows-1:
raise ValueError(f'Require {nrows-1} height spacings for {nrows} rows, got {len(hspace)}.')
# Assign spacing as ratios
wratios_final = [None]*self._ncols
wratios_final[::2] = list(wratios)
if self._ncols>1:
wratios_final[1::2] = list(wspace)
hratios_final = [None]*self._nrows
hratios_final[::2] = list(hratios)
if self._nrows>1:
hratios_final[1::2] = list(hspace)
return wratios_final, hratios_final, kwargs # bring extra kwargs back
def update(self, **gridspec_kw):
# Handle special hspace/wspace arguments, and just set the simple
# left/right/top/bottom attributes
wratios, hratios, edges_kw = self._spaces_as_ratios(**gridspec_kw)
edges_kw = {key:value for key,value in edges_kw.items()
if key not in ('nrows','ncols')} # cannot be modified
self.set_width_ratios(wratios)
self.set_height_ratios(hratios)
super().update(**edges_kw) # remaining kwargs should just be left/right/top/bottom
return _GridSpec
# Make classes
FlexibleGridSpec = flexible_gridspec_factory(mgridspec.GridSpec)
FlexibleGridSpec.__name__ = 'FlexibleGridSpec'
FlexibleGridSpecFromSubplotSpec = flexible_gridspec_factory(mgridspec.GridSpecFromSubplotSpec)
FlexibleGridSpecFromSubplotSpec.__name__ = 'FlexibleGridSpecFromSubplotSpec'
<file_sep>#!/usr/bin/env python3
"""
Script to set up magic commands and other notebook properties.
Just call this in the first cell with "run pyfuncs/notebook". And voila!
Call with optional directory argument to make that the new working directory.
Unbelievably weird problem:
* Warning on calling rcdefaults(): https://stackoverflow.com/q/48320804/4970632
Apparently you can change the backend until the first plot is drawn, then
it stays the same. So the rcdefault() command changes the backend to a
non-inline version.
Notes on python figures:
* Can use InlineBackend rc configuration to make inline figure properties
different from figure.<subproperty> settings in rcParams.
* Problem is, whenever rcParams are reset/pyfuncs module is reloaded, the previous
InlineBackend properties disappear.
* It is *also* necessary to maintain separate savefig options, including 'transparent'
and 'facecolor' -- cannot just set these to use the figure properties.
If transparent set to False, saved figure will have no transparency *even if* the
default figure.facecolor has zero alpha. Will *only* be transparent if alpha explicitly
changed by user command. Try playing with settings in plot.globals to see.
* In conclusion: Best workflow is probably to set InlineBackend settings to empty, but
control figure settings separate from savefig settings. Also need to test: if
transparent=True but patches were set to have zero transparency manually, will they
be made re-transparent when figure is saved?
Notes on jupyter configuration:
* In .jupyter, the jupyter_nbconvert_config.json sets up locations of stuff; templates
for nbextensions and formatting files for markdown/code cells.
* In .jupyter, the jupyter_notebook_config.json installs the configurator extension
for managing extra plugins.
* In .jupyter, not sure yet how to successfully use jupyter_console_config.py and
jupyter_notebook_config.py; couldn't get it to do what this function does on startup.
* In .jupyter/custom, current_theme.txt lists the current jupyterthemes theme, custom.css
contains CSS formatting for it, and fonts should contain font files -- note that there
are not font files on my Mac, even though jupyterthemes works; sometimes may be empty
* In .jupyter/nbconfig, tree.json loads the extra tab for the NBconfigurator, and
common.json gives option to hide incompatible plugs, and notebook.json contains all
the new settings; just copy it over to current notebook to update
"""
# Imports
from IPython import get_ipython
from IPython.utils import io
import os
import sys
import socket
from .rcmod import rc
from matplotlib import rcParams
# @block_printing
def nbsetup(directory=None, backend='inline'):
# Variables
cd = os.getcwd()
home = os.path.expanduser('~')
hostname = socket.gethostname().split('.')[0]
autosave = 30
# Rc initial
# rcinit = rcParams.copy()
# Make sure we are in session
ipython = get_ipython() # save session
if ipython is None:
print("Warning: IPython kernel not found.")
return
# exit()
# Optional argument
if directory:
os.chdir(os.path.expanduser(directory)) # move to this directory
print(f'Moved to directory {os.path.expanduser(directory)}.')
# Reload modules, so can easily edit/run imported functions
# with redirect_stdout(_null):
if 'autoreload' not in ipython.magics_manager.magics['line']:
# Only do this if not already loaded -- otherwise will get *recursive*
# reloading, even with unload_ext command!
# with redirect_stdout(_null):
ipython.magic("reload_ext autoreload") # reload instead of load, to avoid annoying message
ipython.magic("autoreload 2") # turn on expensive autoreloading
# Autosaving
# with redirect_stdout(_null):
# with redirect_stdout(_null):
with io.capture_output() as captured:
ipython.magic(f"autosave {autosave:d}") # autosave every minute
# sys.stdout.write("\033[F") #back to previous line
# sys.stdout.write("\033[K") #clear line
# Initialize with default 'inline' settings
ipython.magic("matplotlib " + backend) # change print_figure_kwargs to see edges
# Below so don't have memory issues/have to keep re-closing them
ipython.magic("config InlineBackend.close_figures = True")
# Retina probably more space efficient (high-res bitmap), but svg is prettiest
# and is only one preserving vector graphics
ipython.magic("config InlineBackend.figure_formats = ['retina','svg']")
# Control all rc settings directly with 'rc' object, *no* notebook-
# specific overrides.
ipython.magic("config InlineBackend.rc = {}")
# For some reason this is necessary, even with rc['savefig.bbox'] = 'standard'
ipython.magic("config InlineBackend.print_figure_kwargs = {'bbox_inches':None}") #bbox_inches=\'tight\', pad_inches=0.1)')
# Print difference
# rcfinal = rcParams.copy()
# print({key:(value1,value2) for key,value1,value2 in
# zip(rcParams.keys(), rcinit.values(), rcfinal.values())
# if value1 != value2})
# Re-assert defaults (some get overwritten on inline initiatoin)
rc.reset()
# Message
print("Configured ipython notebook.")
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# This configures the global working environment
"""
See: https://matplotlib.org/users/customizing.html
Here's a quick list of rcParam categories:
"lines", "patch", "hatch", "legend"
"font", "text", "mathtext"
"axes", "figure"
"date", "xtick", "ytick", "grid"
"contour", "image"
"boxplot", "errorbar", "hist", "scatter"
"path", "savefig", "ps", "tk", "pdf", "svg"
"debug", "keymap", "examples"
"animation"
Notes
-----
* Note the figure settings are used when printing interactively or just making
the figure object, but the savefig ones are used when calling savefig.
* Note that if *autoreload* is triggered/global defauls are reset, it seems that
any options set with InlineBackend in ipython are ***ignored***. But if you query
settings, options still present -- you just need to call nbsetup again.
"""
#------------------------------------------------------------------------------#
# First just make sure some dependencies are loaded
import re
from matplotlib.pyplot import figure, get_fignums
from cycler import cycler
from . import colortools
from . import utils
from .utils import timer, counter, ic
from matplotlib import rcParams, style
# Will add our own dictionary to the top-level matplotlib module, to go
# alongside rcParams
# Default settings
# List of linked settings
rcGlobals = {
# Apply these ones to list of rcParams
'color': 'k',
'xcolor': None, # these are special; can be used to set particular spine colors
'ycolor': None,
'cycle': 'colorblind',
# 'facecolor': '#0072b2', # 0072B2
'facecolor': 'w', # 0072B2
'facehatch': None, # hatching on background, useful for indicating invalid data
'gridalpha': 0.1,
'small': 8,
'large': 9,
'linewidth': 0.6,
'gridwidth': 0.6,
'bottom': True,
'top': False,
'left': True,
'right': False,
'ticklen': 4.0,
'tickpad': 2.0,
'tickdir' : 'out',
# Convenient aliases (i.e. they do not bulk apply to a bunch of settings, just shorter names)
# 'fontname': 'DejaVu Sans',
# 'fontname': 'Verdana', # the prettiest IMO
'fontname': 'Helvetica Neue', # best one; and less crammed than Helvetica
'titleweight': 'normal',
'suptitleweight': 'bold',
'abcweight': 'bold',
# Special ones
'tickratio': 0.5, # ratio of major-to-minor tick size
'minorwidth': 0.8, # ratio of major-to-minor tick width
'gridratio': 0.5, # ratio of major-to-minor grid line widths
}
rcGlobals_children = {
# Most important ones, expect these to be used a lot
# The xcolor/ycolor we don't use 'special' props (since we'd be duplicating ones
# that already exist for all spines/labels). Instead just manually use the
# global property in the format script.
# NOTE: Hatches are weird: https://stackoverflow.com/questions/29549530/how-to-change-the-linewidth-of-hatch-in-matplotlib
# Linewidths can only be controlled with a global property!
# NOTE: Should I even bother setting these? Yes: Idea is maybe we change
# underlying global keywords, but have rcupdate always refer to
# corresponding builtin values.
'xcolor': [],
'ycolor': [],
'color': ['axes.labelcolor', 'axes.edgecolor', 'axes.hatchcolor', 'map.color', 'map.hatchcolor', 'xtick.color', 'ytick.color'], # change the 'color' of an axes
'facecolor': ['axes.facecolor', 'map.facecolor'], # simple alias
'facehatch': ['axes.facehatch', 'map.facehatch'], # optionally apply background hatching
'small': ['font.size', 'xtick.labelsize', 'ytick.labelsize', 'axes.labelsize', 'legend.fontsize'], # the 'small' fonts
'large': ['abc.fontsize', 'figure.titlesize', 'axes.titlesize'], # the 'large' fonts
'linewidth': ['axes.linewidth', 'map.linewidth', 'hatch.linewidth', 'axes.hatchlw',
# 'grid.linewidth', # should not be coupled, looks ugly
'map.hatchlw', 'xtick.major.width', 'ytick.major.width'], # gridline widths same as tick widths
'gridalpha': ['grid.alpha', 'gridminor.alpha'],
'gridcolor': ['grid.color', 'gridminor.color'],
'gridstyle': ['grid.linestyle', 'gridminor.linestyle'],
# Aliases
'fontname': ['font.family'], # specify family directly, so we can easily switch between serif/sans-serif; requires text.usetex = False; see below
'abcweight': ['abc.weight'],
'titleweight': ['axes.titleweight'],
'suptitleweight': ['figure.titleweight'],
# Less important ones
'bottom': ['xtick.major.bottom', 'xtick.minor.bottom'], # major and minor ticks should always be in the same place
'top': ['xtick.major.top', 'xtick.minor.top'],
'left': ['ytick.major.left', 'ytick.minor.left'],
'right': ['ytick.major.right', 'ytick.minor.right'],
'ticklen' : ['xtick.major.size', 'ytick.major.size'],
'tickdir': ['xtick.direction', 'ytick.direction'],
'tickpad': ['xtick.major.pad', 'xtick.minor.pad', 'ytick.major.pad', 'ytick.minor.pad'],
}
# Settings that apply to just one thing, and are
# already implemented by matplotlib
rcDefaults = {
'figure.dpi': 90, # save ipython notebook space
'figure.facecolor': (0.95,0.95,0.95,1),
'figure.max_open_warning': 0,
'figure.autolayout': False,
'figure.titleweight': 'bold',
'savefig.facecolor': (1,1,1,1),
'savefig.transparent': True,
'savefig.dpi': 300,
'savefig.pad_inches': 0,
'savefig.directory': '',
'savefig.bbox': 'standard',
'savefig.format': 'pdf',
'axes.xmargin': 0,
'axes.ymargin': 0.05,
'axes.titleweight': 'normal',
'axes.grid': True,
'axes.labelweight': 'normal',
'axes.labelpad': 3.0,
'axes.titlepad': 3.0,
'axes.axisbelow': 'lines', # for ticks/gridlines *above* patches, *below* lines, use 'lines'
'xtick.minor.visible' : True,
'ytick.minor.visible' : True,
'grid.color': 'k',
'grid.alpha': 0.1,
'grid.linestyle': '-',
'grid.linewidth': 0.6, # a bit thinner
'font.family': 'DejaVu Sans', # allowed to be concrete name(s) when usetex is False
# 'font.family': 'sans-serif',
# 'font.sans-serif': 'DejaVu Sans',
'text.latex.preamble': r'\usepackage{cmbright}', # https://stackoverflow.com/a/16345065/4970632
'text.usetex': False, # use TeX for *all* font handling (limits available fonts)
'mathtext.default': 'regular', # no italics
'mathtext.bf' : 'sans:bold',
'mathtext.it' : 'sans:it',
'image.cmap': 'sunset',
'image.lut': 256,
'patch.facecolor': 'C0',
'patch.edgecolor': 'k',
'patch.linewidth': 1.0,
'hatch.color': 'k',
'hatch.linewidth': 0.7,
'markers.fillstyle': 'full',
'scatter.marker': 'o',
'lines.linewidth' : 1.3,
'lines.color' : 'C0',
'lines.markeredgewidth' : 0,
'lines.markersize' : 3.0,
'lines.dash_joinstyle' : 'miter',
'lines.dash_capstyle' : 'projecting',
'lines.solid_joinstyle' : 'miter', # joinstyle opts= miter, round, bevel
'lines.solid_capstyle' : 'projecting', # capstyle opts= butt, round, projecting
'legend.fancybox' : False,
'legend.frameon' : False,
'legend.labelspacing' : 0.5,
'legend.handletextpad' : 0.5,
'legend.handlelength' : 1.5,
'legend.columnspacing' : 1,
'legend.facecolor' : 'w',
'legend.numpoints' : 1,
'legend.borderpad' : 0.5,
'legend.borderaxespad' : 0,
}
# Special settings, should be thought of as extension of rcParams
rcDefaults_sp = {
# These ones just need to be present, will get reset by globals
'map.facecolor': None,
'map.color': None,
'map.linewidth': None,
'abc.fontsize': None,
'rowlabel.fontsize': None,
'collabel.fontsize': None,
'gridminor.alpha': None,
'axes.facehatch': None,
'axes.hatchcolor': None,
'axes.hatchlw': None,
'map.facehatch': None,
'map.hatchcolor': None,
'map.hatchlw' : None,
# The rest can be applied as-is
'abc.weight': 'bold',
'abc.color': 'k',
'rowlabel.weight': 'bold',
'rowlabel.color': 'k',
'collabel.weight': 'bold',
'collabel.color': 'k',
'gridminor.color': 'k',
'gridminor.linestyle': '-',
'gridminor.linewidth': 0.1,
'land.linewidth': 0, # no boundary for patch object
'land.color': 'k',
'ocean.linewidth': 0, # no boundary for patch object
'ocean.color': 'w',
'coastline.linewidth' : 1.0,
'coastline.color' : 'k',
'lonlatlines.linewidth': 1.0,
'lonlatlines.linestyle': ':',
# 'lonlatlines.linestyle': '--',
'lonlatlines.alpha': 0.4,
'lonlatlines.color': 'k',
'gridspec.title': 0.2, # extra space for title/suptitle
'gridspec.inner': 0.2, # just have ticks, no labeels
'gridspec.legend': 0.25, # default legend space (bottom of figure)
'gridspec.cbar': 0.17, # default colorbar width
'gridspec.ylab': 0.7, # default space wherever we expect tick and axis labels (a bit large if axis has no negative numbers/minus sign tick labels)
'gridspec.xlab': 0.55, # for horizontal text should have more space
'gridspec.nolab': 0.15, # only ticks
}
rcParams_sp = rcDefaults_sp.copy()
# Generate list of valid names, and names with subcategories
rc_names = {
*rcParams.keys(),
*rcParams_sp.keys(),
}
rc_categories = {
*(re.sub('\.[^.]*$', '', name) for name in rc_names),
*(re.sub('\..*$', '', name) for name in rc_names)
}
def _get_alias(key):
alias = {alias for alias,names in rcGlobals_children.items() if key in names}
if len(alias)!=0:
key = alias.pop() # use
return key
#-------------------------------------------------------------------------------
# Contextual settings management
# Adapted from seaborn; see: https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py
#-------------------------------------------------------------------------------
class AttributeDict(dict):
# Dictionary elements are attributes too.
def __getattr__(self, attr): # invoked only if __getattribute__ fails
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
class rc_configurator(object):
_public_api = ('reset', 'update', 'fill') # getattr and setattr will not look for these items on underlying dictionary
def __init__(self):
"""
Magical abstract class for handling custom settings, builtin rcParams
settings, and artificial 'global' params that keep certain groups
of settings synced. Also includes context manager.
"""
# First initialize matplotlib
# Note rcdefaults() changes the backend! Inline plotting will fail for
# rest of notebook session if you call rcdefaults before drawing a figure!
# After first figure made, backend property is 'sticky', never changes!
# See: https://stackoverflow.com/a/48322150/4970632
style.use('default') # mpl.style function does not change the backend
# Add simple attributes to rcParams
self._rcCache = {}
self._rcGlobals = rcGlobals.copy()
for key,value in rcDefaults.items():
rcParams[key] = value
for key,value in rcDefaults_sp.items():
rcParams_sp[key] = value
# Apply linked attributes to rcParams
self._set_cycler('colorblind')
rc, rc_sp = self._get_globals()
rcParams.update(rc)
rcParams_sp.update(rc_sp)
# Settings
self._init = True
self._cache_orig = {}
self._cache_added = {}
self._getitem_mode = 0 # 0 means look for everything, including cache
self._setitem_mode = 0 # 0 means set underlying props
def __enter__(self):
# Apply new settings (will get added to _rcCache)
for key,value in self._cache_added.items():
self[key] = value # applies globally linked and individual settings
def __exit__(self, _type, _value, _traceback):
# Restore configurator cache to its previous state.
self._rcCache = self._cache_orig
self._cache_orig = {}
self._cache_added = {}
self._getitem_mode = 0
# @counter
def __getitem__(self, key):
# Can get a whole bunch of different things
# Get full dictionary e.g. for rc[None]
if not key:
return {**rcParams, **rcParams_sp}
# Allow for special time-saving modes where we *ignore rcParams*
# or even *ignore rcParams_sp*.
mode = self._getitem_mode
if mode==0:
kws = (self._rcCache, rcParams_sp, rcParams)
elif mode==1:
kws = (self._rcCache, rcParams_sp)
elif mode==2:
kws = (self._rcCache,)
else:
raise ValueError(f'Invalid _getitem_mode {mode}.')
# If it is available, return the values corresponding to names in
# user dictionary; e.g. {'color':'axes.facecolor'} becomes {'color':'w'}
# NOTE: Got weird bugs here. Dunno why. Use self.fill method instead.
if key in rc_categories:
params = {}
for kw in kws:
for category,value in kw.items():
if re.search(f'^{key}\.', category):
subcategory = re.sub(f'^{key}\.', '', category)
if subcategory and '.' not in subcategory:
params[subcategory] = value
if mode==0 and not params:
raise ValueError(f'Invalid category "{key}".')
else:
return params
# Get individual property. Will successively index a few different dicts
# Try to return the value
for kw in (*kws[:1], self._rcGlobals, *kws[1:]):
try:
return kw[key]
except KeyError:
continue
# If we were in one of the exlusive modes, return None
if mode==0:
raise ValueError(f'Invalid prop name "{key}".')
else:
return None
# @counter
def __setitem__(self, key, value):
# Keep certain properties *coupled*; always set the global one
# NOTE: We use the 'setitem mode' of 1 when *entering the with..as
# context* -- the point being that *the with..ax construct is
# only used when axes have already been drawn*.
key = _get_alias(key)
# First the special cycler
# NOTE: No matter the 'setitem mode' this will always set the axes
# prop_cycle rc settings
if key=='cycle':
self._set_cycler(value)
self._rcCache['cycle'] = value
# Apply global settings
elif key in rcGlobals:
if value=='default':
value = rcGlobals[key]
rc, rc_sp = self._get_globals(key, value)
self._rcCache.update(rc)
self._rcCache.update(rc_sp)
self._rcCache[key] = value # also update cached global property itself
self._rcGlobals[key] = value
# Directly modify single parameter
# NOTE: If 'setitem mode' is 0, this means user has directly set
# something (we are not in a with..as context in format()), so we
# want to directly modify rcParams.
elif key in rc_names:
self._rcCache[key] = value
if self._setitem_mode==0:
try:
rcParams[key] = value
except KeyError:
pass
else:
raise ValueError(f'Invalid key "{key}".')
self._init = False # no longer in initial state
def __getattribute__(self, attr):
# Alias to getitem
if attr[:1]=='_' or attr in self._public_api: # no recursion since second comparison won't be evaluated if first comparison evaluates True
return super().__getattribute__(attr)
else:
return self.__getitem__(attr)
def __setattr__(self, attr, value):
# Alias to setitem
if attr[:1]=='_' or attr in self._public_api:
super().__setattr__(attr, value)
else:
self.__setitem__(attr, value)
def __str__(self):
# Alias to __repr__
return self.__repr__()
def __repr__(self):
# Nice string representation
length = 1 + max(len(key) for key in self._rcGlobals.keys())
string = '\n'.join(f'{key}: {" "*(length-len(key))}{value}'
for key,value in self._rcGlobals.items())
return string
def _set_cycler(self, value):
# Set the color cycler.
# NOTE: Generally if user uses 'C0', et cetera, assume they want to
# refer to the *default* cycler colors; so first reset
if isinstance(value, str) or utils.isnumber(value):
value = value,
colors = colortools.colors('colorblind')
rcParams['axes.prop_cycle'] = cycler('color', colors)
colors = colortools.colors(*value)
rcParams['axes.prop_cycle'] = cycler('color', colors)
figs = list(map(figure, get_fignums()))
for fig in figs:
for ax in fig.axes:
ax.set_prop_cycle(cycler('color', colors))
def _get_globals(self, key=None, value=None):
# Apply all properties in some group.
kw = {}
kw_sp = {}
if key is not None and value is not None:
items = [(key,value)]
else:
items = self._rcGlobals.items()
for key,value in items:
# Tick length/major-minor tick length ratio
if key in ('ticklen','tickratio'):
if key=='tickratio':
ticklen = self._rcGlobals['ticklen']
ratio = value
else:
ticklen = value
ratio = self._rcGlobals['tickratio']
kw['xtick.minor.size'] = ticklen*ratio
kw['ytick.minor.size'] = ticklen*ratio
# Spine width/major-minor tick width ratio
if key in ('linewidth','minorwidth'):
if key=='linewidth':
tickwidth = value
ratio = self._rcGlobals['minorwidth']
else:
tickwidth = self._rcGlobals['linewidth']
ratio = value
kw['xtick.minor.width'] = tickwidth*ratio
kw['ytick.minor.width'] = tickwidth*ratio
# kw_sp['gridminor.linewidth'] = tickwidth*ratio # special
# Grid line
if key in ('gridwidth', 'gridratio'):
if key=='gridwidth':
gridwidth = value
ratio = self._rcGlobals['gridratio']
else:
gridwidth = self._rcGlobals['gridwidth']
ratio = value
kw_sp['gridminor.linewidth'] = gridwidth*ratio
# Now update linked settings
for name in rcGlobals_children.get(key,[]):
if name in rcParams_sp:
kw_sp[name] = value
else:
kw[name] = value
return kw, kw_sp
def _context(self, *args, mode=0, **kwargs):
"""
Temporarily modify rc configuration. Do this by simply
saving the cache, allowing modification of the cache, then
restoring the old cache.
Three modes:
0) __getitem__ searches everything, the default.
1) __getitem__ ignores rcParams (assumption is these have already
been set). Used during Axes __init__ calls to _rcupdate.
2) __getitem__ ignores rcParams and rcParams_sp; only read from
cache, i.e. settings that user has manually changed.
Used during Axes format() calls to _rcupdate.
Notes
-----
This is kept private, because it's only mean to be used within
the 'format()' method automatically! Instead of user having to use
with..as, they should just pass rc_kw dict or kwargs to format().
"""
# Apply mode
if mode not in range(3):
raise ValueError(f'Invalid _getitem_mode {mode}.')
for arg in args:
if not isinstance(arg, dict):
raise ValueError('rc_context() only accepts dictionary args and kwarg pairs.')
kwargs.update(arg)
self._getitem_mode = mode
self._cache_orig = rc._rcCache.copy()
self._cache_added = kwargs # could be empty
return self
def update(self, *args, **kwargs):
"""
Same as setting rc['axes'] = {'name':value}, but do this for bunch
of different propts.
"""
if len(args)==0:
args = [{}]
kw = args[-1]
kw.update(kwargs)
if len(args)==1:
for key,value in kw.items():
self[key] = value
elif len(args)==2:
category = args[0]
for key,value in kw.items():
self[category + '.' + key] = value
else:
raise ValueError('rc.update() accepts 1-2 positional arguments. Use rc.update(kw) to update a bunch of names, or rc.update(category, kw) to update subcategories belonging to single category e.g. axes. All kwargs will be added to the dict.')
def fill(self, props):
"""
Function that only updates a property if self.__getitem__ returns not None.
Meant for optimization; hundreds of 200-item dictionary lookups over several
subplots end up taking toll, almost 1s runtime.
"""
props_out = {}
for key,value in props.items():
value = self[value]
if value is not None:
props_out[key] = value
return props_out
def reset(self):
"""
Restore settings to default.
"""
return self.__init__()
# Instantiate object
rc = rc_configurator()
<file_sep>#!/usr/bin/env python3
from matplotlib import rcParams
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as mcm
import matplotlib.colors as mcolors
from .rcmod import rc
from . import colortools as tools
from . import subplots # actually imports the function, since __init__ makes it global
_data = f'{os.path.dirname(__file__)}' # or parent, but that makes pip install distribution hard
_scales = {'rgb':(1,1,1), 'default':(360,100,100)}
_names = {'rgb':('red', 'green', 'blue'),
'hcl':('hue', 'chroma', 'luminance'),
'hsl':('hue', 'saturation', 'luminance'),
'hsv':('hue', 'saturation', 'value'),
'hpl':('hue', 'partial sat', 'luminance')}
#------------------------------------------------------------------------------#
# Demo of channel values and colorspaces
#------------------------------------------------------------------------------#
def colorspace_breakdown(luminance=None, chroma=None, saturation=None, hue=None,
N=100, space='hcl'):
# Dictionary
hues = np.linspace(0, 360, 361)
sats = np.linspace(0, 120, 120) # use 120 instead of 121, prevents annoying rough edge on HSL plot
lums = np.linspace(0, 99.99, 101)
chroma = saturation if saturation is not None else chroma
if luminance is None and chroma is None and hue is None:
luminance = 50
if luminance is not None:
hsl = np.concatenate((
np.repeat(hues[:,None], len(sats), axis=1)[...,None],
np.repeat(sats[None,:], len(hues), axis=0)[...,None],
np.ones((len(hues), len(sats)))[...,None]*luminance,
), axis=2)
suptitle = f'Hue-chroma cross-section for luminance {luminance}'
xlabel, ylabel = 'hue', 'chroma'
xloc, yloc = 60, 20
elif chroma is not None:
hsl = np.concatenate((
np.repeat(hues[:,None], len(lums), axis=1)[...,None],
np.ones((len(hues), len(lums)))[...,None]*chroma,
np.repeat(lums[None,:], len(hues), axis=0)[...,None],
), axis=2)
suptitle = f'Hue-luminance cross-section for chroma {chroma}'
xlabel, ylabel = 'hue', 'luminance'
xloc, yloc = 60, 20
elif hue is not None:
hsl = np.concatenate((
np.ones((len(lums), len(sats)))[...,None]*hue,
np.repeat(sats[None,:], len(lums), axis=0)[...,None],
np.repeat(lums[:,None], len(sats), axis=1)[...,None],
), axis=2)
suptitle = 'Luminance-chroma cross-section'
xlabel, ylabel = 'luminance', 'chroma'
xloc, yloc = 20, 20
# Make figure, with hatching indiatinc invalid values
# Note we invert the x-y ordering for imshow
# rc['facehatch'] = '....'
rc['facecolor'] = 'k'
# rc['facehatch'] = 'xxx'
f, axs = subplots(ncols=3, bottomlegends=True, rightcolorbar=True,
span=0, share=0, wspace=0.6, axwidth=2.5,
bottom=0, left=0, right=0,
aspect=1, tight=True)
for i,(ax,space) in enumerate(zip(axs,('hcl','hsl','hpl'))):
rgba = np.ones((*hsl.shape[:2][::-1], 4)) # RGBA
for j in range(hsl.shape[0]):
for k in range(hsl.shape[1]):
rgb_jk = tools.to_rgb(hsl[j,k,:].flat, space)
# rgba[k,j,:3] = np.clip(rgb_jk, 0, 1)
if not all(0 <= c <= 1 for c in rgb_jk):
rgba[k,j,3] = 0 # transparent cell
else:
rgba[k,j,:3] = rgb_jk
ax.imshow(rgba, origin='lower', aspect='auto')
ax.format(xlabel=xlabel, ylabel=ylabel, suptitle=suptitle,
grid=False, tickminor=False,
xlocator=xloc, ylocator=yloc,
title=space.upper(), title_kw={'weight':'bold'})
return f
def cmap_breakdown(name, N=100, space='hcl'):
# Figure
f, axs = subplots(ncols=4, bottomlegends=True, rightcolorbar=True,
span=0, sharey=1, wspace=0.5,
bottom=0.4, axwidth=2, aspect=1, tight=True)
x = np.linspace(0, 1, N)
cmap = tools.colormap(name, N=N)
cmap._init()
for j,(ax,space) in enumerate(zip(axs,('hcl','hsl','hpl','rgb'))):
# Get RGB table, unclipped
hs = []
if hasattr(cmap, 'space'):
cmap._init()
lut = cmap._lut_hsl[:,:3].copy()
for i in range(len(lut)):
lut[i,:] = tools.to_rgb(lut[i,:], cmap.space)
else:
lut = cmap._lut[:,:3].copy()
# Convert RGB to space
for i in range(len(lut)):
lut[i,:] = tools.to_xyz(lut[i,:], space=space)
scale = _scales.get(space, _scales['default'])
labels = _names[space]
# Draw line, add legend
colors = ['C1', 'C2', 'C0'] # corresponds with RGB roughly
m = 0
for i,label in enumerate(labels):
y = lut[:-2,i]/scale[i]
y = np.clip(y, 0, 5)
h, = ax.plot(x, y, color=colors[i], lw=2, label=label)
m = max(m, max(y))
hs += [h]
f.bottompanel[j].legend(hs)
ax.axhline(1, color='gray7', dashes=(1.5, 2.5), alpha=0.8, zorder=0, lw=2)
ax.format(title=space.upper(), titlepos='oc', ylim=(0-0.1, m + 0.1))
# Draw colorbar
with np.errstate(all='ignore'):
m = ax.contourf([[np.nan,np.nan],[np.nan,np.nan]], levels=100, cmap=name)
f.rightpanel.colorbar(m, clocator='none', cformatter='none', clabel=f'{name} colors')
locator = [0, 0.25, 0.5, 0.75, 1, 2, 3, 4, 5, 6, 7, 8, 10]
axs.format(suptitle=f'{name} colormap breakdown', ylim=None, ytickminor=False,
yscale=('cutoff', 4, 1), ylocator=locator, # progress 10x faster above x=1
xlabel='position', ylabel='scaled channel value')
#------------------------------------------------------------------------------#
# Reference tables for colors, colormaps, cycles
#------------------------------------------------------------------------------#
def color_show(groups=None, ncols=4, nbreak=12, minsat=0.2):
"""
Visualize all possible named colors. Wheee!
Modified from: https://matplotlib.org/examples/color/named_colors.html
* Special Note: The 'Tableau Colors' are just the *default matplotlib
color cycle colors*! So don't bother iterating over them.
"""
# Get colors explicitly defined in _colors_full_map, or the default
# components of that map (see soure code; is just a dictionary wrapper
# on some simple lists)
figs = []
scale = (360, 100, 100)
groups = groups or [['xkcd','crayons']]
for group in groups:
# Get group colors
group = group or 'open'
if isinstance(group, str):
group = [group]
color_dict = {}
for name in group:
# Read colors from current cycler
if name=='cycle':
seen = set() # trickery
cycle_colors = rcParams['axes.prop_cycle'].by_key()['color']
cycle_colors = [color for color in cycle_colors if not (color in seen or seen.add(color))] # trickery
color_dict.update({f'C{i}':v for i,v in enumerate(cycle_colors)})
# Read custom defined colors
else:
color_dict.update(tools.colors_filtered[name]) # add category dictionary
# Group colors together by discrete range of hue, then sort by value
# For opencolors this is not necessary
if 'open' in group:
# Sorted color columns and plot settings
wscale = 0.5
swatch = 1.5
names = ['red', 'pink', 'grape', 'violet', 'indigo', 'blue', 'cyan', 'teal', 'green', 'lime', 'yellow', 'orange', 'gray']
nrows, ncols = 10, len(names) # rows and columns
plot_names = [[name+str(i) for i in range(nrows)] for name in names]
nrows = nrows*2
ncols = (ncols+1)//2
plot_names = np.array(plot_names, order='C')
plot_names.resize((ncols, nrows))
plot_names = plot_names.tolist()
else:
# For other palettes this is necessary
# Get colors in perceptally uniform space
# Then will group based on hue thresholds
wscale = 1
swatch = 1
colors_hsl = {key:
[c/s for c,s in zip(tools.to_xyz(value,
tools._distinct_colors_space), scale)]
for key,value in color_dict.items()}
# Keep in separate columns
breakpoints = np.linspace(0,1,nbreak) # group in blocks of 20 hues
plot_names = [] # initialize
sat_test = (lambda x: x<minsat) # test saturation for 'grays'
for n in range(len(breakpoints)):
# Get 'grays' column
if n==0:
hue_colors = [(name,hsl) for name,hsl in colors_hsl.items()
if sat_test(hsl[1])]
# Get column for nth color
else:
b1, b2 = breakpoints[n-1], breakpoints[n]
hue_test = ((lambda x: b1<=x<=b2) if b2 is breakpoints[-1]
else (lambda x: b1<=x<b2))
hue_colors = [(name,hsl) for name,hsl in colors_hsl.items() if
hue_test(hsl[0]) and not sat_test(hsl[1])] # grays have separate category
# Get indices to build sorted list, then append sorted list
sorted_index = np.argsort([pair[1][2] for pair in hue_colors])
plot_names.append([hue_colors[i][0] for i in sorted_index])
# Concatenate those columns so get nice rectangle
# nrows = max(len(huelist) for huelist in plot_names) # number of rows
# ncols = nbreak-1 # allow custom setting
names = [i for sublist in plot_names for i in sublist]
plot_names = [[]]
nrows = len(names)//ncols+1
for i,name in enumerate(names):
if ((i + 1) % nrows)==0:
plot_names.append([]) # add new empty list
plot_names[-1].append(name)
# Create plot by iterating over columns
# Easy peasy. And put 40 colors in a column
fig, ax = subplots(width=8*wscale*(ncols/4),
height=5*(nrows/40),
left=0, right=0, top=0, bottom=0,
tight=False)
# asdfsda
X, Y = fig.get_dpi()*fig.get_size_inches() # size in *dots*; make these axes units
# print(X, Y)
# dx, dy = fig.get_dpi()
# X, Y = ax.width, ax.height
# print(X, Y)
hsep, wsep = Y/(nrows+1), X/ncols # height and width of row/column in *dots*
for col,huelist in enumerate(plot_names):
for row,name in enumerate(huelist): # list of colors in hue category
if not name: # empty slot
continue
y = Y - hsep*(row + 1)
y_line = y + hsep*0.1
xi_line = wsep*(col + 0.05)
xf_line = wsep*(col + 0.25*swatch)
xi_text = wsep*(col + 0.25*swatch + 0.03*swatch)
print_name = name.split('xkcd:')[-1] # make sure no xkcd:
ax.text(xi_text, y, print_name,
fontsize=hsep*0.8, ha='left', va='center')
ax.hlines(y_line, xi_line, xf_line, color=color_dict[name], lw=hsep*0.6)
# Format and save figure
ax.format(xlim=(0,X), ylim=(0,Y))
ax.set_axis_off()
fig.save(f'{_data}/colors/colors_{"-".join(group)}.pdf',
format='pdf', transparent=False)
# asdfasd
figs += [fig]
return figs
def cycle_show():
"""
Show off the different color cycles.
Wrote this one myself, so it uses the custom API.
"""
# Get the list of cycles
_cycles = {**{name:mcm.cmap_d[name].colors for name in tools._cycles_cmap},
**{name:mcm.cmap_d[name].colors for name in tools._cycles_list.keys()}}
nrows = len(_cycles)//2+len(_cycles)%2
# Create plot
state = np.random.RandomState(528)
fig, axs = subplots(width=6, wspace=0.05, hspace=0.25,
sharey=False, sharex=False,
aspect=2, ncols=2, nrows=nrows)
for i,(ax,(key,cycle)) in enumerate(zip(axs, _cycles.items())):
key = key.lower()
array = state.rand(20,len(cycle)) - 0.5
array = array[:,:1] + array.cumsum(axis=0) + np.arange(0,len(cycle))
for j,color in enumerate(cycle):
l, = ax.plot(array[:,j], lw=5, ls='-', color=color)
l.set_zorder(10+len(cycle)-j) # make first lines have big zorder
title = f'{key}: {len(cycle)} colors'
ax.set_title(title)
ax.grid(True)
for axis in 'xy':
ax.tick_params(axis=axis,
which='both', labelbottom=False, labelleft=False,
bottom=False, top=False, left=False, right=False)
if len(_cycles)%2==1:
axs[-1].set_visible(False)
# Save
fig.savefig(f'{_data}/colors/cycles.pdf', format='pdf')
return fig
# def cmap_show(N=31, ignore=['Miscellaneous','Sequential2','Diverging2']):
def cmap_show(N=31):
"""
Plot all current colormaps, along with their catgories.
This example comes from the Cookbook on www.scipy.org. According to the
history, <NAME> did the conversion from an old page, but it is
unclear who the original author is.
See: http://matplotlib.org/examples/color/colormaps_reference.html
"""
# Have colormaps separated into categories:
# NOTE: viridis, cividis, plasma, inferno, and magma are all
# listed colormaps for some reason
exceptions = ['viridis','cividis','plasma','inferno','magma']
cmaps_reg = [name for name in mcm.cmap_d.keys() if
not name.endswith('_r')
and name not in tools._cmaps_lower
and 'Vega' not in name
and (isinstance(mcm.cmap_d[name],mcolors.LinearSegmentedColormap) or name in exceptions)]
# cmaps_listed = [name for name in mcm.cmap_d.keys() if
# and (not isinstance(mcm.cmap_d[name],mcolors.LinearSegmentedColormap) and name not in exceptions)]
# Detect unknown/manually created colormaps, and filter out
# colormaps belonging to certain section
categories = {cat:names for cat,names in tools._cmap_categories.items()
if cat not in tools._cmap_categories_delete}
cmaps_ignore = [name for cat,names in tools._cmap_categories.items() for name in names
if cat in tools._cmap_categories_delete]
cmaps_known = [name for cat,names in categories.items() for name in names
if name in cmaps_reg]
cmaps_missing = [name for cat,names in categories.items() for name in names
if name not in cmaps_reg]
cmaps_custom = [name for name in cmaps_reg
if name not in cmaps_known and name not in cmaps_ignore]
if cmaps_missing:
print(f'Missing colormaps: {", ".join(cmaps_missing)}')
if cmaps_ignore:
print(f'Ignored colormaps: {", ".join(cmaps_ignore)}')
if cmaps_custom:
print(f'New colormaps: {", ".join(cmaps_custom)}')
# Attempt to auto-detect diverging colormaps, just sample the points on either end
# Do this by simply summing the RGB channels to get HSV brightness
# l = lambda i: to_xyz(to_rgb(m(i)), 'hcl')[2] # get luminance
# if (l(0)<l(0.5) and l(1)<l(0.5)): # or (l(0)>l(0.5) and l(1)>l(0.5)):
# if name.lower() in custom_diverging:
# Attempt sorting based on hue
# for cat in ['ProPlot Sequential', 'cmOcean Sequential', 'ColorBrewer2.0 Sequential']:
# for cat in ['ProPlot Sequential', 'ColorBrewer2.0 Sequential']:
for cat in []:
hues = [np.mean([tools.to_xyz(tools.to_rgb(color),'hsl')[0]
for color in mcm.cmap_d[name](np.linspace(0.3,1,20))])
for name in categories[cat]]
categories[cat] = [categories[cat][idx] for
idx,name in zip(np.argsort(hues), categories[cat])]
# Array for producing visualization with imshow
a = np.linspace(0, 1, 257).reshape(1,-1)
a = np.vstack((a,a))
# Figure
extra = 1 # number of axes-widths to allocate for titles
nmaps = len(cmaps_known) + len(cmaps_custom) + len(categories)*extra
fig, axs = subplots(nrows=nmaps, axwidth=4.5, axheight=0.23,
span=False, share=False, hspace=0.07)
# Make plot
iax = -1
ntitles, nplots = 0, 0 # for deciding which axes to plot in
for cat in categories:
# Space for title
ntitles += extra # two axes-widths
for imap,name in enumerate(categories[cat]):
# Checks
iax += 1
if imap + ntitles + nplots > nmaps:
ax.invisible()
break
ax = axs[iax]
if imap==0:
iax += 1
ax.invisible()
ax = axs[iax]
if name not in mcm.cmap_d or name not in cmaps_reg: # i.e. the expected builtin colormap is missing
ax.invisible() # empty space
continue
# Draw map
# cmap = mcm.get_cmap(name, N) # interpolate
# print(cmap.N)
ax.imshow(a, cmap=name, origin='lower', aspect='auto', levels=N)
ax.format(ylabel=name, ylabel_kw={'rotation':0, 'ha':'right', 'va':'center'},
xticks='none', yticks='none', # no ticks
xloc='neither', yloc='neither', # no spines
title=(cat if imap==0 else None),
)
# Space for plots
nplots += len(categories[cat])
# Save
filename = f'{_data}/cmaps/colormaps.pdf'
fig.save(filename)
return fig
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------
# Figure subclass and axes subclasses central to this library
#------------------------------------------------------------------------------#
# Decorators used a lot here; below is very simple example that demonstrates
# how simple decorator decorators work
# def decorator1(func):
# def decorator():
# print('decorator 1 called')
# func()
# print('decorator 1 finished')
# return decorator
# def decorator2(func):
# def decorator():
# print('decorator 2 called')
# func()
# print('decorator 2 finished')
# return decorator
# @decorator1
# @decorator2
# def hello():
# print('hello world!')
# hello()
#------------------------------------------------------------------------------
# Recommended using functools.wraps from comment:
# https://stackoverflow.com/a/739665/4970632
# This tool preserve __name__ metadata.
# Builtin module requirements
# Note that even if not in IPython notebook, io capture output still works;
# seems to return some other module in that case
import os
import numpy as np
import warnings
from IPython.utils import io
from matplotlib.cbook import mplDeprecation
from matplotlib.projections import register_projection, PolarAxes
# from matplotlib.lines import _get_dash_pattern, _scale_dashes
from functools import wraps
import matplotlib.figure as mfigure
import matplotlib.axes as maxes
import matplotlib.scale as mscale
import matplotlib.contour as mcontour
import matplotlib.patheffects as mpatheffects
import matplotlib.dates as mdates
import matplotlib.colors as mcolors
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.artist as martist
import matplotlib.gridspec as mgridspec
import matplotlib.transforms as mtransforms
import matplotlib.collections as mcollections
# Local modules, projection sand formatters and stuff
from .gridspec import _gridspec_kwargs, FlexibleGridSpecFromSubplotSpec
# from .rcmod import rc, rcParams
from .rcmod import rc
from .proj import Aitoff, Hammer, KavrayskiyVII, WinkelTripel, Circle
from . import colortools, fonttools, axistools, utils
from .utils import _dot_dict, _fill, ic, timer, counter, docstring_fix
# Silly function, returns a...z...aa...zz...aaa...zzz
# God help you if you ever need that many indices
_abc = 'abcdefghijklmnopqrstuvwxyz'
def _ascii(i, prefix=''):
if i < 26:
return prefix + _abc[i]
else:
return _ascii(i - 26, prefix) + _abc[i % 26]
# Filter warnings, seems to be necessary before drawing stuff for first time,
# otherwise this has no effect (e.g. if you stick it in a function)
warnings.filterwarnings('ignore', category=mplDeprecation)
# Optionally import mapping toolboxes
# Main conda distro says they are incompatible, so make sure not required!
# try:
# import mpl_toolkits.basemap as mbasemap
# except ModuleNotFoundError:
# pass
try:
from cartopy.mpl.geoaxes import GeoAxes
from cartopy.crs import PlateCarree
except ModuleNotFoundError:
GeoAxes = PlateCarree = object
# Global variables
# First distinguish plot types
_line_methods = ( # basemap methods you want to wrap that aren't 2D grids
'plot', 'scatter', 'tripcolor', 'tricontour', 'tricontourf'
)
_contour_methods = (
'contour', 'tricontour',
)
_pcolor_methods = (
'pcolor', 'pcolormesh', 'pcolorpoly', 'tripcolor'
)
_contourf_methods = (
'contourf', 'tricontourf',
)
_show_methods = (
'imshow', 'matshow', 'spy', 'hist2d',
)
_center_methods = (
'contour', 'contourf', 'quiver', 'streamplot', 'barbs'
)
_edge_methods = (
'pcolor', 'pcolormesh', 'pcolorpoly',
)
# Next distinguish plots by more broad properties
_nolevels_methods = (
'pcolor', 'pcolormesh', 'pcolorpoly', 'tripcolor', 'imshow', 'matshow', 'spy'
)
_cycle_methods = (
'plot', 'scatter', 'bar', 'barh', 'hist', 'boxplot', 'errorbar'
)
_cmap_methods = (
'cmapline',
'contour', 'contourf', 'pcolor', 'pcolormesh',
'matshow', 'imshow', 'spy', 'hist2d',
'tripcolor', 'tricontour', 'tricontourf',
)
# Finally disable some stuff for all axes, and just for map projection axes
# The keys in below dictionary are error messages
_disabled_methods = {
"Unsupported plotting function {}.":
('pie', 'table', 'hexbin', 'eventplot',
'xcorr', 'acorr', 'psd', 'csd', 'magnitude_spectrum',
'angle_spectrum', 'phase_spectrum', 'cohere', 'specgram'),
"Redundant function {} has been disabled.":
('plot_date', 'semilogx', 'semilogy', 'loglog'),
"Redundant function {} has been disabled. Just use projection='polar' instead.":
('polar',)
}
_map_disabled_methods = (
'matshow', 'imshow', 'spy', 'bar', 'barh',
# 'triplot', 'tricontour', 'tricontourf', 'tripcolor',
'hist', 'hist2d', 'errorbar', 'boxplot', 'violinplot', 'step', 'stem',
'hlines', 'vlines', 'axhline', 'axvline', 'axhspan', 'axvspan',
'fill_between', 'fill_betweenx', 'fill', 'stackplot')
# Map projections
_map_pseudocyl = ['moll','robin','eck4','kav7','sinu','mbtfpq','vandg','hammer']
#------------------------------------------------------------------------------
# Helper functions for plot overrides
# List of stuff in pcolor/contourf that need to be fixed:
# * White lines between the edges; cover them by changing edgecolors to 'face'.
# * Determination of whether we are using graticule edges/centers; not sure
# what default behavior is but harder to debug. My decorator is nicer.
# * Pcolor can't take an extend argument, and colorbar can take an extend argument
# but it is ignored when the mappable is a contourf. Make our pcolor decorator
# add an "extend" attribute on the mappable that our colorbar decorator detects.
# * Extend used in contourf causes color-change between in-range values and
# out-of-range values, while extend used in colorbar on pcolor has no such
# color change. Standardize by messing with the colormap.
#------------------------------------------------------------------------------
def _parse_args(args, rowmajor):
"""
Parse arguments for checking 2D data centers/edges.
"""
if len(args)>2:
Zs = args[2:]
else:
Zs = args
Zs = [np.array(Z) for Z in Zs] # ensure array
if rowmajor: # input has shape 'y-by-x' instead of 'x-by-y'
Zs = [Z.T for Z in Zs]
if len(args)>2:
x, y = args[:2]
else:
x = np.arange(Zs[0].shape[0])
y = np.arange(Zs[0].shape[1])
return np.array(x), np.array(y), Zs
def _check_centers(func):
"""
Check shape of arguments passed to contour, and fix result.
Optional numbers of arguments:
* Z
* U, V
* x, y, Z
* x, y, U, V
"""
@wraps(func)
def decorator(*args, rowmajor=False, **kwargs):
# Checks whether sizes match up, checks whether graticule was input
x, y, Zs = _parse_args(args, rowmajor)
xlen, ylen = x.shape[0], y.shape[-1]
for Z in Zs:
if Z.ndim!=2:
raise ValueError(f'Input arrays must be 2D, instead got shape {Z.shape}.')
elif Z.shape[0]==xlen-1 and Z.shape[1]==ylen-1:
x, y = (x[1:]+x[:-1])/2, (y[1:]+y[:-1])/2 # get centers, given edges
elif Z.shape[0]!=xlen or Z.shape[1]!=ylen:
raise ValueError(f'X ({"x".join(str(i) for i in x.shape)}) '
f'and Y ({"x".join(str(i) for i in y.shape)}) must correspond to '
f'nrows ({Z.shape[0]}) and ncolumns ({Z.shape[1]}) of Z, or its borders.')
Zs = [Z.T for Z in Zs]
result = func(x, y, *Zs, **kwargs)
return result
return decorator
def _check_edges(func):
"""
Check shape of arguments passed to pcolor, and fix result.
"""
@wraps(func)
def decorator(*args, rowmajor=False, **kwargs):
# Checks that sizes match up, checks whether graticule was input
x, y, Zs = _parse_args(args, rowmajor)
xlen, ylen = x.shape[0], y.shape[-1]
for Z in Zs:
if Z.ndim!=2:
raise ValueError(f'Input arrays must be 2D, instead got shape {Z.shape}.')
elif Z.shape[0]==xlen and Z.shape[1]==ylen:
x, y = utils.edges(x), utils.edges(y)
elif Z.shape[0]!=xlen-1 or Z.shape[1]!=ylen-1:
raise ValueError(f'X ({"x".join(str(i) for i in x.shape)}) '
f'and Y ({"x".join(str(i) for i in y.shape)}) must correspond to '
f'nrows ({Z.shape[0]}) and ncolumns ({Z.shape[1]}) of Z, or its borders.')
Zs = [Z.T for Z in Zs]
result = func(x, y, *Zs, **kwargs)
return result
# return func(self, x, y, *Zs, **kwargs)
return decorator
def _cycle_features(self, func):
"""
Allow specification of color cycler at plot-time. Will simply set the axes
property cycler, and if it differs from user input, update it.
See: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_base.py
The set_prop_cycle command modifies underlying _get_lines and _get_patches_for_fill.
"""
@wraps(func)
def decorator(*args, cycle=None, cycle_kw={}, **kwargs):
# Determine and temporarily set cycler
if cycle is not None:
if not utils.isvector(cycle):
cycle = cycle,
cycle = colortools.cycle(*cycle, **cycle_kw)
self.set_prop_cycle(color=cycle)
return func(*args, **kwargs)
return decorator
def _cmap_features(self, func):
"""
Manage output of contour and pcolor functions.
New features:
* Create new colormaps on the fly, and merge arbitrary named
or created colormaps.
* Always use full range of colormap, whether you are extending
max, min, neither, or both. For the first three, will reconstruct
colormap so 'out-of-bounds' have same color as edge colors
from 'in-bounds' region.
Also see: https://stackoverflow.com/a/48614231/4970632
Notes
-----
The 'bins' argument lets you choose between:
1) (True) Use a *discrete* normalizer with a *continuous* (i.e. very
high resolution) color table.
2) (False) Use a *continuous* normalizer with a *discrete* (containing
the number of colors you want) color table.
"""
@wraps(func)
def decorator(*args, cmap=None, cmap_kw={},
bins=True, # use *discrete* normalizer with 'continuous' color table
values=None, levels=None, norm=None,
values_as_levels=True, # if values are passed, treat them as levels? or just use them for e.g. cmapline, then do whatever?
extend='neither', **kwargs):
# First get normalizer (i.e. a callable with an .inverse attribute
# that inverts the call) and levels. If user provided one, and also
# specified *values* (bin centers), make sure you get the bin levels
# (halfway points) in *transformed space*, e.g. log space.
name = func.__name__
norm = colortools.norm(norm, levels=levels) # if None, returns None; for my custom colormaps, we will need the levels
if kwargs.get('interp', 0): # e.g. for cmapline, we want to *interpolate*
values_as_levels = False # get levels later down the line
if utils.isvector(values) and values_as_levels:
if norm: # is not None
levels = norm.inverse(utils.edges(norm(values)))
else:
levels = utils.edges(values)
levels = _fill(levels, 11) # e.g. pcolormesh can auto-determine levels if you input a number
# Call function with custom stuff
# NOTE: For contouring, colors discretized automatically. But we also
# do it with a BinNorm. Redundant? So far no harm so seriosuly leave it alone.
if name in _contour_methods or name in _contourf_methods: # only valid kwargs for contouring
kwargs.update({'levels': levels, 'extend': extend})
if name == 'cmapline':
kwargs.update({'values': values}) # implement this directly
if name in _show_methods: # *do not* auto-adjust aspect ratio! messes up subplots!
kwargs.update({'aspect': 'auto'})
result = func(*args, **kwargs)
if name in _nolevels_methods:
result.extend = extend
# Get levels automatically determined by contourf, or make them
# from the automatically chosen pcolor/imshow clims
# the normalizers will ***prefer*** this over levels
if not utils.isvector(levels): # i.e. was an integer
if hasattr(result, 'levels'):
levels = result.levels
else:
levels = np.linspace(*result.get_clim(), levels)
result.levels = levels # make sure they are on there!
if name in _contour_methods and cmap is None:
# Contour *lines* can be colormapped, but this should not be
# default if user did not input a cmap
N = None
else:
# Choose to either:
# 1) Use len(levels) lookup table values and a smooth normalizer
# TODO: Figure out how extend stuff works, a bit confused again.
if not bins:
offset = {'neither':-1, 'max':0, 'min':0, 'both':1}
N = len(values) + offset[extend]
norm = colortools.LinearSegmentedNorm(norm=norm, levels=levels)
# 2) Use a high-resolution lookup table with a discrete normalizer
# NOTE: Unclear which is better/more accurate? Intuition is this one.
else:
N = None # will be ignored
norm = colortools.BinNorm(norm=norm, levels=levels, extend=extend)
result.set_norm(norm)
# Specify colormap
cmap = cmap or rc['image.cmap']
if isinstance(cmap, (str, dict, mcolors.Colormap)):
cmap = cmap, # make a tuple
cmap = colortools.colormap(*cmap, N=N, extend=extend, **cmap_kw)
if not cmap._isinit:
cmap._init()
result.set_cmap(cmap)
# Fix white lines between filled contours/mesh
linewidth = 0.4 # seems to be lowest threshold where white lines disappear
if name in _contourf_methods:
for contour in result.collections:
contour.set_edgecolor('face')
contour.set_linewidth(linewidth)
if name in _pcolor_methods:
result.set_edgecolor('face')
result.set_linewidth(linewidth) # seems to do the trick, without dots in corner being visible
return result
return decorator
#------------------------------------------------------------------------------#
# Helper functions for basemap and cartopy plot overrides
# NOTE: These wrappers should be invoked *after* _check_centers and _check_edges,
# which perform basic shape checking and permute the data array, so the data
# will now be y by x (or lat by lon) instead of lon by lat.
#------------------------------------------------------------------------------#
# Normally we *cannot* modify the underlying *axes* pcolormesh etc. because this
# this will cause basemap's self.m.pcolormesh etc. to use my *custom* version and
# cause a suite of weird errors. Prevent this recursion with the below decorator.
def _m_call(self, func):
"""
Call the basemap version of the function of the same name.
"""
name = func.__name__
@wraps(func)
def decorator(*args, **kwargs):
return self.m.__getattribute__(name)(ax=self, *args, **kwargs)
return decorator
def _no_recurse(self, func):
"""
Decorator to prevent recursion in Basemap method overrides.
See: https://stackoverflow.com/a/37675810/4970632
"""
@wraps(func)
# def decorator(self, *args, **kwargs):
def decorator(*args, **kwargs):
name = getattr(func, '__name__')
if self._recurred:
# Don't call func again, now we want to call the parent function
# Note this time 'self' is repeated in position args[0]
self._recurred = False
result = super(BasemapAxes, self).__getattribute__(name)(*args, **kwargs)
else:
# Actually return the basemap version
self._recurred = True
# result = self.m.__getattribute__(name)(ax=self, *args, **kwargs)
result = func(*args, **kwargs)
self._recurred = False # cleanup, in case recursion never occurred
return result
return decorator
def _linefix_basemap(self, func):
"""
Simply add an additional kwarg. Needs whole function because we
want to @wrap it to preserve documentation.
"""
@wraps(func)
# def decorator(self, *args, **kwargs):
def decorator(*args, **kwargs):
kwargs.update(latlon=True)
return func(*args, **kwargs)
# return func(self, *args, **kwargs)
return decorator
def _gridfix_basemap(self, func):
"""
Interpret coordinates and fix discontinuities in grid.
"""
@wraps(func)
def decorator(lon, lat, Z, fix_poles=True, **kwargs):
# def decorator(self, lon, lat, Z, **kwargs):
# Raise errors
# print('lon', lon, 'lat', lat, 'Z', Z)
lonmin, lonmax = self.m.lonmin, self.m.lonmax
if lon.max()>lon.min()+360:
raise ValueError(f'Longitudes span {lon.min()} to {lon.max()}. Can only span 360 degrees at most.')
if lon.min()<-360 or lon.max()>360:
raise ValueError(f'Longitudes span {lon.min()} to {lon.max()}. Must fall in range [-360, 360].')
if lonmin<-360 or lonmin>0:
print(f'Warning: Minimum longitude is {lonmin}, not in range [-360,0].')
# raise ValueError('Minimum longitude must fall in range [-360, 0].')
# 1) Establish 360-degree range
lon -= 720
while True:
filter_ = lon<lonmin
if filter_.sum()==0:
break
lon[filter_] += 360
# 2) Roll, accounting for whether ends are identical
# If go from 0,1,-->,359,0 (borders), returns id of first zero
roll = -np.argmin(lon) # always returns *first* value
if lon[0]==lon[-1]:
lon = np.roll(lon[:-1], roll)
lon = np.append(lon, lon[0]+360)
else:
lon = np.roll(lon, roll)
Z = np.roll(Z, roll, axis=1)
# 3) Roll in same direction some more, if some points on right-edge
# extend more than 360 above the minimum longitude; THEY should be the
# ones on west/left-hand-side of map
lonroll = np.where(lon>lonmin+360)[0] # tuple of ids
if lonroll: # non-empty
roll = lon.size-min(lonroll) # e.g. if 10 lons, lonmax id is 9, we want to roll once
lon = np.roll(lon, roll) # need to roll foreward
Z = np.roll(Z, roll, axis=1) # roll again
lon[:roll] -= 360 # retains monotonicity
# 4) Set NaN where data not in range lonmin, lonmax
# This needs to be done for some regional smaller projections or otherwise
# might get weird side-effects due to having valid data way outside of the
# map boundaries -- e.g. strange polygons inside an NaN region
Z = Z.copy()
if lon.size-1==Z.shape[1]: # test western/eastern grid cell edges
# remove data where east boundary is east of min longitude or west
# boundary is west of max longitude
Z[:,(lon[1:]<lonmin) | (lon[:-1]>lonmax)] = np.nan
elif lon.size==Z.shape[1]: # test the centers
# this just tests centers and pads by one for safety
# remember that a *slice* with no valid range just returns empty array
where = np.where((lon<lonmin) | (lon>lonmax))[0]
Z[:,where[1:-1]] = np.nan
# 5) Fix holes over poles by interpolating there (equivalent to
# simple mean of highest/lowest latitude points)
# if self.m.projection[:4] != 'merc': # did not fix the problem where Mercator goes way too far
if fix_poles:
Z_south = np.repeat(Z[0,:].mean(), Z.shape[1])[None,:]
Z_north = np.repeat(Z[-1,:].mean(), Z.shape[1])[None,:]
lat = np.concatenate(([-90], lat, [90]))
Z = np.concatenate((Z_south, Z, Z_north), axis=0)
# 6) Fix seams at map boundary; 3 scenarios here:
# Have edges (e.g. for pcolor), and they fit perfectly against basemap seams
# this does not augment size
if lon[0]==lonmin and lon.size-1==Z.shape[1]: # borders fit perfectly
pass # do nothing
# Have edges (e.g. for pcolor), and the projection edge is in-between grid cell boundaries
# this augments size by 1
elif lon.size-1==Z.shape[1]: # no interpolation necessary; just make a new grid cell
lon = np.append(lonmin, lon) # append way easier than concatenate
lon[-1] = lonmin + 360 # we've added a new tiny cell to the end
Z = np.concatenate((Z[:,-1:], Z), axis=1) # don't use pad; it messes up masked arrays
# Have centers (e.g. for contourf), and we need to interpolate to the
# left/right edges of the map boundary
# this augments size by 2
elif lon.size==Z.shape[1]: # linearly interpolate to the edges
x = np.array([lon[-1], lon[0]+360]) # x
if x[0] != x[1]:
y = np.concatenate((Z[:,-1:], Z[:,:1]), axis=1)
xq = lonmin+360
yq = (y[:,:1]*(x[1]-xq) + y[:,1:]*(xq-x[0]))/(x[1]-x[0]) # simple linear interp formula
Z = np.concatenate((yq, Z, yq), axis=1)
lon = np.append(np.append(lonmin, lon), lonmin+360)
else:
raise ValueError()
# Finally get grid of x/y map projection coordinates
lat[lat>90], lat[lat<-90] = 90, -90 # otherwise, weird stuff happens
x, y = self.m(*np.meshgrid(lon, lat))
# Prevent error where old boundary, drawn on a different axes, remains
# to the Basemap instance, which means it is not in self.patches, which
# means Basemap tries to draw it again so it can clip the contours by the
# resulting path, which raises error because you can't draw on Artist on multiple axes
self.m._mapboundarydrawn = self.boundary # stored the axes-specific boundary here
# Call function
return func(x, y, Z, **kwargs)
return decorator
def _linefix_cartopy(func):
"""
Simply add an additional kwarg. Needs whole function because we
want to @wrap it to preserve documentation.
"""
@wraps(func)
def decorator(*args, transform=PlateCarree, **kwargs):
if isinstance(transform, type):
transform = transform() # instantiate
return func(*args, transform=transform, **kwargs)
return decorator
def _gridfix_cartopy(func):
"""
Apply default transform and fix discontinuities in grid.
Note for cartopy, we don't have to worry about meridian at which longitude
wraps around; projection handles all that.
Todo
----
Contouring methods for some reason have issues with circularly wrapped
data. Triggers annoying TopologyException statements, which we suppress
with IPython capture_output() tool, like in nbsetup().
See: https://github.com/SciTools/cartopy/issues/946
"""
@wraps(func)
def decorator(lon, lat, Z, transform=PlateCarree, fix_poles=True, **kwargs):
# 1) Fix holes over poles by *interpolating* there (equivalent to
# simple mean of highest/lowest latitude points)
if fix_poles:
Z_south = np.repeat(Z[0,:].mean(), Z.shape[1])[None,:]
Z_north = np.repeat(Z[-1,:].mean(), Z.shape[1])[None,:]
lat = np.concatenate(([-90], lat, [90]))
Z = np.concatenate((Z_south, Z, Z_north), axis=0)
# 2) Fix seams at map boundary; by ensuring circular coverage
if (lon[0] % 360) != ((lon[-1] + 360) % 360):
lon = np.array((*lon, lon[0] + 360)) # make longitudes circular
Z = np.concatenate((Z, Z[:,:1]), axis=1) # make data circular
# Call function
if isinstance(transform, type):
transform = transform() # instantiate
with io.capture_output() as captured:
result = func(lon, lat, Z, transform=transform, **kwargs)
# Call function
return result
return decorator
#------------------------------------------------------------------------------
# Custom figure class
#------------------------------------------------------------------------------
class EmptyPanel(object):
"""
Dummy object to put in place when an axes or figure panel does not exist.
Makes nicer error message than if we just put 'None' or nothing there.
Remember: __getattr__ is invoked only when __getattribute__ fails, i.e.
when user requests anything that isn't a hidden object() method.
"""
def __bool__(self):
return False # it's empty, so this is 'falsey'
def __getattr__(self, attr, *args):
raise AttributeError('Panel does not exist.')
@docstring_fix
class Figure(mfigure.Figure):
# Subclass adding some super cool features
def __init__(self, figsize,
gridspec=None, subplots_kw=None,
rcreset=True, auto_adjust=True, pad=0.1,
**kwargs):
"""
Matplotlib figure with some pizzazz.
Requires:
figsize:
figure size (width, height) in inches
subplots_kw:
dictionary-like container of the keyword arguments used to
initialize
Optional:
rcreset (True):
when figure is drawn, reset rc settings to defaults?
auto_adjust (True):
when figure is drawn, trim the gridspec edges without messing
up axes aspect ratios and internal spacing?
"""
# Initialize figure with some custom attributes.
# Whether to reset rcParams wheenver a figure is drawn (e.g. after
# ipython notebook finishes executing)
self._rcreset = rcreset
self._smart_pad = pad
self._smart_tight = auto_adjust # note name _tight already taken!
self._smart_tight_init = True # is figure in its initial state?
self._span_labels = [] # add axis instances to this, and label position will be updated
# Gridspec information
self._gridspec = gridspec # gridspec encompassing drawing area
self._subplots_kw = _dot_dict(subplots_kw) # extra special settings
# Figure dimensions
self.width = figsize[0] # dimensions
self.height = figsize[1]
# Panels, initiate as empty
self.leftpanel = EmptyPanel()
self.bottompanel = EmptyPanel()
self.rightpanel = EmptyPanel()
self.toppanel = EmptyPanel()
# Proceed
super().__init__(figsize=figsize, **kwargs) # python 3 only
# Initialize suptitle, adds _suptitle attribute
self.suptitle('')
def _rowlabels(self, labels, **kwargs):
# Assign rowlabels
axs = []
for ax in self.axes:
if isinstance(ax, BaseAxes) and not isinstance(ax, PanelAxes) and ax._col_span[0]==0:
axs.append(ax)
if isinstance(labels,str): # common during testing
labels = [labels]*len(axs)
if len(labels)!=len(axs):
raise ValueError(f'Got {len(labels)} labels, but there are {len(axs)} rows.')
axs = [ax for _,ax in sorted(zip([ax._row_span[0] for ax in axs],axs))]
for ax,label in zip(axs,labels):
if label and not ax.rowlabel.get_text():
# Create a CompositeTransform that converts coordinates to
# universal dots, then back to axes
label_to_ax = ax.yaxis.label.get_transform() + ax.transAxes.inverted()
x, _ = label_to_ax.transform(ax.yaxis.label.get_position())
ax.rowlabel.set_visible(True)
# Add text
ax.rowlabel.update({'text':label,
'position':[x,0.5],
'ha':'right', 'va':'center', **kwargs})
def _collabels(self, labels, **kwargs):
# Assign collabels
axs = []
for ax in self.axes:
if isinstance(ax, BaseAxes) and not isinstance(ax, PanelAxes) and ax._row_span[0]==0:
axs.append(ax)
if isinstance(labels,str):
labels = [labels]*len(axs)
if len(labels)!=len(axs):
raise ValueError(f'Got {len(labels)} labels, but there are {len(axs)} columns.')
axs = [ax for _,ax in sorted(zip([ax._col_span[0] for ax in axs],axs))]
for ax,label in zip(axs,labels):
if label and not ax.collabel.get_text():
ax.collabel.update({'text':label, **kwargs})
def _suptitle_setup(self, renderer=None, offset=False, **kwargs):
# Intelligently determine supertitle position:
# Determine x by the underlying gridspec structure, where main axes lie.
left = self._subplots_kw.left
right = self._subplots_kw.right
if self.leftpanel:
left += (self._subplots_kw.lwidth + self._subplots_kw.lspace)
if self.rightpanel:
right += (self._subplots_kw.rwidth + self._subplots_kw.rspace)
xpos = left/self.width + 0.5*(self.width - left - right)/self.width
if not offset or not kwargs.get('text', self._suptitle.get_text()):
# Simple offset, not using the automatically determined
# title position for guidance
base = rc['axes.titlepad']/72 + self._gridspec.top*self.height
ypos = base/self.height
transform = self.transFigure
else:
# Figure out which title on the top-row axes will be offset the most
# NOTE: Have to use private API to figure out whether axis has
# tick labels or not! Seems to be no other way to do it.
# See: https://matplotlib.org/_modules/matplotlib/axis.html#Axis.set_tick_params
title_lev1, title_lev2, title_lev3 = None, None, None
for ax in self.axes:
# TODO: Need to ensure we do not test *bottom* axes panels
if not isinstance(ax, BaseAxes) or not ax._row_span[0]==0 or \
(isinstance(ax, PanelAxes) and ax.panel_side=='bottom'):
continue
title_lev1 = ax.title # always will be non-None
if ((ax.title.get_text() and not ax._title_inside) or ax.collabel.get_text()):
title_lev2 = ax.title
if ax.xaxis.get_ticks_position() == 'top':
test = 'label1On' not in ax.xaxis._major_tick_kw \
or ax.xaxis._major_tick_kw['label1On'] \
or ax.xaxis._major_tick_kw['label2On']
if test:
title_lev3 = ax.title
# Hacky bugfixes:
# 1) If no title, fill with spaces. Does nothing in most cases, but
# if tick labels are on top, without this step matplotlib tight subplots
# will not see the suptitle; now suptitle will just occupy empty title space.
# 2) If title and tick labels on top, offset the suptitle and get
# matplotlib to adjust tight_subplot by prepending newlines to title.
# 3) Otherwise, offset suptitle, and matplotlib will recognize the
# suptitle during tight_subplot adjustment.
# ic(title_lev2, title_lev1, title_lev3)
if not title_lev2: # no title present
line = 0
title = title_lev1
if not title.get_text():
# if not title.axes._title_inside:
title.set_text('\n ') # dummy spaces, so subplots adjust will work properly
elif title_lev3: # upper axes present
line = 1.0 # looks best empirically
title = title_lev3
text = title.get_text()
title.set_text('\n\n' + text)
else:
line = 1.2 # default line spacing; see: https://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_linespacing
title = title_lev1 # most common one
# First idea: Create blended transform, end with newline
# ypos = title.get_position()[1]
# transform = mtransforms.blended_transform_factory(
# self.transFigure, title.get_transform())
# text = kwargs.pop('text', self._suptitle.get_text())
# if text[-1:] != '\n':
# text += '\n'
# kwargs['text'] = text
# New idea: Get the transformed position
# NOTE: Seems draw() is called more than once, and the last times
# are when title positions are appropriately offset.
# NOTE: Default linespacing is 1.2; it has no get, only a setter; see
# https://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_linespacing
transform = title.get_transform() + self.transFigure.inverted()
ypos = transform.transform(title.get_position())[1]
line = line*(rc['axes.titlesize']/72)/self.height
ypos = ypos + line
transform = self.transFigure
# Update settings
self._suptitle.update({'position':(xpos, ypos),
'transform':transform,
'ha':'center', 'va':'bottom', **kwargs})
# @counter
def draw(self, renderer, *args, **kwargs):
# Special: Figure out if other titles are present, and if not
# bring suptitle close to center
ref_ax = None
self._suptitle_setup(renderer, offset=True) # just applies the spacing
self._auto_smart_tight_layout(renderer)
# If rc settings have been changed, reset them when the figure is
# displayed (usually means we have finished executing a notebook cell).
if not rc._init and self._rcreset:
print('Resetting rcparams.')
rc.reset()
return super().draw(renderer, *args, **kwargs)
def panel_factory(self, subspec, whichpanels=None,
hspace=None, wspace=None,
hwidth=None, wwidth=None,
sharex=None, sharey=None, # external sharing
sharex_level=3, sharey_level=3,
sharex_panels=True, sharey_panels=True, # by default share main x/y axes with panel x/y axes
**kwargs):
# Helper function for creating paneled axes.
width, height = self.width, self.height
translate = {'bottom':'b', 'top':'t', 'right':'r', 'left':'l'}
whichpanels = translate.get(whichpanels, whichpanels)
whichpanels = whichpanels or 'r'
hspace = _fill(hspace, 0.13) # teeny tiny space
wspace = _fill(wspace, 0.13)
hwidth = _fill(hwidth, 0.45) # default is panels for plotting stuff, not colorbars
wwidth = _fill(wwidth, 0.45)
if any(s.lower() not in 'lrbt' for s in whichpanels):
raise ValueError(f'Whichpanels argument can contain characters l (left), r (right), b (bottom), or t (top), instead got "{whichpanels}".')
# Determine rows/columns and indices
nrows = 1 + sum(1 for i in whichpanels if i in 'bt')
ncols = 1 + sum(1 for i in whichpanels if i in 'lr')
sides_lr = [l for l in ['l',None,'r'] if not l or l in whichpanels]
sides_tb = [l for l in ['t',None,'b'] if not l or l in whichpanels]
# Detect empty positions and main axes position
main_pos = (int('t' in whichpanels), int('l' in whichpanels))
corners = {'tl':(0,0), 'tr':(0,main_pos[1]+1),
'bl':(main_pos[0]+1,0), 'br':(main_pos[0]+1,main_pos[1]+1)}
empty_pos = [position for corner,position in corners.items() if
corner[0] in whichpanels and corner[1] in whichpanels]
# Fix wspace/hspace in inches, using the Bbox from get_postition
# on the subspec object to determine physical width of axes to be created
# * Consider writing some convenience funcs to automate this unit conversion
bbox = subspec.get_position(self) # valid since axes not drawn yet
if hspace is not None:
hspace = np.atleast_1d(hspace)
if hspace.size==1:
hspace = np.repeat(hspace, (nrows-1,))
boxheight = np.diff(bbox.intervaly)[0]*height
height = boxheight - hspace.sum()
hspace = hspace/(height/nrows)
if wspace is not None:
wspace = np.atleast_1d(wspace)
if wspace.size==1:
wspace = np.repeat(wspace, (ncols-1,))
boxwidth = np.diff(bbox.intervalx)[0]*width
width = boxwidth - wspace.sum()
wspace = wspace/(width/ncols)
# Figure out hratios/wratios
# Will enforce (main_width + panel_width)/total_width = 1
wwidth_ratios = [width - wwidth*(ncols-1)]*ncols
if wwidth_ratios[0]<0:
raise ValueError(f'Panel wwidth {wwidth} is too large. Must be less than {width/(nrows-1):.3f}.')
for i in range(ncols):
if i!=main_pos[1]: # this is a panel entry
wwidth_ratios[i] = wwidth
hwidth_ratios = [height-hwidth*(nrows-1)]*nrows
if hwidth_ratios[0]<0:
raise ValueError(f'Panel hwidth {hwidth} is too large. Must be less than {height/(ncols-1):.3f}.')
for i in range(nrows):
if i!=main_pos[0]: # this is a panel entry
hwidth_ratios[i] = hwidth
# Create subplotspec and draw the axes
# Will create axes in order of rows/columns so that the "base" axes
# are always built before the axes to be "shared" with them
panels = []
gs = FlexibleGridSpecFromSubplotSpec(
nrows = nrows,
ncols = ncols,
subplot_spec = subspec,
wspace = wspace,
hspace = hspace,
width_ratios = wwidth_ratios,
height_ratios = hwidth_ratios,
)
# Draw main axes
ax = self.add_subplot(gs[main_pos[0], main_pos[1]], **kwargs)
axmain = ax
# Draw axes
panels = {}
kwpanels = {**kwargs, 'projection':'panel'} # override projection
kwpanels.pop('number', None) # don't want numbering on panels
translate = {'b':'bottom', 't':'top', 'l':'left', 'r':'right'} # inverse
for r,side_tb in enumerate(sides_tb): # iterate top-bottom
for c,side_lr in enumerate(sides_lr): # iterate left-right
if (r,c) in empty_pos or (r,c)==main_pos:
continue
side = translate.get(side_tb or side_lr, None)
ax = self.add_subplot(gs[r,c], panel_side=side, panel_parent=axmain, **kwpanels)
panels[side] = ax
# Finally add as attributes, and set up axes sharing
axmain.bottompanel = panels.get('bottom', EmptyPanel())
axmain.toppanel = panels.get('top', EmptyPanel())
axmain.leftpanel = panels.get('left', EmptyPanel())
axmain.rightpanel = panels.get('right', EmptyPanel())
if sharex_panels:
axmain._sharex_panels()
if sharey_panels:
axmain._sharey_panels()
axmain._sharex_setup(sharex, sharex_level)
axmain._sharey_setup(sharey, sharey_level)
return axmain
def smart_tight_layout(self, renderer=None, pad=None):
"""
Get arguments necessary passed to subplots() to create a tight figure
bounding box without screwing aspect ratios, widths/heights, and such.
"""
# Get bounding box that encompasses *all artists*, compare to bounding
# box used for saving *figure*
if pad is None:
pad = self._smart_pad
if self._subplots_kw is None or self._gridspec is None:
raise ValueError("Initialize figure with 'subplots_kw' and 'gridspec' to draw tight grid.")
obbox = self.bbox_inches # original bbox
if not renderer: # cannot use the below on figure save! figure becomes a special FigurePDF class or something
renderer = self.canvas.get_renderer()
bbox = self.get_tightbbox(renderer)
ox, oy, x, y = obbox.intervalx, obbox.intervaly, bbox.intervalx, bbox.intervaly
x1, y1, x2, y2 = x[0], y[0], ox[1]-x[1], oy[1]-y[1] # deltas
# Apply new settings
lname = 'lspace' if self.leftpanel else 'left'
rname = 'rspace' if self.rightpanel else 'right'
bname = 'bspace' if self.bottompanel else 'bottom'
tname = 'top'
subplots_kw = self._subplots_kw
left = getattr(subplots_kw, lname) - x1 + pad
right = getattr(subplots_kw, rname) - x2 + pad
bottom = getattr(subplots_kw, bname) - y1 + pad
top = getattr(subplots_kw, tname) - y2 + pad
subplots_kw.update({lname:left, rname:right, bname:bottom, tname:top})
figsize, *_, gridspec_kw = _gridspec_kwargs(**subplots_kw)
self._smart_tight_init = False
self._gridspec.update(**gridspec_kw)
self.set_size_inches(figsize)
# Fix any spanning labels that we've added to _span_labels
# These need figure-relative height coordinates
for axis in self._span_labels:
axis.axes._share_span_label(axis)
def _auto_smart_tight_layout(self, renderer=None):
# If we haven't already, compress edges
# _repeat_tight = bool(self._suptitle.get_text()) # optionally also try this
if not self._smart_tight_init or not self._smart_tight:
return
# Cartopy sucks at labels! Bounding box identified will be wrong.
# 1) If you used set_bounds to zoom into part of a cartopy projection,
# this can erroneously identify invisible edges of map as being part of boundary
# 2) If you have gridliner text labels, matplotlib won't detect them.
if not any(isinstance(ax, CartopyAxes) for ax in self.axes):
if self._smart_tight_init:
print('Adjusting gridspec.')
self.smart_tight_layout(renderer)
# @timer
def save(self, filename, silent=False, auto_adjust=True, pad=0.1, **kwargs):
# Notes:
# * Gridspec object must be updated before figure is printed to
# screen in interactive environment; will fail to update after that.
# Seems to be glitch, should open thread on GitHub.
# * To color axes patches, you may have to explicitly pass the
# transparent=False kwarg.
# Some kwarg translations, to pass to savefig
if 'alpha' in kwargs:
kwargs['transparent'] = not bool(kwargs.pop('alpha')) # 1 is non-transparent
if 'color' in kwargs:
kwargs['facecolor'] = kwargs.pop('color') # the color
kwargs['transparent'] = True
# Finally, save
self._auto_smart_tight_layout()
if not silent:
print(f'Saving to "{filename}".')
return super().savefig(os.path.expanduser(filename), **kwargs) # specify DPI for embedded raster objects
def savefig(self, *args, **kwargs):
# Alias for save.
return self.save(*args, **kwargs)
#------------------------------------------------------------------------------#
# Generalized custom axes class
#------------------------------------------------------------------------------#
@docstring_fix
class BaseAxes(maxes.Axes):
"""
Subclass the default Axes class. Then register it as the 'base' projection,
and you will get a subclass Subplot by calling fig.add_subplot(projection='base').
Notes:
* You cannot subclass SubplotBase directly, should only be done with
maxes.subplot_class_factory, which is called automatically when using add_subplot.
* Cartopy projections should use same methods as for ordinary 'cartesian'
plot, so we put a bunch of definition overrides in here.
"""
# Initial stuff
name = 'base'
def __init__(self, *args, number=None,
sharex=None, sharey=None, spanx=None, spany=None,
sharex_level=0, sharey_level=0,
map_name=None,
panel_parent=None, panel_side=None,
**kwargs):
# Initialize
self._spanx = spanx # boolean toggles, whether we want to span axes labels
self._spany = spany
self._title_inside = True # toggle this to figure out whether we need to push 'super title' up
self._zoom = None # if non-empty, will make invisible
self._inset_parent = None # change this later
self._insets = [] # add to these later
self._map_name = map_name # consider conditionally allowing 'shared axes' for certain projections
super().__init__(*args, **kwargs)
# Panels
if panel_side not in (None, 'left','right','bottom','top'):
raise ValueError(f'Invalid panel side "{panel_side}".')
self.panel_side = panel_side
self.panel_parent = panel_parent # used when declaring parent
self.bottompanel = EmptyPanel()
self.toppanel = EmptyPanel()
self.leftpanel = EmptyPanel()
self.rightpanel = EmptyPanel()
# Number and size
if isinstance(self, maxes.SubplotBase):
nrows, ncols, subspec = self._topmost_subspec()
self._row_span = ((subspec.num1 // ncols) // 2, (subspec.num2 // ncols) // 2)
self._col_span = ((subspec.num1 % ncols) // 2, (subspec.num2 % ncols) // 2)
else:
self._row_span = None
self._col_span = None
self.number = number # for abc numbering
self.width = np.diff(self._position.intervalx)*self.figure.width # position is in figure units
self.height = np.diff(self._position.intervaly)*self.figure.height
# Turn off tick labels and axis label for shared axes
# Want to do this ***manually*** because want to have the ability to
# add shared axes ***after the fact in general***. If the API changes,
# will modify the below methods.
self._sharex_setup(sharex, sharex_level)
self._sharey_setup(sharey, sharey_level)
# Add extra text properties for abc labeling, rows/columns labels
# (can only be filled with text if axes is on leftmost column/topmost row)
self.abc = self.text(0, 0, '') # position tbd
self.collabel = self.text(*self.title.get_position(), '',
va='baseline', ha='center', transform=self.title.get_transform())
self.rowlabel = self.text(*self.yaxis.label.get_position(), '',
va='center', ha='right', transform=self.transAxes)
# Enforce custom rc settings! And only look for rcSpecial settings.
with rc._context(mode=1):
self._rcupdate()
# Apply some simple featueres, and disable spectral and triangular features
# See: https://stackoverflow.com/a/23126260/4970632
# Also see: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py
# for all Axes methods ordered logically in class declaration.
def __getattribute__(self, attr, *args):
for message,attrs in _disabled_methods.items():
if attr in attrs:
raise NotImplementedError(message.format(attr))
if attr=='pcolorpoly':
attr = 'pcolor' # use alias so don't run into recursion issues due to internal pcolormesh calls to pcolor()
obj = super().__getattribute__(attr, *args)
if attr in _cmap_methods:
obj = _cmap_features(self, obj)
elif attr in _cycle_methods:
obj = _cycle_features(self, obj)
return obj
def _topmost_subspec(self):
# Needed for e.g. getting the top-level SubplotSpec (i.e. the one
# encompassed by an axes and all its panels, if any are present)
subspec = self.get_subplotspec()
gridspec = subspec.get_gridspec()
while isinstance(gridspec, mgridspec.GridSpecFromSubplotSpec):
try:
subspec = gridspec._subplot_spec
except AttributeError:
raise ValueError('The _subplot_spec attribute is missing from this GridSpecFromSubplotSpec. Cannot determine the parent GridSpec rows/columns occupied by this slot.')
gridspec = subspec.get_gridspec()
nrows, ncols = gridspec.get_geometry()
return nrows, ncols, subspec
def _sharex_setup(self, sharex, level):
if sharex is None:
return
if self is sharex:
return
if isinstance(self, MapAxes) or isinstance(sharex, MapAxes):
return
if level not in range(4):
raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')
# Share vertical panel x-axes with *eachother*
if self.leftpanel and sharex.leftpanel:
self.leftpanel._sharex_setup(sharex.leftpanel, level)
if self.rightpanel and sharex.rightpanel:
self.rightpanel._sharex_setup(sharex.rightpanel, level)
# Share horizontal panel x-axes with *sharex*
if self.bottompanel and sharex is not self.bottompanel:
self.bottompanel._sharex_setup(sharex, level)
if self.toppanel and sharex is not self.toppanel:
self.toppanel._sharex_setup(sharex, level)
# Builtin features
self._sharex = sharex
if level>1:
self._shared_x_axes.join(self, sharex)
# Simple method for setting up shared axes
# WARNING: It turned out setting *another axes' axis label* as
# this attribute caused error, because matplotlib tried to add
# the same artist instance twice. Can only make it invisible.
if level>2:
for t in self.xaxis.get_ticklabels():
t.set_visible(False)
self.xaxis.label.set_visible(False)
def _sharey_setup(self, sharey, level):
if sharey is None:
return
if self is sharey:
return
if isinstance(self, MapAxes) or isinstance(sharey, MapAxes):
return
if level not in range(4):
raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')
# Share horizontal panel y-axes with *eachother*
if self.bottompanel and sharey.bottompanel:
self.bottompanel._sharey_setup(sharey.bottompanel, level)
if self.toppanel and sharey.toppanel:
self.toppanel._sharey_setup(sharey.toppanel, level)
# Share vertical panel y-axes with *sharey*
if self.leftpanel:
self.leftpanel._sharey_setup(sharey, level)
if self.rightpanel:
self.rightpanel._sharey_setup(sharey, level)
# sharey = self.leftpanel._sharey or self.leftpanel
# Builtin features
self._sharey = sharey
if level>1:
self._shared_y_axes.join(self, sharey)
# Simple method for setting up shared axes
if level>2:
for t in self.yaxis.get_ticklabels():
t.set_visible(False)
self.yaxis.label.set_visible(False)
def _sharex_panels(self):
# Call this once panels are all declared
if self.bottompanel:
self._sharex_setup(self.bottompanel, 3)
bottom = self.bottompanel or self
if self.toppanel:
self.toppanel._sharex_setup(bottom, 3)
def _sharey_panels(self):
# Same but for y
if self.leftpanel:
self._sharey_setup(self.leftpanel, 3)
left = self.leftpanel or self
if self.rightpanel:
self.rightpanel._sharey_setup(left, 3)
def _rcupdate(self):
# Figure patch (for some reason needs to be re-asserted even if declared before figure drawn)
kw = rc.fill({'facecolor':'figure.facecolor'})
self.figure.patch.update(kw)
# Axes, figure title (builtin settings)
kw = rc.fill({'fontsize':'axes.titlesize', 'weight':'axes.titleweight', 'fontname':'fontname'})
self.title.update(kw)
kw = rc.fill({'fontsize':'figure.titlesize', 'weight':'figure.titleweight', 'fontname':'fontname'})
self.figure._suptitle.update(kw)
# Row and column labels, ABC labels
kw = rc.fill({'fontsize':'abc.fontsize', 'weight':'abc.weight', 'color':'abc.color', 'fontname':'fontname'})
self.abc.update(kw)
kw = rc.fill({'fontsize':'rowlabel.fontsize', 'weight':'rowlabel.weight', 'color':'rowlabel.color', 'fontname':'fontname'})
self.rowlabel.update(kw)
kw = rc.fill({'fontsize':'collabel.fontsize', 'weight':'collabel.weight', 'color':'collabel.color', 'fontname':'fontname'})
self.collabel.update(kw)
def _text_update(self, obj, kwargs):
# Allow updating properties introduced by the BaseAxes.text() override.
# Don't really want to subclass mtext.Text; only have a few features
# NOTE: Don't use kwargs because want this to look like standard
# artist self.update.
try:
obj.update(kwargs)
except Exception:
obj.set_visible(False)
text = kwargs.pop('text', obj.get_text())
color = kwargs.pop('color', obj.get_color())
weight = kwargs.pop('weight', obj.get_weight())
fontsize = kwargs.pop('fontsize', obj.get_fontsize())
x, y = None, None
pos = obj.get_position()
if 'position' in kwargs:
x, y = kwargs.pop('position')
x = kwargs.pop('x', x)
y = kwargs.pop('y', y)
if x is None:
x = pos[0]
if y is None:
y = pos[1]
try:
x = x[0]
except TypeError:
pass
try:
y = y[0]
except TypeError:
pass
obj = self.text(x, y, text, color=color, weight=weight, fontsize=fontsize, **kwargs)
return obj
def _title_pos(self, pos, **kwargs):
# Position arbitrary text to left/middle/right either inside or outside
# of axes (default is center, outside)
ypad = (rc['axes.titlepad']/72)/self.height # to inches --> to axes relative
xpad = (rc['axes.titlepad']/72)/self.width # why not use the same for x?
xpad_i, ypad_i = xpad*1.5, ypad*1.5 # inside labels need a bit more room
pos = pos or 'oc'
extra = {}
if not isinstance(pos, str):
ha = va = 'center'
x, y = pos
transform = self.transAxes
else:
# Get horizontal position
if not any(c in pos for c in 'lcr'):
pos += 'c'
if not any(c in pos for c in 'oi'):
pos += 'o'
if 'c' in pos:
x = 0.5
ha = 'center'
elif 'l' in pos:
x = 0 + xpad_i*('i' in pos)
ha = 'left'
elif 'r' in pos:
x = 1 - xpad_i*('i' in pos)
ha = 'right'
# Record _title_inside so we can automatically deflect suptitle
# If *any* object is outside (title or abc), want to deflect it up
if 'o' in pos:
y = 1 # 1 + ypad # leave it alone, may be adjusted during draw-time to account for axis label (fails to adjust for tick labels; see notebook)
va = 'baseline'
self._title_inside = False
transform = self.title.get_transform()
elif 'i' in pos:
y = 1 - ypad_i
va = 'top'
transform = self.transAxes
extra['border'] = _fill(kwargs.pop('border', None), True) # by default
return {'x':x, 'y':y, 'transform':transform, 'ha':ha, 'va':va, **extra}
# Make axes invisible
def invisible(self):
# Make axes invisible
for s in self.spines.values():
s.set_visible(False)
self.xaxis.set_visible(False)
self.yaxis.set_visible(False)
self.patch.set_alpha(0)
# New convenience feature
# The title position can be a mix of 'l/c/r' and 'i/o'
def format(self,
suptitle=None, suptitle_kw={},
collabels=None, collabels_kw={},
rowlabels=None, rowlabels_kw={}, # label rows and columns
title=None, titlepos=None, title_kw={},
abc=None, abcpos=None, abcformat=None, abc_kw={},
rc_kw={}, **kwargs,
):
"""
Function for formatting axes of all kinds; some arguments are only relevant to special axes, like
colorbar or basemap axes. By default, simply applies the dictionary values from settings() above,
but can supply many kwargs to further modify things.
Todo
----
* Add options for datetime handling; note possible date axes handles are TimeStamp (pandas),
np.datetime64, DateTimeIndex; can fix with fig.autofmt_xdate() or manually set options; uses
ax.is_last_row() or ax.is_first_column(), so should look that up.
* Problem is there is no autofmt_ydate(), so really should implement my own
version of this.
"""
# NOTE: These next two are actually *figure-wide* settings, but that
# line seems to get blurred -- where we have shared axes, spanning
# labels, and whatnot. May result in redundant assignments if formatting
# more than one axes, but operations are fast so some redundancy is nbd.
# Create figure title
fig = self.figure # the figure
if suptitle is not None:
fig._suptitle_setup(text=suptitle, **suptitle_kw)
if rowlabels is not None:
fig._rowlabels(rowlabels, **rowlabels_kw)
if collabels is not None:
fig._collabels(collabels, **collabels_kw)
# Create axes title
# Input needs to be emptys string
if title is not None:
pos_kw = self._title_pos(titlepos or 'oc', **title_kw)
self.title = self._text_update(self.title, {'text':title, 'visible':True, **pos_kw, **title_kw})
# Create axes numbering
if self.number is not None and abc:
# Get text
abcformat = abcformat or 'a'
if 'a' not in abcformat:
raise ValueError(f'Invalid abcformat {abcformat}.')
abcedges = abcformat.split('a')
text = abcedges[0] + _ascii(self.number-1) + abcedges[-1]
pos_kw = self._title_pos(abcpos or 'il')
self.abc = self._text_update(self.abc, {'text':text, **abc_kw, **pos_kw})
elif hasattr(self, 'abc') and abc is not None and not abc:
# Hide
self.abc.set_visible(False)
# First update (note that this will call _rcupdate overridden by child
# classes, which can in turn call the parent class version, so we only
# need to call this from the base class, and all settings will be applied)
with rc._context(rc_kw, mode=2, **kwargs):
self._rcupdate()
# Create legend creation method
def legend(self, *args, **kwargs):
# Call custom legend() function.
return legend_factory(self, *args, **kwargs)
# Fill entire axes with colorbar
def colorbar(self, *args, **kwargs):
# Call colorbar() function.
return colorbar_factory(self, *args, **kwargs)
# Fancy wrappers
def text(self, x, y, text,
transform=None, border=False, invert=False,
linewidth=2, lw=None, **kwargs): # linewidth is for the border
"""
Wrapper around original text method. Adds feature for easily drawing
text with white border around black text, or vice-versa with invert==True.
Warning
-------
Basemap gridlining methods call text, so if you change the default
transform, will not be able to draw lat/lon labels!
"""
# Get default transform by string name
linewidth = lw or linewidth
if not transform:
transform = self.transData
elif isinstance(transform, mtransforms.Transform):
pass # do nothing
elif transform=='figure':
transform = self.figure.transFigure
elif transform=='axes':
transform = self.transAxes
elif transform=='data':
transform = self.transData
else:
raise ValueError(f"Unknown transform {transform}. Use string \"axes\" or \"data\".")
# Raise more helpful error message if font unavailable
name = kwargs.pop('fontname', rc['fontname']) # is actually font.sans-serif
if name not in fonttools.fonts:
suffix = ''
if name not in fonttools._missing_fonts:
suffix = f' Available fonts are: {", ".join(fonttools.fonts)}.'
print(f'Warning: Font "{name}" unavailable, falling back to DejaVu Sans.' + suffix)
fonttools._missing_fonts.append(name)
name = 'DejaVu Sans'
# Call parent, with custom rc settings
# These seem to sometimes not get used by default
size = kwargs.pop('fontsize', rc['font.size'])
color = kwargs.pop('color', rc['text.color'])
weight = kwargs.pop('font', rc['font.weight'])
t = super().text(x, y, text, transform=transform, fontname=name,
fontsize=size, color=color, fontweight=weight, **kwargs)
# Optionally draw border around text
if border:
facecolor, bgcolor = ('wk' if invert else 'kw')
t.update({'color':facecolor, 'zorder':1e10, # have to update after-the-fact for path effects
'path_effects': [mpatheffects.Stroke(linewidth=linewidth, foreground=bgcolor), mpatheffects.Normal()]})
return t
# @_cycle_features
def plot(self, *args, cmap=None, values=None, **kwargs):
"""
Expand functionality of plot to also make LineCollection lines, i.e. lines
whose colors change as a function of some key/indicator.
"""
if cmap is None and values is None:
# Make normal boring lines
lines = super().plot(*args, **kwargs)
elif cmap is not None and values is not None:
# Make special colormap lines
lines = self.cmapline(*args, cmap=cmap, values=values, **kwargs)
else:
# Error
raise ValueError('To draw colormap line, must provide kwargs "values" and "cmap".')
return lines
# @_cycle_features
def scatter(self, *args, **kwargs):
"""
Just add some more consistent keyword argument options.
"""
# Manage input arguments
if len(args)>4:
raise ValueError(f'Function accepts up to 4 args, received {len(args)}.')
args = [*args]
if len(args)>3:
kwargs['c'] = args.pop(3)
if len(args)>2:
kwargs['s'] = args.pop(2)
# Apply some aliases for keyword arguments
aliases = {'c': ['markercolor', 'color'],
's': ['markersize', 'size'],
'linewidths': ['lw','linewidth','markeredgewidth', 'markeredgewidths'],
'edgecolors': ['markeredgecolor', 'markeredgecolors']}
for name,options in aliases.items():
for option in options:
if option in kwargs:
kwargs[name] = kwargs.pop(option)
return super().scatter(*args, **kwargs)
# @_cmap_features
def cmapline(self, *args, cmap=None, norm=None,
values=None, interp=0, **kwargs):
"""
Create lines with colormap.
See: https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html
Will manage input more strictly, this is harder to generalize.
Optional
--------
values:
the values to which each (x,y) coordinate corresponds.
bins:
do you want values to be *discretized*, or do you want to
*interpolate* values between points? not yet implemented.
interp:
number of values between each line joint and each *halfway* point
between line joints to which you want to interpolate. for bins,
we don't need any interpolation.
"""
# First error check
if values is None:
raise ValueError('For line with a "colormap", must input values=<iterable> to which colors will be mapped.')
if len(args) not in (1,2):
raise ValueError(f'Function requires 1-2 arguments, got {len(args)}.')
y = np.array(args[-1]).squeeze()
x = np.arange(y.shape[-1]) if len(args)==1 else np.array(args[0]).squeeze()
values = np.array(values).squeeze()
if x.ndim!=1 or y.ndim!=1 or values.ndim!=1:
raise ValueError(f'Input x ({x.ndim}-d), y ({y.ndim}-d), and values ({values.ndim}-d) must be 1-dimensional.')
if len(x)!=len(y) or len(x)!=len(values) or len(y)!=len(values):
raise ValueError(f'Got {len(x)} xs, {len(y)} ys, but {len(values)} colormap values.')
# Next draw the line
# Interpolate values to optionally allow for smooth gradations between
# values (bins=False) or color switchover halfway between points (bins=True)
# Next optionally interpolate the corresponding colormap values
# NOTE: We linearly interpolate here, but user might use a normalizer that
# e.g. performs log before selecting linear color range; don't need to
# implement that here
if interp>0:
xorig, yorig, vorig = x, y, values
x, y, values = [], [], []
for j in range(xorig.shape[0]-1):
idx = (slice(None, -1) if j+1<xorig.shape[0]-1 else slice(None))
x.extend(np.linspace(xorig[j], xorig[j+1], interp + 2)[idx].flat)
y.extend(np.linspace(yorig[j], yorig[j+1], interp + 2)[idx].flat)
values.extend(np.linspace(vorig[j], vorig[j+1], interp + 2)[idx].flat)
x, y, values = np.array(x), np.array(y), np.array(values)
coords, vals = [], []
edges = utils.edges(values)
for j in range(y.shape[0]):
# Get x/y coordinates and values for points to the 'left' and
# 'right' of each joint. Also prevent duplicates.
if j==0:
xleft, yleft = [], []
else:
xleft = [(x[j-1] + x[j])/2, x[j]]
yleft = [(y[j-1] + y[j])/2, y[j]]
if j+1==y.shape[0]:
xright, yright = [], []
else:
xleft = xleft[:-1] # prevent repetition when joined with xright/yright
yleft = yleft[:-1] # actually need numbers of x/y coordinates to be same for each segment
xright = [x[j], (x[j+1] + x[j])/2]
yright = [y[j], (y[j+1] + y[j])/2]
pleft = np.stack((xleft, yleft), axis=1)
pright = np.stack((xright, yright), axis=1)
coords.append(np.concatenate((pleft, pright), axis=0))
# Create LineCollection and update with values
# TODO: Why not just pass kwargs to class?
collection = mcollections.LineCollection(np.array(coords), cmap=cmap, norm=norm, linestyles='-')
collection.set_array(np.array(values))
collection.update({key:value for key,value in kwargs.items() if key not in ('color',)})
# Add collection, with some custom attributes
self.add_collection(collection)
collection.values = values
collection.levels = edges # needed for other functions some
return collection
#------------------------------------------------------------------------------#
# Specific classes, which subclass the base one
#------------------------------------------------------------------------------#
@docstring_fix
class XYAxes(BaseAxes):
"""
Subclass for ordinary Cartesian-grid axes.
"""
# Initialize
name = 'xy'
# @timer
def __init__(self, *args, **kwargs):
# Create simple x by y subplot.
super().__init__(*args, **kwargs)
# Change the default formatter (mine is better)
formatter = axistools.formatter('custom')
self.xaxis.set_major_formatter(formatter)
self.yaxis.set_major_formatter(formatter)
def __getattribute__(self, attr, *args):
# Attribute
obj = super().__getattribute__(attr, *args)
if attr in _center_methods:
obj = _check_centers(obj)
elif attr in _edge_methods:
obj = _check_edges(obj)
return obj
def _share_span_label(self, axis):
# Bail
# TODO: This works, but for spanning y-axes there is danger that we
# pick the y-label where y ticks are really narrow and spanning
# label crashes into tick labels on another axes.
name = axis.axis_name
base = self
base = getattr(base, '_share' + name, None) or base
base = getattr(base, '_share' + name, None) or base
if not getattr(base, '_span' + name):
return getattr(base, name + 'axis').label
# Get the 'edge' we want to share (bottom row, or leftmost column),
# and then finding the coordinates for the spanning axes along that edge
axs = []
span = lambda ax: getattr(ax, '_col_span') if name=='x' else getattr(ax, '_row_span')
edge = lambda ax: getattr(ax, '_row_span')[1] if name=='x' else getattr(ax, '_col_span')[0]
# Identify the *main* axes spanning this edge, and if those axes have
# a panel and are shared with it (i.e. has a _sharex/_sharey attribute
# declared with _sharex_panels), point to the panel label
axs = [ax for ax in self.figure.axes if isinstance(ax, BaseAxes)
and not isinstance(ax, PanelAxes) and edge(ax)==edge(base)]
span_all = np.array([span(ax) for ax in axs])
# Build the transform object
idx = slice(span_all.min(), span_all.max() + 1)
if name=='x': # span columns
subspec = self.figure._gridspec[0,idx]
else: # spans rows
subspec = self.figure._gridspec[idx,0]
bbox = subspec.get_position(self.figure) # in figure-relative coordinates
x0, y0, width, height = bbox.bounds
if name=='x':
transform = mtransforms.blended_transform_factory(self.figure.transFigure, mtransforms.IdentityTransform())
position = (x0 + width/2, 1)
else:
transform = mtransforms.blended_transform_factory(mtransforms.IdentityTransform(), self.figure.transFigure)
position = (1, y0 + height/2)
# Update the label we selected
if axis not in self.figure._span_labels:
self.figure._span_labels.append(axis)
ax = axs[np.argmin(span_all[:,0])]
if name=='x':
axis = (ax._sharex or ax).xaxis
else:
axis = (ax._sharey or ax).yaxis
axis.label.update({'visible':True, 'position':position, 'transform':transform})
return axis.label
# @timer
# @counter
def _rcupdate(self):
# Axis settings
for name,axis in zip('xy', (self.xaxis, self.yaxis)):
# Optionally apply an x/y axis specific color
axis_side = axis.get_label_position()
axis_color = rc[name + 'color']
axis_color = {'color': axis_color} if axis_color else {}
sides = ('bottom','top') if name=='x' else ('left','right')
# Update the rcParams according to user input.
# The ticks/spines can be on both sides or just one, while the
# tick labels and axis label on just one side
for side in sides:
# Simply updates the spines and whatnot
override_color = axis_color if side==axis_side else {}
kw = rc.fill({'lw':'axes.linewidth', 'color':'axes.edgecolor'})
self.spines[side].update({**kw, **axis_color})
# Tick marks
# NOTE: We decide that tick location should be controlled only
# by format(), so don't override that here.
kw_both = rc.fill({'color': name + 'tick.color'})
for which in ('major','minor'):
kw = rc[name + 'tick.' + which]
axis.set_tick_params(which=which, **kw, **{**kw_both, **axis_color})
# Tick labels
# NOTE: Assumed
for t in axis.get_ticklabels():
kw = rc.fill({'color':'axes.edgecolor', 'fontname':'fontname', 'fontsize':name+'tick.labelsize'})
t.update({**kw, **axis_color})
# Axis label
kw = rc.fill({'color':'axes.edgecolor', 'fontname':'fontname', 'fontsize':'axes.labelsize', 'weight':'axes.labelweight'})
axis.label.update({**kw, **axis_color})
# Manually update gridlines
for grid,ticks in zip(['grid','gridminor'],[axis.get_major_ticks(), axis.get_minor_ticks()]):
kw = rc[grid]
for tick in ticks:
tick.gridline.update(kw)
# Background patch basics
self.patch.set_clip_on(False)
self.patch.set_zorder(-1)
kw = rc.fill({'facecolor': 'axes.facecolor'})
self.patch.update(kw)
# Hatching options (useful where we want to highlight invalid data)
# NOTE: So that we can keep re-accessing hatches between multiple calls,
# we will add hatches to the patch object directly. Edge/linewidth and
# hatch width are decoupled (latter only controllable with hatch.linewidth),
# so we can do this without adding edges to the background patch (which
# normally we want to control with 'spines').
# NOTE: Currently cannot reset linewidth on existing hathces... or maybe
# we can? Maybe linewidth delayed to drawtime, since it can only be set
# with an rc setting?
kw = rc.fill({'hatch':'axes.facehatch', 'edgecolor':'axes.hatchcolor', 'alpha':'axes.hatchalpha'})
self.patch.update(kw)
# if kw and kw.get('hatch',None): # non-empty
# self.fill_between([0,1], 0, 1, zorder=0, # put in back
# facecolor='none', transform=self.transAxes, **kw)
# Call parent
super()._rcupdate()
# Cool overrides
def format(self,
xloc=None, yloc=None, # aliases for 'where to put spine'
xspineloc=None, yspineloc=None, # deals with spine options
xtickloc=None, ytickloc=None, # which spines to draw ticks on
xlabelloc=None, ylabelloc=None,
xticklabelloc=None, yticklabelloc=None, # where to put tick labels
xtickdir=None, ytickdir=None, tickdir=None, # which direction ('in', 'out', or 'inout')
tickminor=None, xtickminor=True, ytickminor=True, # minor ticks on/off
grid=None, xgrid=None, ygrid=None, # gridline toggle
gridminor=None, xgridminor=None, ygridminor=None, # minor grids on/off (if ticks off, grid will always be off)
xticklabeldir=None, yticklabeldir=None, ticklabeldir=None, # which direction to draw labels
xtickrange=None, ytickrange=None, # limit regions where we assign ticklabels to major-ticks
xreverse=False, yreverse=False, # special properties
xlabel=None, ylabel=None, # axis labels
xlim=None, ylim=None,
xbounds=None, ybounds=None, # limit spine bounds?
xscale=None, yscale=None,
xformatter=None, yformatter=None, xticklabels=None, yticklabels=None,
xticks=None, xminorticks=None, xlocator=None, xminorlocator=None,
yticks=None, yminorticks=None, ylocator=None, yminorlocator=None, # locators, or derivatives that are passed to locators
xlabel_kw={}, ylabel_kw={},
xscale_kw={}, yscale_kw={},
xlocator_kw={}, ylocator_kw={},
xformatter_kw={}, yformatter_kw={},
xminorlocator_kw={}, yminorlocator_kw={},
**kwargs): # formatter
"""
Format the x/y labels, tick locators, tick formatters, and more.
Needs more documentation.
Todo
----
* Consider redirecting user to another label rather than making
this one invisible for spanning/shared axes.
* More intelligent axis sharing with map axes. Consider optionally
anchoring them by locator/limits like the default API, or just
disable ticklabels/labels for some.
"""
# Set axis scaling and limits
# These do not seem to have their own axes-specific public methods,
# so do the x/y one by one here
if xscale is not None:
if hasattr(xscale,'name'):
xscale = xscale.name
self.set_xscale(axistools.scale(xscale, **xscale_kw))
if yscale is not None:
if hasattr(yscale,'name'):
yscale = yscale.name
self.set_yscale(axistools.scale(yscale, **yscale_kw))
if xlim is not None:
if xreverse:
xlim = xlim[::-1]
self.set_xlim(xlim)
if ylim is not None:
if yreverse:
ylim = ylim[::-1]
self.set_ylim(ylim)
if (xlim is not None or ylim is not None) and self._inset_parent:
self.indicate_inset_zoom()
# Control axis ticks and labels and stuff
# Allow for flexible input
xspineloc = _fill(xloc, xspineloc)
yspineloc = _fill(yloc, yspineloc)
xformatter = _fill(xticklabels, xformatter)
yformatter = _fill(yticklabels, yformatter)
xlocator = _fill(xticks, xlocator)
ylocator = _fill(yticks, ylocator)
xminorlocator = _fill(xminorticks, xminorlocator)
yminorlocator = _fill(yminorticks, yminorlocator)
xtickminor = _fill(tickminor, xtickminor)
ytickminor = _fill(tickminor, ytickminor)
xgrid = _fill(grid, xgrid)
ygrid = _fill(grid, ygrid)
xgridminor = _fill(gridminor, xgridminor)
ygridminor = _fill(gridminor, ygridminor)
xtickdir = _fill(tickdir, xtickdir)
ytickdir = _fill(tickdir, ytickdir)
xticklabeldir = _fill(ticklabeldir, xticklabeldir)
yticklabeldir = _fill(ticklabeldir, yticklabeldir)
# Override for weird bug where title doesn't get automatically offset
# from ticklabels in certain circumstance; check out notebook
xtickloc = _fill(xtickloc, xticklabelloc) # if user specified labels somewhere, make sure to put ticks there by default!
ytickloc = _fill(ytickloc, yticklabelloc)
if xtickloc=='both' and xticklabelloc in ('both','top') and not xlabel: # xtickloc *cannot* be 'top', *only* appears for 'both'
print('Warning: This keyword combination causes matplotlib bug where title is not offset from tick labels. Try adding an x-axis label or ticking only the top axis.')
# Begin loop
for axis, label, tickloc, spineloc, ticklabelloc, labelloc, bounds, gridminor, tickminor, tickminorlocator, \
grid, ticklocator, tickformatter, tickrange, tickdir, ticklabeldir, \
label_kw, formatter_kw, locator_kw, minorlocator_kw in \
zip((self.xaxis, self.yaxis), (xlabel, ylabel),
(xtickloc,ytickloc), (xspineloc, yspineloc), # other stuff
(xticklabelloc, yticklabelloc), (xlabelloc, ylabelloc),
(xbounds, ybounds),
(xgridminor, ygridminor), (xtickminor, ytickminor), (xminorlocator, yminorlocator), # minor ticks
(xgrid, ygrid),
(xlocator, ylocator), (xformatter, yformatter), # major ticks
(xtickrange, ytickrange), # range in which we label major ticks
(xtickdir, ytickdir), (xticklabeldir, yticklabeldir), # tick direction
(xlabel_kw, ylabel_kw), (xformatter_kw, yformatter_kw), (xlocator_kw, ylocator_kw), (xminorlocator_kw, yminorlocator_kw),
):
# NOTE: Some of these settings are also rc settings, but I think a
# good rule of thumb is format() methods should control toggling of
# features, while _rcupdate() controls the look of those features.
# Example: Set spine/tick locations with this func, but control
# color/linewidth through _rcupdate().
# TODO: Maybe the '_kw' stuff should be done in _rcupdate()?
# Axis spine visibility and location
sides = ('bottom','top') if axis.axis_name=='x' else ('left','right')
spines = [self.spines[s] for s in sides]
for spine, side in zip(spines, sides):
# Line properties
spineloc = getattr(self, f'twin_{axis.axis_name}spine_override', spineloc) # optionally override; necessary for twinx/twiny situation
# Override if we're settings spine bounds
if bounds is not None and spineloc not in sides:
spineloc = sides[0] # by default, should just have spines on edges in this case
# Eliminate sides
if spineloc=='neither':
spine.set_visible(False)
elif spineloc=='both':
spine.set_visible(True)
elif spineloc in sides: # make relevant spine visible
b = True if side==spineloc else False
spine.set_visible(b)
elif spineloc is not None:
# Special spine location
# Note special 'spine location' options include 'zero', 'center',
# and tuple with (units, location) where units can be axes, data, or outward
if side==sides[0]: # move the left/semabottom spine onto the specified location, with set_position
spine.set_visible(True)
spine.set_position(spineloc)
else:
spine.set_visible(False)
# Apply spine bounds
if bounds is not None and spine.get_visible():
spine.set_bounds(*bounds)
spines = [side for side,spine in zip(sides,spines) if spine.get_visible()]
# Set the major and minor locators and formatters
# Also automatically detect whether axis is a 'time axis' (i.e.
# whether user has plotted something with x/y as datetime/date/np.datetime64
# objects, and matplotlib automatically set the unit converter)
time = isinstance(axis.converter, mdates.DateConverter)
if ticklocator is not None:
axis.set_major_locator(axistools.locator(ticklocator, time=time, **locator_kw))
if tickformatter is not None:
axis.set_major_formatter(axistools.formatter(tickformatter, tickrange=tickrange, time=time, **formatter_kw))
if not tickminor and tickminorlocator is None:
axis.set_minor_locator(axistools.locator('null'))
elif tickminorlocator is not None:
locator = axistools.locator(tickminorlocator, minor=True, time=time, **minorlocator_kw)
axis.set_minor_locator(locator)
axis.set_minor_formatter(mticker.NullFormatter())
# Tick properties
# * Weird issue seems to cause set_tick_params to reset/forget that the grid
# is turned on if you access tick.gridOn directly, instead of passing through tick_params.
# Since gridOn is undocumented feature, don't use it. So calling _format_axes() a second time will remove the lines
# * Can specify whether the left/right/bottom/top spines get ticks; sides will be
# group of left/right or top/bottom
# * Includes option to draw spines but not draw ticks on that spine, e.g.
# on the left/right edges
# First determine tick sides
ticklocs_kw = {None: None, 'both': sides, 'neither': (), 'none': ()}
if bounds is not None and tickloc not in sides:
tickloc = sides[0] # override to just one side
ticklocs = ticklocs_kw.get(tickloc, (tickloc,))
if ticklocs is None:
ticks_sides = {}
else:
ticks_sides = {side: (side in ticklocs) for side in sides}
ticks_sides.update({side: False for side in sides if side not in spines}) # override
# Next the tick label sides
# Will override to make sure sides match
ticklabellocs = ticklocs_kw.get(ticklabelloc, (ticklabelloc,))
if ticklabellocs is None:
ticklabels_sides = {}
else:
ticklabels_sides = {'label' + side: (side in ticklabellocs) for side in sides}
ticklabels_sides.update({'label' + side: False for side in sides
if (side not in spines or (ticklocs is not None and side not in ticklocs))}) # override
# Finally the label side
if labelloc is None:
if ticklocs is not None:
options = [side for side in sides if (side in ticklocs and side in spines)]
if len(options)==1:
labelloc = options[0]
elif labelloc not in sides:
raise ValueError('Got labelloc "{labelloc}", valid options are {sides}.')
if labelloc is not None:
axis.set_label_position(labelloc)
# Apply settings to ticks
ticks_major, ticks_minor = {}, {}
if tickdir is not None:
ticks_major.update({'direction':tickdir})
ticks_minor.update({'direction':tickdir})
if tickdir=='in':
ticks_major.update({'pad':1}) # ticklabels should be much closer
ticks_minor.update({'pad':1})
if ticklabeldir=='in': # put tick labels inside the plot; sometimes might actually want this
pad = rc['xtick.major.size'] + rc['xtick.major.pad'] + rc['xtick.labelsize']
ticks_major.update({'pad':-pad})
ticks_minor.update({'pad':-pad})
axis.set_tick_params(which='major', **ticks_sides, **ticklabels_sides, **ticks_major)
axis.set_tick_params(which='minor', **ticks_sides, **ticklabels_sides, **ticks_minor) # have length
# Ensure no out-of-bounds ticks! Even set_smart_bounds() does not
# always fix this! Need to try manual approach.
# NOTE: set_bounds also failed, and fancy method overrides did
# not work, so instead just turn locators into fixed version
# NOTE: most locators take no arguments in call(), and some have
# no tick_values method; so do the following
# TODO: add optional override to do this every time
if bounds is not None or axis.get_scale()=='cutoff':
if bounds is None: # no API for this on axis
bounds = getattr(self, 'get_' + axis.axis_name + 'lim')()
locator = axistools.locator([x for x in axis.get_major_locator()() if bounds[0] <= x <= bounds[1]])
axis.set_major_locator(locator)
locator = axistools.locator([x for x in axis.get_minor_locator()() if bounds[0] <= x <= bounds[1]])
axis.set_minor_locator(locator)
# Axis label properties
# First redirect user request to the correct *shared* axes, then
# redirect to the correct *spanning* axes if the label is meant
# to span multiple subplot
if label is not None:
# Shared and spanning axes; try going a few layers deep
# The _span_label method changes label position so it spans axes
# If axis spanning not enabled, will just return the shared axis
label_text = label
label = self._share_span_label(axis)
label.update({'text':label_text, **label_kw})
if axis.get_label_position() == 'top':
label.set_va('bottom') # baseline was cramped if no ticklabels present
# Gridline activation and setting (necessary because rcParams has no 'minorgrid'
# property, must be set in rcSpecial settings)
# NOTE: Inexplicably, for a twinx axis, could only get the minor gridlines
# to disappear if we changed the 'visible' property on each one.
# for tick in axis.get_major_ticks():
# if grid is not None:
# tick.gridline.set_visible(grid)
# tick.gridline.update(rc['grid']) # already set but why not, for symmetry
# # for tick in axis.minorTicks:
# for tick in axis.get_minor_ticks():
# if gridminor is not None:
# tick.gridline.set_visible(gridminor)
# tick.gridline.update(rc['gridminor'])
# For some insane reasion, these are ***both*** needed
# Without this below stuff, e.g. gridminor=True doesn't draw gridlines
if grid is not None: # grid changes must be after tick
axis.grid(grid, which='major')
if gridminor is not None:
axis.grid(gridminor, which='minor') # ignore if no minor ticks
# Pass stuff to parent formatter, e.g. title and abc labeling
super().format(**kwargs)
def twiny(self, **kwargs):
# Create second x-axis extending from shared ("twin") y-axis
# Note: Cannot wrap twiny() because then the axes created will be
# instantiated from the parent class, which doesn't have format() method.
# Instead, use hidden method _make_twin_axes.
# See https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_subplots.py
ax = self._make_twin_axes(sharey=self, projection=self.name)
self.xaxis.tick_bottom()
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
ax.set_autoscaley_on(self.get_autoscaley_on())
ax.yaxis.set_visible(False)
ax.patch.set_visible(False)
ax.grid(False)
# Special settings, force spine locations when format() called
self.twin_xspine_override = 'bottom' # original axis ticks on bottom
ax.twin_xspine_override = 'top' # new axis ticks on top
ax.twin_yspine_override = 'neither'
return ax
def twinx(self, yscale=None, **kwargs):
# Create second y-axis extending from shared ("twin") x-axis
# Note: Cannot wrap twinx() because then the axes created will be
# instantiated from the parent class, which doesn't have format() method.
# Instead, use hidden method _make_twin_axes.
ax = self._make_twin_axes(sharex=self, projection=self.name)
self.yaxis.tick_left()
ax.yaxis.tick_right()
ax.yaxis.set_label_position('right')
ax.yaxis.set_offset_position('right')
ax.set_autoscalex_on(self.get_autoscalex_on())
ax.xaxis.set_visible(False)
ax.patch.set_visible(False)
ax.grid(False)
# Apply scale and axes sharing
# NOTE: Forget about this because often (for height/pressure scales)
# the units won't match because we didn't use p0
# if yscale:
# transform = mscale.scale_factory(yscale, self.yaxis).get_transform()
# lims = self.get_ylim()
# lims = transform.transform(np.array(lims))
# ax.set_ylim(lims)
# Special settings, force spine locations when format() called
self.twin_yspine_override = 'left' # original axis ticks on left
ax.twin_yspine_override = 'right' # new axis ticks on right
ax.twin_xspine_override = 'neither'
return ax
def _make_inset_locator(self, bounds, trans):
# Helper function, had to be copied from private matplotlib version.
def inset_locator(ax, renderer):
bbox = mtransforms.Bbox.from_bounds(*bounds)
bb = mtransforms.TransformedBbox(bbox, trans)
tr = self.figure.transFigure.inverted()
bb = mtransforms.TransformedBbox(bb, tr)
return bb
return inset_locator
def inset_axes(self, bounds, *, transform=None, zorder=5, zoom=True, zoom_kw={}, **kwargs):
# Carbon copy, but use my custom axes
# Defaults
if transform is None:
transform = self.transAxes
label = kwargs.pop('label', 'inset_axes')
# This puts the rectangle into figure-relative coordinates.
locator = self._make_inset_locator(bounds, transform)
bb = locator(None, None)
ax = XYAxes(self.figure, bb.bounds, zorder=zorder, label=label, **kwargs)
# The following locator lets the axes move if in data coordinates, gets called in ax.apply_aspect()
ax.set_axes_locator(locator)
self.add_child_axes(ax)
self._insets += [ax]
ax._inset_parent = self
# Finally add zoom
# NOTE: Requirs version >=3.0
if zoom:
ax.indicate_inset_zoom(**zoom_kw)
return ax
def indicate_inset_zoom(self, alpha=None, linewidth=None, color=None, edgecolor=None, **kwargs):
# Custom version that can be *refreshed*
# Makes more sense to be defined on the inset axes, since parent
# could have multiple insets
parent = self._inset_parent
alpha = alpha or 1.0
linewidth = linewidth or rc['axes.linewidth']
edgecolor = color or edgecolor or rc['axes.edgecolor']
if not parent:
raise ValueError(f'{self} is not an inset axes.')
xlim = self.get_xlim()
ylim = self.get_ylim()
rect = [xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0]]
kwargs.update({'linewidth': linewidth, 'edgecolor':edgecolor, 'alpha':alpha})
rectpatch, connects = parent.indicate_inset(rect, self, **kwargs)
# Adopt properties from old one
if self._zoom:
rectpatch_old, connects_old = self._zoom
rectpatch.update_from(rectpatch_old)
rectpatch_old.set_visible(False)
for line,line_old in zip(connects,connects_old):
# Actually want to *preserve* whether line is visible! This
# is automatically determined!
visible = line.get_visible()
line.update_from(line_old)
line.set_visible(visible)
line_old.set_visible(False)
# By default linewidth is only applied to box
else:
for line in connects:
line.set_linewidth(linewidth)
line.set_color(edgecolor)
line.set_alpha(alpha)
self._zoom = (rectpatch, connects)
return (rectpatch, connects)
def inset(self, *args, **kwargs):
# Just an alias
return self.inset_axes(*args, **kwargs)
def inset_zoom(self, *args, **kwargs):
# Just an alias
return self.indicate_inset_zoom(*args, **kwargs)
@docstring_fix
class PanelAxes(XYAxes):
name = 'panel'
def __init__(self, *args, panel_side=None, invisible=False, **kwargs):
"""
Axes with added utilities that make it suitable for holding a legend or
colorbar meant to reference several other subplots at once.
Notes
-----
See: https://stackoverflow.com/a/52121237/4970632
Also an example: https://stackoverflow.com/q/26236380/4970632
"""
# Initiate
if panel_side is None:
raise ValueError('Must specify side.')
super().__init__(*args, panel_side=panel_side, **kwargs)
# Make everything invisible
if invisible:
self.invisible()
def legend(self, handles, **kwargs):
# Allocate invisible axes for drawing legend.
# Returns the axes and the output of legend_factory().
self.invisible()
kwlegend = {'borderaxespad': 0,
'frameon': False,
'loc': 'upper center',
'bbox_transform': self.transAxes}
kwlegend.update(kwargs)
return self, legend_factory(self, handles, **kwlegend)
def colorbar(self, *args, i=0, n=1, length=1,
space=0, hspace=None, wspace=None,
**kwargs):
# Draw colorbar with arbitrary length relative to full length of the
# panel, and optionally *stacking* multiple colorbars
# Will always redraw an axes with new subspec
self.invisible()
side = self.panel_side
space = _fill(hspace, _fill(wspace, space)) # flexible arguments
figure = self.figure
subspec = self.get_subplotspec()
# if n>2:
# raise ValueError('I strongly advise against drawing more than 2 stacked colorbars.')
if length!=1 or n!=1:
# First get gridspec
# Note formula: total width = n*<colorbar width> + (n-1)*<space width>
if side in ['bottom','top']:
hwidth = (self.height - (n-1)*space)/n # express height ratios in physical units
if hwidth<0:
raise ValueError(f'Space {space} too big for {n} colorbars on panel with width {self.height}.')
gridspec = FlexibleGridSpecFromSubplotSpec(
nrows=n, ncols=3,
wspace=0, hspace=space,
subplot_spec=subspec,
width_ratios=((1-length)/2, length, (1-length)/2),
height_ratios=hwidth,
)
subspec = gridspec[i,1]
elif side in ['left','right']:
wwidth = (self.width - (n-1)*space)/n
if wwidth<0:
raise ValueError(f'Space {space} too big for {n} colorbars on panel with width {self.width}.')
gridspec = FlexibleGridSpecFromSubplotSpec(
nrows=3, ncols=n,
wspace=wspace, hspace=hspace,
subplot_spec=subspec,
height_ratios=((1-length)/2, length, (1-length)/2),
width_ratios=wwidth,
)
subspec = gridspec[1,i]
# Next redraw axes
# self.remove() # save memory
self.set_visible(False)
# Allocate axes for drawing colorbar.
# Returns the axes and the output of colorbar_factory().
ax = figure.add_subplot(subspec, projection=None)
if side in ['bottom','top']:
outside, inside = 'bottom', 'top'
if side=='top':
outside, inside = inside, outside
# ticklocation = outside if i==n-1 else inside
ticklocation = outside
orientation = 'horizontal'
elif side in ['left','right']:
outside, inside = 'left', 'right'
if side=='right':
outside, inside = inside, outside
# ticklocation = outside if i==n-1 else inside
ticklocation = outside
orientation = 'vertical'
kwargs.update({'orientation':orientation, 'ticklocation':ticklocation})
return ax, colorbar_factory(ax, *args, **kwargs)
class MapAxes(BaseAxes):
"""
Dummy intermediate class that just disables a bunch of methods that are
inappropriate for map projections.
"""
# Disable some methods to prevent weird shit from happening
# Originally used property decorators for this but way too verbose
# See: https://stackoverflow.com/a/23126260/4970632
def __getattribute__(self, attr, *args):
if attr in _map_disabled_methods:
raise NotImplementedError('Invalid plotting function {} for map projection axes.'.format(attr))
return super().__getattribute__(attr, *args)
def _parse_labels(self, labels, mode):
"""
Parse lonlabels/latlabels argument.
Four different options:
1) use a string e.g. 'lr', 'bt'
2) boolean True; left for latitudes, bottom for longitudes
3) a (n1,n2) tuple ((left,right) for latitudes, (bottom,top) for longitudes)
4) a (n1,n2,n3,n4) tuple like normal
"""
if labels is False:
return [0]*4
if labels is None:
labels = True # use the default
if isinstance(labels, str):
string = labels
labels = [0]*4
for idx,char in zip([0,1,2,3],'lrbt'):
if char in string:
labels[idx] = 1
if utils.isnumber(labels): # e.g. *boolean*
labels = np.atleast_1d(labels)
if len(labels)==1:
labels = [*labels, 0] # default is to label bottom/left
if len(labels)==2:
if mode=='x':
labels = [0, 0, *labels]
elif mode=='y':
labels = [*labels, 0, 0]
elif len(labels)!=4:
raise ValueError(f'Invalid labels: {labels}.')
return labels
@docstring_fix
class BasemapAxes(MapAxes):
"""
Axes subclass for basemap plotting.
"""
name = 'basemap'
def __init__(self, *args, map_projection=None, **kwargs):
"""
Declare basemap projection instance, add it as the 'm' attribute.
The 'map_projection' argument sets projection, because this axes itself
is called from add_subplot using projection='basemap'.
"""
# * Must set boundary before-hand, otherwise the set_axes_limits method called
# by mcontourf/mpcolormesh/etc draws two mapboundary Patch objects called "limb1" and
# "limb2" automatically: one for fill and the other for the edges
# * Then, since the patch object in _mapboundarydrawn is only the fill-version, calling
# drawmapboundary() again will replace only *that one*, but the original visible edges
# are still drawn -- so e.g. you can't change the color
# * If you instead call drawmapboundary right away, _mapboundarydrawn will contain
# both the edges and the fill; so calling it again will replace *both*
import mpl_toolkits.basemap as mbasemap # verify package is available
if not isinstance(map_projection, mbasemap.Basemap):
raise ValueError('You must initialize BasemapAxes with map_projection=(basemap.Basemap instance).')
self.m = map_projection
self.boundary = None
self._recurred = False # use this so we can override plotting methods
self._mapboundarydrawn = None
self._land = None
self._coastline = None
# Initialize
super().__init__(*args, map_name=self.m.projection, **kwargs)
def _rcupdate(self):
# Map boundary
# * First have to *manually replace* the old boundary by just deleting
# the original one
# * If boundary is drawn successfully should be able to call
# self.m._mapboundarydrawn.set_visible(False) and edges/fill color disappear
# * For now will enforce that map plots *always* have background whereas
# axes plots can have transparent background
self.axesPatch = self.patch # for bugfix
# if self.m._mapboundarydrawn:
# self.m._mapboundarydrawn.remove()
# Draw boundary
kw_face = rc.fill({'facecolor': 'map.facecolor'})
if self.m.projection in _map_pseudocyl:
self.patch.set_alpha(0) # make patch invisible
kw_edge = rc.fill({'linewidth': 'map.linewidth', 'edgecolor': 'map.edgecolor'})
if not self.m._mapboundarydrawn:
p = self.m.drawmapboundary(ax=self, **kw_edge) # set fill_color to 'none' to make transparent
else:
p = self.m._mapboundarydrawn
p.update({**kw_face, **kw_edge})
p.set_rasterized(False) # not sure about this; might be rasterized
p.set_clip_on(False) # so edges of *line* denoting boundary aren't cut off
self.boundary = p # not sure why this one
else:
self.patch.update({**kw_face, 'edgecolor':'none'})
kw_edge = rc.fill({'linewidth': 'map.linewidth', 'color': 'map.edgecolor'})
for spine in self.spines.values():
spine.update(kw_edge)
# Call parent
super()._rcupdate()
# Basemap overrides
# WARNING: Never ever try to just make blanket methods on the Basemap
# instance accessible from axes instance! Can of worms and had bunch of
# weird errors! Just pick the ones you think user will want to use.
def __getattribute__(self, attr, *args):
if attr=='pcolorpoly': # need to specify this again to access the .m method
attr = 'pcolor' # use alias so don't run into recursion issues due to internal pcolormesh calls to pcolor()
obj = super().__getattribute__(attr, *args)
if attr in _line_methods or attr in _edge_methods or attr in _center_methods:
obj = _m_call(self, obj) # this must be the *last* step!
if attr in _line_methods:
if attr[:3] != 'tri':
obj = _cycle_features(self, obj)
obj = _linefix_basemap(self, obj)
elif attr in _edge_methods or attr in _center_methods:
obj = _cmap_features(self, obj)
obj = _gridfix_basemap(self, obj)
if attr in _edge_methods:
obj = _check_edges(obj)
else:
obj = _check_centers(obj)
obj = _no_recurse(self, obj)
return obj
# Format basemap axes
# Add documentation here.
def format(self,
xlim=None, ylim=None, lonlim=None, latlim=None,
xticks=None, xminorticks=None, xlocator=None, xminorlocator=None,
yticks=None, yminorticks=None, ylocator=None, yminorlocator=None,
latticks=None, latminorticks=None, latlocator=None, latminorlocator=None,
lonticks=None, lonminorticks=None, lonlocator=None, lonminorlocator=None,
land=False, ocean=False, coastline=False, # coastlines and land
xlabels=None, ylabels=None,
latlabels=None, lonlabels=None, # sides for labels [left, right, bottom, top]
**kwargs):
# Parse flexible input
xlim = _fill(lonlim, xlim)
ylim = _fill(latlim, ylim)
lonlocator = _fill(lonlocator, _fill(lonticks, _fill(xlocator, xticks)))
latlocator = _fill(latlocator, _fill(latticks, _fill(ylocator, yticks)))
lonminorlocator = _fill(lonminorlocator, _fill(lonminorticks, _fill(xminorlocator, xminorticks)))
latminorlocator = _fill(latminorlocator, _fill(latminorticks, _fill(yminorlocator, yminorticks)))
lonlabels = self._parse_labels(_fill(xlabels, lonlabels), 'x')
latlabels = self._parse_labels(_fill(ylabels, latlabels), 'y')
# Basemap axes setup
# Coastlines, parallels, meridians
if land and not self._land:
self._land = self.m.fillcontinents(ax=self)
for p in self._land:
p.update(rc['land'])
if coastline and not self._coastline:
self._coastline = self.m.drawcoastlines(ax=self, **rc['coastline'])
# Function to make gridlines look like cartopy lines
# NOTE: For some reason basemap gridlines look different from cartopy ones
# Have absolutely *no idea* why; cartopy seems to do something weird because
# there is no _dashSeq attribute on lines and line styles are always '-'.
# See: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html
# The dots ':' look better on cartopy so we try to mimick them below.
def ls_translate(obj, style):
if style=='-':
dashes = [None,None]
else:
dashes = [*obj._dashSeq]
if style==':':
dashes[0] /= 10
dashes[1] *= 1.5
elif style=='--':
dashes[0] /= 1.5
dashes[1] *= 1.5
else:
raise ValueError(f'Invalid style {style}.')
return dashes
# Longitude/latitude lines
# Make sure to turn off clipping by invisible axes boundary; otherwise
# get these weird flat edges where map boundaries, parallel/meridian markers come up to the axes bbox
tsettings = {'color':rc['xtick.color'], 'fontsize':rc['xtick.labelsize']}
latlabels[2:] = latlabels[2:][::-1] # default is left/right/top/bottom which is dumb
lonlabels[2:] = lonlabels[2:][::-1] # change to left/right/bottom/top
lsettings = rc['lonlatlines']
linestyle = lsettings['linestyle']
latlocator = _fill(latlocator, 20) # gridlines by default
lonlocator = _fill(lonlocator, 60)
if latlocator is not None:
if utils.isnumber(latlocator):
latlocator = utils.arange(self.m.latmin+latlocator, self.m.latmax-latlocator, latlocator)
p = self.m.drawparallels(latlocator, labels=latlabels, ax=self)
for pi in p.values(): # returns dict, where each one is tuple
# Tried passing clip_on to the below, but it does nothing; must set
# for lines created after the fact
for obj in [i for j in pi for i in j]: # magic
if isinstance(obj, mtext.Text):
obj.update(tsettings)
else:
obj.update(lsettings)
obj.set_dashes(ls_translate(obj, linestyle))
if lonlocator is not None:
if utils.isnumber(lonlocator):
lonlocator = utils.arange(self.m.lonmin+lonlocator, self.m.lonmax-lonlocator, lonlocator)
p = self.m.drawmeridians(lonlocator, labels=lonlabels, ax=self)
for pi in p.values():
for obj in [i for j in pi for i in j]: # magic
if isinstance(obj, mtext.Text):
obj.update(tsettings)
else:
obj.update(lsettings)
obj.set_dashes(ls_translate(obj, linestyle))
# Pass stuff to parent formatter, e.g. title and abc labeling
super().format(**kwargs)
@docstring_fix
# class CartopyAxes(GeoAxes, MapAxes):
class CartopyAxes(MapAxes, GeoAxes): # custom one has to be higher priority, so the methods can overwrite stuff
# Cartopy takes advantage of documented feature where any class with method
# named _as_mpl_axes can be passed as 'projection' object.
# Feature documented here: https://matplotlib.org/devel/add_new_projection.html
# Used in Projection parent class here: https://scitools.org.uk/cartopy/docs/v0.13/_modules/cartopy/crs
name = 'cartopy'
def __init__(self, *args, map_projection=None, circle_center=90, circle_edge=0, **kwargs):
"""
Initialize cartopy projection, and allow for *partial* (i.e. not global)
coverage for azimuthal projections by zooming into the full projection,
then drawing a circle boundary around some latitude away from the center.
* The 'map_projection' argument sets projection, because this axes itself
is called from add_subplot using projection='basemap'.
* Number 'ncircle' controls number of points for drawing circular projection
boundary. For more info see: https://scitools.org.uk/cartopy/docs/v0.15/examples/always_circular_stereo.html
"""
# Dependencies
import cartopy.crs as ccrs # verify package is available
# Do the GeoAxes initialization steps manually (there are very few)
if not isinstance(map_projection, ccrs.Projection):
raise ValueError('You must initialize CartopyAxes with map_projection=(cartopy.crs.Projection instance).')
self._hold = None # dunno
self.projection = map_projection # attribute used extensively by GeoAxes methods, and by builtin one
# Below will call BaseAxes, which will call GeoAxes as the superclass
# NOTE: Previously did stuff in __init__ manually, and called self._boundary,
# which hides existing border patch and rewrites as None. Don't do that again.
try:
map_name = map_projection.name
except AttributeError:
map_name = map_projection.proj4_params['proj']
super().__init__(*args, map_projection=map_projection, map_name=map_name, **kwargs)
# Apply circle boundary
self._land = None
self._ocean = None
self._coastline = None
crs_circles = (ccrs.LambertAzimuthalEqualArea, ccrs.AzimuthalEquidistant)
if any(isinstance(map_projection, cp) for cp in crs_circles):
self.set_extent([-180, 180, circle_edge, circle_center], PlateCarree()) # use platecarree transform
self.set_boundary(Circle(100), transform=self.transAxes)
# self.projection.threshold = kwargs.pop('threshold', self.projection.threshold) # optionally modify threshold
self.set_global() # see: https://stackoverflow.com/a/48956844/4970632
def __getattribute__(self, attr, *args):
obj = super().__getattribute__(attr, *args)
if attr in _line_methods:
obj = _linefix_cartopy(obj)
elif attr in _edge_methods or attr in _center_methods:
obj = _gridfix_cartopy(obj)
if attr in _edge_methods:
obj = _check_edges(obj)
else:
obj = _check_centers(obj)
return obj
def _rcupdate(self):
# Update properties controlled by custom rc settings
self.set_global() # see: https://stackoverflow.com/a/48956844/4970632
kw = rc.fill({'facecolor': 'map.facecolor'})
self.background_patch.update(kw)
kw = rc.fill({'edgecolor': 'map.edgecolor', 'linewidth': 'map.linewidth'})
self.outline_patch.update(kw)
# Call parent
super()._rcupdate()
# Format cartopy GeoAxes.
# Add documentation here.
def format(self,
xlim=None, ylim=None, lonlim=None, latlim=None,
xticks=None, xminorticks=None, xlocator=None, xminorlocator=None,
yticks=None, yminorticks=None, ylocator=None, yminorlocator=None,
latticks=None, latminorticks=None, latlocator=None, latminorlocator=None,
lonticks=None, lonminorticks=None, lonlocator=None, lonminorlocator=None,
land=False, ocean=False, coastline=False, # coastlines and continents
reso='hi',
xlabels=None, ylabels=None,
latlabels=None, lonlabels=None, # sides for labels [left, right, bottom, top]
**kwargs):
# Dependencies
import cartopy.feature as cfeature
import cartopy.crs as ccrs # verify package is available
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# Parse flexible input
xlim = _fill(lonlim, xlim)
ylim = _fill(latlim, ylim)
lonlocator = _fill(lonlocator, _fill(lonticks, _fill(xlocator, xticks)))
latlocator = _fill(latlocator, _fill(latticks, _fill(ylocator, yticks)))
lonminorlocator = _fill(lonminorlocator, _fill(lonminorticks, _fill(xminorlocator, xminorticks)))
latminorlocator = _fill(latminorlocator, _fill(latminorticks, _fill(yminorlocator, yminorticks)))
lonlabels = self._parse_labels(_fill(xlabels, lonlabels), 'x')
latlabels = self._parse_labels(_fill(ylabels, latlabels), 'y')
# Configure extents?
# WARNING: The set extents method tries to set a *rectangle* between
# the *4* (x,y) coordinate pairs (each corner), so something like
# (-180,180,-90,90) will result in *vertical line*, causing error!
# NOTE: proj4_params stores keyword-arg pairs, proj4_init stores
# the shell string passed
# NOTE: They may add this in set_xlim and set_ylim in the
# near future; see:
# https://github.com/SciTools/cartopy/blob/master/lib/cartopy/mpl/geoaxes.py#L638
if xlim is not None or ylim is not None:
xlim = xlim or [None,None]
ylim = ylim or [None,None]
xlim, ylim = [*xlim], [*ylim]
lon_0 = self.projection.proj4_params.get('lon_0', 0)
if xlim[0] is None:
xlim[0] = lon_0 - 180
if xlim[1] is None:
xlim[1] = lon_0 + 180
if ylim[0] is None:
ylim[0] = -90
if ylim[1] is None:
ylim[1] = 90
self.set_extent([*xlim, *ylim], PlateCarree())
# Add geographic features
# Use the NaturalEarthFeature to get more configurable resolution; can choose
# between 10m, 50m, and 110m (scales 1:10mil, 1:50mil, and 1:110mil)
if reso not in ('lo','med','hi'):
raise ValueError(f'Invalid resolution {reso}.')
reso = {'lo':'110m', 'med':'50m', 'hi':'10m'}.get(reso)
if coastline and not self._coastline:
# self.add_feature(cfeature.COASTLINE, **rc['coastlines'])
feat = cfeature.NaturalEarthFeature('physical', 'coastline', reso)
self.add_feature(feat, **rc['coastline'])
self._coastline = feat
if land and not self._land:
# self.add_feature(cfeature.LAND, **rc['continents'])
feat = cfeature.NaturalEarthFeature('physical', 'land', reso)
self.add_feature(feat, **rc['land'])
self._land = feat
if ocean and not self._ocean:
# self.add_feature(cfeature.OCEAN, **rc['oceans'])
feat = cfeature.NaturalEarthFeature('physical', 'ocean', reso)
self.add_feature(feat, **rc['ocean'])
self._ocean = feat
# Draw gridlines
# WARNING: For some reason very weird side effects happen if you try
# to call gridlines() twice on same axes. Can't do it. Which is why
# we do this nonsense with the formatter below, instead of drawing 'major'
# grid lines and 'minor' grid lines.
lonvec = lambda v: [] if v is None else [*v] if utils.isvector(v) else [*utils.arange(-180,180,v)]
latvec = lambda v: [] if v is None else [*v] if utils.isvector(v) else [*utils.arange(-90,90,v)]
lonminorlocator, latminorlocator = lonvec(lonminorlocator), latvec(latminorlocator)
lonlocator, latlocator = lonvec(lonlocator), latvec(latlocator)
lonlines = lonminorlocator or lonlocator # where we draw gridlines
latlines = latminorlocator or latlocator
# First take care of gridlines
draw_labels = (isinstance(self.projection, ccrs.Mercator) or isinstance(self.projection, ccrs.PlateCarree))
if latlines and latlines[0]==-90:
latlines[0] += 0.001
if lonlines and lonlines[0]==-90:
lonlines[0] -= 0.001
gl = self.gridlines(**rc['lonlatlines'], draw_labels=draw_labels)
if lonlines: # NOTE: using mticker.NullLocator results in error!
gl.xlocator = mticker.FixedLocator(lonlines)
if latlines:
gl.ylocator = mticker.FixedLocator(latlines)
# Now take care of labels
if draw_labels:
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabels_bottom, gl.xlabels_top = lonlabels[2:]
gl.ylabels_left, gl.ylabels_right = latlabels[:2]
# Pass stuff to parent formatter, e.g. title and abc labeling
super().format(**kwargs)
@docstring_fix
class PolarAxes(MapAxes, PolarAxes):
"""
Thin decorator around PolarAxes with my new plotting features.
So far just intended to mix the two classes.
"""
name = 'newpolar'
# Register the projection
register_projection(XYAxes)
register_projection(PanelAxes)
register_projection(PolarAxes)
register_projection(BasemapAxes)
register_projection(CartopyAxes)
#------------------------------------------------------------------------------#
# Custom legend and colorbar factories
#------------------------------------------------------------------------------#
def map_projection_factory(package, projection, **kwargs):
"""
Returns Basemap object or cartopy ccrs instance.
"""
# Initial stuff
# Create projection and determine required aspect ratio
if package=='basemap':
import mpl_toolkits.basemap as mbasemap # verify package is available
projection = mbasemap.Basemap(projection=(projection or 'cyl'), **{**kwargs, 'fix_aspect':True}) # cylindrical by default
aspect = (projection.urcrnrx - projection.llcrnrx)/(projection.urcrnry - projection.llcrnry)
# Get the projection instance from a string and determine required aspect ratio
elif package=='cartopy':
import cartopy.crs as ccrs # verify package is importable
crs_translate = { # less verbose keywords, actually match proj4 keywords and are similar to basemap
**{k:'central_latitude' for k in ('lat0','lat_0')},
**{k:'central_longitude' for k in ('lon0', 'lon_0')},
}
crs_dict = { # interpret string, create cartopy projection
**{key: ccrs.PlateCarree for key in ('cyl', 'equirectangular', 'rectilinear','pcarree','platecarree')},
**{key: ccrs.Mollweide for key in ('moll','mollweide')},
**{key: ccrs.Stereographic for key in ('stereo','stereographic')},
**{key: ccrs.Mercator for key in ('merc', 'mercator')},
'aeqd': ccrs.AzimuthalEquidistant, 'aeqa': ccrs.LambertAzimuthalEqualArea,
'robinson': ccrs.Robinson, 'ortho': ccrs.Orthographic,
'hammer': Hammer, 'aitoff': Aitoff,
'wintri': WinkelTripel, 'kav7': KavrayskiyVII,
}
projection = projection or 'cyl'
if projection not in crs_dict:
raise ValueError(f'For cartopy, projection must be one of the following: {", ".join(crs_dict.keys())}.')
projection = crs_dict[projection](**{crs_translate.get(key,key):value for key,value in kwargs.items()})
aspect = (np.diff(projection.x_limits)/np.diff(projection.y_limits))[0]
# Error
else:
raise ValueError(f'Unknown package "{package}".')
return projection, aspect
def legend_factory(ax, handles=None, align=None, rowmajor=True, **lsettings): #, settings=None): # can be updated
"""
Function for formatting legend-axes (invisible axes with centered legends on them).
Should update my legend function to CLIP the legend box when it goes outside axes area, so
the legend-width and bottom/right widths can be chosen propertly/separately.
"""
# First get legend settings (usually just one per plot so don't need to declare
# this dynamically/globally), and interpret kwargs
if 'ncols' in lsettings:
lsettings['ncol'] = lsettings.pop('ncols') # pyplot subplot uses 'ncols', but legend uses 'ncol'... annoying!
if 'frame' in lsettings: # again, confusing choice
lsettings['frameon'] = lsettings.pop('frame')
# Setup legend text and handle properties
hsettings = {}
for candidate in ['linewidth', 'color']: # candidates for modifying legend objects
if candidate in lsettings:
hsettings[candidate] = lsettings.pop(candidate)
hsettings.update({'alpha':1.0}) # always maximimum opacity
lsettings.update({'prop':{'family':rc['fontname']}}) # 'prop' can be a FontProperties object or a dict for the kwargs to instantiate one
# Detect if user wants to specify rows manually
# Gives huge latitude for user input:
# 1) user can specify nothing and align will be inferred (list of iterables
# will always be False, i.e. we draw consecutive legends, and list of handles is always true)
# 2) user can specify align (needs list of handles for True, list of handles or list
# of iterables for False and if the former, will turn into list of iterables)
if handles is None:
handles = ax.get_legend_handles_labels()[0]
for i,handle in enumerate(handles):
if hasattr(handle, 'cmap'):
# Make sure we sample the *center* of the colormap
print('Warning: Creating legend for colormap object.')
size = np.mean(handle.get_sizes())
handles[i] = ax.scatter([0], [0],
markersize=size,
color=[handle.cmap(0.5)],
label=handle.get_label())
list_of_lists = not isinstance(handles[0], martist.Artist)
if align is None: # automatically guess
align = not list_of_lists
else: # standardize format based on input
if not align and not list_of_lists: # separate into columns
# raise ValueError("Need to specify number of columns with ncol.")
list_of_lists = True
lsettings['ncol'] = lsettings.get('ncol',3)
handles = [handles[i*lsettings['ncol']:(i+1)*lsettings['ncol']]
for i in range(len(handles))] # to list of iterables
if align and list_of_lists: # unfurl, because we just want one legend!
list_of_lists = False
handles = [handle for isiterable in handles for handle in isiterable]
list_of_lists = False # no longer is list of lists
# Now draw legend, with two options
# 1) Normal legend, just draw everything like normal and columns
# will be aligned; we re-order handles to be row-major, is only difference
if align:
# Prepare settings
if list_of_lists:
lsettings['ncol'] = len(handles[0]) # choose this for column length
elif 'ncol' not in lsettings:
lsettings['ncol'] = 3
# Split up into rows and columns -- by default matplotlib will
# sort them in ***column-major*** order but that's dumb, we want row-major!
# See: https://stackoverflow.com/q/10101141/4970632
if rowmajor:
newhandles = []
ncol = lsettings['ncol'] # number of columns
handlesplit = [handles[i*ncol:(i+1)*ncol] for i in range(len(handles)//ncol+1)] # split into rows
nrowsmax, nfinalrow = len(handlesplit), len(handlesplit[-1]) # max possible row count, and columns in final row
nrows = [nrowsmax]*nfinalrow + [nrowsmax-1]*(lsettings['ncol']-nfinalrow)
# e.g. if 5 columns, but final row length 3, columns 0-2 have N rows but 3-4 have N-1 rows
for col,nrow in enumerate(nrows): # iterate through cols
newhandles.extend(handlesplit[row][col] for row in range(nrow))
handles = newhandles
# Finally draw legend, mimicking row-major ordering
leg = super(BaseAxes, ax).legend(handles=handles, **lsettings)
legends = [leg]
# 2) Separate legend for each row
# The labelspacing/borderspacing will be exactly replicated, as if we were
# using the original legend command
# Means we also have to overhaul some settings
else:
legends = []
for override in ['loc','ncol','bbox_to_anchor','borderpad','borderaxespad','frameon','framealpha']:
lsettings.pop(override, None)
# Determine space we want sub-legend to occupy, as fraction of height
# Don't normally save "height" and "width" of axes so keep here
fontsize = lsettings.get('fontsize', None) or rc['legend.fontsize']
spacing = lsettings.get('labelspacing', None) or rc['legend.labelspacing']
interval = 1/len(handles) # split up axes
interval = (((1 + spacing)*fontsize)/72) / \
(ax.figure.get_figheight() * np.diff(ax._position.intervaly))
# Iterate and draw
if not rowmajor:
raise ValueError('Using rowmajor=False with align=False does not make sense.')
for h,hs in enumerate(handles):
bbox = mtransforms.Bbox([[0,1-(h+1)*interval],[1,1-h*interval]])
leg = super(BaseAxes, ax).legend(handles=hs, ncol=len(hs),
loc='center',
frameon=False,
borderpad=0,
bbox_to_anchor=bbox,
**lsettings) # _format_legend is overriding original legend Method
legends.append(leg)
for l in legends[:-1]:
ax.add_artist(l) # because matplotlib deletes previous ones
# Properties for legends
outline = {'linewidth': rc['axes.linewidth'],
'edgecolor': rc['axes.edgecolor'],
'facecolor': rc['axes.facecolor']}
for leg in legends:
leg.legendPatch.update(outline) # or get_frame()
for obj in leg.legendHandles:
obj.update(hsettings)
# for t in leg.texts:
# t.update(tsettings) # or get_texts()
return legends
def colorbar_factory(ax, mappable,
grid=None, locator=None, tickminor=None, minorlocator=None, ticklabels=None, formatter=None, label=None,
cgrid=False, clocator=None, ctickminor=False, cminorlocator=None, cticklabels=None, cformatter=None, clabel=None,
errfix=True, extend='neither', extendlength=0.2, # in inches
values=None, orientation='horizontal', ticklocation='outer', **kwargs): #, settings=None):
"""
Description
-----------
Function for formatting colorbar-axes (axes that are "filled" by a colorbar).
* There are options on the colorbar object (cb.locator, cb.formatter with cb.update_ticks)
and by passing kwargs (ticks=x, format=y) that allow uer to not reference the underlying
"axes" when fixing ticks. Don't use this functionality because not necessary for us and
is missing many features, e.g. minorlocators/minorformatters. Also is different syntax.
* There is an INSANELY WEIRD problem with colorbars when simultaneously passing levels
and norm object to a mappable; fixed by passing vmin/vmax INSTEAD OF levels
(see: https://stackoverflow.com/q/40116968/4970632).
* Problem is, often WANT levels instead of vmin/vmax, while simultaneously
using a Normalize (for example) to determine colors between the levels
(see: https://stackoverflow.com/q/42723538/4970632).
* Workaround is to make sure locators are in vmin/vmax range exclusively;
cannot match/exceed values.
* The 'extend' kwarg is used for the case when you are manufacturing colorbar
from list of colors or lines. Most of the time want 'neither'.
"""
# Parse flexible input
clocator = _fill(locator, clocator)
cgrid = _fill(grid, cgrid)
ctickminor = _fill(tickminor, ctickminor)
cminorlocator = _fill(minorlocator, cminorlocator)
cformatter = _fill(ticklabels, _fill(cticklabels, _fill(formatter, cformatter)))
clabel = _fill(label, clabel)
# Test if we were given a mappable, or iterable of stuff; note Container and
# PolyCollection matplotlib classes are iterable.
fromlines, fromcolors = False, False
if utils.isvector(mappable) and len(mappable)==2:
mappable, values = mappable
if not isinstance(mappable, martist.Artist) and not isinstance(mappable, mcontour.ContourSet):
if isinstance(mappable[0], martist.Artist):
fromlines = True # we passed a bunch of line handles; just use their colors
else:
fromcolors = True # we passed a bunch of color strings or tuples
csettings = {'cax':ax, 'orientation':orientation, 'use_gridspec':True, # use space afforded by entire axes
'spacing':'uniform', 'extend':extend, 'drawedges':cgrid} # this is default case unless mappable has special props
# Update with user-kwargs
csettings.update(**kwargs)
if hasattr(mappable, 'extend') and mappable.extend is not None:
csettings.update({'extend':mappable.extend})
# Option to generate colorbar/colormap from line handles
# * Note the colors are perfect if we don't extend them by dummy color on either side,
# but for some reason labels for edge colors appear offset from everything
# * Too tired to figure out why so just use this workaround
if fromcolors: # we passed the colors directly
colors = mappable
if values is None:
raise ValueError('Must pass "values", corresponding to list of colors.')
if fromlines: # the lines
if values is None:
raise ValueError('Must pass "values", corresponding to list of handles.')
if len(mappable)!=len(values):
raise ValueError('Number of "values" should equal number of handles.')
colors = [h.get_color() for h in mappable]
if fromlines or fromcolors:
# Get colors, and by default, label each value directly
cmap = colortools.colormap(colors)
values = np.array(values) # needed for below
levels = utils.edges(values) # get "edge" values between centers desired
mappable = ax.contourf([[0,0],[0,0]],
levels=levels, cmap=cmap,
extend='neither', norm=colortools.BinNorm(values)) # workaround
if clocator is None:
nstep = len(values)//20
clocator = values[::nstep]
if clocator is None:
# By default, label the discretization levels (if there aren't too many)
# Prefer centers (i.e. 'values') to edges (i.e. 'levels')
clocator = getattr(mappable, 'values', getattr(mappable, 'levels', None))
if clocator is not None:
step = 1 + len(clocator)//20
clocator = clocator[::step]
# Determine major formatters and major/minor tick locators
# Can pass clocator/cminorlocator as the *jump values* between the mappables
# vmin/vmax if desired
fixed = None # so linter doesn't detect error in if i==1 block
normfix = False # whether we need to modify the norm object
locators = [] # put them here
for i,locator in enumerate((clocator,cminorlocator)):
# Get the locator values
# Need to use tick_values instead of accessing 'locs' attribute because
# many locators don't have these attributes; require norm.vmin/vmax as input
if i==1 and not ctickminor and locator is None: # means we never wanted minor ticks
locators.append(axistools.locator('null'))
continue
values = np.array(axistools.locator(locator).tick_values(mappable.norm.vmin, mappable.norm.vmax)) # get the current values
# Modify ticks to work around mysterious error, and to prevent annoyance
# where minor ticks extend beyond extendlength.
# We need to figure out the numbers that will eventually be rendered to
# solve the error, so we will always use a fixedlocator.
values_min = np.where(values>=mappable.norm.vmin)[0]
values_max = np.where(values<=mappable.norm.vmax)[0]
if len(values_min)==0 or len(values_max)==0:
# print(f'Warning: no ticks are within the colorbar range {mappable.norm.vmin:.3g} to {mappable.norm.vmax:.3g}.')
locators.append(axistools.locator('null'))
continue
values_min, values_max = values_min[0], values_max[-1]
values = values[values_min:values_max+1]
if values[0]==mappable.norm.vmin:
normfix = True
if i==1:
# Prevent annoying major/minor overlaps where one is slightly shifted left/right
# Consider floating point weirdness too
# length = len(values)
eps = 1e-10
values = [v for v in values if not any(o+eps >= v >= o-eps for o in fixed)]
# print(f'Removed {length-len(values)}/{length} minor ticks(s).')
fixed = values # record as new variable
locators.append(axistools.locator(fixed)) # final locator object
# Next the formatter
cformatter = axistools.formatter(cformatter)
# Fix the norm object
# Check out the *insanely weird error* that occurs when you comment out this block!
# * The error is triggered when a *major* tick sits exactly on vmin, but
# the actual error is due to processing of *minor* ticks, even if the
# minor locator was set to NullLocator; very weird
# * Happens when we call get_ticklabels(which='both') below. Can be prevented
# by just calling which='major'. Minor ticklabels are never drawn anyway.
# * We can eliminate the normfix below, but that actually causes an annoying
# warning to be printed (related to same issue I guess). So we keep this.
# The culprit for all of this seems to be the colorbar API line:
# z = np.take(y, i0) + (xn - np.take(b, i0)) * dy / db
# * Also strange that minorticks extending *below* the minimum
# don't raise the error. It is only when they are exaclty on the minimum.
# * Note that when changing the levels attribute, need to make sure the
# levels datatype is float; otherwise division will be truncated and bottom
# level will still lie on same location, so error will occur
if normfix:
mappable.norm.vmin -= (mappable.norm.vmax-mappable.norm.vmin)/10000
if hasattr(mappable.norm, 'levels'):
mappable.norm.levels = np.atleast_1d(mappable.norm.levels).astype(np.float)
if normfix:
mappable.norm.levels[0] -= np.diff(mappable.norm.levels[:2])[0]/10000
# Draw the colorbar
# NOTE: For whatever reason the only way to avoid bugs seems to be to pass
# the major formatter/locator to colorbar commmand and directly edit the
# minor locators/formatters; update_ticks after the fact ignores the major formatter
# axis.set_major_locator(locators[0]) # does absolutely nothing
# axis.set_major_formatter(cformatter)
if orientation=='horizontal':
axis = ax.xaxis
scale = ax.figure.width*np.diff(getattr(ax.get_position(),'intervalx'))[0]
else:
axis = ax.yaxis
scale = ax.figure.height*np.diff(getattr(ax.get_position(),'intervaly'))[0]
extendlength = extendlength/(scale - 2*extendlength)
csettings.update({'extendfrac':extendlength}) # width of colorbar axes and stuff
cb = ax.figure.colorbar(mappable,
ticklocation=ticklocation,
ticks=locators[0],
format=cformatter,
**csettings)
# Make edges/dividers consistent with axis edges
if cb.dividers is not None:
cb.dividers.update(rc['grid'])
# The minor locators and formatters
# * The minor locator must be set with set_ticks after transforming an array
# using the mappable norm object; see: https://stackoverflow.com/a/20079644/4970632
# * The set_minor_locator seems to be completely ignored depending on the colorbar
# in question, for whatever reason
# * The major locator and formatter settings here are also not ideal since we'd have to
# update_ticks which might throw off the minor ticks again
# WARNING: If functionality of BoundaryNorm is modified so data is transformed
# by some linear transformation before getting binned, below may fail.
# cb.minorticks_on() # alternative, but can't control the god damn spacing/set our own version
# axis.set_minor_locator(locators[1]) # does absolutely nothing
# WARNING: For some reason, pcolor mappables need to take *un-normalized
# ticks* when set_ticks is called, while contourf mappables need to
# take *normalized* data (verify by printing)
minorvals = np.array(locators[1].tick_values(mappable.norm.vmin, mappable.norm.vmax))
# axis.set_ticks(mappable.norm(majorvals), minor=False)
if isinstance(mappable.norm, mcolors.BoundaryNorm): # including my own version
vmin, vmax = mappable.norm.vmin, mappable.norm.vmax
minorvals = (minorvals-vmin)/(vmax-vmin)
elif hasattr(mappable, 'levels'):
minorvals = mappable.norm(minorvals)
axis.set_ticks(minorvals, minor=True)
axis.set_minor_formatter(mticker.NullFormatter()) # to make sure
# Set up the label
if clabel is not None:
axis.label.update({'text':clabel})
# Fix alpha issues (cannot set edgecolor to 'face' if alpha non-zero
# because blending will occur, will get colored lines instead of white ones;
# need to perform manual alpha blending)
# NOTE: For some reason cb solids uses listed colormap with always 1.0
# alpha, then alpha is applied after.
# See: https://stackoverflow.com/a/35672224/4970632
alpha = None
if cb.solids: # for e.g. contours with colormap, colorbar will just be lines
alpha = cb.solids.get_alpha()
if alpha is not None and alpha<1:
# First get reference color
print('Performing manual alpha-blending for colorbar solids.')
reference = mappable.axes.get_facecolor() # the axes facecolor
reference = [(1 - reference[-1]) + reference[-1]*color for color in reference[:3]]
# Next get solids
reference = [1,1,1] # override?
alpha = 1 - (1 - alpha)**2 # make more colorful
colors = cb.solids.get_cmap().colors
colors = np.array(colors)
for i in range(3): # Do not include the last column!
colors[:,i] = (reference[i] - alpha) + alpha*colors[:,i]
cmap = mcolors.ListedColormap(colors, name='colorbar-fix')
cb.solids.set_cmap(cmap)
cb.solids.set_alpha(1.0)
# cb.solids.set_cmap()
# Fix pesky white lines between levels + misalignment with border due to rasterized blocks
if cb.solids:
cb.solids.set_linewidth(0.2) # something small
cb.solids.set_edgecolor('face')
cb.solids.set_rasterized(False)
return cb
<file_sep>#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# Import everything in this folder into a giant module
# Files are segretated by function, so we don't end up with
# giant 5,000-line single file
#------------------------------------------------------------------------------#
# First set up notebook
from .notebook import *
name = 'ProPlot'
# Then import stuff
from .utils import * # misc stuff
from .rcmod import * # custom configuration implementation
from .base import * # basic tools
from .subplots import *
from .gridspec import *
from .colortools import * # color tools
from .fonttools import * # fonts
from .axistools import * # locators, normalizers, and formatters
from .proj import * # cartopy projections and whatnot
from .demos import * # demonstrations
<file_sep># ProPlot
A library providing helpful and versatile plotting utilities to hasten the process of crafting publication-quality graphics with `matplotlib`.
## Overview
Import with
```
import proplot as plot
```
Most of the features derive from the **`subplots`** command, inspired by the `pyplot` command of the same name. This generates a scaffolding of axes and panels, which may have shared axes and spanning axis labels.
The next most important utility is the **`format`** method, available on every axes generated by `subplots`. Use this method to fine-tune your axis properties, titles, labels, limits, and much more.
Quick overview of additional features:
* Geometry: A smarter "tight subplots" method. Panels and empty spaces are held *fixed*, while the figure and axes dimensions are allowed to change. This acheives a "tight border" without messing up axes aspect ratios or spaces.
* Colors: Perceptually distinct named colors, powerful colormap-generating tools, ability to trivially swap between "color cycles" and "colormaps". A few new, beautiful colormaps and color cycles. Make colorbars from lists of lines or colors.
* Maps: Integration with basemap *and* cartopy. Generate arbitrary grids of map projections in one go. Switch between basemap and cartopy painlessly. Add geographical features as part of the `format` process.
## Showcase
For a showcase of all ProPlot features, check out [**this online jupyter notebook**](https://lukelbd.github.io/tools/proplot).
## Documentation
The full documentation can be found [**here**](https://lukelbd.github.io/tools/proplot_doc). It is a work-in-progress.
## Installation
This package is a work-in-progress. Currently there is no formal releas on PyPi. However, feel free to install directly from Github using:
```
pip install git+https://github.com/lukelbd/proplot.git#egg=proplot
```
I only push to this repo when new features are completed and working properly.
Dependencies are `matplotlib` and `numpy`. The geographic mapping mapping features require `basemap` or `cartopy`. Note that [basemap is no longer under active development](https://matplotlib.org/basemap/users/intro.html#cartopy-new-management-and-eol-announcement) -- cartopy is integrated more intelligently with the matplotlib API.
However, for the time being, basemap *retains several advantages* over cartopy (namely [more tools for labeling meridians/parallels](https://github.com/SciTools/cartopy/issues/881) and more available projections -- see [basemap](https://matplotlib.org/basemap/users/mapsetup.html) vs. [cartopy](https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html)). Therefore, I decided to support both.
<!-- may be preferred in some circumstances. -->
## How is this different from seaborn?
There is already a great matplotlib wrapper called [seaborn](https://seaborn.pydata.org/). What makes this project different?
While some of `proplot`'s tools were inspired by seaborn (in particular much of `colors.py` is drawn from seaborn's `palettes.py`), the goal for this project was quite different -- it is intended to simplify the task of crafting publication-quality graphics, and no more.
Seaborn largely attempts to merge the tasks of data analysis and visualization, and many of its features require neatly tabulated data in a standard form. ProPlot contains no analysis tools -- it is expected that you analyze your data on your own time. Anyway, as an atmospheric scientist, the datasets I use usually do not lend themselves to fitting in a simple DataFrame -- so this seaborn feature was not particularly useful for me. For data analysis tools I use in my physical climatology research, check out my [ClimPy](https://github.com/lukelbd/climpy`) project (still in preliminary stages).
By focusing on this one task, I was able to create a number of powerful features well beyond the scope of `seaborn`. See the documentation and showcase for details.
## Donations
This package took a shocking amount of time to write. If you've found it useful, feel free to buy me a cup of coffee :)
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5SP6S8RZCYMQA&source=url)
<file_sep>#------------------------------------------------------------------------------#
# This module contains some custom cartopy projections, and tools for
# making stuff easier
#------------------------------------------------------------------------------#
import numpy as np
import matplotlib.path as mpath
# import cartopy.crs as ccrs
try:
from cartopy.crs import _WarpedRectangularProjection
except ModuleNotFoundError:
_WarpedRectangularProjection = object
#------------------------------------------------------------------------------#
# Path boundaries for projections
#------------------------------------------------------------------------------#
# Circle path suitable for polar stereo/aeqd/lambert conformal projections
def Circle(ax, N=100):
theta = np.linspace(0, 2*np.pi, N)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
return mpath.Path(verts * radius + center)
#------------------------------------------------------------------------------#
# Simple projections
# Inspired by source code for Mollweide implementation
#------------------------------------------------------------------------------#
class Hammer(_WarpedRectangularProjection):
__name__ = 'hammer'
name = 'hammer'
def __init__(self, central_longitude=0, globe=None): #, threshold=1e2):
# self._threshold = threshold
proj4_params = [('proj', 'hammer'), ('lon_0', central_longitude)]
proj4_params = {'proj':'hammer', 'lon_0':central_longitude}
super().__init__(proj4_params, central_longitude, globe=globe)
@property
def threshold(self): # how finely to interpolate line data, etc.
# return self._threshold
return 1e4
class Aitoff(_WarpedRectangularProjection):
__name__ = 'aitoff'
name = 'aitoff'
def __init__(self, central_longitude=0, globe=None): #, threshold=1e2):
# self._threshold = threshold
proj4_params = [('proj', 'aitoff'), ('lon_0', central_longitude)]
proj4_params = {'proj':'aitoff', 'lon_0':central_longitude}
super().__init__(proj4_params, central_longitude, globe=globe)
@property
def threshold(self): # how finely to interpolate line data, etc.
# return self._threshold
return 1e4
class KavrayskiyVII(_WarpedRectangularProjection):
__name__ = 'kavrayskiyVII'
name = 'kavrayskiyVII'
def __init__(self, central_longitude=0, globe=None):
proj4_params = [('proj', 'kav7'), ('lon_0', central_longitude)]
super(KavrayskiyVII, self).__init__(
proj4_params,
central_longitude,
globe=globe)
@property
def threshold(self):
return 1e4
# TODO: Check this, but should be pretty much identical to above
class WinkelTripel(_WarpedRectangularProjection):
__name__ = 'winkeltripel'
name = 'winkeltripel'
def __init__(self, central_longitude=0, globe=None):
proj4_params = [('proj', 'wintri'), ('lon_0', central_longitude)]
super(WinkelTripel, self).__init__(
proj4_params,
central_longitude,
globe=globe)
@property
def threshold(self):
return 1e4
#------------------------------------------------------------------------------#
# Wrappers around existing projections
#------------------------------------------------------------------------------#
# class LambertAzimuthalEqualArea(ccrs.LambertAzimuthalEqualArea)
# def __init__(self, *args, **kwargs):
# super(LambertAzimuthalEqualArea, self)
#
# class AzimuthalEquidistant(ccrs.AzimuthalEquidistant)
# def __init__(self, *args, **kwargs):
# super(AzimuthalEquidistant, self)
<file_sep>from setuptools import setup
# For including non-python data, see:
# https://stackoverflow.com/a/1857436/4970632
# NOTE: To rename the repo (which you do a lot), use this command:
# find . \( -name '*.ipynb' -o -name '*.py' -o -name '*.md' -o -name '*.txt' -o -name '.vimsession' \) -exec gsed -i 's/panplot/proplot/g' {} +
setup(
# Needed to silence warnings (and to be a worthwhile package)
name = 'ProPlot',
url = 'https://github.com/lukelbd/proplot',
author = '<NAME>',
author_email = '<EMAIL>',
# Package stuff
# Also include package data
packages = ['proplot'],
package_data = {'': ['cmaps/*', 'fonts/*', 'colors/*']},
# Command-line scripts
# scripts = ['scripts/proplot_fonts'],
# Needed for dependencies
install_requires = ['numpy', 'matplotlib'],
# *Strongly* suggested for sharing
version = '1.0',
# The license can be anything you like
license = open('LICENSE.txt').read(),
description = 'Matplotlib wrapper for making clear, concise, publication-quality graphics quickly and easily.',
long_description = open('README.md').read(),
)
|
9745c1f55511b73c7d8ad1902845d03d3cbdf9a9
|
[
"Markdown",
"Python"
] | 16
|
Python
|
lukelbd/pubplot
|
b6648baef49dabc7d410e5a152171393541b2b88
|
0c2973609486fc0bc34c83a66215db9a4d7ab1ad
|
refs/heads/master
|
<repo_name>Peony27/Mafia<file_sep>/src/Suspect.java
public class Suspect {
}
|
12ce560444e1f36d811cb13d125c52401ed391c2
|
[
"Java"
] | 1
|
Java
|
Peony27/Mafia
|
159fbe2872154e5bf1688ebd6ab173c3740885a9
|
e5f709ecbe946222df0bf5271aea6f8b608f534d
|
refs/heads/main
|
<file_sep># Shapes Intersection code test
<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
namespace Shapes_Intersection_test
{
class Program
{
static List<Shape> shapes;
static List<int> results;
static Dictionary<int, List<int>> intersectionDictionary;
static void Main(string[] args)
{
Console.WriteLine("Checking intersections...");
CreateShapes();
intersectionDictionary = FindIntersections(shapes);
for (int i = 0; i < intersectionDictionary.Count; i++)
{
results = intersectionDictionary[i + 1];
Console.Write(" Shape of ID " + (i + 1));
Console.Write(" Intersects with Shape with ID ");
for (int j = 0; j < results.Count; j++)
{
Console.Write(results[j]);
if (j + 1 < results.Count)
{
Console.Write(", ");
}
}
Console.WriteLine(" ");
}
}
public static Dictionary<int, List<int>> FindIntersections(List<Shape> shapes)
{
// define dictionary
Dictionary<int, List<int>> returnDictionary = new Dictionary<int, List<int>>();
// for every shape check for a intersection between the other shapes
for(int i = 0; i < shapes.Count; i++)
{
List<int> intersections = new List<int>();
for (int j = 0; j < shapes.Count; j++)
{
if(shapes[i] != shapes[j])
{
if(intersectionType(shapes[i], shapes[j]))
{
intersections.Add(shapes[j].ID);
}
}
}
//add results to dictionary
returnDictionary.Add(shapes[i].ID, intersections);
}
return returnDictionary;
}
public static void CreateShapes()
{
shapes = new List<Shape>();
shapes.Add(new CustomRectangle(55, 70, 170, 90, 1));
shapes.Add(new CustomRectangle(90, 120, 20, 90, 2));
shapes.Add(new Circle(20, 20, 10, 3));
shapes.Add(new Circle(12, 9, 15, 4));
}
public static bool intersectionType(Shape a, Shape b)
{
bool returnBool = false;
//take in what type class the shapes are
Type shapeA = a.GetType();
Type shapeB = b.GetType();
//if a rectangle and circle need to be compared use the specific intersectCheck for that combination
if (shapeA == typeof(CustomRectangle) && shapeB == typeof(Circle))
{
returnBool = intersectCheck(a as CustomRectangle, b as Circle);
}
//if two rectangles used the specific intersectCheck for that
if (shapeA == typeof(CustomRectangle) && shapeB == typeof(CustomRectangle))
{
returnBool = intersectCheck(a as CustomRectangle, b as CustomRectangle);
}
//same as the top but checking if it's the otherway around.
if (shapeA == typeof(Circle) && shapeB == typeof(CustomRectangle))
{
returnBool = intersectCheck(b as CustomRectangle, a as Circle);
}
//if two circles use that specific intersectCheck
if (shapeA == typeof(Circle) && shapeB == typeof(Circle))
{
returnBool = intersectCheck(b as Circle, a as Circle);
}
return returnBool;
}
//intersectCheck for two rectangles, casts them into the System.Drawing rectangle type so it can use the Rectangle.IntersectsWith method.
//I did this because the maths was already built in and it saved me time.
public static bool intersectCheck(CustomRectangle rect1, CustomRectangle rect2)
{
Rectangle rectangle1 = new Rectangle(rect1.dimensions.X, rect1.dimensions.Y, rect1.dimensions.Width, rect1.dimensions.Height);
Rectangle rectangle2 = new Rectangle(rect2.dimensions.X, rect2.dimensions.Y, rect2.dimensions.Width, rect2.dimensions.Height);
if (rectangle1.IntersectsWith(rectangle2))
{
return true;
}
else
{
return false;
}
}
// intersect check for two circles.
public static bool intersectCheck(Circle circ1, Circle circ2)
{
//gets the distance between the two and if circles and if the distance is greater than the combined radii then they don't intersect
float xDistance = circ1.X - circ2.X;
float yDistance = circ1.Y - circ2.Y;
var distance = Math.Sqrt(xDistance * xDistance + yDistance * yDistance);
if (distance < circ1.Radius + circ2.Radius)
{
return true;
}
else
{
return false;
}
}
//intersect check for a rectangle and a circle.
public static bool intersectCheck(CustomRectangle rect, Circle circ)
{
float cx = Math.Abs(circ.X - rect.dimensions.X - rect.dimensions.Width / 2);
float distanceX = rect.dimensions.Width / 2 + circ.Radius;
if(cx > distanceX)
{
return false;
}
float cy = Math.Abs(circ.Y - rect.dimensions.Y - rect.dimensions.Height / 2);
float distanceY = rect.dimensions.Height / 2 + circ.Radius;
if (cy > distanceY)
{
return false;
}
if (cx <= rect.dimensions.Width / 2 || cy <= rect.dimensions.Height / 2)
{
return true;
}
float xCornerDist = cx - rect.dimensions.Width / 2;
float yCornerDist = cy - rect.dimensions.Height / 2;
float xCornerDistSq = xCornerDist * xCornerDist;
float yCornerDistSq = yCornerDist * yCornerDist;
float maxCornerDistSq = circ.Radius * circ.Radius;
return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
}
}
public class Shape
{
public int ID { get; set; }
public float X { get; set; }
public float Y { get; set; }
}
public class Circle : Shape
{
public int Radius { get; private set; }
public Circle(float x, float y, int radius, int id)
{
Radius = radius;
X = x;
Y = y;
ID = id;
}
}
public class CustomRectangle : Shape
{
public Rectangle dimensions;
public CustomRectangle(int x, int y, int width, int height, int id)
{
dimensions.X = x;
dimensions.Y = y;
dimensions.Width = width;
dimensions.Height = height;
ID = id;
}
}
}
|
b97f174f3cfa18789af5ab0e5c85f272f015ffd1
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
RabidChinchilla/Shapes-Intersection-code-test
|
6f208121e674a49e5646129846a747201cdab8ce
|
10e780f8d77b65f22816ea2dd53f42d7c063e770
|
refs/heads/master
|
<file_sep>package com.xiaobo.common.utils;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import org.apache.commons.lang.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* class反射工具
* @author zhangxiaobo
* @date 2018年8月17日 上午10:37:16
*/
public class ReflectUtils {
/**
* 反射得出该实体配置的具体表名
* @param c
* @return
*/
public static <T> String reflectObjectTable(Class<T> c) {
TableName tn = c.getAnnotation(TableName.class);
if(tn != null) {
return tn.value();
}
return null;
}
/**
* 通过mybatis反射获取当前字段的数据库字段名称
* @param t 实体类型
* @param fieldName 字段名称
* @return 数据库中该字段的映射
*/
public static <T> String reflectFiledTableColumn(Class<T> t , String fieldName) {
try {
Field f = t.getDeclaredField(fieldName);
if(f == null) return null ;
if(f.isAnnotationPresent(TableField.class)) {
TableField tf = f.getAnnotation(TableField.class);
// 字段不再表中体现
if(tf != null && !tf.exist()) return null;
if(tf != null && tf.exist()) {
return tf.value();
}
}
// 没有注解 则将大写转下划线
return com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(fieldName);
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String str = "tableName" ;
str = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(str);
System.out.println(str);
}
/**
* 拿到object中 注解TableId的值
* @param t 实体
* @return 实体中���解了tableId的字段的值,如果没有注解tableid,或者没有get方法 返回null
*/
public static <T> Object reflectObjectId(T t) {
//Field[] fs = t.getClass().getDeclaredFields();
List<Field> fs = getAllFields(t);
for(Field f : fs) {
if(f.isAnnotationPresent(TableId.class)) {
//拿到get方法 获取值
String getMethodName = "get" + StringUtils.capitalize(f.getName());
try {
Method m = t.getClass().getMethod(getMethodName, null);
if(m != null) {
return m.invoke(t, null);
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/**
* 获取包含父类在内的所有字段Field
* @param t
* @return
*/
private static List<Field> getAllFields(Object t){
List<Field> fieldList = new ArrayList<>() ;
Class tempClass = t.getClass();
while (tempClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类).
fieldList.addAll(Arrays.asList(tempClass .getDeclaredFields()));
tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
}
return fieldList;
}
}
<file_sep>package com.xiaobo.common.utils.Excel;
import com.xiaobo.common.utils.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Date;
import java.util.function.Consumer;
public class ExcelConsumer implements Consumer<Row>{
private int cnt ;
private String file_id;
private String split;
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public String getFile_id() {
return file_id;
}
public void setFile_id(String file_id) {
this.file_id = file_id;
}
public String getSplit() {
return split;
}
public void setSplit(String split) {
this.split = split;
}
private BufferedWriter bw = null;
public ExcelConsumer(BufferedWriter bw, String file_id, String split) {
super();
this.bw = bw;
this.file_id = file_id;
this.split = split;
}
private int cellCnt = 0;
@Override
public void accept(Row t) {
int rowcnt = t.getPhysicalNumberOfCells();
if(rowcnt == 0) return ;
if(cnt == 0) {
cellCnt = rowcnt;
cnt++;
return ;
}
StringBuffer sb = new StringBuffer();
sb.append(file_id + split);
int v_cnt = 0; // 实际由数据的字段 如果一行中一个由数据的字段都没有 说明结束了
for(int i = 0 ; i < cellCnt ; i++) {
Cell cell = t.getCell(i);
Object value = ExcelUtils.getCellValue(cell);
String valueStr = "" ;
if(value != null ) {
if(value instanceof Date) {
valueStr = DateUtils.format((Date)value , DateUtils.DATE_TIME_PATTERN);
} else {
valueStr = value.toString();
}
}
sb.append(valueStr + split);
v_cnt += (value != null ? 1 : 0);
}
if(v_cnt == 0) return ;
sb.deleteCharAt(sb.length() - 1);
try {
bw.write(sb.toString());
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb.delete(0, sb.length());
cnt++;
}
}
<file_sep>package com.xiaobo.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobo.common.form.LoginForm;
import com.xiaobo.common.utils.PageUtils;
import com.xiaobo.common.utils.R;
import com.xiaobo.modules.sys.entity.SysUserEntity;
import java.util.List;
import java.util.Set;
/**
* 系统用户
*
* zhangxiaobo
* @email <EMAIL>
* @date 2016年9月18日 上午9:43:39
*/
public interface SysUserService extends IService<SysUserEntity> {
PageUtils queryPage(SysUserEntity entity, PageUtils page);
List<SysUserEntity> queryList(SysUserEntity entity);
/**
* 查询用户的所有权限
* @param userId 用户ID
*/
Set<String> queryAllPerms(String userId);
/**
* 查询用户的所有菜单ID
*/
List<String> queryAllMenuId(String userId);
/**
* 根据用户名,查询系统用户
*/
SysUserEntity queryByUserNo(String userNo);
/**
* 修改用户
*/
void update(SysUserEntity user);
/**
* 删除用户
*/
void deleteBatch(String[] userIds);
/**
* 修改密码
* @param userId 用户ID
* @param password 原密码
* @param newPassword 新密码
*/
boolean updatePassword(String userId, String password, String newPassword);
/**
* 重置用户密码
* @param userId 用户ID
* @param newPass 新密码,经过加密后的
* @return
*/
public boolean resetPass(String userId, String newPass);
/**
* 用户登录
* @param form 登录表单
* @return 返回用户权限和用户信息 登陆异常返回登陆错误信息
*/
R appLogin(LoginForm form);
/**
* 保存用户
*/
void saveUser(SysUserEntity user);
/**
* 查询自己添加的账户
*/
List<SysUserEntity> queryByCreateID(String createuserid);
/**
* 查询账户列表
*/
List<SysUserEntity> queryUsers();
/**
* 修改最后登录时间
* */
void updateLastDate(SysUserEntity user);
int queryMainNum(String orgId);
//查询用户当前单位及下属的账号
List<SysUserEntity> queryByOrgParent(String orgId, String currUserId);
SysUserEntity queryById(String id);
}
<file_sep>
package com.xiaobo;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis-plus配置
*
* @author Mark <EMAIL>
* @since 2.0.0 2018-02-05
*/
@Configuration
//@MapperScan(basePackages= {"com.tr.*.dao","com.tr.*.*.dao"})
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
<file_sep>export default {
namespaced: true,
state: {
userId: null,
name: '',
orgId:'',
headImage:'',
titles:'',
},
mutations: {
updateId (state, id) {
state.userId = id
},
updateName (state, name) {
state.name = name
},
updateOrgId(state,orgId){
state.orgId = orgId
},
updateHeadImage(state,headImage){
state.headImage = headImage
},
updateTitles(state,titles){
state.titles = titles
}
}
}
<file_sep>package com.xiaobo;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* 〈返回json空值去掉null和""〉 〈功能详细描述〉
*
* @author zhangxiaobo
* @see JacksonConfig
* @since
*/
//@Configuration
public class JacksonConfig {
// @Bean
// @Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
objectMapper.setSerializationInclusion(Include.NON_NULL);
// 字段保留,将null值转为"" -- 将为null的全部去掉
// objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
// @Override
// public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
// throws IOException, JsonProcessingException {
// jsonGenerator.writeString("");
//
// }
// });
return objectMapper;
}
}
<file_sep>package com.xiaobo.common.app.annotation;
import java.lang.annotation.*;
/**
* app perm验证
* @author zhangxiaobo
*
* @date 2017/9/23 14:30
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AppPerm {
String perm() default ""; // 权限码
//UserType role() default UserType.unknow; // 用户类型
}
<file_sep>package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysOrganizationEntity;
import com.xiaobo.modules.sys.entity.vo.SysOrgVo;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface SysOrganizationDao extends BaseMapper<SysOrganizationEntity> {
@Select("select id,name,parent_id,order_num,create_time,update_time, 'filedk' as fileIconName from sys_organization where id = #{parentId} " +
"order by order_num")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "parent_id", property = "parentId"),
@Result(column = "order_num", property = "orderNum"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime"),
@Result(column = "fileIconName", property = "fileIconName"),
@Result(column = "id", property = "list",
many = @Many(select = "com.tr.modules.sys.dao.SysOrganizationDao.findParentId1")),
})
List<SysOrgVo> findParentId(@Param("parentId") String parentId);
@Select("select id,name,parent_id,order_num,create_time,update_time,'filedk' as fileIconName from sys_organization where parent_id = #{parentId} " +
"order by order_num")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "parent_id", property = "parentId"),
@Result(column = "order_num", property = "orderNum"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime"),
@Result(column = "fileIconName", property = "fileIconName"),
@Result(column = "id", property = "list",
many = @Many(select = "com.tr.modules.sys.dao.SysOrganizationDao.findParentId1")),
})
List<SysOrgVo> findParentId1(@Param("parentId") String parentId);
@Select("select id,name,parent_id,order_num,create_time,update_time from sys_organization where parent_id = #{parentId} " +
"order by order_num")
List<SysOrganizationEntity> findChild(@Param("parentId") String parentId);
@Select("select id,name,parent_id from sys_organization where id = #{orgId}")
SysOrganizationEntity queryById(String orgId);
@Select("select id from sys_organization where parent_id = '0'")
String findSgjId();
@Select("select DISTINCT t1.* from\n" +
"(\n" +
"\tWITH RECURSIVE T (ID, NAME, PARENT_ID, order_num ) AS (\n" +
" SELECT ID,NAME, PARENT_ID, order_num \n" +
" FROM sys_organization WHERE ID = #{orgId}\n" +
"\t\t\t\t\t\t\t\t\t\tUNION ALL\n" +
" SELECT T1.ID, T1.NAME,T1.PARENT_ID,T1.order_num \n" +
" FROM sys_organization T1\n" +
" JOIN T ON T1.PARENT_ID = T.ID \n" +
" )\n" +
"\t\tselect * from T\t\t\n" +
") t1 \n" +
"\n" +
" order by t1.order_num ")
List<SysOrganizationEntity> getTreeList(@Param("orgId") String orgId);
/**
* 递归查询orgID
*/
@Select("with recursive t(id) as (\n" +
" select id from sys_organization where parent_id = #{orgId} \n" +
" union all\n" +
" select s.id from t , sys_organization as s\n" +
" where t.id = s.parent_id \n" +
"),\n" +
"t2 as (\n" +
" select #{orgId} as id \n" +
"union \n" +
"select id from t \n" +
")\n" +
"select id FROM t2")
List<String> recursiveQuery(String orgId);
//递归查询单位
@Select("WITH RECURSIVE T ( ID, NAME, PARENT_ID, order_num ) AS (\n" +
"SELECT ID\n" +
"\t,\n" +
"\tNAME,\n" +
"\tPARENT_ID,\n" +
"\torder_num \n" +
"FROM\n" +
"\tsys_organization \n" +
"WHERE\n" +
"\tID = #{orgId} UNION ALL\n" +
"SELECT\n" +
"\tT1.ID,\n" +
"\tT1.NAME,\n" +
"\tT1.PARENT_ID,\n" +
"\tT1.order_num \n" +
"FROM\n" +
"\tsys_organization T1\n" +
"\tJOIN T ON T1.PARENT_ID = T.ID \n" +
"\t) SELECT\n" +
"\t* from sys_organization \n" +
"WHERE\n" +
"\tid IN ( SELECT ID FROM T )")
List<SysOrganizationEntity> recursiveQueryEntity(String orgId);
@Select("select id,name from sys_organization ORDER BY id")
List<SysOrganizationEntity> queryName();
@Select("SELECT id FROM sys_organization where parent_id= #{parentOrgId} order by order_num")
List<String> queryChildrenIds(String parentOrgId);
}
<file_sep>package com.xiaobo.modules.sys.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobo.common.redis.RedisUtils;
import com.xiaobo.common.utils.Constant;
import com.xiaobo.common.utils.R;
import com.xiaobo.common.utils.TokenGenerator;
import com.xiaobo.modules.sys.dao.SysUserTokenDao;
import com.xiaobo.modules.sys.entity.SysUserTokenEntity;
import com.xiaobo.modules.sys.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class SysUserAppTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
@Autowired
private RedisUtils redisUtils;
@Override
public R createToken(String userId, String browser, String os) {
//生成一个token
String token = TokenGenerator.generateValue();
//当前时间
Date now = new Date();
//过期时间
Date expireTime = new Date(now.getTime() + Constant.EXPIRE * 1000);
//判断是否生成过token
SysUserTokenEntity tokenEntity = this.getById(userId);
if(tokenEntity == null){
tokenEntity = new SysUserTokenEntity();
tokenEntity.setUserId(userId);
tokenEntity.setToken(token);
tokenEntity.setUpdateTime(now);
tokenEntity.setExpireTime(expireTime);
tokenEntity.setBrowser(browser);
tokenEntity.setOs(os);
//保存token
this.save(tokenEntity);
}else{
tokenEntity.setToken(token);
tokenEntity.setUpdateTime(now);
tokenEntity.setExpireTime(expireTime);
tokenEntity.setBrowser(browser);
tokenEntity.setOs(os);
//更新token
this.updateById(tokenEntity);
}
//清理用户之前的token
if(redisUtils.containKey(getClass().getSimpleName() + userId)) {
String oToken = redisUtils.get(getClass().getSimpleName() + userId);
redisUtils.delete(getClass().getSimpleName() + oToken);
}
redisUtils.set(getClass().getSimpleName() + userId, token);
redisUtils.set(getClass().getSimpleName() + token, tokenEntity);
R r = R.ok().put("token", token).put("expire", Constant.EXPIRE);
return r;
}
@Override
public void logout(String userId) {
//生成一个token
String token = TokenGenerator.generateValue();
//修改token
SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
tokenEntity.setUserId(userId);
tokenEntity.setToken(token);
this.updateById(tokenEntity);
//清理用户之前的token
if(redisUtils.containKey(getClass().getSimpleName() + userId)) {
String oToken = redisUtils.get(getClass().getSimpleName() + userId);
redisUtils.delete(getClass().getSimpleName() + oToken);
}
redisUtils.set(getClass().getSimpleName() + userId, token);
redisUtils.set(getClass().getSimpleName() + token, tokenEntity);
}
@Override
public SysUserTokenEntity queryByToken(String token) {
// TODO Auto-generated method stub
if(redisUtils.containKey(getClass().getSimpleName() + token)) {
return redisUtils.get(getClass().getSimpleName() + token, SysUserTokenEntity.class);
}
return baseMapper.queryByToken(token);
}
/**
* 基于redis,如果redis没有开启则不管
*/
@Override
public String queryTokenByUserId(String userId) {
if(redisUtils.containKey(getClass().getSimpleName() + userId)) {
return redisUtils.get(getClass().getSimpleName() + userId);
}
return null;
}
public void updateLogoutTime(String userId){ baseMapper.updateLogoutTime(userId);}
}
<file_sep>
package com.xiaobo.modules.sys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobo.common.entity.SysUser;
import com.xiaobo.common.enums.MenuType;
import com.xiaobo.common.exception.RRException;
import com.xiaobo.common.log.annotation.SysLog;
import com.xiaobo.common.utils.Constant;
import com.xiaobo.common.utils.R;
import com.xiaobo.modules.sys.entity.SysMenuEntity;
import com.xiaobo.modules.sys.service.*;
import com.xiaobo.sys.controller.AbstractController;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* 系统菜单
*
* zhangxiaobo
* @date 2017年10月27日 下午9:58:15
*/
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {
@Autowired
private SysMenuService sysMenuService;
@Autowired
private ShiroService shiroService;
@Autowired
private SysUserService sysUserService ;
@Autowired
private com.xiaobo.common.security.SecurityUtils securityUtils ;
@Autowired
private SysUserRoleService sysUserRoleService;
@Autowired
private SysRoleMenuService sysRoleMenuService;
/**
* 导航菜单
*/
@GetMapping("/nav")
public R nav(){
SysUser user = getUser();
List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(user.getUserId());
Set<String> permissions = shiroService.getUserPermissions(user.getUserId());
List<SysMenuEntity> departingTools = this.departingTools();
return R.ok()
.put("menuList", menuList)
.put("permissions", permissions)
.put("departingTools",departingTools);
}
/**
* 离职人员库的工具栏
* */
public List<SysMenuEntity> departingTools(){
List<SysMenuEntity> menuList = new ArrayList<>();
//离职人员库的工具栏工具栏第一层 工作管理
SysMenuEntity sysMenuEntityWork = new SysMenuEntity();
sysMenuEntityWork.setMenuId(UUID.randomUUID().toString().replaceAll("-",""));
sysMenuEntityWork.setName("工作管理");
sysMenuEntityWork.setLocationType(2);
sysMenuEntityWork.setIcon("gzgl");
sysMenuEntityWork.setType(MenuType.CATALOG);
sysMenuEntityWork.setRouteOnly(1);
sysMenuEntityWork.setEnabled(1);
List<SysMenuEntity> menuList1 = new ArrayList<>();
sysMenuEntityWork.setList(menuList1);
//给离职人员库工具栏添加工具
menuList.add(sysMenuEntityWork);
// menuList.add(sysMenuEntityMess);
return menuList;
}
/**
* 所有菜单列表
*/
@GetMapping("/list")
@RequiresPermissions("sys:menu:list")
public R list(){
List<SysMenuEntity> menuList = sysMenuService.list();
Map<String, String> parent_name = new HashMap<>();
menuList.forEach(new Consumer<SysMenuEntity>() {
@Override
public void accept(SysMenuEntity t) {
parent_name.put(t.getMenuId() , t.getName());
}
});
for(SysMenuEntity sysMenuEntity : menuList){
String pname = parent_name.get(sysMenuEntity.getParentId());
if(pname != null){
sysMenuEntity.setParentName(pname);
}
}
// 过滤拆分除工具和菜单
List<SysMenuEntity> mlist = menuList.stream()
.filter(m -> m.getLocationType() == 1)
.sorted( (x , y)-> x.getOrderNum().compareTo(y.getOrderNum()))
.collect(Collectors.toList());
List<SysMenuEntity> tlist = menuList.stream()
.filter(m -> m.getLocationType() == 2)
.sorted( (x , y)-> x.getOrderNum().compareTo(y.getOrderNum()))
.collect(Collectors.toList());
return R.ok().put("mlist", mlist).put("tlist", tlist);
}
/**
* 登录用户的菜单列表
*/
@GetMapping("/newlist")
public R newList(){
//获取当前登录ID
SysUser user = securityUtils.getCurrentUser();
String userid = user.getUserId();
List<SysMenuEntity> menuList = new ArrayList<SysMenuEntity>();
if ("admin".equals(userid)){
/*if ("admin".equals(userid)){*/
//获取全部menu
menuList = sysMenuService.list();
}else {
/*//查询自己的roleid
String roleId = sysUserRoleService.queryRoleId(userid);
//根据roleid查询menuid
List<String> menuIds = sysRoleMenuService.queryMenuIdList(roleId);*/
//根据userid查询menu实体
menuList = sysMenuService.getMenuListByID(userid);
}
Map<String, String> parent_name = new HashMap<>();
menuList.forEach(new Consumer<SysMenuEntity>() {
@Override
public void accept(SysMenuEntity t) {
parent_name.put(t.getMenuId() , t.getName());
}
});
for(SysMenuEntity sysMenuEntity : menuList){
String pname = parent_name.get(sysMenuEntity.getParentId());
if(pname != null){
sysMenuEntity.setParentName(pname);
}
}
// 过滤拆分除工具和菜单
List<SysMenuEntity> mlist = menuList.stream()
.filter(m -> m.getLocationType() == 1)
.sorted( (x , y)-> x.getOrderNum().compareTo(y.getOrderNum()))
.collect(Collectors.toList());
List<SysMenuEntity> tlist = menuList.stream()
.filter(m -> m.getLocationType() == 2)
.sorted( (x , y)-> x.getOrderNum().compareTo(y.getOrderNum()))
.collect(Collectors.toList());
return R.ok().put("mlist", mlist).put("tlist", tlist);
}
/**
* 根据权限码获取子菜单列表
* @param perm权限码
* @return
*/
@GetMapping("/childByPerm")
public R childByPerm(String perm) {
if(StringUtils.isBlank(perm)) return R.error();
QueryWrapper<SysMenuEntity> query = new QueryWrapper<>();
query.eq("perms", perm);
SysMenuEntity parent = sysMenuService.getOne(query);
if(parent == null) return R.error();
List<SysMenuEntity> list = sysMenuService.queryListParentId(parent.getMenuId());
if(list != null) {
// 权限筛选
String userId = securityUtils.getCurrentUser().getUserId();
if(!userId.equals(Constant.SUPER_ADMIN)) {
List<String> userMenuIds = sysUserService.queryAllMenuId(userId);
// 筛选过滤
list = list.stream().filter(t->userMenuIds.contains(t.getMenuId())).collect(Collectors.toList());
}
}
return R.ok().put("data", list);
}
/**
* 根据权限码获取子菜单列表
* @param perm权限码
* @return
*/
@GetMapping("/childById")
public R childById(String id) {
if(StringUtils.isBlank(id)) return R.error();
List<SysMenuEntity> list = sysMenuService.queryListParentId(id);
if(list != null) {
// 权限筛选
String userId = securityUtils.getCurrentUser().getUserId();
if(!userId.equals(Constant.SUPER_ADMIN)) {
List<String> userMenuIds = sysUserService.queryAllMenuId(userId);
// 筛选过滤
list = list.stream().filter(t->userMenuIds.contains(t.getMenuId())).collect(Collectors.toList());
}
}
return R.ok().put("data", list);
}
/**
* 选择菜单(添加、修改菜单)
*/
@GetMapping("/select")
@RequiresPermissions("sys:menu:select")
public R select(){
//查询列表数据
List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();
// 拆解菜单栏和工具栏
List<SysMenuEntity> mlist = menuList.stream().filter(m -> m.getLocationType() == 1).collect(Collectors.toList());
{
//添加顶级菜单
SysMenuEntity root = new SysMenuEntity();
root.setMenuId("0");
root.setName("一级菜单");
root.setParentId("-1");
root.setOpen(true);
mlist.add(root);
}
List<SysMenuEntity> tlist = menuList.stream().filter(m -> m.getLocationType() == 2).collect(Collectors.toList());
{
//添加顶级菜单
SysMenuEntity root = new SysMenuEntity();
root.setMenuId("0");
root.setName("一级工具");
root.setParentId("-1");
root.setOpen(true);
tlist.add(root);
}
return R.ok().put("menuList", mlist).put("toolList", tlist);
}
/**
* 菜单信息
*/
@GetMapping("/info/{menuId}")
@RequiresPermissions("sys:menu:info")
public R info(@PathVariable("menuId") String menuId){
SysMenuEntity menu = sysMenuService.getById(menuId);
return R.ok().put("menu", menu);
}
/**
* 保存
*/
@SysLog("保存菜单")
@PostMapping("/save")
@RequiresPermissions("sys:menu:save")
public R save(@RequestBody SysMenuEntity menu){
//数据校验
verifyForm(menu);
sysMenuService.save(menu);
return R.ok();
}
/**
* 修改
*/
@SysLog("修改菜单")
@PostMapping("/update")
@RequiresPermissions("sys:menu:update")
public R update(@RequestBody SysMenuEntity menu){
//数据校验
verifyForm(menu);
sysMenuService.updateById(menu);
return R.ok();
}
/**
* 删除
*/
@SysLog("删除菜单")
@PostMapping("/delete/{menuId}")
@RequiresPermissions("sys:menu:delete")
public R delete(@PathVariable("menuId") String menuId){
/*if(menuId <= 31){
return R.error("系统菜单,不能删除");
}
*/
//判断是否有子菜单或按钮
List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
if(menuList.size() > 0){
return R.error("请先删除子菜单或按钮");
}
sysMenuService.delete(menuId);
return R.ok();
}
/**
* 验证参数是否正确
*/
private void verifyForm(SysMenuEntity menu){
if(StringUtils.isBlank(menu.getName())){
throw new RRException("菜单名称不能为空");
}
if(menu.getParentId() == null){
throw new RRException("上级菜单不能为空");
}
//菜单
if(menu.getType() == MenuType.MENU){
if(StringUtils.isBlank(menu.getUrl())){
throw new RRException("菜单URL不能为空");
}
}
//上级菜单类型
/*MenuType parentType = MenuType.CATALOG;
if(!menu.getParentId().equals("0")){
SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
parentType = parentMenu.getType();
}
//目录、菜单
if(menu.getType() == MenuType.CATALOG ||
menu.getType() == MenuType.MENU ){
if(parentType != MenuType.CATALOG ){
throw new RRException("上级菜单只能为目录类型");
}
return ;
}
//按钮
if(menu.getType() == MenuType.BUTTON ){
if(parentType != MenuType.MENU ){
throw new RRException("上级菜单只能为菜单类型");
}
return ;
}*/
}
}
<file_sep>package com.xiaobo.common.utils;
public interface TValue<T> {
Object getValue(T t);
}
<file_sep>package com.xiaobo.app.resolver;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.xiaobo.common.app.annotation.LoginUser;
import com.xiaobo.common.entity.SysUser;
import com.xiaobo.common.utils.JwtUtils;
import com.xiaobo.oauth2.service.OauthService;
/**
* 有@LoginUser注解的方法参数,注入当前登录用户
* @author zhangxiaobo
* @email <EMAIL>
* @date 2017-03-23 22:02
*/
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private OauthService oauthService;
@Autowired
private JwtUtils jwtUtils;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().isAssignableFrom(SysUser.class) && parameter.hasParameterAnnotation(LoginUser.class) ;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
SysUser user = null;
// 判断request里是否已经由了user
Object user_ = request.getAttribute("user", RequestAttributes.SCOPE_REQUEST);
if(user_ != null && user_ instanceof SysUser) {
user = (SysUser) user_ ;
}
if(user == null) {
// 再次判断请求的request里是否包含token 尝试通过token获取user
String token = request.getHeader(jwtUtils.getHeader());
if(StringUtils.isBlank(token)){
token = request.getParameter(jwtUtils.getHeader());
}
if(!StringUtils.isBlank(token)) {
// user 存在说明还在有效期并且用户存在
user = oauthService.queryByAppToken(token);
}
}
/*
if(user == null ) {
return null;
//throw new RRException("请先登录", HttpStatus.UNAUTHORIZED.value());
}
*/
return user;
}
}
<file_sep>package com.xiaobo.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobo.common.utils.PageUtils;
import com.xiaobo.modules.sys.entity.SysRoleEntity;
import java.util.List;
/**
* 角色
*
* zhangxiaobo
* @email <EMAIL>
* @date 2016年9月18日 上午9:42:52
*/
public interface SysRoleService extends IService<SysRoleEntity> {
PageUtils queryPage(SysRoleEntity entity, PageUtils page);
void update(SysRoleEntity role);
void deleteBatch(String[] roleIds);
/**
* 查询用户创建的角色ID列表
*/
List<Long> queryRoleIdList(String createUserId);
/**
* 查询用户创建的角色列表
*/
List<SysRoleEntity> queryRoleList(String createUserId);
}
<file_sep>package com.xiaobo.modules.sys.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobo.common.exception.RRException;
import com.xiaobo.common.form.LoginForm;
import com.xiaobo.common.redis.RedisUtils;
import com.xiaobo.common.utils.*;
import com.xiaobo.common.validator.Assert;
import com.xiaobo.modules.sys.dao.SysUserDao;
import com.xiaobo.modules.sys.entity.SysUserEntity;
import com.xiaobo.modules.sys.service.ShiroService;
import com.xiaobo.modules.sys.service.SysUserRoleService;
import com.xiaobo.modules.sys.service.SysUserService;
import com.xiaobo.modules.sys.service.SysUserTokenService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* 系统用户
*
* zhangxiaobo
* @date 2016年9月18日 上午9:46:09
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
@Autowired
private SysUserRoleService sysUserRoleService;
// @Autowired
// private SysRoleService sysRoleService;
/**
* 缓存基于token,这样每次登陆后重新拉取数据,避免根据用户之后任意的修改导致数据没有清退机制
*/
@Autowired
private SysUserTokenService tokenService ;
@Autowired
private ShiroService shiroService;
@Autowired
private RedisUtils redisUtils ;
@Autowired
private JwtUtils jwtUtils ;
@Override
public PageUtils queryPage(SysUserEntity entity , PageUtils page) {
String username = entity.getUsername();// (String)params.get("username");
//String createUserId = (String)params.get("createUserId");
IPage<SysUserEntity> ipage = this.page(
new Query<SysUserEntity>(page).getPage(),
new QueryWrapper<SysUserEntity>()
.like(StringUtils.isNotBlank(username),"username", username)
//.eq(createUserId != null,"create_user_id", createUserId)
);
return new PageUtils(ipage);
}
@Override
public List<SysUserEntity> queryList(SysUserEntity entity) {
String username = entity.getUsername();
String createUserId = entity.getCreateUserId();
QueryWrapper<SysUserEntity> wrapper = new QueryWrapper();
wrapper.like(StringUtils.isNotBlank(username),"username", username)
.eq(createUserId != null,"create_user_id", createUserId)
.eq(entity.getUserTypeValue() != null,"user_type", entity.getUserTypeValue())
//不查当前用户
.ne(entity.getUserId() != null,"user_id", entity.getUserId())
//不查admin
.ne(entity.getUserId() != null,"user_id", Constant.SUPER_ADMIN)
.orderByAsc("create_time");
List<SysUserEntity> list = this.baseMapper.selectList(wrapper);
return list;
}
@SuppressWarnings("unchecked")
@Override
public Set<String> queryAllPerms(String userId) {
//拿到用户token
String token = tokenService.queryTokenByUserId(userId);
String key = getClass().getSimpleName() + "-queryAllPerms-" + token ;
if(token != null) {
if(redisUtils.containKey(key)) {
return redisUtils.get(key , Set.class);
}
}
Set<String> list = shiroService.getUserPermissions(userId);
if(token != null) {
redisUtils.set(key, list);
}
return list ;
}
@SuppressWarnings("unchecked")
@Override
public List<String> queryAllMenuId(String userId) {
//拿到用户token
String token = tokenService.queryTokenByUserId(userId);
String key = getClass().getSimpleName() + "-queryAllMenuId-" + token ;
if(token != null) {
if(redisUtils.containKey(key)) {
return redisUtils.get(key , List.class);
}
}
List<String> list = baseMapper.queryAllMenuId(userId);
if(token != null) {
redisUtils.set(key, list);
}
return list ;
}
@Override
public SysUserEntity queryByUserNo(String userNo) {
String key = getClass().getSimpleName() + "-no-" + userNo ;
if(redisUtils.containKey(key)) {
return redisUtils.get(key , SysUserEntity.class);
}
SysUserEntity sae = baseMapper.queryByUserNo(userNo);
redisUtils.set(key, sae);
return sae ;
}
// @Transactional
// public boolean save(SysUserEntity user) {
//
//
//
// user.setCreateTime(new Date());
// //sha256加密
// String salt = RandomStringUtils.randomAlphanumeric(20);
// user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
// user.setSalt(salt);
// boolean s = this.save(user);
//
// //检查角色是否越权
// checkRole(user);
//
// //保存用户与角色关系
// //sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
//
//
// String key = getClass().getSimpleName() + "-no-" + user.getUserNo() ;
// if(redisUtils.containKey(key)) {
// redisUtils.delete(key);
// }
// return s ;
// }
@Override
@Transactional
public void update(SysUserEntity user) {
if(StringUtils.isBlank(user.getPassword())){
user.setPassword(null);
}else{
//密码解密
String pass = RsaUtils.decryptByPrivateKey(user.getPassword());
if(pass != null && !pass.isEmpty()){
String salt = RandomStringUtils.randomAlphanumeric(20);
user.setPassword(new Sha256Hash(pass, salt).toHex());
user.setSalt(salt);
}
else {
user.setPassword(null);
}
}
if(user.getRoleId()!=null){
//保存用户与角色关系
sysUserRoleService.newSaveOrUpdate(user.getUserId(), user.getRoleId());
}
this.updateById(user);
//检查角色是否越权
//checkRole(user);
//保存用户与角色关系
//sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
}
@Override
public void deleteBatch(String[] userId) {
this.removeByIds(Arrays.asList(userId));
}
@Override
public boolean updatePassword(String userId, String password, String newPassword) {
SysUserEntity userEntity = new SysUserEntity();
userEntity.setPassword(<PASSWORD>);
return this.update(userEntity,
new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
}
/**
* 检查角色是否越权
*/
private void checkRole(SysUserEntity user){
/*if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
return;
}*/
//如果不是超级管理员,则需要判断用户的角色是否自己创建
/*if(user.getCreateUserId().equals(Constant.SUPER_ADMIN)){
return ;
}*/
/*//查询用户创建的角色列表
List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
//判断是否越权
if(!roleIdList.containsAll(user.getRoleIdList())){
throw new RRException("新增用户所选角色,不是本人创建");
}*/
}
@Override
public boolean resetPass(String userId, String newPass) {
baseMapper.resetPass(userId, newPass);
return true;
}
@Override
public R appLogin(LoginForm form) {
SysUserEntity user = queryByUserNo(form.getUserNo());
Assert.isNull(user, "账号或密码错误");
//密码错误
String pass = new Sha256Hash(form.getPassword(), user.getSalt()).toHex();
if(!user.getPassword().equals(pass)){
throw new RRException("账号或密码错误");
}
//账号锁定
if(user.getStatus() == 0){
return R.error("账号已被锁定,请联系管理员");
}
//生成token
String token = jwtUtils.generateToken(user.getUserId());
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("expire", jwtUtils.getExpire());
Set<String> appPerms = shiroService.getUserPermissions(user.getUserId());
//给用户权限列表
map.put("perms", appPerms);
//redis缓存token到用户的映射
redisUtils.set(getClass().getSimpleName() + "-u-t-" + user.getUserId(), token);
redisUtils.set(getClass().getSimpleName() + "-t-u-" + token, user);
redisUtils.set(getClass().getSimpleName() + "-t-p-" + token, appPerms);
user.setPassword(<PASSWORD>);
//带上用户
map.put("user", user);
return R.ok(map);
}
@Override
public void saveUser(SysUserEntity user) {
user.setCreateTime(new Date());
//sha256加密
String salt = RandomStringUtils.randomAlphanumeric(20);
user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
user.setSalt(salt);
List<SysUserEntity> tmp = this.list(new QueryWrapper<SysUserEntity>()
.eq("user_no", user.getUserNo().trim()));
if(tmp != null && tmp.size() > 0) {
throw new RRException("该账号已存在,请修改");
}
this.save(user);
//检查角色是否越权
checkRole(user);
//保存用户与角色关系
sysUserRoleService.newSaveOrUpdate(user.getUserId(), user.getRoleId());
String key = getClass().getSimpleName() + "-no-" + user.getUserNo() ;
if(redisUtils.containKey(key)) {
redisUtils.delete(key);
}
}
@Override
public List<SysUserEntity> queryByCreateID(String createuserid){
return baseMapper.queryByCreateID(createuserid);
}
@Override
public List<SysUserEntity> queryUsers(){
return baseMapper.queryUsers();
}
@Override
public void updateLastDate(SysUserEntity user) {
baseMapper.updateById(user);
}
@Override
public int queryMainNum(String orgId){ return baseMapper.queryMainNum(orgId);}
@Override
public List<SysUserEntity> queryByOrgParent(String orgId,String currUserId){return baseMapper.queryByOrgParent(orgId,currUserId);}
public SysUserEntity queryById(String id){ return baseMapper.queryById(id);}
}
<file_sep>package com.xiaobo.common.utils.lbs;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
public class GisUtils {
static Logger logger = LoggerFactory.getLogger(GisUtils.class);
static double pi = Math.PI;
static double a = 6378245.0;
static double ee = 0.00669342162296594323;
public static double x_pi = pi * 3000.0 / 180.0;
static double[] wgs2gcj(double lat, double lon) {
double dLat = transformLat(lon - 105.0, lat - 35.0);
double dLon = transformLon(lon - 105.0, lat - 35.0);
double radLat = lat / 180.0 * pi;
double magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
double mgLat = lat + dLat;
double mgLon = lon + dLon;
double[] loc = { mgLat, mgLon };
return loc;
}
static double[] wgs2bd(double lat, double lon) {
double[] wgs_gcj = wgs2gcj(lat, lon);
double[] gcj_bd = gcj2bd(wgs_gcj[0], wgs_gcj[1]);
return gcj_bd;
}
public static double[] gcj2bd(double lat, double lon) {
double x = lon, y = lat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
double bd_lon = z * Math.cos(theta) + 0.0065;
double bd_lat = z * Math.sin(theta) + 0.006;
return new double[] { bd_lat, bd_lon };
}
public static double[] bd2gcj(double lat, double lon) {
double x = lon - 0.0065, y = lat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
double gg_lon = z * Math.cos(theta);
double gg_lat = z * Math.sin(theta);
return new double[] { gg_lat, gg_lon };
}
private static double transformLat(double lat, double lon) {
double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon
+ 0.2 * Math.sqrt(Math.abs(lat));
ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLon(double lat, double lon) {
double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
return ret;
}
public static double distance(double lon1, double lat1, double lon2, double lat2) {
double x, y, outx;
x = (lon2 - lon1) * Math.PI * 6371229 * Math.cos(((lat1 + lat2) / 2) * Math.PI / 180) / 180;
y = (lat2 - lat1) * Math.PI * 6371229 / 180;
outx = Math.sqrt(x * x + y * y);
return outx;
}
/**
* 坐标转换
*
* @param points 点信息
* @param iv T转point
* @param tend point回填
*/
public static <T> void translateWgs84ToBD09(List<T> points, TPointValue<T> iv, TTransEnd<T> tend) {
Map<Point, List<T>> point_cells = new HashMap<Point, List<T>>();
for (T t : points) {
Point p = iv.getPoint(t);
List<T> ts = point_cells.get(p);
if (ts == null) {
ts = new LinkedList<T>();
point_cells.put(p, ts);
}
ts.add(t);
}
//
List<Point> list_points = new LinkedList<Point>();
list_points.addAll(point_cells.keySet());
int psize = list_points.size();
int limit = 100;
int retry = 0;
for (int i = 0; i < psize; i += limit) {
List<Point> ps = list_points.subList(i, i + limit >= psize ? psize : i + limit);
String url = url(ps, 0);
// 解析
String result = null;
try {
result = getHttpGetResponseStream(url);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
logger.error("parse baidu url error ", e);
// continue ;
}
/*
* if(result == null) { throw new RuntimeException("解析异常,url未返回正常数据.url:" +
* url); }
*/
List<Point> rets = result != null ? translate(result) : null;
if (rets == null) {
// 重新请求一次
if (retry > 3) {
System.out.println("解析异常, 转换中第:" + i + " ~ " + (i + limit) + " 条请求三次未能从webservice服务中解析转换");
// throw new RuntimeException("重试3次以上请求无响应");
}
i -= limit;
retry++;
continue;
} else {
retry = 0;
}
if (rets != null && rets.size() == ps.size()) {
// 回填
int index = 0;
for (Point p : ps) {
List<T> ts = point_cells.get(p);
Point trans_p = rets.get(index);
for (T t : ts) {
tend.transEnd(t, trans_p);
}
index++;
}
} else {
System.out.println("解析异常,转换中第:" + i + " ~ " + (i + limit) + " 条未能解析转换");
}
}
}
private static List<Point> translate(String result) {
List<Point> points = new LinkedList<Point>();
JSONObject jsonObject = JSON.parseObject(result);
Integer status = jsonObject.getInteger("status");
if (status.equals(0)) {
JSONArray as = jsonObject.getJSONArray("result");
int size = as.size();
for (int i = 0; i < size; i++) {
Point _point = as.getObject(i, Point.class);
points.add(_point);
}
}
return points;
}
private static String url(List<Point> points, int souse) {
int type = 0;
if (souse == 0) {
type = 1;
} else if (souse == 4) {
type = 2;
} else {
type = 6;
}
StringBuilder sb = new StringBuilder(
"http://api.map.baidu.com/geoconv/v1/?from=" + type + "&to=5&ak=" + getBdAk() + "&coords=");
for (Point p : points) {
// Point p = getPoint(cd);
BigDecimal bny = new BigDecimal(p.getY() + "");
BigDecimal bnx = new BigDecimal(p.getX() + "");
sb.append(bnx + "," + bny + ";");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// 经纬度转地址
private static String transadd(String result) {
JSONObject jsonObject = JSON.parseObject(result);
Integer status = jsonObject.getInteger("status");
String cityname = null;
if (status.equals(0)) {
JSONObject as = jsonObject.getJSONObject("result");
cityname = as.getString("formatted_address");
}
return cityname;
}
private static String urladd(List<Point> points) {
StringBuilder sb = new StringBuilder(
"http://api.map.baidu.com/geocoder/v2/?coordtype=wgs84ll&output=json&ak=" + getBdAk() + "&location=");
for (Point p : points) {
// Point p = getPoint(cd);
sb.append(p.getY() + "," + p.getX());
}
return sb.toString();
}
// 地址转经纬度
// 经纬度转地址
private static Point transaddtolona(String result) {
JSONObject jsonObject = JSON.parseObject(result);
Point point = new Point();
Integer status = jsonObject.getInteger("status");
if (status.equals(0)) {
JSONObject as = jsonObject.getJSONObject("result");
JSONObject obj = as.getJSONObject("location");
Double lon = obj.getDouble("lng");
Double lat = obj.getDouble("lat");
if (lon > 0 && lat > 0) {
point.setX(lon);
point.setY(lat);
}
}
return point;
}
private static String urladdtolona(List<String> str) {
StringBuilder sb = new StringBuilder(
"http://api.map.baidu.com/geocoder/v2/?output=json&ak=" + getBdAk() + "&address=");
for (String p : str) {
// Point p = getPoint(cd);
if (p != null && !p.contains("null") && !p.equals("") && p != "null") {
try {
p = java.net.URLEncoder.encode(p, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
p = "";
}
sb.append(p);
}
return sb.toString();
}
public static List<Point> translateWgs84ToBD09(List<Point> points) {
List<Point> list = new LinkedList<Point>();
int psize = points.size();
StringBuilder sb = new StringBuilder();
sb.append("http://api.map.baidu.com/geoconv/v1/?from=1&to=5&ak=" + getBdAk() + "&coords=");
int index = 0;
for (Point p : points) {
index++;
sb.append(p.getX() + "," + p.getY() + ";");
if (index % 100 == 0 || index == psize) {
// index = 0;
sb.deleteCharAt(sb.length() - 1);
String result = null;
try {
result = getHttpGetResponseStream(sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
if (result == null) {
// return Collections.emptyList();
continue;
}
JSONObject jsonObject = JSON.parseObject(result);
Integer status = jsonObject.getInteger("status");
if (status.equals(0)) {
JSONArray as = jsonObject.getJSONArray("result");
int size = as.size();
for (int i = 0; i < size; i++) {
Point _point = as.getObject(i, Point.class);
list.add(_point);
}
}
sb.delete(0, sb.length());
sb.append("http://api.map.baidu.com/geoconv/v1/?from=1&to=5&ak=" + getBdAk() + "&coords=");
}
}
return list;
}
public static String getHttpGetResponseStream(String url) throws HttpException, IOException {
GetMethod getMethod = new GetMethod(url);
HttpClient client = new HttpClient();
int code = client.executeMethod(getMethod);
if (code == 200) {
String result = getMethod.getResponseBodyAsString();
return result;
}
return null;
}
private static final String[] BDMAP_KEYS = { "<KEY>", "<KEY>",
"<KEY>", "<KEY>", "<KEY>",
"<KEY>", "<KEY>",
"<KEY>" };
/**
* 返回一个百度地图的ak
*
* @return
*/
private static String getBdAk() {
int random = (int) (Math.random() * BDMAP_KEYS.length);
return BDMAP_KEYS[random];
}
/**
* 根据经纬度返回当前位置的城市名称
*
* @param lon 经度
* @param lat 纬度
* @return 传递的位置所处的城市和区
*/
public static String getLocationCity(double lon, double lat) {
String url = "http://api.map.baidu.com/geocoder/v2/?location=" + lat + "," + lon + "&output=json&batch=true&ak="
+ getBdAk();
String result = null;
try {
result = getHttpGetResponseStream(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
if (result == null) {
// return Collections.emptyList();
return null;
}
JSONObject jsonObject = JSON.parseObject(result);
Integer status = jsonObject.getInteger("status");
if (status.equals(0)) {
JSONArray as = jsonObject.getJSONArray("areas");
int size = as.size();
if (size > 0) {
JSONObject obj = as.getJSONObject(0);
return obj.getString("city") + "_" + obj.getString("district");
}
}
return null;
}
public static void main(String[] args) {
Double lon = 120.01;
Double lat = 30.03;
double[] t1 = wgs2bd(lat, lon);
List<Point> list = new ArrayList<>();
list.add(new Point(lon , lat));
List<Point> ps = translateWgs84ToBD09(list);
System.out.println(t1[0] + "_" + t1[1]);
System.out.println(ps.get(0));
}
}
<file_sep>/**
* 邮箱
* @param {*} s
*/
export function isEmail (s) {
return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
/**
* 手机号码
* @param {*} s
*/
export function isMobile (s) {
return /^1[0-9]{10}$/.test(s)
}
/**
* 精确手机号码
* @param {*} s
*/
export function isNicetyMobile(s) {
return /^(1(([38]\d)|(4[57])|(5[0-35-9])|66|(7[0135-8])|(9[89]))\d{8})$/.test(s)
}
/**
* 电话号码
* @param {*} s
*/
export function isPhone (s) {
return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
/**
* 精确电话号码
* @param {*} s
*/
export function isNicetyPhone(s) {
return /^((0\d{2,3}[ -]?)?[2-9]\d{6,7})$/.test(s)
}
/**
* URL地址
* @param {*} s
*/
export function isURL (s) {
return /^http[s]?:\/\/.*/.test(s)
}
/**
* 网址校验
* @param {*} s
*/
export function isFURL(s){
return /^(https?:\/\/)?.+\..+/.test(s)
}
/**
* 整数
* @param {*} s
*/
export function isInteger (s) {
return /^\d+$/.test(s)
}
/**
* 数字,含小数
* @param {*} s
*/
export function isNumber (s) {
return /^\d+(\.\d+)?$/.test(s)
}
/**
* 数字,含小数(含负数)
* @param {*} s
*/
export function isFNumber (s) {
return /^[+-]?\d+(\.\d+)?$/.test(s)
}
/**
* 身份证验证
* @param {*} s
*/
export function isCardId (s){
// return /^[1-9][0-7]\d{4}((19\d{2}(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(19\d{2}(0[13578]|1[02])31)|(19\d{2}02(0[1-9]|1\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\d{3}(\d|X|x)?$/.test(s)
return /^[1-9][0-7]\d{4}(((19|20|21)\d{2}(((0[13578]|1[02])(0[1-9]|([12]\d)|3[0-1]))|(02([01]\d|2[0-8]))|((0[469]|11)([0-2]\d|30))))|(((19(09|17|28|47))|(20(04|23|42|99))|(21(37|86)))0229))\d{3}(\d|X|x)$/.test(s)
}
/**
* 统一社会信用代码简单校验
* @param {*} s
*/
export function isCrtcode (s){
return /^[1-9ANY][1-59]\d{6}[0-9A-Z]{10}$/.test(s)
}
/**
* 银行卡号简单校验(16位、17位、19)
* @param {*} s
*/
export function isBackId (s){
return /^\d{16}(\d(\d{2})?)?$/.test(s)
}
/**
* 邮编
* @param {*} s
*/
export function isPostcode (s){
return /^\d{6}$/.test(s)
}
/**
* 比例:[0-100](含小数)
* @param {*} this_
*/
export function isScale(s) {
return /^(\d?\d(\.\d*)?|100)$/.test(s)
}
/**
* 验证tabs下的各个form
*/
/*
export function validatorForm(this_ , tabs , cb) {
let valids = []
let names = []
for (let i in tabs) {
const vali = this_.$refs[tabs[i].componentName][0].sumbitValidate()
console.log('valid ' , tabs[i].tabName , this_.$refs[tabs[i].componentName][0].validateState , vali)
if(vali && typeof vali == 'object') {
valids.push(vali);
names.push(tabs[i].tabName)
} else if(vali == false){
valids.push(new Promise((resolve, reject)=>{
if(vali) {
resolve(vali) ;
} else {
reject(vali) ;
}
})
)
names.push(tabs[i].tabName)
// break;
}
// console.log('valid ' , tabs[i].tabName , this_.$refs[tabs[i].componentName][0].validateState , vali)
// 获取校验结果
/!* if (!this.$refs[this.tabs[i].componentName][0].validateState) {
return
}*!/
}
console.log('valids' , valids , valids.length)
if(!valids || valids.length == 0) {
console.log('执行操作')
cb()
return ;
}
console.log('valids' , valids)
for(var i in valids) {
console.log(i , valids[i] , names[i])
}
let valid_primase = async (v , index)=>{
let p = new Promise(function(resolve, reject){
v.then((d )=>{
console.log('valiate data : ' + index , d)
if(d == null || d == false) {
this_.$notify({
title: '提示',
offset: 100,
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
reject(false)
} else {
resolve(true)
}
}).catch((e )=>{
// console.log('error' ,index,names[index], e)
setTimeout(function(){
this_.$notify({
title: '提示',
offset: 100,
type:'error',
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
} , index * 50)
reject(false)
})
})
return p ;
}
let fun = ()=>{
let f ;
for(var i in valids) {
const index = i ;
if(i == 0) {
f = valid_primase(valids[index] , index);
} else {
const f_ = valid_primase(valids[index] , index);
f = f.then( function(dat){
return f_
})
}
}
f.then(function(data){
console.log('data@@@' , data)
if(data && data == true) {
console.log('执行操作')
cb()
} else {
}
})
return f;
}
fun();
return ;
/!*for(var i in valids) {
console.log(i + ' : ' , valids[i])
const index = i ;
valids[i].then((d )=>{
console.log('valiate data : ' + i , d)
if(!d) {
this_.$notify({
title: '提示',
offset: 100,
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
}
}).catch((e )=>{
console.log('error' ,index, e)
setTimeout(function(){
this_.$notify({
title: '提示',
offset: 100,
type:'error',
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
} , index * 10)
})
} *!/
/!*
Promise.all(valids).then(data=>{
console.log('valiate data : ' , data)
let result = true ;
for(let i in data) {
result &= data[i];
console.log( i , tabs[i].tabName , data[i])
if(!result) {
this_.$alert("请确保11[" + tabs[i].tabName + "]页面内容填写完整", "提示", {
confirmButtonText: "确定"
});
return ;
}
}
if(result) {
console.log('执行操作')
callback()
} else {
console.log('验证没通过 不执行操作')
}
}) .catch(e=>{
console.log('error' , e)
})
*!/
}
export function validatorFormA(this_ , tabs , cb) {
let valids = []
let names = []
for (let i in tabs) {
const vali = this_.$refs[tabs[i].componentName].sumbitValidate()
if(vali && typeof vali == 'object') {
valids.push(vali);
names.push(tabs[i].tabName)
} else if(vali == false){
valids.push(new Promise((resolve, reject)=>{
if(vali) {
resolve(vali) ;
} else {
reject(vali) ;
}
})
)
names.push(tabs[i].tabName)
// break;
}
}
if(!valids || valids.length == 0) {
cb()
return ;
}
for(var i in valids) {
}
let valid_primase = async (v , index)=>{
let p = new Promise(function(resolve, reject){
v.then((d )=>{
if(d == null || d == false) {
this_.$notify({
title: '提示',
offset: 100,
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
reject(false)
} else {
resolve(true)
}
}).catch((e )=>{
setTimeout(function(){
this_.$notify({
title: '提示',
offset: 100,
type:'error',
message: '请确保[' + names[index] + ']页面内容填写完整',
position: 'bottom-right'
});
} , index * 50)
reject(false)
})
})
return p ;
}
let fun = ()=>{
let f ;
for(var i in valids) {
const index = i ;
if(i == 0) {
f = valid_primase(valids[index] , index);
} else {
const f_ = valid_primase(valids[index] , index);
f = f.then( function(dat){
return f_
})
}
}
f.then(function(data){
if(data && data == true) {
cb()
} else {
}
})
return f;
}
fun();
return ;
}*/
<file_sep>package com.xiaobo.common.utils;
import java.io.*;
import java.util.Base64;
public class IOUtils {
public static String getObjectStr(Object obj) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bout);
out.writeObject(obj);
out.flush();
byte[] bs = bout.toByteArray();
return Base64.getEncoder().encodeToString(bs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
return null ;
}
@SuppressWarnings({ "hiding", "unchecked" })
public static <T> T parseObject(String s , Class<T> clazz) {
byte[] bs = Base64.getDecoder().decode(s);
ObjectInputStream in;
try {
in = new ObjectInputStream(new ByteArrayInputStream(bs));
Object obj = in.readObject();
return (T) obj ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null ;
}
}
<file_sep> //获取当前点击行下标
export function tableRowClassName ({row, rowIndex}) {
row.index = rowIndex;
}<file_sep>package com.xiaobo.common.fileupload.service.impl;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobo.common.fileupload.dao.UploadFileInfoDao;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity;
import com.xiaobo.common.fileupload.service.UploadFileInfoService;
@Service
public class UploadFileInfoServiceImpl extends ServiceImpl<UploadFileInfoDao, UploadFileInfoEntity> implements UploadFileInfoService {
@Override
public boolean insert(UploadFileInfoEntity entity) {
// TODO Auto-generated method stub
return this.save(entity);
}
@Override
public Collection<UploadFileInfoEntity> selectList(String[] ids) {
// TODO Auto-generated method stub
return listByIds(Arrays.asList(ids));
}
}
<file_sep>package com.xiaobo.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
public class StoreUtils {
Logger logger = LoggerFactory.getLogger(getClass());
@Value("${xb.upload.temp}")
private String storePath;
/**
* 返回用户数据目录
* @param userId 用户ID
* @return
*/
public File getUserPath(String userId) {
File f = new File(storePath , userId);
if(!f.exists()) {
boolean mkdir = f.mkdirs();
logger.info("mkdir user path : " + f.getPath() + " , result : " + mkdir);
}
return f ;
}
/**
* 返回用户工参存储目录
* @param userId 用户ID
* @return
*/
public File getUserCellPath(String userId) {
File userStorePath = getUserPath(userId);
File f = new File(userStorePath , "cell");
if(!f.exists()) {
boolean mkdir = f.mkdirs();
logger.info("mkdir user cell path : " + f.getPath() + " , result : " + mkdir);
}
return f ;
}
/**
* 返回用户路测日志存储目录
* @param userId 用户ID
* @return
*/
public File getUserLogPath(String userId) {
File userStorePath = getUserPath(userId);
File f = new File(userStorePath , "log");
if(!f.exists()) {
boolean mkdir = f.mkdirs();
logger.info("mkdir user cell path : " + f.getPath() + " , result : " + mkdir);
}
return f ;
}
}
<file_sep><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>com.xiaobo.employee-common-fileupload</artifactId>
<name>com.xiaobo.employee-common-fileupload</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- fastdfs -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-log</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-security</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-core</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-jpeg</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.3</version>
</dependency>
</dependencies>
</project>
<file_sep>/**
* 全站路由配置
*
* 建议:
* 1. 代码中路由统一使用name属性跳转(不使用path属性)
*/
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import {isURL} from '@/utils/validate'
import {clearLoginInfo, getQueryString} from '@/utils'
Vue.use(Router)
// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)
// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
{path: '/404', component: _import('common/404'), name: '404', meta: {title: '404未找到', isLogin: false}},
{path: '/login', component: _import('common/login'), name: 'login', meta: {title: '登录', isLogin: false}},
]
/*// 前端页面路由
const frontRoutes = {
path: '/' ,
component: _import('front/main'),
redirect: { name: 'login' },
meta: { title: '前端主入口整体布局' ,isLogin:false},
children: [
{ path: '/index', component: _import('common/index'), name: 'index', meta: { title: '首页' } },
{ path: '/help', component: _import('common/help'), name: 'help', meta: { title: '帮助中心' } },
{ path: '/copyright', component: _import('common/copyright'), name: 'copyright', meta: { title: '版权声明' } },
],
}
*/
// 后端整体嵌套路由
const userRoutes = {
path: '/',
component: _import('main'),
name: 'user_main',
redirect: {name: 'index'},
meta: {title: '首页', breadcrumb: false},
children: [
{
path: '/index',
component: _import('modules/index'),
name: 'index',
meta: {title: '信息概览', isTab: false, isLogin: true}
}
],
beforeEnter(to, from, next) {
// let token = Vue.cookie.get('token')
let token = localStorage.getItem('token');
if (!token || !/\S/.test(token)) {
clearLoginInfo()
next({name: 'login'})
}
next()
}
}
const router = new Router({
mode: 'hash',
// base: '/netopt',
scrollBehavior: () => ({y: 0}),
isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
routes: globalRoutes.concat(userRoutes)
})
let isAddDynamicMenuRoutes = false
router.beforeEach((to, from, next) => {
// next() ;
// 添加动态(菜单)路由
// 1. 已经添加 or 全局路由, 直接访问
// 2. 获取菜单列表, 添加并保存本地存储
console.log('isAddDynamicMenuRoutes', router.options.isAddDynamicMenuRoutes)
console.log('to', to)
console.log("进入了beforEach")
if ( router.options.isAddDynamicMenuRoutes || (to.meta && to.meta.isLogin != null && to.meta.isLogin == false)) {
console.log("进入了beforEachrouter.options.isAddDynamicMenuRoutes "+ router.options.isAddDynamicMenuRoutes )
next()
} else {
let token = localStorage.getItem('token');
//console.log("token.length",token )
// 判断账号是否已经登录
if (!token || token.length < 1) {
console.log("token.length1",token )
next({name: 'login'})
return;
}
// console.log("开始请求/sys/menu/nav")
http({
url: http.adornUrl('/sys/menu/nav'),
method: 'get',
params: http.adornParams()
}).then(({data}) => {
//console.log("请求/sys/menu/nav结果",data)
if (data && data.code === 0) {
// console.log("请求/sys/menu/nav成功",data)
fnAddDynamicMenuRoutes(data.menuList)
router.options.isAddDynamicMenuRoutes = true
console.log("修改了后的:", router.options.isAddDynamicMenuRoutes)
sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
next({...to, replace: true})
} else {
console.log("请求/sys/menu/nav失败",data)
sessionStorage.setItem('menuList', '[]')
sessionStorage.setItem('permissions', '[]')
next({name: 'login'})
}
}).catch(err => {
console.log('error' , err)
clearLoginInfo()
next({ name: 'login' })
// reject(err)
})
}
})
/**
* 根据菜单生产路由
*/
function createRoutes(menuList = [], routes = []) {
for (var i = 0; i < menuList.length; i++) {
const menu = menuList[i];
// 类型不是菜单和按钮得直接跳过去
if (menu.type < 1) {
if (menu.list && menu.list.length > 0) {
createRoutes(menu.list, routes)
}
continue
}
if (menu.type == 2) continue
// 菜单和按钮级别必然要添加路由
//console.log('menu', menu)
let route = {
path: menu.url ? menu.url : menu.routeName,
component: null,
name: menu.routeName,
meta: {
menuId: menu.menuId,
title: menu.name,
componentUrl: menu.componentUrl,
isDynamic: true,
isTab: false,
iframeUrl: ''
}
}
// 如果有url则挂载组件
if (menu.url) {
let url = menu.url;
/* if(url && url.indexOf('/') != 0) {
url = '/' + url
}*/
// 判断是否有下一级,如果有则挂载子路由,当前路由指向默认创建得子路由
if (menu.list && menu.list.length > 0) {
//console.log('#################')
route['component'] = _import(`modules/` + menu.componentUrl)
// route['redirect'] = {name : menu.routeName + '_list'}
//route['children'] = []
// 2019-11-11 从下一级菜单中获取第一个作为默认跳转
/* try {
let c = {
path: url + '/list',
component: _import(`modules/${menu.componentUrl}`) || null,
name: menu.routeName + '_list',
meta: { title: '列表',isTab:false,isLogin:true ,breadcrumb: false}
}
console.log('cddddd' , c)
route['children'].push(c)
} catch (e) {
console.log('load component ddddd ' , e)
}*/
let childRoutes = []
// 循环下一级
createRoutes(menu.list, childRoutes)
if (childRoutes && childRoutes.length > 0) {
route['redirect'] = {name: menu.list[0].routeName}
route['children'] = childRoutes
}
} else {
if (isURL(menu.url)) {
route['path'] = `i-${menu.menuId}`
route['name'] = `i-${menu.menuId}`
route['meta']['iframeUrl'] = menu.url
} else {
try {
//console.log('url', menu.url)
route['component'] = _import(`modules/${menu.componentUrl}`) || null
} catch (e) {
console.log('error', menu)
// console.log('load component ', e)
}
}
}
}
//console.log('route', route)
routes.push(route)
}
}
/**
* 添加动态(菜单)路由
* @param {*} menuList 菜单列表
* @param {*} routes 递归创建的动态(菜单)路由
*/
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
createRoutes(menuList, routes)
// if (temp.length >= 1) {
// fnAddDynamicMenuRoutes(temp, routes)
// } else {
// mainRoutes.name = 'main-dynamic'
//console.log('routes', routes)
userRoutes.children = routes
router.addRoutes([
userRoutes,
{path: '*', redirect: {name: '404'}}
])
sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(userRoutes.children || '[]'))
console.log('\n')
console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
console.log(userRoutes.children)
console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
}
//}
export default router
<file_sep>const ipcRenderer = require('electron').ipcRenderer;
const session = require('electron').remote.session;
/**
* 获得
*/
export function getCookie(name,back) {
console.log("进入获取cookie的方法")
session.defaultSession.cookies.get({ url: "http://192.168.127.12:8081/employee-admin" }, (error, cookies)=>{
console.log(cookies);
if (cookies.length > 0) {
var length = cookies.length;
for(var i=0;i<length;i++){
console.log(i);
var _myName = cookies[i].name;
if(name == _myName ){
back(cookies[i].value );
}
}
}
});
};
/**
* 清空缓存
*/
export function clearCookies () {
session.defaultSession.clearStorageData({
origin: "http://192.168.127.12:8081/employee-admin",
storages: ['cookies']
}, function (error) {
if (error) console.error(error);
})
};
/**
* 保存cookie
* @param name cookie名称
* @param value cookie值
*/
export function setCookie (name, value) {
console.log("进入获取setCookie的方法")
let Days = 30;
let exp = new Date();
let date = Math.round(exp.getTime() / 1000) + Days * 24 * 60 * 60;
const cookie = {
url: "http://192.168.127.12:8081/employee-admin",
name: name,
value: value,
expirationDate: date
};
session.defaultSession.cookies.set(cookie, (error) => {
if (error) console.error(error);
});
};
<file_sep>import Vue from 'vue'
import App from '@/App'
import router from '@/router' // api: https://github.com/vuejs/vue-router
import store from '@/store' // api: https://github.com/vuejs/vuex
import VueCookie from 'vue-cookie' // api: https://github.com/alfhen/vue-cookie
import '@/element-ui' // api: https://github.com/ElemeFE/element
import '@/icons' // api: http://www.iconfont.cn/
//import '@/element-ui-theme'
import 'element-ui/lib/theme-chalk/index.css'
import '@/assets/scss/index.scss'
import httpRequest from '@/utils/httpRequest' // api: https://github.com/axios/axios
import { isAuth,toRoute ,back} from '@/utils'
import { tableRowClassName} from '@/utils/elementTable'
import cloneDeep from 'lodash/cloneDeep'
import dict from '@/components/utils/dict.vue'
import dictSelect from '@/components/utils/dict-select.vue'
import echarts from 'echarts'
import {headerStryle,contentHeight} from '@/utils/styleHeight'
const dictComponent={
install:function(Vue){
Vue.component('dict',dict)
} //'Loading'这就是后面可以使用的组件的名字,install是默认的一个方法
};
const dictSelectComponent={
install:function(Vue){
Vue.component('dict-select',dictSelect)
} //'Loading'这就是后面可以使用的组件的名字,install是默认的一个方法
};
Vue.use(VueCookie)
Vue.config.productionTip = false
// 挂载全局
Vue.prototype.$http = httpRequest // ajax请求方法
Vue.prototype.isAuth = isAuth // 权限方法
Vue.prototype.toRoute = toRoute // 权限方法 toRoute
Vue.prototype.back = back // 权限方法 toRoute
Vue.prototype.$echarts = echarts //echarts
Vue.prototype.heightStyle = headerStryle
Vue.prototype.contentHeight = contentHeight
Vue.prototype.tableRowClassName = tableRowClassName
Vue.use(dictComponent)
Vue.use(dictSelectComponent)
// 保存整站vuex本地储存初始状态
window.SITE_CONFIG['storeState'] = cloneDeep(store.state)
// main.js里面使用
import VueCropper from 'vue-cropper'
Vue.use(VueCropper)
Vue.directive('loadmore', {
bind(el, binding) {
const selectWrap = el.querySelector('.el-table__body-wrapper')
selectWrap.addEventListener('scroll', function() {
let sign = 0
const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight-33
if (scrollDistance <= sign) {
binding.value()
}
})
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})<file_sep><?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>com.xiaobo.employee-common-core</artifactId>
<name>com.xiaobo.employee-common-core</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<poi-ooxml.version>3.16</poi-ooxml.version>
<fastjson.version>1.2.47</fastjson.version>
<okhttp.version>3.10.0</okhttp.version>
<fastdfs.client.version>1.27.0.0</fastdfs.client.version>
<streamer.version>1.2.0</streamer.version>
<easyexcel.viersion>1.1.1</easyexcel.viersion>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi-ooxml.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- zxing-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<!-- zxing 二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>${streamer.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.viersion}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
<file_sep>package com.xiaobo.modules.sys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobo.common.entity.SysUser;
import com.xiaobo.common.enums.UserType;
import com.xiaobo.common.log.annotation.SysLog;
import com.xiaobo.common.utils.Constant;
import com.xiaobo.common.utils.PageUtils;
import com.xiaobo.common.utils.R;
import com.xiaobo.common.validator.ValidatorUtils;
import com.xiaobo.modules.sys.entity.SysRoleEntity;
import com.xiaobo.modules.sys.entity.SysUserEntity;
import com.xiaobo.modules.sys.service.SysRoleMenuService;
import com.xiaobo.modules.sys.service.SysRoleService;
import com.xiaobo.modules.sys.service.SysUserService;
import com.xiaobo.sys.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 角色管理
*
* zhangxiaobo
* @email <EMAIL>
* @date 2016年11月8日 下午2:18:33
*/
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
@Autowired
private SysRoleService sysRoleService;
@Autowired
private SysRoleMenuService sysRoleMenuService;
@Autowired
private SysUserService sysUserService;
@Autowired
private com.xiaobo.common.security.SecurityUtils securityUtils ;
/**
* 角色列表-新修改的注释
*/
@GetMapping("/list")
public R list(SysRoleEntity entity , PageUtils page){
//如果不是超级管理员,则只查询自己创建的角色列表
// if(!getUserId().equals(Constant.SUPER_ADMIN) ){
// params.put("createUserId", getUserId());
// }
PageUtils pageData = sysRoleService.queryPage(entity , page);
return R.ok().put("page", pageData);
}
/**
* 角色列表
*/
@GetMapping("/select")
public R select(){
Map<String, Object> map = new HashMap<>();
//如果不��超级管理员,则只查询自己所拥有的角色列表
// if(!getUserId().equals(Constant.SUPER_ADMIN)){
// map.put("createUserId", getUserId());
// }
Collection<SysRoleEntity> list = sysRoleService.listByMap(map);
return R.ok().put("list", list);
}
/**
* 角色信息
*/
@GetMapping("/info/{roleId}")
public R info(@PathVariable("roleId") String roleId){
SysRoleEntity role = sysRoleService.getById(roleId);
//查询角色对应的菜单
List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
role.setMenuIdList(menuIdList);
return R.ok().put("role", role);
}
/**
* 保存角色
*/
@SysLog("保存角色")
@PostMapping("/save")
public R save(@RequestBody SysRoleEntity role){
ValidatorUtils.validateEntity(role);
role.setCreateUserId(getUserId());
sysRoleService.save(role);
return R.ok();
}
/**
* 修改角色
*/
@SysLog("修改角色")
@PostMapping("/update")
public R update(@RequestBody SysRoleEntity role){
ValidatorUtils.validateEntity(role);
role.setCreateUserId(getUserId());
sysRoleService.update(role);
return R.ok();
}
/**
* 删除角色
*/
@SysLog("删除角色")
@PostMapping("/delete")
public R delete(@RequestBody String[] roleIds){
sysRoleService.deleteBatch(roleIds);
return R.ok();
}
/**
* 角色列表
*/
@GetMapping("/newlist")
public R newList(){
SysRoleEntity sr = new SysRoleEntity();
SysUser user = securityUtils.getCurrentUser();
String userid = user.getUserId();
List<SysRoleEntity> roleList = sysRoleService.queryRoleList(userid);
boolean isCanDo = false;
//判断主账号/admin才可以有操作权限
if(user.getUserType()!= UserType.subUser){
isCanDo=true;
}
return R.ok().put("roleList", roleList).put("isCanDo",isCanDo);
}
/**
* @author: zhangxiaobo
* @Date: 2020/3/13 15:02
* @Description:判断是否添加过角色
*/
@GetMapping("/isCreateRoles")
public R isCreateRoles(){
boolean isCreateRoles = false;
SysUser user = securityUtils.getCurrentUser();
if(user.getUserType()!= UserType.subUser){
//判断是否已创建角色
List<SysRoleEntity> sysRoleEntities = sysRoleService.queryRoleList(user.getUserId());
if(!sysRoleEntities.isEmpty()){
isCreateRoles = true;
}
}
return R.ok().put("isCreateRoles",isCreateRoles);
}
/**
* @author: zhangxiaobo
* @Date: 2020/3/13 16:30
* @Description:
* 新增传值为空
*/
@GetMapping("/getRolesByOrgId")
public R getRolesByUserId(@RequestParam("userId") String userId, @RequestParam("orgId") String orgId){
//查询省高级主账号
SysUserEntity adminUser = this.sysUserService.getById(Constant.SUPER_ADMIN);
//admin与省高级机构id一样
String adminOrgId = adminUser.getOrgId();
//当前登录用户
SysUser currUser = getUser();
//被操作的用户
SysUserEntity sysUserEntity1 = sysUserService.queryById(userId);
//如果新增
if(userId.isEmpty()&&orgId.isEmpty()){
//admin,省高级
/*if(Constant.SUPER_ADMIN.equals(getUserId())){
//省高级主账号
QueryWrapper<SysUserEntity> sysUserEntityQueryWrapper = new QueryWrapper<>();
sysUserEntityQueryWrapper.eq("org_id",adminOrgId)
.eq("user_type",UserType.primaryUser);
SysUserEntity topUser = sysUserService.getOne(sysUserEntityQueryWrapper);
QueryWrapper<SysRoleEntity> sysRoleEntityQueryWrapper = new QueryWrapper<>();
sysRoleEntityQueryWrapper.in("create_user_id",new String[]{Constant.SUPER_ADMIN,null!= topUser ?topUser.getUserId() : ""});
List<SysRoleEntity> list = sysRoleService.list(sysRoleEntityQueryWrapper);
return R.ok().put("roleList",list);
}else{
List<SysRoleEntity> roleList = sysRoleService.queryRoleList(getUserId());
return R.ok().put("roleList",roleList);
}*/
//只查询当前用户
List<SysRoleEntity> roleList = sysRoleService.queryRoleList(getUserId());
return R.ok().put("roleList",roleList);
}
//如果修改
//当前操作用户是admin或者省高级主账号,并且修改主账号 要综合二者的权限给主账号
if(sysUserEntity1.getUserType()==UserType.primaryUser && (Constant.SUPER_ADMIN.equals(getUserId()) || (currUser.getUserType()==UserType.primaryUser &&currUser.getOrgId().equals(adminOrgId)))){
//省高级主账号
// QueryWrapper<SysUserEntity> sysUserEntityQueryWrapper = new QueryWrapper<>();
// sysUserEntityQueryWrapper.eq("org_id",adminOrgId)
// .eq("user_type",UserType.primaryUser);
// SysUserEntity topUser = sysUserService.getOne(sysUserEntityQueryWrapper);
//
// QueryWrapper<SysRoleEntity> sysRoleEntityQueryWrapper = new QueryWrapper<>();
// sysRoleEntityQueryWrapper.in("create_user_id",new String[]{Constant.SUPER_ADMIN,null!=topUser ? topUser.getUserId() : ""});
// List<SysRoleEntity> list = sysRoleService.list(sysRoleEntityQueryWrapper);
// return R.ok().put("roleList",list);
//只查询当前用户
List<SysRoleEntity> roleList = sysRoleService.queryRoleList(getUserId());
return R.ok().put("roleList",roleList);
}else{
//子账号动态显示
QueryWrapper<SysUserEntity> sysUserEntityQueryWrapper = new QueryWrapper<>();
sysUserEntityQueryWrapper.eq("org_id",orgId)
.eq("user_type",UserType.primaryUser);
SysUserEntity sysUserEntity = sysUserService.getOne(sysUserEntityQueryWrapper);
List<SysRoleEntity> roleList = sysRoleService.queryRoleList(sysUserEntity.getUserId());
return R.ok().put("roleList",roleList);
}
}
}
<file_sep>
package com.xiaobo.common.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
/**
* 注册表单
*
* @author Mark <EMAIL>
* @since 3.1.0 2018-01-25
*/
@ApiModel(value = "注册表单")
public class RegisterForm implements java.io.Serializable{
//String username, String password, String email, String mobile,String businessType
/**
*
*/
private static final long serialVersionUID = -1555015444386329708L;
@ApiModelProperty(value = "手机号")
@NotBlank(message="手机号不能为空")
@Length(min=11,max=11,message="手机号非法")
private String mobile;
/**
* 用户名
*/
@ApiModelProperty(value = "用户名")
@NotBlank(message="用户名不能为空")
@Length(min = 4, max = 20)
//@Pattern.List({ @Pattern(regexp = "^[0-9a-zA-Z_\\u4e00-\\u9fa5]+$"), @Pattern(regexp = "^.*[^\\d].*$") })
private String username ;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱")
@NotBlank(message="邮箱不能为空")
@Email
@Length(max = 200)
private String email ;
@ApiModelProperty(value = "密码")
@NotBlank(message="密码不能为空")
private String password;
/**
* 登录账号
*/
@ApiModelProperty(value = "登录账号")
@NotBlank(message="登录账号不能为空")
@Length(max = 40)
private String userNo ;
/**
* 验证码
*/
// @ApiModelProperty(value = "验证码,长度为四位数字")
// @NotBlank(message="验证码不能为空")
private String authCode;
/**
* 性别
*/
@ApiModelProperty(value = "性别")
private Integer sex ;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getAuthCode() {
return authCode;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
<file_sep>package com.xiaobo.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobo.modules.sys.entity.SysUserRoleEntity;
import java.util.List;
/**
* 用户与角色对应关系
*
* zhangxiaobo
* @date 2017年9月18日 上午9:43:24
*/
public interface SysUserRoleService extends IService<SysUserRoleEntity> {
void saveOrUpdate(String userId, List<String> roleIdList);
/**
* 根据用户ID,获取角色ID列表
*/
List<String> queryRoleIdList(String userId);
/**
* 根据角色ID数组,批量删除
*/
int deleteBatch(String[] roleIds);
/**
* 根据用户ID,获取角色ID
*/
String queryRoleId(String userId);
void newSaveOrUpdate(String userId, String roleId);
/**
* 根据角色ID数组,批量删除
*/
int deleteUserBatch(String[] roleIds);
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaobo</groupId>
<artifactId>employee</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>com.xiaobo.employee-common</artifactId>
<name>com.xiaobo.employee-common</name>
<packaging>pom</packaging>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<modules>
<module>com.xiaobo.employee-common-core</module>
<module>com.xiaobo.employee-common-security</module>
<module>com.xiaobo.employee-common-log</module>
<module>com.xiaobo.employee-common-fileupload</module>
</modules>
</project>
<file_sep>package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysDepartmentEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 部门表
*
* zhangxiaobo
* @email 1920969<EMAIL>
* @date 2019-11-15 09:05:42
*/
@Mapper
public interface SysDepartmentDao extends BaseMapper<SysDepartmentEntity> {
/*推荐在此直接添加注解写sql,可读性比较好*/
@Select("select * from sys_department where org_id = #{orgid}")
public List<SysDepartmentEntity> childList(String orgid);
@Select("select * from sys_department where dep_id = #{depid} ")
public SysDepartmentEntity queryDeptById(String depid);
@Select("select name from sys_department where org_id = #{orgid}")
public List<String> queryName(String orgid);
}
<file_sep>package com.xiaobo.common.utils.lbs;
public interface TTransEnd<T> {
void transEnd(T t, Point tranPoint);
}
<file_sep>package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysUserRoleEntity;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 用户与角色对应关系
*
* @author zhangxiaobo
* @date 2017年9月18日 上午9:34:46
*/
@Mapper
public interface SysUserRoleDao extends BaseMapper<SysUserRoleEntity> {
/**
* 根据用户ID,获取角色ID列表
*/
@Select("select role_id from sys_user_role where user_id = #{userId}")
List<String> queryRoleIdList(@Param("userId") String userId);
/**
* 根据角色ID数组,批量删除
*/
@Delete({"<script>"
+ "delete from sys_user_role where role_id in ",
" <foreach item='roleId' collection='roleIds' open='(' separator=',' close=')'> ",
" #{roleId} " ,
" </foreach>" ,
"</script>"})
int deleteBatch(@Param("roleIds") String[] roleIds);
/**
* 根据用户ID,获取角色ID
*/
@Select("select role_id from sys_user_role where user_id = #{userId}")
String queryRoleId(@Param("userId") String userId);
/**
* 根据角色ID数组,批量删除用户
*/
@Delete({"<script>"
+ "delete from sys_user where user_id in (select user_id from sys_user_role where role_id in ",
" <foreach item='roleId' collection='roleIds' open='(' separator=',' close=')'> ",
" #{roleId} " ,
" </foreach>)" ,
"</script>"})
int deleteUserBatch(@Param("roleIds") String[] roleIds);
}
<file_sep>package com.xiaobo.modules.sys.controller;
import com.xiaobo.common.utils.R;
import com.xiaobo.modules.sys.entity.SysOrganizationEntity;
import com.xiaobo.modules.sys.service.SysOrganizationService;
import com.xiaobo.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 组织架构层级*/
@RestController
@RequestMapping("/sys/org")
@Api(value="组织架构",tags={"组织架构-通用"} )
public class SysOrgController extends AbstractController {
@Autowired
private SysOrganizationService sysOrganizationService;
@RequestMapping(value = "/list",method = RequestMethod.POST)
@ApiOperation("查询整个组织架构")
public R listAll(){
R r = new R();
List<SysOrganizationEntity> list = sysOrganizationService.list();
return r.put("orgList",list);
}
}
<file_sep>package com.xiaobo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
import java.io.File;
@Configuration
public class MultipartConfig {
@Value("${xb.upload.temp}")
private String tmpPath;
/**
* 文件上传临时路径
*/
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
if(tmpPath == null || tmpPath.trim().isEmpty() || !new File(tmpPath).exists()) {
tmpPath = System.getProperty("java.io.tmpdir");
}
factory.setLocation(tmpPath);
factory.setMaxFileSize("10Mb");
factory.setMaxRequestSize("10Mb");
return factory.createMultipartConfig();
}
}
<file_sep>
export function CellLayer(_cells){
this.cells = _cells;
}
CellLayer.prototype = new BMap.Overlay();
CellLayer.prototype.change = function(_carrierType,_netType){
this.carrierType = _carrierType;
this.netType =_netType;
this.draw();
},
CellLayer.prototype.initialize = function(map){
this._map = map;
canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;left:0;top:0;opacity:0.9;";
var size = map.getSize();
canvas.width = size.width;
canvas.height = size.height;
//panel = this._map.getPanes().labelPane ;
this._map.getPanes().markerPane.appendChild(canvas);
this.canvas = canvas ;
var _celllayer = this;
//注册监听服务,监听鼠标移动
// this._map.addEventListener('mousemove' , this.mouseMove);
this._map._cellLayer = this ;
return canvas;
}
/*CellLayer.prototype.mouseMove = function(e){
//console.log( e.target + ' ' + e.point + ' ' + e.pixel );
var pos=getPosition(e );
var cell = this.selectCell(pos);
if(cell) {
console.log(JSON.stringify(cell));
}
return;
}*/
CellLayer.prototype.numCells = function(_bounds){
var _cells = this.cells ;
if(!_cells) return 0;
var num = 0;
for(var i in _cells){
var c = _cells[i];
if(c.bd_lon >= _bounds.minx && c.bd_lon <= _bounds.maxx
&& c.bd_lat >= _bounds.miny && c.bd_lat <= _bounds.maxy){
num++;
}
}
return num ;
},
CellLayer.prototype.showLayer = function(show){
this._show = show ;
//console.log(this.name + 'set show:' + this._show);
if(show == true) {
this.show() ;
} else {
this.hide() ;
}
this.draw() ;
},
CellLayer.prototype.focusCell = function(_cell) {
//console.log('_cell.id :' + _cell.id );
this.focusCellId = _cell.id ;
},
CellLayer.prototype.getCell = function(_id) {
var _cells = this.cells ;
//修改符合条件的公参都拉出来,取半径最短的那个返回 2018-02-28
for(var i in _cells) {
var cell = _cells[i];
if(cell.polygon && cell.id == _id) {
return cell;
}
}
},
CellLayer.prototype.selectCell = function(pos) {
//console.log(this.name + 'this._show : ' + this._show);
if(this._show != null && this._show == false) return null;
var _cells = this.cells ;
//修改符合条件的公参都拉出来,取半径最短的那个返回 2018-02-28
var _mincell ;
for(var i in _cells) {
var cell = _cells[i];
if(cell.polygon && PointInPoly(pos , cell.polygon)) {
// alert(JSON.stringify(cell));
if(!_mincell || _mincell.r > cell.r) _mincell = cell;
}
}
if(_mincell) {
//找出距离最短的
return _mincell ;
}
return null;
},
CellLayer.prototype.addEventListener = function(type , _callback){
var _celllayer = this ;
if(type == 'click') {
//找到当前的point
_celllayer.canvas.addEventListener('click',function(ev){
var pos=getPosition(ev);
var cell = _celllayer.selectCell(pos);
if(cell) {
_celllayer.focusCell(cell);
_callback(pos ,cell);
if(_celllayer.ctx) {
_celllayer.drawCell( _celllayer.ctx ,cell);
}
}
},false);
}else if(type == 'mouseMove') {
_celllayer.canvas.addEventListener('mousemove',function(ev){
var pos=getPosition(ev);
var cell = _celllayer.selectCell(pos);
// console.log('c:' + JSON.stringify(cell));
if(cell)
_callback(pos ,cell);
},false);
}
},
CellLayer.prototype.clearFocus = function( ) {
/*var fid = this.focusCellId;
if(!fid)return;
var cell = this.getCell(fid);
if(cell) {
}*/
},
CellLayer.prototype.getCenter = function() {
var _center_point = this.center ;
if(_center_point && _center_point.lng > 0 && _center_point.lat > 0){
return _center_point ;
}
var _cells = this.cells ;
var minx,miny,maxx,maxy ;
for(var i in _cells){
var x = _cells[i].bd_lon;
var y = _cells[i].bd_lat;
if(!minx || minx > x){
minx = x;
}
if(!miny || miny > y){
miny = y;
}
if(!maxx || maxx < x){
maxx = x;
}
if(!maxy || maxy < y){
maxy = y;
}
}
if(minx && miny && maxx && maxy && maxx < 180 && maxy < 90) {
_center_point = new BMap.Point((minx + (maxx - minx)/2) , (miny + (maxy-miny)/2)) ;// {x:(minx + (maxx - minx)/2) , y:(miny + (maxy-miny)/2)};
} else if(_cells && _cells.length > 0){
_center_point = new BMap.Point(_cells[0].bd_lon , _cells[0].bd_lat );
}
//console.log('_center_point : ' + JSON.stringify(_center_point) + " @@@ " + minx + '&&' + miny + '&&' + maxx + '&&' + maxy);
return _center_point;
},
CellLayer.prototype.setColorOption = function(_fun){
this._color_option = _fun;
this.draw();
},
CellLayer.prototype.setLabelOption = function(_label_option){
this._label_option = _label_option;
},
CellLayer.prototype.drawCellLabel = function( ctx ,_cell){
} ,
CellLayer.prototype.drawCell = function( ctx ,_cell){
//var map = this._map;
var color ;
if(this._color_option ) {
color = this._color_option(_cell); // 绿色路径
if(!color) return null;
}
//按照像素走,不管缩放到哪个层级,扇区大小都一样大
var radis_color = getRadioAndColor(_cell.fbtype , _cell.indoor , _cell.nettype);
var lon = _cell.bd_lon;
var lat = _cell.bd_lat ;
var azimuth = _cell.azimuth ;
var indoor = _cell.indoor ;
var r = radis_color.radis ;
_cell.r = r ;
if(!color){
color = radis_color.rgba;
}
var _zoom = this._map.getZoom();
/*if(_zoom == 13){
_r = r * 0.2 ;
}
else*/ if(_zoom == 14){
r = r * 0.5 ;
}
else if(_zoom == 16){
r = r * 1.5;
} else if(_zoom >= 17 && _zoom < 19){
r = r * 2;
} else if(_zoom >= 19){
r = r * 3;
}
var offsetX = this.offsetX;
var offsetY = this.offsetY;
var pixel = this._map.pointToOverlayPixel(new BMap.Point(lon,lat));
var x = parseInt(pixel.x - offsetX);
var y = parseInt(pixel.y - offsetY);
var _label_x = x ;
var _label_y = y ;
var points = [];
if(_cell.indoor) {
//室内站,画八边形
for(var i = 0 ; i <= 360 ; i += 45) {
var _x = parseInt(x + r * 1.0 * Math.cos(i * Math.PI / 180)) ;
var _y = parseInt(y + r * 1.0 * Math.sin(i * Math.PI / 180)) ;
//if(_x != x && _y != y)
points.push({x:_x,y:_y});
}
} else {
//室外站 每5度一个点
for(var i = azimuth - 15 ; i < azimuth + 15 ; i += 5) {
var _x = parseInt(x + r * 1.0 * Math.sin(i * Math.PI / 180)) ;
var _y = parseInt(y - r * 1.0 * Math.cos(i * Math.PI / 180)) ;
points.push({x:_x,y:_y});
}
_label_x = parseInt(x + r * 1.0 * Math.sin(azimuth * Math.PI / 180)) ;
_label_y = parseInt(y - r * 1.0 * Math.cos(azimuth * Math.PI / 180)) ;
_label_x = _label_x - 15;
//判断象限
if( azimuth <= 180){
_label_y = _label_y - 15;
} else {
_label_y = _label_y + 15;
}
points.push({x:x,y:y});
}
if(!points ) {
return null;
}
ctx.beginPath();
ctx.fillStyle= color ;//radis_color.rgba; // 绿色路径
ctx.strokeStyle= 'blue'; // 绿色路径
if(this.focusCellId && this.focusCellId == _cell.id){
// console.log(this.focusCellId + ' ' + _cell.id);
ctx.strokeStyle= 'red'; // 绿色路径
ctx.fillStyle= 'red'; // 绿色路径
}
// console.log('style:' + ctx.fillStyle);
if(!_cell.indoor)
ctx.moveTo(x,y);
for(var i in points) {
ctx.lineTo(points[i].x,points[i].y);
}
ctx.stroke();
ctx.fill(); // 进行绘制
var center = getCenter(points);
if(center){
if(_zoom >= 15) {
var enodeb_id = !_cell.nettype || _cell.nettype == 'lte' ? _cell.cgi >>> 8 : _cell.cgi >>> 16;
var ci = !_cell.nettype ||_cell.nettype == 'lte' ? _cell.cgi & 255 : _cell.cgi & 65535;
var _continue = true ;
//15 1/3 ,16 1/5, 17 1/3 , 18 1/2
if((_zoom == 15 && enodeb_id % 3 > 0 && ci % 2 > 0 )
|| (_zoom == 16 && ci % 2 > 0)
/* || (_zoom == 17 && enodeb_id % 2 > 0)
|| (_zoom == 18 && ci % 2 > 0)*/
) {
_continue = false ;
}
//针对室内站 如果重复只打一个label
if(_continue ){
var _p_centers = this._p_centers ;
if(_p_centers) {
for(var k in _p_centers){
var _p = _p_centers[k];
if((_label_x >= _p.x - 15 && _label_x <= _p.x + 15)
&& (_label_y >= _p.y - 10 && _label_y <= _p.y + 10)){ //外廓三个像素
_continue = false;
}
}
}
if(_continue)
_p_centers.push({x:_label_x , y:_label_y});
}
if(_continue && this._label_option) {
var color = this._label_option.color ;
var column = this._label_option.column ;
var fontsize = this._label_option.size;
ctx.strokeStyle = color
ctx.font = fontsize + "px 宋体";
var _text = '';
if(column == 'cellname') {
_text = _cell.cellname;
}else if(column == 'enodebid_ci'){
_text = enodeb_id + '-' + ci;
} else if(column == 'pci') {
_text = _cell.earfcn + '-' + _cell.pci;
}
// var _x = parseInt(x + r * 1.0 * Math.sin(azimuth * Math.PI / 180)) ;
// var _y = parseInt(y - r * 1.0 * Math.cos(azimuth * Math.PI / 180)) ;
// _label_x = _x - parseInt(_text.length * fontsize * 0.1);
// _label_y = _y + parseInt(ci % 3 == 0 ? fontsize : -1 * fontsize) ;
//ctx.strokeText(_text,_label_x, _label_y);
_cell.strokeText = {text:_text , x:_label_x , y:_label_y};
}
}
center.x = center.x + offsetX;
center.y = center.y + offsetY;
points.center = center ;
}
return points;
// ctx.stark();
// ctx.save(); // 进行绘制
// ctx.fillStyle = 'transparent';
}
,
CellLayer.prototype.draw = function(){
this._p_centers = [];
var map = this._map;
var size = map.getSize();
var BW = size.width;
var BH = size.height;
var canvas = this.canvas ;
//this.canvas.style.cssText = "position:absolute;left:0;top:0;";
canvas.width = BW;
canvas.height = BH;
var ctx = canvas.getContext('2d');
if (!ctx) {
return;
}
this.ctx = ctx ;
ctx.save(); // Workaround for a bug in Google Chrome
ctx.fillStyle = 'transparent';
//ctx.fillStyle = '#55000005';
ctx.fillRect(0, 0, BW, BH);
ctx.restore();
if(this._show != null && this._show == false) {
return ;
}
//获取层级
var zoom = map.getZoom();
if(zoom < 14 && this.isVisible()) {
this.hide() ;
}
if(zoom >= 14 && !this.isVisible()) {
this.show() ;
}
// console.log('this.isVisible() :' + this.isVisible());
if(!this.isVisible()) return ;
//ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
//偏移
var someLoc = new BMap.Point(0,0);
var offsetX = map.pointToOverlayPixel(someLoc).x -
map.pointToPixel(someLoc).x;
var offsetY = map.pointToOverlayPixel(someLoc).y -
map.pointToPixel(someLoc).y;
// console.log('offsetx:' + offsetX + ',offsety:' + offsetY);
this. offsetX = offsetX;
this. offsetY = offsetY;
//左上右下的经纬度卡住
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
var _cells = this.cells ;
var draw_labels = [];
for(var i in _cells) {
//console.log('_cell:' + _cells[i]);
var cell = _cells[i];
if(cell.bd_lon < sw.lng || cell.bd_lat < sw.lat
|| cell.bd_lon > ne.lng || cell.bd_lat > ne.lat ){
cell.polygon = null;
continue ;//不在当前显示范围的point
}
cell.strokeText = null;
var cell_polygon = this.drawCell( ctx , cell );
cell.polygon = cell_polygon;
if(cell.strokeText)
draw_labels.push(cell.strokeText);
//ctx.strokeText(_text,_label_x, _label_y);
}
if(this._label_option) {
var color = this._label_option.color ;
var fontsize = this._label_option.size;
ctx.strokeStyle = color
ctx.font = fontsize + "px 宋体";
for(var i in draw_labels){
var l = draw_labels[i];
ctx.strokeText(l.text,l.x, l.y);
//_cell.strokeText = {text:_text , x:_label_x , y:_label_y};
}
}
var dat = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx.putImageData(dat, 0, 0);
canvas.style.left = (offsetX) + 'px';
canvas.style.top = (offsetY) + 'px';
}
function getPosition(ev){
var x, y;
if (ev.layerX || ev.layerX == 0){
x = ev.layerX;
y = ev.layerY;
}else if (ev.offsetX || ev.offsetX == 0){
x = ev.offsetX;
y = ev.offsetY;
}
return {x: x,y: y};
}
function getCenter(polygon) {
var minx,miny,maxx,maxy ;
for(var i in polygon){
var x = polygon[i].x;
var y = polygon[i].y;
if(!minx || minx > x){
minx = x;
}
if(!miny || miny > y){
miny = y;
}
if(!maxx || maxx < x){
maxx = x;
}
if(!maxy || maxy < y){
maxy = y;
}
}
if(minx && miny && maxx && maxy) {
return {x:(minx + (maxx - minx)/2) , y:(miny + (maxy-miny)/2)};
}
return null;
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaobo</groupId>
<artifactId>employee</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>com.xiaobo.employee-sys</artifactId>
<name>com.xiaobo.employee-sys</name>
<url>http://maven.apache.org</url>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>model-sys</finalName>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-core</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-log</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.xiaobo</groupId>
<artifactId>com.xiaobo.employee-common-security</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
<file_sep>package com.xiaobo.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@TableName("sys_res_file")
public class SysFileEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableField("file_uid")
public String fileUid;
@TableField("res_id")
public String resId;
@TableField("file_name")
public String fileName;
@TableField("state")
@ApiModelProperty("0 notice 1 resource")
public Integer state;
@TableField("file_url")
public String fileUrl;
@TableField(exist = false)
public Object response;
public String getFileUid() {
return fileUid;
}
public void setFileUid(String fileUid) {
this.fileUid = fileUid;
}
public String getResId() {
return resId;
}
public void setResId(String resId) {
this.resId = resId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public Object getResponse() {
return response;
}
public void setResponse(Object response) {
this.response = response;
}
}
<file_sep>package com.xiaobo.common.fileupload.service;
import java.io.InputStream;
import java.util.Collection;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity;
/**
*
*
* @author zhangxiaobo
* @email <EMAIL>
* @date 2019-03-25 15:18:30
*/
public interface UploadFileInfoService extends IService<UploadFileInfoEntity> {
/**
* 插入一条附件信息
* @param entity
* @return
*/
boolean insert(UploadFileInfoEntity entity);
/**
* 根据多条ID 查询附件集合
* @param ids
* @return
*/
Collection<UploadFileInfoEntity> selectList(String[] ids);
}
<file_sep>package com.xiaobo.modules.sys.controller;
import com.xiaobo.common.utils.R;
import com.xiaobo.common.utils.RsaUtils;
import com.xiaobo.modules.sys.entity.SysUserEntity;
import com.xiaobo.modules.sys.entity.SysUserTokenEntity;
import com.xiaobo.modules.sys.form.SysLoginForm;
import com.xiaobo.modules.sys.service.SysCaptchaService;
import com.xiaobo.modules.sys.service.SysUserService;
import com.xiaobo.modules.sys.service.SysUserTokenService;
import com.xiaobo.sys.controller.AbstractController;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
/**
* 登录相关
*
* zhangxiaobo
* @date 2017年11月10日 下午1:15:31
*/
@RestController
public class SysLoginController extends AbstractController {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysUserTokenService sysUserTokenService;
@Autowired
private SysCaptchaService sysCaptchaService;
/**
* 验证码
*/
@GetMapping("captcha.jpg")
public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//获取图片验证码
BufferedImage image = sysCaptchaService.nextCaptcha(uuid);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
IOUtils.closeQuietly(out);
}
/**
* 登录
*/
@PostMapping("/sys/login")
public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
if(!captcha){
return R.error("验证码不正确");
}
//用户信息
SysUserEntity user = sysUserService.queryByUserNo(form.getUserNo());
//密码还原
String dePass = RsaUtils.decryptByPrivateKey(form.getPassword());
if(dePass == null) {
return R.error("密码不正确");
}
//账号不存在、密码错误
if(user == null || !user.getPassword().equals(new Sha256Hash(dePass, user.getSalt()).toHex())) {
return R.error("账号或密码不正确");
}
//账号锁定
if(user.getStatus() == 0){
return R.error("账号已被锁定,请联系管理员");
}
//生成token,并保存到数据库
R r = sysUserTokenService.createToken(user.getUserId(),form.getBrowser(),form.getOs());
user.setLastLoginTime(new Date());
//更新最后一次登录时间
sysUserService.updateLastDate(user);
// 查询用户所有权限码 带上
Set<String> perms = sysUserService.queryAllPerms(user.getUserId());
r.put("perms", perms);
// 用户信息
user.setPassword(<PASSWORD>);
user.setSalt(null);
user.setContext(null);
r.put("user", user);
return r;
}
/**
* 退出
*/
@PostMapping("/sys/logout")
public R logout() {
sysUserTokenService.logout(getUserId());
sysUserTokenService.updateLogoutTime(getUserId());
return R.ok();
}
/**
* 强制退出
*/
@PostMapping("/forceToExit")
@ApiOperation("强制退出")
public R forceToExit(@RequestBody String[] ids){
SysUserTokenEntity token = new SysUserTokenEntity();
for (String userId : ids) {
sysUserTokenService.logout(userId);
sysUserTokenService.updateLogoutTime(userId);
}
return R.ok();
}
}
<file_sep>package com.xiaobo.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobo.modules.sys.entity.SysRoleMenuEntity;
import java.util.List;
/**
* 角色与菜单对应关系
*
* zhangxiaobo
* @email <EMAIL>
* @date 2016年9月18日 上午9:42:30
*/
public interface SysRoleMenuService extends IService<SysRoleMenuEntity> {
void saveOrUpdate(String roleId, List<String> menuIdList);
/**
* 根据角色ID,获取菜单ID列表
*/
List<String> queryMenuIdList(String roleId);
/**
* 根据角色ID数组,批量删除
*/
int deleteBatch(String[] roleIds);
}
<file_sep># employee_manage
基于electron-vue的员工信息管理客户端系统(第一版本只有系统管理的信息),可实现软件的自动更新。
建议前端使用淘宝镜像,先cnpm install ,npm run dev运行。报错参考https://segmentfault.com/a/1190000018533945
<file_sep>
package com.xiaobo.common.log.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobo.common.log.entity.SysLogEntity;
import com.xiaobo.common.log.dao.SysLogDao;
import com.xiaobo.common.log.service.SysLogService;
import com.xiaobo.common.utils.PageUtils;
import com.xiaobo.common.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogDao, SysLogEntity> implements SysLogService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
String key = (String)params.get("key");
IPage<SysLogEntity> page = this.page(
new Query<SysLogEntity>(params).getPage(),
// pageI,
new QueryWrapper<SysLogEntity>().like(StringUtils.isNotBlank(key),"username", key)
.orderByDesc("create_date")
);
return new PageUtils(page);
}
public List<SysLogEntity> queryLog(String username){
return this.baseMapper.queryLog(username);
}
}
<file_sep>package com.xiaobo.oauth2.service;
import java.util.Set;
import com.xiaobo.common.entity.SysUser;
public interface OauthService {
/**
* 根据token查询用户
* @param token 用户当前授权token
* @return
*/
public SysUser queryByToken(String token);
/**
* 基于app token查询用户
* @param appToken
* @return
*/
public SysUser queryByAppToken(String appToken);
/**
* 查询用户的权限列表
* @param userId
* @return
*/
public Set<String> queryPermsByUser(String userId);
/**
* 刷新token最后的更新时间
* @param token
*/
public void updateTokenUpdateTime(String token);
}
<file_sep>package com.xiaobo.modules.sys.entity.vo;
import java.util.Date;
import java.util.List;
public class SysOrgVo {
/**
* 组织编码
*/
private String id;
/**
* 名称
*/
private String name;
/**
* 上级组织
*/
private String parentId;
/**
* 排序
* */
private int orderNum;
/**
* 创建时间
* */
private Date createTime;
/**
* 修改时间
* */
private Date updateTime;
/**
* ICON图标*/
private String fileIconName;
private List<SysOrgVo> list;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<SysOrgVo> getList() {
return list;
}
public void setList(List<SysOrgVo> list) {
this.list = list;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getFileIconName() {
return fileIconName;
}
public void setFileIconName(String fileIconName) {
this.fileIconName = fileIconName;
}
}
<file_sep>package com.xiaobo.common.fileupload;
import com.xiaobo.common.exception.RRException;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity;
import com.xiaobo.common.fileupload.utils.FastdfsUtils;
import com.xiaobo.common.fileupload.utils.FtpFileUitls;
import com.xiaobo.common.fileupload.utils.LocalFileUtils;
import com.xiaobo.common.utils.SpringContextUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.OutputStream;
/**
* 文件公共上传下载服务
* @author zhangxiaobo
*
*/
public abstract class AltFileUtils {
/**
* 上传文件
* @param file
* @return
*/
public abstract UploadFileInfoEntity uploadFile(MultipartFile file) ;
/**
* 上传本地文件
* @param file
* @return
*/
public abstract UploadFileInfoEntity uploadFile(File file);
/**
* 下载文件 默认当fastdfs 和ftp 的时候应该通过nginx代理过去直接下载 而不是通过此犯法,但此方法依然要实现下载的业务
* @param entity 实体
* @param out 输出流
*/
public abstract void downFile(UploadFileInfoEntity entity , OutputStream out);
/**
* 删除文件
* @param entity
* @return
*/
public abstract boolean deleteFile(UploadFileInfoEntity entity);
private static AltFileUtils uploadFile ;
/**
* 读取文件流
* @param path
* @return
*/
public abstract byte[] readFile(String path);
/**
* 根据配置获取当前的上传附件配置信息 获取对应的上传util类
* @return
*/
public static AltFileUtils getFileUtil() {
if(uploadFile != null) {
return uploadFile ;
}
// 取出配置 判断当前基于哪一个上传
// 获取配置信息
Environment env = SpringContextUtils.getBean(Environment.class);
String type = env.getProperty("tr.upload.type").trim();
// 判断类型 0- 本地 1- ftp 2- fastdfs
if(type != null && (type.equals("local") || type.equals("0") )) {
// local
String localPath = env.getProperty("tr.upload.local.upload_local_path");
uploadFile = new LocalFileUtils(localPath);
} else if(type != null && (type.equals("ftp") || type.equals("1")) ) {
// 回填参数
String host = env.getProperty("tr.upload.ftp.host");
Integer port = env.getProperty("tr.upload.ftp.hport" ,Integer.class);
String username = env.getProperty("tr.upload.ftp.husername");
String pass = env.getProperty("tr.upload.ftp.hpassword");
String baseDir = env.getProperty("tr.upload.ftp.hbase");
uploadFile = new FtpFileUitls(host , port , username , pass , baseDir);
} else if(type != null && (type.equals("fastdfs") || type.equals("2"))) {
// fastdfs的配置 政务外网
//System.out.println("-----------fastdfsConfig------:"+fastdfsConfig);
String tracker_server = env.getProperty("tr.upload.fastDfs.tracker_server");
String storage_server = env.getProperty("tr.upload.fastDfs.storage_server");
String nginxUrl = env.getProperty("tr.upload.fastDfs.nginx_url");
//System.out.println("---------server info:" + tracker_server+","+ storage_server + ","+ nginxUrl);
//Integer secret_key = jo.getInteger("secret_key");
uploadFile = new FastdfsUtils(tracker_server ,storage_server, nginxUrl);
}
if(uploadFile == null) {
throw new RRException("上传请求错误,请稍后再试");
}
return uploadFile ;
}
}
<file_sep>package com.xiaobo.common.fileupload.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.SocketException;
import java.util.Date;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.xiaobo.common.fileupload.AltFileUtils;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity.StoreType;
import com.xiaobo.common.utils.DateUtils;
import com.xiaobo.common.utils.StringUtils;
public class FtpFileUitls extends AltFileUtils implements Serializable {
org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
/**
*
*/
private static final long serialVersionUID = 1L;
private String host;
private Integer port;
private String username;
private String password;
/**
* 上传的基础目录 然后按照每个月一个大目录
*/
private String baseDir ;
public String getHost() {
return host;
}
public FtpFileUitls(String host, Integer port, String username, String password, String baseDir) {
super();
this.host = host;
this.port = port;
this.username = username;
this.password = <PASSWORD>;
this.baseDir = baseDir.endsWith("/") || baseDir.endsWith("\\") ? baseDir : baseDir + "/";
}
public boolean equals(String host, Integer port, String username, String password, String baseDir) {
String dir = baseDir.endsWith("/") || baseDir.endsWith("\\") ? baseDir : baseDir + "/";
if(this.host.equals(host)
&& this.port.equals(port)
&& this.username.equals(username)
&& this.password.equals(<PASSWORD>)
&& this.baseDir.equals(dir)) {
return true ;
}
return false;
}
//连接ftp服务器
public FTPClient initFtpClient() {
FTPClient ftpClient = new FTPClient();
try {
// 连接FTP服务器
ftpClient.connect(host, port );
//获取服务器返回码
int reply = ftpClient.getReplyCode();
//验证服务器是否连接成功
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return null;
}
ftpClient.setControlEncoding("utf-8");
/*boolean login =*/ ftpClient.login(username, password); //登录ftp服务器
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftpClient;
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean uploadFile(String fileDir , String fileName,InputStream inputStream){
boolean flag = false;
FTPClient ftpClient = initFtpClient();
try{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
createDirecroty(ftpClient , fileDir);
//ftpClient.makeDirectory(fileDir);
ftpClient.changeWorkingDirectory(fileDir);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
}catch (Exception e) {
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean createDirecroty(FTPClient client , String remote) throws IOException {
boolean success = true;
String dir = remote.replace(baseDir, "");
if(dir.startsWith("/")) {
dir = dir.substring(1);
}
String[] ss = dir.split("/");
client.changeWorkingDirectory(baseDir);
for(String s : ss) {
boolean change = client.changeWorkingDirectory(s);
if(!change) {
boolean makeDir = client.makeDirectory(s);
logger.info("make dir " + s + " ,result : " + makeDir);
}
success |= change ;
}
/*
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("UTF-8"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
System.out.println("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}*/
return success;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @return */
public byte[] readFile(String filePath){
OutputStream os=null;
FTPClient ftpClient = initFtpClient();
String path = filePath;
try {
//切换FTP目录
//ftpClient.changeWorkingDirectory(baseDir);
InputStream inputstream = ftpClient.retrieveFileStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int num = -1 ;
while ((num = inputstream.read(buffer)) != -1 ) {
baos.write(buffer, 0, num);
}
baos.flush();
byte[] by = baos.toByteArray();
ftpClient.logout();
return by ;
} catch (Exception e) {
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名��� *
* @return */
public boolean deleteFile( String filePath){
boolean flag = false;
FTPClient ftpClient = initFtpClient();
try {
//切换FTP目录
ftpClient.deleteFile(filePath);
ftpClient.logout();
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return flag;
}
@Override
public UploadFileInfoEntity uploadFile(MultipartFile file) {
String filename = file.getOriginalFilename();
String month = DateUtils.format(new Date(), "yyyyMM");
String fileDir =baseDir + month ;
String suffix = StringUtils.getSuffixName(filename);
// 文件名随机
String currName = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ((int)(Math.random() * 100000) ) + "." + suffix ;
try {
InputStream input = file.getInputStream();
boolean upload = uploadFile(fileDir , currName, input);
if(upload ) {
UploadFileInfoEntity entity = new UploadFileInfoEntity();
/* entity.setCreateDate(new Date());
entity.setFileName(currName);
entity.setFilePath(fileDir + "/" + currName);
entity.setStoreType(StoreType.ftp.ordinal());*/
entity.setCreatedAt(new Date());
entity.setOldFileName(filename);
entity.setFileSuffix(suffix);
entity.setFileSize(file.getSize());
entity.setFileUrl(fileDir + "/" + currName);
entity.setName(currName);
entity.setStoreType(StoreType.ftp.ordinal());
return entity;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void downFile(UploadFileInfoEntity entity, OutputStream out) {
// TODO Auto-generated method stub
// ftp 获取流
byte[] bs = readFile(entity.getFileUrl());
try {
out.write(bs);
out.flush(); //将存储在管道中的数据强制刷新出去
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean deleteFile(UploadFileInfoEntity entity) {
return deleteFile(entity.getFileUrl());
}
@Override
public UploadFileInfoEntity uploadFile(File file) {
String filename = file.getName();
String month = DateUtils.format(new Date(), "yyyyMM");
String fileDir =baseDir + month ;
String suffix = StringUtils.getSuffixName(filename);
// 文件名随机
String currName = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ((int)(Math.random() * 100000) ) + "." + suffix ;
try {
InputStream input = new FileInputStream(file);
boolean upload = uploadFile(fileDir , currName, input);
if(upload ) {
UploadFileInfoEntity entity = new UploadFileInfoEntity();
entity.setCreatedAt(new Date());
entity.setOldFileName(filename);
entity.setFileSuffix(suffix);
entity.setFileSize(file.length());
entity.setFileUrl(fileDir + "/" + currName);
entity.setName(currName);
entity.setStoreType(StoreType.ftp.ordinal());
return entity;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
<file_sep>import JsEncrypt from 'jsencrypt'
// 实例化一个JSEncrypt对象
let jse = new JSEncrypt()
jse.setPublicKey('<KEY>')
export function encrypt(data){
let encrypted = jse.encrypt(data)
console.log('en pass ' , encrypted)
return encrypted;
}<file_sep>
package com.xiaobo.common.log.controller;
import com.xiaobo.common.log.entity.SysLogEntity;
import com.xiaobo.common.log.service.SysLogService;
import com.xiaobo.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 系统日志
*
* @author zhangxiaobo
* @email <EMAIL>
* @date 2017-03-08 10:40:56
*/
@Controller
@RequestMapping("/sys/log")
public class SysLogController {
@Autowired
private SysLogService sysLogService;
/**
* 列表
*/
@ResponseBody
@GetMapping("/list")
public R list(@RequestParam Map<String, Object> params){
/*PageUtils page = sysLogService.queryPage(params);*/
List<SysLogEntity> list = sysLogService.queryLog(params.get("key").toString());
return R.ok().put("list", list);
}
/**
* 删除日志*/
@ResponseBody
@PostMapping("/delete")
public R delete(@RequestBody String ids){
List<String> strings = Arrays.asList(ids);
ArrayList<Long> longs = new ArrayList<>();
for (String string : strings) {
Long aLong = Long.valueOf(string);
longs.add(aLong);
}
try {
sysLogService.removeByIds(longs);
return R.ok();
} catch (Exception e) {
e.printStackTrace();
return R.error();
}
}
}
<file_sep>package com.xiaobo.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
/**
* 部门表
*
* zhangxiaobo
* @email <EMAIL>
* @date 2019-11-15 09:05:42
*/
@TableName("sys_department")
@ApiModel("部门表")
public class SysDepartmentEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 创建时间
*/
@TableField("create_time")
@ApiModelProperty("创建时间")
private Date createTime;
/**
* 部门主键id
*/
@TableId(type = IdType.UUID)
@TableField("dep_id")
@ApiModelProperty("部门主键id")
private String depId;
/**
* 部门名称
*/
@TableField("name")
@ApiModelProperty("部门名称")
private String name;
/**
* 外键_组织架构id
*/
@TableField("org_id")
@ApiModelProperty("外键_组织架构id")
private String orgId;
/**
* 负责人
*/
@TableField("principal")
@ApiModelProperty("负责人")
private String principal;
/**
* 修改时间
*/
@TableField("update_time")
@ApiModelProperty("修改时间")
private Date updateTime;
/**
* 设置:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置:部门主键id
*/
public void setDepId(String depId) {
this.depId = depId;
}
/**
* 获取:部门主键id
*/
public String getDepId() {
return depId;
}
/**
* 设置:部门名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取:部门名称
*/
public String getName() {
return name;
}
/**
* 设置:外键_组织架构id
*/
public void setOrgId(String orgId) {
this.orgId = orgId;
}
/**
* 获取:外键_组织架构id
*/
public String getOrgId() {
return orgId;
}
/**
* 设置:负责人
*/
public void setPrincipal(String principal) {
this.principal = principal;
}
/**
* 获取:负责人
*/
public String getPrincipal() {
return principal;
}
/**
* 设置:修改时间
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* 获取:修改时间
*/
public Date getUpdateTime() {
return updateTime;
}
}
<file_sep>import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
public static void main(String[] args) throws IOException {
String path = "test.png" ;
File f = new File(path);
FileInputStream input = new FileInputStream(f);
ByteArrayOutputStream output= new ByteArrayOutputStream();
int a = -1 ;
byte[] b1 = new byte[1024];
while((a = input.read(b1)) != -1) {
output.write(b1 , 0 , a);
}
output.flush();
input.close();
byte[] bs = output.toByteArray();
byte[] out = addWaterMark(bs, "测试123456", Color.RED);
BufferedImage bi = ImageIO.read(new ByteArrayInputStream(out));
ImageIO.write(bi, "png", new File("out.png"));
}
/**
* @param input 传入图片字节数组
* @param waterMarkContent 水印内容
* @param markContentColor 水印颜色
* @param font 水印字体
*/
public static byte[] addWaterMark(byte[] input,String waterMarkContent,Color markContentColor) {
try {
// 读取原图片信息
Image srcImg = ImageIO.read(new ByteArrayInputStream(input));//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
g.setColor(markContentColor); //根据图片的背景设置水印颜色
//int min = Math.min(srcImgWidth, srcImgHeight);
//Font font = Font.createFont(Font.BOLD, WaterMarkUtils.class.getResourceAsStream("/MSYHBD.TTC"));
// Font font = new Font("微软雅黑",Font.BOLD,min/10);
//g.setFont(font); //设置字体
//设置水印的坐标
int x = srcImgWidth/2 ;
int y = srcImgHeight/2;
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
ByteArrayOutputStream outImgStream = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
byte[] out = outImgStream.toByteArray();
outImgStream.close();
return out ;
} catch (Exception e) {
e.printStackTrace();
}
return null ;
}
}
<file_sep>
package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysCaptchaEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 验证码
*
* @author Mark <EMAIL>
* @since 3.1.0 2018-02-10
*/
@Mapper
public interface SysCaptchaDao extends BaseMapper<SysCaptchaEntity> {
}
<file_sep>package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysFileEntity;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface SysFileDao extends BaseMapper<SysFileEntity> {
@Select("select file_uid,file_name,file_url from sys_res_file where res_id = #{resId} and state = #{state}")
List<SysFileEntity> queryFileList(String resId, Integer state);
@Delete("delete from sys_res_file where res_id = #{resId} and state = #{state}")
void deleteByResId(String resId, Integer state);
}
<file_sep>package com.xiaobo.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaobo.modules.sys.entity.SysUserTokenEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
* 系统用户Token
*
* zhangxiaobo
* @date 2017-03-23 15:22:07
*/
@Mapper
public interface SysUserTokenDao extends BaseMapper<SysUserTokenEntity> {
@Select("select * from sys_user_token where token = #{token}")
SysUserTokenEntity queryByToken(@Param("token") String token);
@Update("update sys_user_token set update_time = update_time - '0.51 hour'::interval where user_id = #{userId}")
void updateLogoutTime(String userId);
}
<file_sep>package com.xiaobo.common.form;
import io.swagger.annotations.ApiModelProperty;
public class IdForm implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = -3881316087785444236L;
@ApiModelProperty("ID")
private String id ;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
<file_sep>package com.xiaobo.common.redis;
/**
* Redis切面处理类
*
* @author zhangxiaobo
*
* @date 2017-07-17 23:30
*/
//@Aspect
//@Configuration
public class RedisAspect {
/* private Logger logger = LoggerFactory.getLogger(getClass());
// 是否开启redis缓存 true开启 false关闭
@Value("${spring.redis.open: false}")
private boolean open;
public RedisAspect() {
// TODO Auto-generated constructor stub
System.out.println("###############");
}
// 定义一个切入点
// @Pointcut("execution (* findById*(..))")
@Pointcut("@annotation(com.tr.common.annotation.TrCache)")
public void excudeRedis(){
}
@Around("excudeRedis()")
public Object around(ProceedingJoinPoint point) throws Throwable {
Object result = null;
if(open){
try{
result = point.proceed();
}catch (Exception e){
logger.error("redis error", e);
throw new RRException("Redis服务异常");
}
System.out.println("redis open ....: " + result);
}
return result;
} */
}
<file_sep>package com.xiaobo.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 角色
*
* zhangxiaobo
* @email <EMAIL>
* @date 2016年9月18日 上午9:27:38
*/
@TableName("sys_role")
public class SysRoleEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 角色ID
*/
@TableId(type= IdType.UUID)
private String roleId;
/**
* 角色名称
*/
@NotBlank(message="角色名称不能为空")
private String roleName;
/**
* 备注
*/
private String remark;
/**
* 创建者ID
*/
private String createUserId;
@TableField(exist=false)
private List<String> menuIdList;
/**
* 创建时间
*/
private Date createTime;
/**
* 设置:
* @param roleId
*/
public void setRoleId(String roleId) {
this.roleId = roleId;
}
/**
* 获取:
* @return Long
*/
public String getRoleId() {
return roleId;
}
/**
* 设置:角色名称
* @param roleName 角色名称
*/
public void setRoleName(String roleName) {
this.roleName = roleName;
}
/**
* 获取:角色名称
* @return String
*/
public String getRoleName() {
return roleName;
}
/**
* 设置:备注
* @param remark 备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取:备注
* @return String
*/
public String getRemark() {
return remark;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public List<String> getMenuIdList() {
return menuIdList;
}
public void setMenuIdList(List<String> menuIdList) {
this.menuIdList = menuIdList;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
}
<file_sep>package com.xiaobo.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
/**
* 数据字典
*
* zhangxiaobo
* @email <EMAIL>
* @date 2019-03-20 10:54:34
*/
@TableName("sys_dict")
public class SysDictEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4754957935328935572L;
/**
* id
*/
@TableId(type = IdType.UUID)
@TableField("dict_id")
@ApiModelProperty("ID")
private String dictId;
/**
* 值
*/
@TableField("value")
@ApiModelProperty("值")
private String value;
/**
* 标签
*/
@ApiModelProperty("标签")
@TableField("dict_name")
private String dictName;
/**
* 字典分类
*/
@TableField("type")
@ApiModelProperty("字典分类")
private String type;
/**
* 类型名称
*/
@ApiModelProperty("类型名称/描述")
@TableField("description")
private String description;
/**
* 序号
*/
@TableField("seq")
@ApiModelProperty("序号")
private Integer seq;
/**
* 创建时间
*/
@TableField("create_date")
@ApiModelProperty(hidden=true)
private Date createDate;
/**
* 更新时间
*/
@TableField("update_date")
@ApiModelProperty(hidden=true)
private Date updateDate;
/**
* 删除状态(0:可用 1:不可用)
*/
@TableField("del_flag")
@ApiModelProperty("删除状态(0:可用 1:不可用)")
private Integer delFlag;
/**
* 创建Id
*/
@TableField("create_by")
@ApiModelProperty(hidden=true)
private String createBy;
/**
* 更新Id
*/
@TableField("update_by")
@ApiModelProperty()
private String updateBy;
public String getIsDict() {
return isDict;
}
public void setIsDict(String isDict) {
this.isDict = isDict;
}
@TableField("is_dict")
@ApiModelProperty()
private String isDict;
@TableField(exist = false)
@ApiModelProperty(hidden=true)
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getDictId() {
return dictId;
}
public void setDictId(String dictId) {
this.dictId = dictId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getSeq() {
return seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
}
<file_sep>package com.xiaobo.common.fileupload.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.io.Files;
import com.xiaobo.common.fileupload.AltFileUtils;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity;
import com.xiaobo.common.fileupload.entity.UploadFileInfoEntity.StoreType;
import com.xiaobo.common.utils.DateUtils;
import com.xiaobo.common.utils.StringUtils;
/**
*
*
*
* @author Administrator
* @version 1.0
*
*/
public class LocalFileUtils extends AltFileUtils implements Serializable {
Logger logger = LoggerFactory.getLogger(getClass());
/**
*
*/
private static final long serialVersionUID = 1L;
private String path ;
public String getPath() {
return path;
}
public LocalFileUtils(String path) {
super();
this.path = path.endsWith("/") || path.endsWith("\\") ? path : path + "/";
}
/**
文件下载
* @param filePath
* @return
* @throws IOException
*/
public byte[] readFile(String filePath) {
InputStream inStream;
try {
inStream = new FileInputStream(filePath);
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
inStream.close();
swapStream.close();
return in2b;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 删除文件
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if(file.exists()) {
boolean flag = file.delete();
return flag;
}
return false;
}
@Override
public UploadFileInfoEntity uploadFile(MultipartFile file) {
String month = DateUtils.format(new Date(), "yyyyMM");
File dirFile = new File(path , month);
if(!dirFile.exists()) {
boolean mkdirs = dirFile.mkdirs();
logger.info("mkdirs " + dirFile.getPath() + " , result : " + mkdirs);
}
String filename = file.getOriginalFilename();
String suffix = StringUtils.getSuffixName(filename);
// 文件名随机
String currName = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ((int)(Math.random() * 100000) ) + "." + suffix ;
File localFile = new File(dirFile , currName);
try {
file.transferTo(localFile);
UploadFileInfoEntity entity = new UploadFileInfoEntity();
/*entity.setCreateDate(new Date());
entity.setFileName(currName);
entity.setFilePath(localFile.getPath());
entity.setStoreType(StoreType.lcoal.ordinal());
entity.setRealName(filename);
*/
entity.setCreatedAt(new Date());
entity.setOldFileName(filename);
entity.setName(currName);
entity.setFileUrl(localFile.getPath());
entity.setFileSize(file.getSize());
entity.setStoreType(StoreType.lcoal.ordinal());
return entity;
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void downFile(UploadFileInfoEntity entity, OutputStream out) {
String path = entity.getFileUrl();
try {
IOUtils.copy(new FileInputStream(path), out, 5 * 1024);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean deleteFile(UploadFileInfoEntity entity) {
return deleteFile(entity.getFileUrl());
}
@Override
public UploadFileInfoEntity uploadFile(File file) {
String month = DateUtils.format(new Date(), "yyyyMM");
File dirFile = new File(path , month);
if(!dirFile.exists()) {
boolean mkdirs = dirFile.mkdirs();
logger.info("mkdirs " + dirFile.getPath() + " , result : " + mkdirs);
}
String filename = file.getName();
String suffix = StringUtils.getSuffixName(filename);
// 文件名随机
String currName = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ((int)(Math.random() * 100000) ) + "." + suffix ;
File localFile = new File(dirFile , currName);
try {
Files.copy(file, localFile);
UploadFileInfoEntity entity = new UploadFileInfoEntity();
entity.setCreatedAt(new Date());
entity.setOldFileName(filename);
entity.setName(currName);
entity.setFileUrl(localFile.getPath());
entity.setFileSize(file.length());
entity.setStoreType(StoreType.lcoal.ordinal());
return entity;
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
<file_sep>
package com.xiaobo.modules.sys.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobo.common.entity.SysUser;
import com.xiaobo.common.redis.RedisUtils;
import com.xiaobo.common.utils.Constant;
import com.xiaobo.common.utils.MapUtils;
import com.xiaobo.modules.sys.dao.SysMenuDao;
import com.xiaobo.modules.sys.entity.SysMenuEntity;
import com.xiaobo.modules.sys.service.SysMenuService;
import com.xiaobo.modules.sys.service.SysRoleMenuService;
import com.xiaobo.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysRoleMenuService sysRoleMenuService;
@Autowired
private com.xiaobo.common.security.SecurityUtils securityUtils ;
/* @Autowired
private SysUserTokenService userTokenService;
*/
@Autowired
private RedisUtils redisUtils ;
public List<SysMenuEntity> queryListParentId(String parentId, List<String> menuIdList , List<SysMenuEntity> allMenu) {
List<SysMenuEntity> menuList = allMenu.stream().
filter(t-> (menuIdList != null ? menuIdList.contains(t.getMenuId()) : true ) && (t.getParentId() != null ? t.getParentId().equals(parentId) : true ))
.sorted((t1 , t2)-> t1.getOrderNum().compareTo(t2.getOrderNum()))
.collect(Collectors.toList());
/*if(menuIdList == null){
return menuList;
}
List<SysMenuEntity> userMenuList = new ArrayList<>();
for(SysMenuEntity menu : menuList){
if(menuIdList.contains(menu.getMenuId())){
userMenuList.add(menu);
}
}*/
return menuList;
}
@Override
public List<SysMenuEntity> queryNotButtonList() {
return baseMapper.queryNotButtonList();
}
@Override
@Cacheable(value="tr", key="methodName + '-' + #userId" )
public List<SysMenuEntity> getUserMenuList(String userId) {
/*String token = userTokenService.queryTokenByUserId(userId);
String key = getClass().getSimpleName() + "-getUserMenuList-" + userId;
if(token != null) {
//redis 判断
if(redisUtils.containKey(key)) {
return redisUtils.get(key , List.class);
}
}*/
List<SysMenuEntity> list = new ArrayList<>();
//系统管理员,拥有最高权限
if(userId.equals(Constant.SUPER_ADMIN)|| userId.equals("6f6c2e30ee6f4379b39435cbfda70647") ){
list = getAllMenuList(null);
} else {
//用户菜单列表
List<String> menuIdList = sysUserService.queryAllMenuId(userId);
list = getAllMenuList(menuIdList);
}
/*if(token != null) {
//redis 缓存
redisUtils.set(key, list);
}*/
return list ;
}
@Cacheable(value="tr")
public List<SysMenuEntity> getAllMenu() {
String key = getClass().getSimpleName() + "-getAllMenu";
if(redisUtils.containKey(key)) {
return redisUtils.get(key, List.class);
}
List<SysMenuEntity> list = super.list();
redisUtils.set(key, list , 5*60);
return list ;
}
@Override
public void delete(String menuId){
//删除菜单
this.removeById(menuId);
//删除菜单与角色关联
sysRoleMenuService.removeByMap(new MapUtils().put("menu_id", menuId));
clearCache();
}
/**
* 获取所有菜单列表
*/
private List<SysMenuEntity> getAllMenuList(List<String> menuIdList){
// 拿到所有菜单
List<SysMenuEntity> allMenu = getAllMenu();
if(allMenu == null || allMenu.isEmpty()) return Collections.emptyList() ;
SysUser user = securityUtils.getCurrentUser();
List<String> pid = this.baseMapper.queryParent(user.getUserId());
if (!pid.isEmpty()&&null != menuIdList){
menuIdList.removeAll(pid);
menuIdList.addAll(pid);
}
//查询根菜单列表
List<SysMenuEntity> menuList = queryListParentId("0", menuIdList ,allMenu);
/*List<String> pid = new ArrayList<>();
if(menuList.isEmpty()&&!menuIdList.isEmpty()){
SysUser user = securityUtils.getCurrentUser();
pid = this.baseMapper.queryParent(user.getUserId());
menuIdList.removeAll(pid);
menuIdList.addAll(pid);
menuList = queryListParentId("0", menuIdList ,allMenu);
}*/
//递归获取子菜单
getMenuTreeList(menuList, menuIdList ,allMenu);
return menuList;
}
/**
* 递归
*/
private List<SysMenuEntity> getMenuTreeList(List<SysMenuEntity> menuList, List<String> menuIdList , List<SysMenuEntity> allMenu){
List<SysMenuEntity> subMenuList = new ArrayList<SysMenuEntity>();
for(SysMenuEntity entity : menuList){
//目录
//if(entity.getType().getValue() <= MenuType.CATALOG.getValue()){
entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList,allMenu), menuIdList ,allMenu));
//}
subMenuList.add(entity);
}
return subMenuList;
}
@Override
public List<SysMenuEntity> queryListParentId(String parentId) {
return baseMapper.queryListParentId(parentId);
}
@Override
public void clearCache() {
//每次删除之后直接清空当前类下的所有缓存
redisUtils.deletePattern(getClass().getSimpleName() + "*");
}
@Override
public List<SysMenuEntity> getMenuListByID(String userId){
List<SysMenuEntity> lists = new ArrayList<SysMenuEntity>();
lists = this.baseMapper.queryMenuById(userId);
return lists;
}
}
<file_sep>package com.xiaobo.common.fileupload.vo;
public class FastdfsUploadResult implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = -8616555289515702973L;
private boolean isSuccess;
private String filePath;
private byte[] fileContent;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public byte[] getFileContent() {
return fileContent;
}
public void setFileContent(byte[] fileContent) {
this.fileContent = fileContent;
}
}
<file_sep>package com.xiaobo.common.fileupload.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.enums.IEnum;
/**
* 文件信息表
* @author CaoRui
* @email <EMAIL>
* @date 2019-04-10 18:20:48
*/
public class UploadFileInfoEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 存储方式
* @author zhangxiaobo
*
*/
public enum StoreType implements IEnum<Integer>{
lcoal, // 本地
ftp, //ftp
fastDfs ,;
@Override
public Integer getValue() {
// TODO Auto-generated method stub
return this.ordinal();
} // fastdfs
}
/**
* 主键id
*/
@TableId(type = IdType.UUID)
private String fileId;
/**
* 原始(自定义)文件名称
*/
private String oldFileName;
/**
* 文件类型,即后缀
*/
private String fileSuffix;
/**
* 文件保存父路径
*/
private String parentPath;
/**
* 文件路径
*/
private String fileUrl;
/**
* 文件大小(byte),预留
*/
private long fileSize;
/**
* 创建时间
*/
private Date createdAt;
/**
*文件名
*/
private String name;
/**
*事项文件表Id
*/
private String materialId;
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getOldFileName() {
return oldFileName;
}
public void setOldFileName(String oldFileName) {
this.oldFileName = oldFileName;
}
public String getFileSuffix() {
return fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMaterialId() {
return materialId;
}
public void setMaterialId(String materialId) {
this.materialId = materialId;
}
public String getParentPath() {
return parentPath;
}
public void setParentPath(String parentPath) {
this.parentPath = parentPath;
}
/**
* 存储类型 0- 本地 1- ftp 2- fastdfs
*/
@TableField(exist=false)
private Integer storeType ;
public void setStoreType(Integer storeType) {
this.storeType = storeType;
}
public Integer getStoreType() {
return storeType;
}
}
<file_sep>import Vue from 'vue'
import router from '@/router'
import store from '@/store'
import {isURL} from './gis/validate'
const root = process.env.API_ROOT
export default root;
/**
* 获取uuid
*/
export function getUUID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
export function endWith(s1 , s2){
if(s2==null||s2==""||s1.length==0||s2.length>s1.length)
return false;
if(s1.substring(s1.length-s2.length)==s2)
return true;
else
return false;
return true;
}
export function getFileSize(fileByte) {
let fileSizeByte = fileByte;
let fileSizeMsg = "";
if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
else fileSizeMsg = "文件超过1TB";
return fileSizeMsg;
}
export function getQueryString(name)
{
//console.log('url' , window.location.search)
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);//search,查询?后面的参数,并匹配正则
if(r!=null)return unescape(r[2]); return null;
}
export function back(){
history.go(-1)
}
/**
* 是否有权限
* @param {*} key
*/
export function isAuth (key) {
return JSON.parse(localStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}
/**
* 登录后赋权
* @param {*} perms 权限码集合 数组
*/
export function setAuth(perms) {
localStorage.setItem('permissions', JSON.stringify(perms || '[]'))
}
/**
* 树形数据转换
* @param {*} data
* @param {*} id
* @param {*} pid
*/
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
var res = []
var temp = {}
for (var i = 0; i < data.length; i++) {
temp[data[i][id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
if (!temp[data[k][pid]]['children']) {
temp[data[k][pid]]['children'] = []
}
if (!temp[data[k][pid]]['_level']) {
temp[data[k][pid]]['_level'] = 1
}
data[k]['_level'] = temp[data[k][pid]]._level + 1
temp[data[k][pid]]['children'].push(data[k])
} else {
res.push(data[k])
}
}
return res
}
export function toRoute(url , target) {
if(isURL( url)) {
// 加参
/*if(url.indexOf('?') > 0) {
url = url
} else {
url = url
}*/
if(target && target == 'this') {
this.$router.push({name: index})
} else {
window.open( url , target ? target : '_blank')
}
} else {
if(url.indexOf('/') != 0) {
url = '/' + url ;
}
// 判断路由中是否存在
if(target && target == 'this') {
this.$router.push({path:url})
} else {
let routeUrl = this.$router.resolve({
path: url,
//params: {id:menu.menuId}
});
window.open(routeUrl.href, target ? target : '_blank');
}
}
}
/**
* 清除登录信息
*/
export function clearLoginInfo () {
localStorage.removeItem('token')
//Vue.cookie.delete('token')
store.commit('resetStore')
router.options.isAddDynamicMenuRoutes = false
}
<file_sep>package com.xiaobo.common.utils;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CollectionsUtils {
public static Set<String> transletPerms(List<String> perms) {
Set<String> set = new HashSet<>();
for(String p : perms) {
if(p == null || p.isEmpty()) continue;
String[] ps = p.split(",");
for(String s : ps) {
set.add(s);
}
}
return set ;
}
public static <T> Set<String> transletPerms(List<T> perms , TValue<T> tv) {
Set<String> set = new HashSet<>();
for(T p : perms) {
if(p == null ) continue;
Object v = tv.getValue(p);
if(v == null || v.equals("")) continue ;
String[] ps = v.toString().split(",");
for(String s : ps) {
set.add(s);
}
}
return set ;
}
public static String collectionsToString(Collection<String> colls) {
StringBuffer sb = new StringBuffer();
for(String s : colls) {
sb.append(s + ",");
}
if(sb.length() > 1) {
sb.deleteCharAt(sb.length() - 1 ) ;
}
return sb.toString();
}
}
<file_sep>package com.xiaobo.common.log.annotation;
public enum SysModule {
sys("用户中心") , unknow("未知");
private String name ;
private SysModule(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
|
a2ea4671f0213c1188e6e4c5c8b94ad1c08e4753
|
[
"JavaScript",
"Java",
"Maven POM",
"Markdown"
] | 64
|
Java
|
changyongyong/employee_manage
|
9c3ffbf2cf8c4fbb562f4d064fe6c59d5924da8d
|
bdb4bb4ca93e2180f164deb6ee5e8069f1a4fd8a
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace Cobalt.Core
{
public class Agent
{
internal static SerialPort com;
private Agent() { }
static Agent()
{
com = new SerialPort(Properties.Settings.Default.SerialPortName, Properties.Settings.Default.SerialPortBaudRate,
Parity.None, 8, StopBits.None);
}
static void OpenSerialPort(string portName, int baudRate)
{
com.PortName = portName;
com.BaudRate = baudRate;
}
static void SendRequest(Transaction request, ref Transaction response)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cobalt.Core
{
class Transaction
{
enum TransactionMode
{
Register,
InternalRegister,
Memory
}
TransactionMode Mode { get; set; }
}
}
|
66fc22205ccc071fccf6e675df76ca3e0fad117c
|
[
"C#"
] | 2
|
C#
|
Dolan1998/cobaltmips
|
9830370353c701ac3dcebff76fff2c64ff089c4c
|
1448403943ea92fab91f8cd3cfa6f0f75dcb5eee
|
refs/heads/main
|
<repo_name>Opake12/Text-similarity<file_sep>/README.md
## Text Similarity Project
# Pipeline that creates a trained model
CONTENTS OF THIS FILE
---------------------
* [Introduction](#introduction)
* [Requirements](#requirements)
* [Installation](#installation)
* [License](#license)
### Introduction
Project goal is to deploy a pipeline that on the one hand a feature engineering process that is used to generate and select features and to create a training and test data set. It takes then the data sets and uses them to train a model. This model is going to be saved in the models folder.
### Requirements
1. Anaconda with latest Python 3 version (includes Python, Jupyter Notebook, and commonly used packages)
2. text-similarities package (please refer to installation)
### Installation
Please install the [text-similarities](https://test.pypi.org/project/text-similarities/) in the terminal with the following command:
pip install -i https://test.pypi.org/simple/ text-similarities
As this is a test pypi package please install the dependencies from the requirments.txt file with the following command:
pip install -r requirements.txt
### License
The content of this project itself is licensed under the [Creative Commons Attribution 3.0 Unported license](https://creativecommons.org/licenses/by/3.0/),
and the underlying source code for calculations is licenced under the [Apache Version 2](LICENCE)
<file_sep>/requirements.txt
async-generator==1.10
backports.functools-lru-cache==1.6.1
certifi==2020.6.20
cycler==0.10.0
decorator==4.4.2
defusedxml==0.6.0
ipython-genutils==0.2.0
Jinja2==2.11.2
joblib==0.17.0
kiwisolver==1.2.0
matplotlib==3.3.2
mkl-fft==1.2.0
mkl-random==1.1.1
mkl-service==2.3.0
pandas==1.1.3
pandocfilters==1.4.2
Pillow==8.0.0
ptyprocess==0.6.0
pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2020.1
pyzmq==19.0.2
scikit-learn==0.23.2
scipy==1.5.3
sklearn==0.0
testpath==0.4.4
threadpoolctl==2.1.0
webencodings==0.5.1
<file_sep>/problem_unittests.py
from unittest.mock import MagicMock, patch
import sklearn.naive_bayes
import numpy as np
import pandas as pd
import re
# test csv file
TEST_CSV = 'data/test_info.csv'
class AssertTest(object):
'''Defines general test behavior.'''
def __init__(self, params):
self.assert_param_message = '\n'.join([str(k) + ': ' + str(v) + '' for k, v in params.items()])
def test(self, assert_condition, assert_message):
assert assert_condition, assert_message + '\n\nUnit Test Function Parameters\n' + self.assert_param_message
def _print_success_message():
print('Tests Passed!')
# test clean_dataframe
def test_numerical_df(numerical_dataframe):
# test result
transformed_df = numerical_dataframe(TEST_CSV)
# Check type is a DataFrame
assert isinstance(transformed_df, pd.DataFrame), 'Returned type is {}.'.format(type(transformed_df))
# check columns
column_names = list(transformed_df)
assert 'File' in column_names, 'No File column, found.'
assert 'Task' in column_names, 'No Task column, found.'
assert 'Category' in column_names, 'No Category column, found.'
assert 'Class' in column_names, 'No Class column, found.'
# check conversion values
assert transformed_df.loc[0, 'Category'] == 1, '`heavy` plagiarism mapping test, failed.'
assert transformed_df.loc[2, 'Category'] == 0, '`non` plagiarism mapping test, failed.'
assert transformed_df.loc[30, 'Category'] == 3, '`cut` plagiarism mapping test, failed.'
assert transformed_df.loc[5, 'Category'] == 2, '`light` plagiarism mapping test, failed.'
assert transformed_df.loc[37, 'Category'] == -1, 'original file mapping test, failed; should have a Category = -1.'
assert transformed_df.loc[41, 'Category'] == -1, 'original file mapping test, failed; should have a Category = -1.'
_print_success_message()
def test_data_split(train_x, train_y, test_x, test_y):
# check types
assert isinstance(train_x, np.ndarray),\
'train_x is not an array, instead got type: {}'.format(type(train_x))
assert isinstance(train_y, np.ndarray),\
'train_y is not an array, instead got type: {}'.format(type(train_y))
assert isinstance(test_x, np.ndarray),\
'test_x is not an array, instead got type: {}'.format(type(test_x))
assert isinstance(test_y, np.ndarray),\
'test_y is not an array, instead got type: {}'.format(type(test_y))
# should hold all 95 submission files
assert len(train_x) + len(test_x) == 95, \
'Unexpected amount of train + test data. Expecting 95 answer text files, got ' +str(len(train_x) + len(test_x))
assert len(test_x) > 1, \
'Unexpected amount of test data. There should be multiple test files.'
# check shape
assert train_x.shape[1]==2, \
'train_x should have as many columns as selected features, got: {}'.format(train_x.shape[1])
assert len(train_y.shape)==1, \
'train_y should be a 1D array, got shape: {}'.format(train_y.shape)
_print_success_message()
|
32db9e6a12088595b6b8cc4cf8da6ea74890ccc6
|
[
"Markdown",
"Python",
"Text"
] | 3
|
Markdown
|
Opake12/Text-similarity
|
4d86b15af8504bf849ef3cc2fdbc8a2240028e4e
|
52cde4bdc9ff351d15ed2bf37d990a7137547857
|
refs/heads/master
|
<repo_name>fxgao/vuepress<file_sep>/docs/.vuepress/config.js
const blogConfig = {
title:'V房前端文档',
description: 'V房前端文档',
head: [
['link', { rel: 'icon', href: '/assets/favicon.ico' }],
['link', { rel: 'manifest', href: '/manifest.json' }],
['link', { rel: 'apple-touch-icon', href: '/assets/favicon.ico' }]
],
themeConfig: {
logo: '/assets/1.png',
nav: [
{ text: '主页', link: '/' },
{ text: '前端规范',
items: [
{ text: '代码规范', link: '/codeStandard/V房前端规范1.0.md' },
{ text: '分支规范', link: '/branchStandard/代码分支合并.md' }
]
},
{ text: '关于', link: '/about/' },
{ text: 'Github', link: 'https://www.github.com/davfang' },
],
sidebar:[
{
title: '代码规范', // 必要的
path: '/codeStandard/', // 可选的, 标题的跳转链接,应为绝对路径且必须存在
collapsable: true, // 可选的, 默认值是 true,
sidebarDepth: 1, // 可选的, 默认值是 1
children: [
{
title: 'V房前端规范1.0', // 必要的
path: 'codeStandard/V房前端规范1.0.md',
}
]
},
{
title: '分支规范', // 必要的
path: '/branchStandard/', // 可选的, 标题的跳转链接,应为绝对路径且必须存在
collapsable: true, // 可选的, 默认值是 true,
sidebarDepth: 1, // 可选的, 默认值是 1
children: [
{
title: '分支合并', // 必要的
path: 'branchStandard/代码分支合并.md',
}
]
},
],
markdown: {
lineNumbers: true
},
sidebarDepth: 2, // 可选的, 默认值是 1
lastUpdated: 'Last Updated',
},
// serviceWorker: true, // PWA
}
module.exports = blogConfig;<file_sep>/docs/README.md
---
home: true
heroImage: /assets/1.png
heroText: V房前端文档
tagline: 日常工作文档
actionText: 开始 →
actionLink: /about/
footer: MIT Licensed | Copyright © 2020-present Vfang
features: null
---<file_sep>/README.md
# vuepress
a simple vuepress docs
<file_sep>/docs/branchStandard/代码分支合并.md
**代码分支合并**
l 关于分支的概念:
在Git中,每次提交都会被汇总成一条时间线,每个时间节点都包含了一些提交,这条时间线就是一个分支。
l 分支的创建与合并
假设现在我们的项目只有master分支,Git用`master`指向最新的提交,再用`HEAD`指向`master`,就能确定当前分支,以及当前分支的提交点:

每次提交,`master`分支都会向前移动一步,这样,随着你不断提交,`master`分支的线也越来越长

当我们创建新的分支,例如`dev`时,Git新建了一个指针叫`dev`,指向`master`相同的提交,再把`HEAD`指向`dev`,就表示当前分支在`dev`上

现在,对工作区的修改和提交就是针对`dev`分支了,比如新提交一次后,`dev`指针往前移动一步,而`master`指针不变

假如我们在`dev`上的工作完成了,就可以把`dev`合并到`master`上。合并完分支后,甚至可以删除`dev`分支。删除`dev`分支就是把`dev`指针给删掉,删掉后,我们就剩下了一条`master`分支

l 合并代码冲突的情况:
1.先来了解一下,sysManager项目的分支构成:
Master分支: 网站线上环境运行的代码,每次上线结束,都将pre-online分支代码同步到此分支;
pre-online分支:用来进行最终测试,并随时准备上线的分支;
michael、bob等开发分支:用来进行项目开发,应基于最新pre-online分支创建

\2. 冲突发生的情况:
假设michael和bob都基于pre-online某一版本创建了各自的开发分支,两人都需要修改A文件中的代码。Michael先进行了分支合并(假设没有冲突),这时A文件第200行的代码已经由Michael进行过修改了。Bob此时也要进行分支合并,由于也修改了A文件200行的代码,git不能自动识别哪个是正确的代码,此时就会造成冲突。

上图中红圈标识的时间节点都有可能发生冲突
l 解决方法
1.“合并”方法
方法:假设你要使用合并(merge)方法将dev分支合并到preonline分支。
首先通过“Switch/CheckOut”(“切换/检出”)切换到主干分支(preonline分支),然后通过“Merge”继进行合并操作,在对话框中选择需要合并的分支(dev分支)。期间可能会出现代码冲突,解决之。分支合并成功后,我们即可以通过Commit与PUSH操作将合并上传到远端preonline分支。
#### 2.“变基”方法(Rebase)
变基:变基其实是复制要被变基的分支上的提交,然后在别的分支上把提交依次重演出来。
**注意**:变基操作的实质是丢弃一些现有的提交,然后相应地新建一些内容一样但实际上不同的提交。 如果你已经将提交推送至某个仓库,而其他人也已经从该仓库拉取提交并进行了后续工作,此时,如果你用 git rebase命令重新整理了提交并再次推送,你的同伴因此将不得不再次将他们手头的工作与你的提交进行整合,如果接下来你还要拉取并整合他们修改过的提交,**事情就会变得一团糟**。
方法:假设你要使用变基方法将dev分支合并到preonline分支。
我们需要先切换分支到preonline,拉取远程preonline分支保持本地分支最新,然后进行变基。变基时,分支选择preonline,上游选择你要合并的分支dev。即在dev分支复制preonline上的提交并一步一步重演出来,你需要解决冲突重演过程中可能会出现代码冲突,最后提交这些更改并推送到远端preonline分支。(原来的提交记录会被此次变基的提交记录覆盖)
以上内容皆基于廖雪峰大大Git教程整理,如有疑惑请参照https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000<file_sep>/docs/codeStandard/V房前端规范1.0.md
# sysmanager
V房管理平台简化版
# 命名规范
## 变量名
1、 【强制】自描述属性里不要出现类名的描述
2、 【强制】属性超过三个的,必须换行
方便删除属性,不会引起错误。
3、 【强制】组件命名:动词+名词。
## 【建议】css
* 显隐
* 布局
* 结构
* 显示
* 动画
## 浏览器前缀禁止手写
## div禁止多个结构只包裹一个文字
## 公用的样式,概念一样,通过预定义变量来实现
less
## image必须有宽高
* 图片太大
* 防止它重绘
目的
统一团队Git Commit标准,便于后续代码review、版本发布、自动化生成change log;
可以提供更多更有效的历史信息,方便快速预览以及配合cherry-pick快速合并代码;
团队其他成员进行类git blame时可以快速明白代码用意;
分支
master分支为主分支(保护分支),不能直接在master上进行修改代码和提交;
pre-online分支为测试分支,所以开发完成需要提交测试的功能合并到该分支;
feature分支为开发分支,大家根据不同需求创建独立的功能分支,开发完成后合并到pre-online分支;
fix分支为bug修复分支,需要根据实际情况对已发布的版本进行漏洞修复;
## Git 提交的正确姿势 type(scope):subject
type用于说明 commit 的类别,只允许使用下面7个标识。
- feat:新功能(feature)
- fix:修补bug
- docs:文档(documentation)
- style: 格式(不影响代码运行的变动)
- build:改变构建流程,新增依赖库、工具等(例如webpack修改)
- perf:改善性能和体现的修改
- refactor:重构(即不是新增功能,也不是修改bug的代码变动)
- test:增加测试
- chore:构建过程或辅助工具的变动
scope:用于说明commit的影响范围
subject:commit的简要说明,尽量简短
例如:
需求:楼盘责任人
git commit -m 'feat:楼盘责任人首次提交'
git commit -m 'fix:修复某某bug问题'
git commit -m 'style:样式修改'
git commit -m 'style:样式修改-fix:修复某某bug问题'
# src目录结构详细
- |——src
- |——components 组件目录,主要存放 通用组件
- |——directive 公共指令
- |——filters 公共过滤器
- |——assets 资源目录
- |——icons 全局SVG
- |——lang 语言设置
- |——mock MockJs
- |——styles 自定义样式
- |——store store状态管理
- |——utils 公共JS
- |——vendor 第三方库
- |——views 以页面形式存放 页面结构
- |——ad 广告
- |——statistics 数据统计
- |——login 登录
- |——building 楼盘详情
- |——propertyBank 楼盘录入
- |——client 预警列表
- |——api 主要存放 API
- |——main.js js入口文件
- |——permission.js 路由权限
- |——errorLog.js 路由权限
- |——routes.js 路由文件
- |——saaslib.js saas方法库
|
8be1017a3459c969b15def49b1f6256729eefad4
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
fxgao/vuepress
|
30caac947a8b381f02f8fe2a712c5e7b2a37df83
|
5b64995626ecd39103762e4aa036f757372e53c3
|
refs/heads/master
|
<file_sep>(function(){
'use strict';
angular.module('virtualScrollingApp').controller('TableCtrl', function TableCtrl($scope) {
$scope.log = {
title: "None",
msgs: [{
time: new Date(),
message: "First thing that happened"
},{
time: new Date(),
message: "Second thing that happened"
},{
time: new Date(),
message: "Third thing that happened"
},{
time: new Date(),
message: "Fourth thing that happened - now add your own"
}]
};
$scope.message = '';
$scope.logit = function(){
$scope.log.msgs.push({ time: new Date(), message: $scope.message });
};
});
}());
|
3f4566e06c7ed775a2d23d1c396eb91e1a151d56
|
[
"JavaScript"
] | 1
|
JavaScript
|
mrcljx/angular-virtual-scroll
|
bee2fc35483ba0bcddca0e2fe04c33615947a25d
|
9560a1f9defefb30e775faf9ab709f740ba95633
|
refs/heads/master
|
<repo_name>fch910519/HandyControl<file_sep>/HandyControlDemo/UserControl/Styles/CheckBoxDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class CheckBoxDemoCtl
{
public CheckBoxDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Controls/StepBarDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// StepBarDemoCtl.xaml 的交互逻辑
/// </summary>
public partial class StepBarDemoCtl
{
public StepBarDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Styles/CalendarDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class CalendarDemoCtl
{
public CalendarDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Controls/GrowlDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// GrowlDemoGrid.xaml 的交互逻辑
/// </summary>
public partial class GrowlDemoCtl
{
public GrowlDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControl/Data/Enum/TipPlacement.cs
// ReSharper disable once CheckNamespace
namespace HandyControl.Data
{
public enum TipPlacement
{
TopLeft,
BottomRight,
}
}<file_sep>/HandyControlDemo/UserControl/Controls/WindowDemoCtl.xaml.cs
using System.Windows;
using HandyControl.Controls;
using HandyControl.Tools;
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class WindowDemoCtl
{
public WindowDemoCtl()
{
InitializeComponent();
}
private void ButtonMessage_OnClick(object sender, RoutedEventArgs e)
{
PopupWindow.ShowDialog(Properties.Langs.Lang.GrowlAsk, showCancel: true);
}
private void ButtonMouseFollow_OnClick(object sender, RoutedEventArgs e)
{
var picker = SingleOpenHelper.CreateControl<ColorPicker>();
var window = new PopupWindow
{
PopupElement = picker
};
picker.SelectedColorChanged += delegate { window.Close(); };
picker.Canceled += delegate { window.Close(); };
window.Show(ButtonMouseFollow, false);
}
private void ButtonCustomContent_OnClick(object sender, RoutedEventArgs e)
{
var picker = SingleOpenHelper.CreateControl<ColorPicker>();
var window = new PopupWindow
{
PopupElement = picker,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
AllowsTransparency = true,
WindowStyle = WindowStyle.None,
MinWidth = 0,
MinHeight = 0,
Title = Properties.Langs.Lang.ColorPicker
};
picker.SelectedColorChanged += delegate { window.Close(); };
picker.Canceled += delegate { window.Close(); };
window.Show();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Controls/TimeBarDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class TimeBarDemoCtl
{
public TimeBarDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControl/Controls/Window/Window.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools;
#if netle40
using Microsoft.Windows.Shell;
#else
using System.Windows.Shell;
#endif
namespace HandyControl.Controls
{
public class Window : System.Windows.Window
{
private Thickness _tempThickness;
public static readonly DependencyProperty NonClientAreaContentProperty = DependencyProperty.Register(
"NonClientAreaContent", typeof(object), typeof(Window), new PropertyMetadata(default(object)));
public static readonly DependencyProperty CloseButtonHoverBackgroundProperty = DependencyProperty.Register(
"CloseButtonHoverBackground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty CloseButtonHoverForegroundProperty =
DependencyProperty.Register(
"CloseButtonHoverForeground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty CloseButtonBackgroundProperty = DependencyProperty.Register(
"CloseButtonBackground", typeof(Brush), typeof(Window), new PropertyMetadata(Brushes.Transparent));
public static readonly DependencyProperty CloseButtonForegroundProperty = DependencyProperty.Register(
"CloseButtonForeground", typeof(Brush), typeof(Window),
new PropertyMetadata(Brushes.White));
public static readonly DependencyProperty OtherButtonBackgroundProperty = DependencyProperty.Register(
"OtherButtonBackground", typeof(Brush), typeof(Window), new PropertyMetadata(Brushes.Transparent));
public static readonly DependencyProperty OtherButtonForegroundProperty = DependencyProperty.Register(
"OtherButtonForeground", typeof(Brush), typeof(Window),
new PropertyMetadata(Brushes.White));
public static readonly DependencyProperty OtherButtonHoverBackgroundProperty = DependencyProperty.Register(
"OtherButtonHoverBackground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty OtherButtonHoverForegroundProperty =
DependencyProperty.Register(
"OtherButtonHoverForeground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty NonClientAreaBackgroundProperty = DependencyProperty.Register(
"NonClientAreaBackground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty NonClientAreaForegroundProperty = DependencyProperty.Register(
"NonClientAreaForeground", typeof(Brush), typeof(Window),
new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty NonClientAreaHeightProperty = DependencyProperty.Register(
"NonClientAreaHeight", typeof(double), typeof(Window),
new PropertyMetadata(28.0));
public static readonly DependencyProperty ShowNonClientAreaProperty = DependencyProperty.Register(
"ShowNonClientArea", typeof(bool), typeof(Window), new PropertyMetadata(ValueBoxes.TrueBox));
public static readonly DependencyProperty ShowTitleProperty = DependencyProperty.Register(
"ShowTitle", typeof(bool), typeof(Window), new PropertyMetadata(ValueBoxes.FalseBox));
public static readonly DependencyProperty IsFullScreenProperty = DependencyProperty.Register(
"IsFullScreen", typeof(bool), typeof(Window), new PropertyMetadata(ValueBoxes.FalseBox,
(o, args) =>
{
var ctl = (Window)o;
var v = (bool)args.NewValue;
if (v)
{
ctl.OriginState = ctl.WindowState;
ctl.OriginStyle = ctl.WindowStyle;
ctl.OriginResizeMode = ctl.ResizeMode;
ctl.WindowStyle = WindowStyle.None;
//下面三行不能改变,就是故意的
ctl.WindowState = WindowState.Maximized;
ctl.WindowState = WindowState.Minimized;
ctl.WindowState = WindowState.Maximized;
}
else
{
ctl.WindowState = ctl.OriginState;
ctl.WindowStyle = ctl.OriginStyle;
ctl.ResizeMode = ctl.OriginResizeMode;
}
}));
public Window()
{
var chrome = new WindowChrome
{
CornerRadius = new CornerRadius(),
GlassFrameThickness = new Thickness(1)
};
BindingOperations.SetBinding(chrome, WindowChrome.CaptionHeightProperty,
new Binding(NonClientAreaHeightProperty.Name) {Source = this});
WindowChrome.SetWindowChrome(this, chrome);
Loaded += delegate
{
_tempThickness = BorderThickness;
if (WindowState == WindowState.Maximized)
{
BorderThickness = new Thickness();
}
CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand,
(s, e) => WindowState = WindowState.Minimized));
CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand,
(s, e) => WindowState = WindowState.Maximized));
CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand,
(s, e) => WindowState = WindowState.Normal));
CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, (s, e) => Close()));
CommandBindings.Add(new CommandBinding(SystemCommands.ShowSystemMenuCommand, ShowSystemMenu));
};
}
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (WindowState == WindowState.Maximized)
{
BorderThickness = new Thickness();
}
else if (WindowState == WindowState.Normal)
{
BorderThickness = _tempThickness;
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (SizeToContent != SizeToContent.WidthAndHeight)
return;
SizeToContent = SizeToContent.Height;
Dispatcher.BeginInvoke(new Action(() => { SizeToContent = SizeToContent.WidthAndHeight; }));
}
public Brush CloseButtonBackground
{
get => (Brush)GetValue(CloseButtonBackgroundProperty);
set => SetValue(CloseButtonBackgroundProperty, value);
}
public Brush CloseButtonForeground
{
get => (Brush)GetValue(CloseButtonForegroundProperty);
set => SetValue(CloseButtonForegroundProperty, value);
}
public Brush OtherButtonBackground
{
get => (Brush)GetValue(OtherButtonBackgroundProperty);
set => SetValue(OtherButtonBackgroundProperty, value);
}
public Brush OtherButtonForeground
{
get => (Brush)GetValue(OtherButtonForegroundProperty);
set => SetValue(OtherButtonForegroundProperty, value);
}
/// <summary>
/// 原始状态
/// </summary>
private WindowState OriginState { get; set; }
/// <summary>
/// 原始样式
/// </summary>
private WindowStyle OriginStyle { get; set; }
/// <summary>
/// 原始尺寸调节模式
/// </summary>
private ResizeMode OriginResizeMode { get; set; }
public double NonClientAreaHeight
{
get => (double)GetValue(NonClientAreaHeightProperty);
set => SetValue(NonClientAreaHeightProperty, value);
}
public bool IsFullScreen
{
get => (bool)GetValue(IsFullScreenProperty);
set => SetValue(IsFullScreenProperty, value);
}
public object NonClientAreaContent
{
get => GetValue(NonClientAreaContentProperty);
set => SetValue(NonClientAreaContentProperty, value);
}
public Brush CloseButtonHoverBackground
{
get => (Brush)GetValue(CloseButtonHoverBackgroundProperty);
set => SetValue(CloseButtonHoverBackgroundProperty, value);
}
public Brush CloseButtonHoverForeground
{
get => (Brush)GetValue(CloseButtonHoverForegroundProperty);
set => SetValue(CloseButtonHoverForegroundProperty, value);
}
public Brush OtherButtonHoverBackground
{
get => (Brush)GetValue(OtherButtonHoverBackgroundProperty);
set => SetValue(OtherButtonHoverBackgroundProperty, value);
}
public Brush OtherButtonHoverForeground
{
get => (Brush)GetValue(OtherButtonHoverForegroundProperty);
set => SetValue(OtherButtonHoverForegroundProperty, value);
}
public Brush NonClientAreaBackground
{
get => (Brush)GetValue(NonClientAreaBackgroundProperty);
set => SetValue(NonClientAreaBackgroundProperty, value);
}
public Brush NonClientAreaForeground
{
get => (Brush)GetValue(NonClientAreaForegroundProperty);
set => SetValue(NonClientAreaForegroundProperty, value);
}
public bool ShowNonClientArea
{
get => (bool)GetValue(ShowNonClientAreaProperty);
set => SetValue(ShowNonClientAreaProperty, value);
}
public bool ShowTitle
{
get => (bool)GetValue(ShowTitleProperty);
set => SetValue(ShowTitleProperty, value);
}
private void ShowSystemMenu(object sender, ExecutedRoutedEventArgs e)
{
var point = WindowState == WindowState.Maximized
? new Point(0, 28)
: new Point(Left, Top + 28);
SystemCommands.ShowSystemMenu(this, point);
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
if (SizeToContent == SizeToContent.WidthAndHeight)
InvalidateMeasure();
}
/// <summary>
/// 获取自定义窗口
/// </summary>
/// <returns></returns>
public static Window GetCustomWindow(FrameworkElement content)
{
var window = new Window
{
Style = ResourceHelper.GetResource<Style>(ResourceToken.WindowWin10),
Content = content
};
window.Loaded += (s, e) =>
{
window.Width = window.BorderThickness.Left + window.BorderThickness.Right + content.Width;
if (!(window.Template.FindName("GridMenu", window) is Grid nemuArea))
throw new NullReferenceException("can not find GridMenu in template");
window.Height = window.BorderThickness.Top + window.BorderThickness.Bottom + content.Height +
nemuArea.ActualHeight;
};
return window;
}
}
}<file_sep>/HandyControl/Data/GrowlInfo.cs
using System;
namespace HandyControl.Data
{
public class GrowlInfo
{
public string Message { get; set; }
public bool ShowDateTime { get; set; } = true;
public string CancelStr { get; set; } = Properties.Langs.Lang.Cancel;
public string ConfirmStr { get; set; } = Properties.Langs.Lang.Confirm;
public Func<bool, bool> ActionBeforeClose { get; set; }
internal InfoType Type { get; set; }
internal string IconKey { get; set; }
internal string IconBrushKey { get; set; }
internal bool StaysOpen { get; set; }
internal bool ShowCloseButton { get; set; } = true;
}
}<file_sep>/HandyControlDemo/UserControl/Styles/ToggleButtonDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// ToggleButtonDemoCtl.xaml 的交互逻辑
/// </summary>
public partial class ToggleButtonDemoCtl
{
public ToggleButtonDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControl/Tools/Helper/ColorHelper.cs
using System.Windows.Media;
namespace HandyControl.Tools
{
public class ColorHelper
{
private const int Win32RedShift = 0;
private const int Win32GreenShift = 8;
private const int Win32BlueShift = 16;
public static int ToWin32(Color c) => c.R << Win32RedShift | c.G << Win32GreenShift | c.B << Win32BlueShift;
}
}<file_sep>/HandyControlDemo/UserControl/Controls/ColorPickerDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class ColorPickerDemoCtl
{
public ColorPickerDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControl/Controls/Window/BlurWindow.cs
using System.Runtime.InteropServices;
using System.Windows.Interop;
using HandyControl.Data;
using HandyControl.Tools;
namespace HandyControl.Controls
{
public class BlurWindow : Window
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
EnableBlur(this);
}
public static SystemVersionInfo SystemVersionInfo { get; set; }
internal static void EnableBlur(Window window)
{
var accentPolicy = new ExternDllHelper.ACCENTPOLICY();
var accentPolicySize = Marshal.SizeOf(accentPolicy);
if (SystemVersionInfo >= SystemVersionInfo.Windows10_1809)
{
accentPolicy.AccentState = ExternDllHelper.ACCENTSTATE.ACCENT_ENABLE_ACRYLICBLURBEHIND;
}
else if (SystemVersionInfo >= SystemVersionInfo.Windows10)
{
accentPolicy.AccentState = ExternDllHelper.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND;
}
else
{
accentPolicy.AccentState = ExternDllHelper.ACCENTSTATE.ACCENT_ENABLE_TRANSPARENTGRADIENT;
}
accentPolicy.AccentFlags = 2;
accentPolicy.GradientColor = ResourceHelper.GetResource<uint>(ResourceToken.BlurGradientValue);
var accentPtr = Marshal.AllocHGlobal(accentPolicySize);
Marshal.StructureToPtr(accentPolicy, accentPtr, false);
var data = new ExternDllHelper.WINCOMPATTRDATA
{
Attribute = ExternDllHelper.WINDOWCOMPOSITIONATTRIB.WCA_ACCENT_POLICY,
DataSize = accentPolicySize,
Data = accentPtr
};
ExternDllHelper.SetWindowCompositionAttribute(new WindowInteropHelper(window).Handle, ref data);
Marshal.FreeHGlobal(accentPtr);
}
}
}<file_sep>/HandyControlDemo/UserControl/Styles/SliderDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class SliderDemoCtl
{
public SliderDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControl/Tools/Helper/VisualHelper.cs
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace HandyControl.Tools
{
internal class VisualHelper
{
public static VisualStateGroup TryGetVisualStateGroup(DependencyObject dependencyObject, string groupName)
{
var root = GetImplementationRoot(dependencyObject);
if (root == null)
{
return null;
}
return VisualStateManager
.GetVisualStateGroups(root)?
.OfType<VisualStateGroup>()
.FirstOrDefault(group => string.CompareOrdinal(groupName, group.Name) == 0);
}
public static FrameworkElement GetImplementationRoot(DependencyObject dependencyObject)
{
return 1 == VisualTreeHelper.GetChildrenCount(dependencyObject)
? VisualTreeHelper.GetChild(dependencyObject, 0) as FrameworkElement
: null;
}
}
}<file_sep>/HandyControlDemo/UserControl/Styles/BorderDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class BorderDemoCtl
{
public BorderDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Main/ContributorsView.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class ContributorsView
{
public ContributorsView()
{
InitializeComponent();
}
}
}<file_sep>/HandyControlDemo/UserControl/Styles/TreeViewDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class TreeViewDemoCtl
{
public TreeViewDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Main/LeftMainContent.xaml.cs
using System.Windows.Controls;
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// 左侧主内容
/// </summary>
public partial class LeftMainContent
{
public LeftMainContent()
{
InitializeComponent();
}
private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count == 0) return;
if (e.AddedItems[0] is TabItem tabItem && tabItem.Content is ListBox listBox)
{
if (listBox.SelectedItem != null)
{
var item = listBox.SelectedItem;
listBox.SelectedIndex = -1;
listBox.SelectedItem = item;
}
}
}
}
}
<file_sep>/HandyControlDemo/UserControl/Controls/CircleProgressBarDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
public partial class CircleProgressBarDemoCtl
{
public CircleProgressBarDemoCtl()
{
InitializeComponent();
}
}
}
<file_sep>/HandyControlDemo/UserControl/Styles/ButtonDemoCtl.xaml.cs
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// ButtonDemoCtl.xaml 的交互逻辑
/// </summary>
public partial class ButtonDemoCtl
{
public ButtonDemoCtl()
{
InitializeComponent();
}
}
}
|
243afae8a388a57e726106153c98adb4da620e3e
|
[
"C#"
] | 21
|
C#
|
fch910519/HandyControl
|
ad6083fe78497f35c50d37314f29e8feaa2ea6c9
|
d17c7b79cca1a7fec3d4112713e6aa7ad583c65c
|
refs/heads/master
|
<file_sep>package com.imran.dao;
public class MainDao {
}
|
84802cdb46ddbd7904baae65ef75f3188faaab5c
|
[
"Java"
] | 1
|
Java
|
getimran/SpringHibernateCurd
|
5d05308fa9b5fada5a0c4a5fa834eeb64eb4752b
|
d7f8bc3db1e5a5917fc028f85dc167247b68ab3d
|
refs/heads/master
|
<file_sep>import productListReducer from './component/ProductList/Reducer';
export {
productListReducer,
}
|
e1645a532b360e9379206039fd386ccfdca09192
|
[
"JavaScript"
] | 1
|
JavaScript
|
nileshvarishe/edkal
|
d5e145b01a3f73d1b5d1fe64fbbd64371d3e5ab1
|
ee4ad422a7a702f9a50f037de29bcd6160629617
|
refs/heads/master
|
<file_sep># Object Storage Java test app
This application is designed to undertake CRD operations on Object Storage app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava.
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaObjectStorage
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the Object Storage service and bind it with the Java Liberty App.
## 3. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 4. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaObjectStorage
random-route: true
path: target/TestJavaObjectStorage.war
memory: 256M
instances: 1
name: test-java-objectstorage
host: test-java-objectstorage
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 5. Access the test object storage application
Enter the name of the application and add the API call for the test:
https://test-java-objectstorage.dys0.mybluemix.net/test/objectstorage/all
You should be seeing something like this:
```javascript
{service: 'objectstorage', operations: [
{type: 'create', response_time: 1871, response_code: 200, desc: {'visitor': '1504886518291,test case: 1504886518291'}},
{type: 'read', response_time: 351, response_code: 200, desc: {'visitor id': '1504886518291'}},
{type: 'delete', response_time: 477, response_code: 200, desc: {'visitor id': '1504886518291'}}
], response_code: 200, desc:'operations implemented crd/CRD'}
```<file_sep># MongoDB Java test app
This application is designed to undertake CRUD operations on Compose MongoDB app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava.
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaMongoDb
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the Compose MongoDb service and bind it with the Java Liberty App.
## 3. JVM System Properties for TLS/SSL connection to Compose MongoDB
You might notice that Compose MongoDB connectivity is SSL enabled.
Identify the Compose MongoDB connection URL and Certificate - find the link at the management console.
<p align="center">
<kbd>
<img src="docs/mongo_mngmnt.png" width="300" style="1px solid">
</kbd>
</p>
Therefore our application will need to set several JVM system properties to ensure that the client is able to validate the TLS/SSL certificate presented by the server:
javax.net.ssl.trustStore: The path to a trust store containing the certificate of the signing authority
javax.net.ssl.trustStorePassword: The password to access this trust store
The trust store is typically created with the keytool command line program provided as part of the JDK. For example:
```keytool -importcert -trustcacerts -file <path to certificate authority file> -keystore <path to trust store> -storepass <password>```
To make this work, we need to go back to the Compose console and get the SSL certificate (the certificate authority file) available on the Overview page - find it by clicking the button to reveal it and then copy it to a file - use ```cat > mongodbcert.crt``` and then paste the copied text:
```
-----BEGIN CERTIFICATE-----
MIIDezCCAmOgAwIBAgIEWUkeGzANBgkqhkiG9w0BAQ0FADA/MT0wOwYDVQQDDDRt
...skipping some lines...
nnRSLAtnmc+bx02bK7IqWzEJIDWwr543HDhbqwMLYJbZukKThJ8hpzts3rw1uYND
etzf6nD4gf9ovB/UpCF7cvJPpPN/YR9eLlYlJ51vkA==
-----END CERTIFICATE-----
```
The next step is then quite easy:
The command to create the mongoDBKey store for our system is the following:
```keytool -importcert -trustcacerts -file ./mongodbcert.crt -keystore ./mongoKeyStore -storepass <PASSWORD>```
When done place the mongoKeyStore at this location: ```GetStartedJavaMongoDb/src/main/resources/mongoKeyStore```
Update the java class wasdev.sample.store.MongoDbVisitorStore at the createClient method if anything changes:
the document after the mvn install is going to be stored at this location:
- locally: ```/your path to the target: GetStartedJavaMongoDb/target/TestJavaMongo-1.0-SNAPSHOT/WEB-INF/classes/mongoKeyStore```
- on Bluemix (after cf push command) : ```/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.war/WEB-INF/classes/mongoKeyStore```
A typical application will also need to set several JVM system properties to ensure that the client presents an TLS/SSL certificate to the MongoDB server:
- javax.net.ssl.keyStore The path to a key store containing the client’s TLS/SSL certificates
- javax.net.ssl.keyStorePassword The password to access this key store
## 4. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 5. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaMongoDB
random-route: true
path: target/TestJavaMongo.war
memory: 256M
instances: 1
name: test-java-mongodb
host: test-java-mongodb
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 6. Access the test MongoDb application
Enter the name of the application and add the API call for the test:
https://test-java-mongodb.dys0.mybluemix.net/TestJavaMongo/test/mongo/all
You should be seeing something like this:
```javascript
{service: 'mongodb', operations: [
{type: 'create', response_time: 30, response_code: 200, desc: {'visitor id': '594ddeee34a639002645674d'}},
{type: 'read', response_time: 25, response_code: 200, desc: {'visitor id': '594ddeee34a639002645674d'}},
{type: 'update', response_time: 49, response_code: 200, desc: {'visitor id': '594ddeee34a639002645674d'}},
{type: 'delete', response_time: 28, response_code: 200, desc: { 'deleted visitor id': '594ddeee34a639002645674d'}}
], response_code: 200, desc:'operations implemented CRUD/CRUD'
}
```
Further reading:
- https://www.compose.com/articles/how-to-connecting-to-compose-mongodb-with-java-and-ssl/
- https://www.compose.com/articles/easier-java-connections-to-mongodb-at-compose-2/
- http://www.journaldev.com/3963/mongodb-java-crud-example-tutorial
<file_sep># BluemixTestDashboard
checking the response times of the IBM Cloud basic services - if you are using it please give me a star.
## TestDashboard
This service enables you to test the apps deployed on the bluemix. They ping these applications over the Restful API call. In return the application respond with the following JSON:
```
{service: 'mongodb', operations: [
{type: 'create', response_time: 38, response_code: 200, desc: {'visitor id': '5955a851ccc001002d0c0552'}},
{type: 'read', response_time: 22, response_code: 200, desc: {'visitor id': '5955a851ccc001002d0c0552'}},
{type: 'update', response_time: 32, response_code: 200, desc: {'visitor id': '5955a851ccc001002d0c0552'}},
{type: 'delete', response_time: 28, response_code: 200, desc: { 'deleted visitor id': '5955a851ccc001002d0c0552'}}
], response_code: 200, desc:'operations implemented CRUD/CRUD'}
```
[Use this link to view the test dashboard repo](TestDashboard)
## JavaCloudant test application
This application tests connectivity to Cloudant NoSQLDb from Java platform.
[Use this link to view the test java Cloudant NoSQLDb repo](get-started-java-master)
## JavaMongoDB test application
This test application checks connectivity to MongoDB from Java platform.
[Use this link to view the test java MongoDB repo](GetStartedJavaMongoDb)
## Java Message Hub test application
This test application checks producing and consuming of the messages with IBM Message Hub.
[Use this link to view the test app for Message Hub](GetStartedJavaMessageHub)
## Java Compose for ElasticSearch test application
This test application checks indexing and searching thru the documents with Compose for ElasticSearch.
[Use this link to view the test app for Compose for ElasticSearch](GetStartedJavaComposeElasticSearch)
## Java Compose for Redis test application
This test application checks "Create Read Push Pop Sets" operations for Compose for Redis with Java on Bluemix.
[Use this link to view the test app for Compose for Redis](GetStartedJavaRedis)
## Java Compose for Postgresql test application
This test application checks CRUD operations for Compose for PostgreSQL with Java on Bluemix.
[Use this link to view the test app for Compose for PostgreSQL](GetStartedJavaPostgresql)
## Java Object Storage test application
This test application checks CRD operations for Object Storage with Java on Bluemix.
[Use this link to view the test app for Object Storage](GetStartedJavaObjectStorage)
## Java Compose for MySQL test application
This test application checks CRUD operations for Compose for MySql with Java on Bluemix.
[Use this link to view the test app for MySql](GetStartedJavaMySQL)
<file_sep># IBM Event Streams (Kafka as a Service on IBM Cloud) Java test app
This application is designed to undertake Create Topic, Produce Message, Consume Message operations on IBM Message-Hub app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava.
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaMessageHub
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the IBM Message Hub service and bind it with the Java Liberty App.
## 3. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 4. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaMessageHub
random-route: true
path: target/TestJavaMessageHub.war
memory: 256M
instances: 1
name: test-java-messagehub
host: test-java-messagehub
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 5. Access the test MessageHub application
Enter the name of the application and add the API call for the test:
https://(link to your app on bluemix.mybluemix.net)/TestJavaMessageHub/test/messagehub/all
You should be seeing something like this:
```javascript
{service: 'message-hub', operations: [
{type: 'create topic', response_time: 121, response_code: 200, desc: {'Admin REST response': 'no response - the topic has been already created'}},
{type: 'produce message', response_time: 1, response_code: 200, desc: {'Message created': 'Message produced, offset: 523'}},
{type: 'consume message', response_time: 2064, response_code: 200, desc: {'Message consumed': 'Message consumed: ConsumerRecord(topic = test-java-messagehub-topic, partition = 0, offset = 523, CreateTime = 1499458409907, serialized key size = 3, serialized value size = 25, headers = RecordHeaders(headers = [], isReadOnly = false), key = key, value = This is a test message #2)'}}
], response_code: 200, desc:'operations implemented CrPCo/CrPCoD'}
```
<file_sep>package com.ibm.dashboard.servlet;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import com.cloudant.client.org.lightcouch.NoDocumentException;
import com.ibm.dashboard.singleton.DashboardData;
import com.ibm.dashboard.store.UrlStatusPersistedStore;
import com.ibm.dashboard.store.UrlStatusPersistedStoreFactory;
/**
* Servlet implementation class RemoveUrlFormHandler
*/
@WebServlet("/RemoveUrlFormHandler")
public class RemoveUrlFormHandler extends HttpServlet {
private static String FORWARD_TO_PAGE = "/manageUrls.jsp";
private static final long serialVersionUID = 1L;
UrlStatusPersistedStore store = UrlStatusPersistedStoreFactory.getInstance();
/**
* Default constructor.
*/
public RemoveUrlFormHandler() {
// TODO Auto-generated constructor stub
}
/**
* Removing urls to monitoring the status provided as the url ids (from db)
*
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Deleting URLs from the DB - Served at: ").append(request.getContextPath());
String paramName = "urls";
String[] urls = request.getParameterValues(paramName);
for (String url_id : urls) {
if (url_id != null) {
System.out.println("url to delete: " + url_id);
if (store == null) {
System.out.println("store is null!!!");
} else {
System.out.println("the store is not null.");
try {
store.delete(url_id);
System.out.println("deleted url...");
// TODO: reset the cache
DashboardData dashboardData = DashboardData.getInstance();
dashboardData.resetUrls();
// TODO: rev1.0 insert a message: Schedule changes will take effect at XX:XX:XXX Pacific time
// get the XX:XX:XXX Pacific time from the RefreshData
String deleteMessage = "The URL deleted (delete servlet) successfully. Changes will take effect at XX:XX:XXX Pacific time";
// adding session
// Retrieve the current session. Create one if not exists
HttpSession session = request.getSession(true);
//adding the message
session.setAttribute("message", deleteMessage);
} catch (NoDocumentException e) {
System.out.println(e.getError());
}
}
}
}
//getting back to the page who potentially called this servlet
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(FORWARD_TO_PAGE);
dispatcher.forward(request, response);
}
}
<file_sep>/**
*
*/
package com.ibm.dashboard.store;
import java.util.Collection;
import com.cloudant.client.api.Database;
/**
* @author mareksadowski
*
*/
public interface SchedulerSettingsStore {
/**
* Get the target db object.
*
* @return Database.
* @throws Exception
*/
public Database getDB();
/**
* Gets all Visitors from the store.
*
* @return All SchedulerSettings objects.
* @throws Exception
*/
public Collection<SchedulerSettings> getAll();
/**
* Gets an individual SchedulerSettings from the store.
* @param id The ID of the SchedulerSettings to get.
* @return The SchedulerSettings.
*/
public SchedulerSettings get(String id);
/**
* Persists an SchedulerSettings to the store.
* @param SchedulerSettings The SchedulerSettings to persist.
* @return The persisted SchedulerSettings. The SchedulerSettings will not have a unique ID..
*/
public SchedulerSettings persist(SchedulerSettings schedulerSettings);
/**
* Updates an SchedulerSettings in the store.
* @param id The ID of the SchedulerSettings to update.
* @param SchedulerSettings The SchedulerSettings with updated information.
* @return The updated SchedulerSettings.
*/
public SchedulerSettings update(String id, SchedulerSettings schedulerSettings);
/**
* Deletes an SchedulerSettings from the store.
* @param id The ID of the SchedulerSettings to delete.
*/
public void delete(String id);
/**
* Counts the number of SchedulerSettings
* @return The total number of SchedulerSettings objects.
* @throws Exception
*/
public int count() throws Exception;
}
<file_sep>/*******************************************************************************
* Copyright (c) 2017 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package wasdev.sample.rest;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.cluster.Health;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.IndicesExists;
import wasdev.sample.model.Article;
import wasdev.sample.store.SearchlyJestStore;
@ApplicationPath("test")
@Path("/elasticsearch")
public class ElasticSearchTestAPI extends Application {
final static Logger logger = LoggerFactory.getLogger(ElasticSearchTestAPI.class);
// Our database store
SearchlyJestStore store = new SearchlyJestStore();
/**
* //cleaning the db afterwards //System.out.println(deleteAll());
*
* @return A test case result of all CRUD operations
*/
@GET
@Path("/all")
@Produces({ "application/json" })
public String doTestCRUD() {
if (store == null) {
return "{service: 'elasticsearch', operations:[], response_code: 404, desc:'Error: no connection to elasticsearch'}";
}
// Call elasticsearch Search...
String response = "{service: 'elasticsearch', operations: [" + searchlyHealth() + "," + indexSampleArticles() + ","
+ searchlySearch() // + "," + deleteIndexSampleArticles()
+ "]"
+ ", response_code: 200, desc:'operations implemented CISDI/CISDI'}";
return response;
}
private String searchlyHealth() {
long responseTime = 0;
String responseCode = "200";
String responseDesc = "''";
long startTime;
long endTime;
JestClient client = store.getClient();
JestResult result = null;
Health health = new Health.Builder().build();
// timed operation
startTime = System.currentTimeMillis();
if (client != null) {
try {
result = client.execute(health);
// prints output of Elasticsearch cluster health check
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
endTime = System.currentTimeMillis();
// end of timed operation
System.out.printf("\n\n<------ CLUSTER HEALTH ------>\n%s\n\n", result.getJsonObject());
responseTime = (endTime - startTime);
// rev 0.5 jsonObject instead of jsonPrimitive - string
if (result != null) {
responseDesc = result.getJsonObject().toString();
} else {
responseDesc = "{health: 'null'}";
}
String responseString = "{type: 'health', response_time: " + responseTime + ", response_code: " + responseCode
+ ", desc: " + responseDesc + "}";
System.out.println(responseString);
return responseString;
// shuts down the connection
// client.shutdownClient();
}
/**
* Reading all the documents from the db - returning the code 200, response
* time in ms, and the contents of the db in desc
*
* @return A test case result of READ/CRUD operation
*/
private String searchlySearch() {
long responseTime = 0;
String responseCode = "200";
String responseDesc = "''";
long startTime;
long endTime;
String searchParameter = "epic";
// timed operation
startTime = System.currentTimeMillis();
List<Article> results = searchArticles(searchParameter);
// TODO: get the ObjectID
// Visitor readVisitor = read(operationalVisitor.getName());
endTime = System.currentTimeMillis();
// end of timed operation
responseTime = (endTime - startTime);
// rev 0.5 jsonObject instead of jsonPrimitive - string
responseDesc = "{'search string':'"
+ searchParameter + "', "
+ "'search result': '"
+ (results.size() > 0 ? (results.get(0)).getContent() : "")
+ "'}";
String responseString = "{type: 'search', response_time: " + responseTime + ", response_code: " + responseCode
+ ", desc: " + responseDesc + "}";
System.out.println(responseString);
return responseString;
}
public String indexSampleArticles() {
long responseTime = 0;
String responseCode = "200";
String responseDesc = "''";
long startTime;
long endTime;
Article article1 = new Article();
article1.setId(1L);
article1.setAuthor("<NAME>");
article1.setContent("Homeland follows the story of Drizzt from around the time and circumstances of his birth and his upbringing amongst the drow (dark elves). " +
"The book takes the reader into Menzoberranzan, the drow home city. From here, the reader follows Drizzt on his quest to follow his principles in a land where such " +
"feelings are threatened by all his family including his mother <NAME>. In an essence, the book introduces Drizzt Do'Urden," +
" one of Salvatore's more famous characters from the Icewind Dale Trilogy.");
Article article2 = new Article();
article2.setId(2L);
article2.setAuthor("<NAME>");
article2.setContent("The Lord of the Rings is an epic high fantasy novel written by English philologist and University of Oxford professor <NAME>. " +
"The story began as a sequel to Tolkien's 1937 children's fantasy novel The Hobbit, but eventually developed into a much larger work. " +
"It was written in stages between 1937 and 1949, much of it during World War II.[1] It is the third best-selling novel ever written, with over 150 million copies sold");
// timed operation
startTime = System.currentTimeMillis();
try {
JestClient client = store.getClient();
IndicesExists indicesExists = new IndicesExists.Builder("articles").build();
JestResult result = client.execute(indicesExists);
if (!result.isSucceeded()) {
// Create articles index
CreateIndex createIndex = new CreateIndex.Builder("articles").build();
client.execute(createIndex);
}
/**
* if you don't want to use bulk api use below code in a loop.
*
* Index index = new Index.Builder(source).index("articles").type("article").build();
* jestClient.execute(index);
*
*/
Bulk bulk = new Bulk.Builder()
.addAction(new Index.Builder(article1).index("articles").type("article").build())
.addAction(new Index.Builder(article2).index("articles").type("article").build())
.build();
bulk = new Bulk.Builder()
.addAction(new Index.Builder(article1).index("articles").type("article").build())
.addAction(new Index.Builder(article2).index("articles").type("article").build())
.build();
result = client.execute(bulk);
responseDesc = result.getJsonString();
//System.out.println(result.getJsonString());
} catch (IOException e) {
logger.error("Indexing error", e);
} catch (Exception e) {
logger.error("Indexing error", e);
}
endTime = System.currentTimeMillis();
// end of timed operation
responseTime = (endTime - startTime);
// rev 0.5 jsonObject instead of jsonPrimitive - string
String responseString = "{type: 'create-indexes-articles', response_time: " + responseTime + ", response_code: " + responseCode
+ ", desc: " + responseDesc + "}";
System.out.println(responseString);
return responseString;
}
public List<Article> searchArticles(String param) {
try {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryString(param));
Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex("articles")
.addType("article")
.build();
JestClient client = store.getClient();
JestResult result = client.execute(search);
return result.getSourceAsObjectList(Article.class);
} catch (IOException e) {
logger.error("Search error", e);
} catch (Exception e) {
logger.error("Search error", e);
}
return null;
}
public String deleteIndexSampleArticles() {
long responseTime = 0;
String responseCode = "200";
String responseDesc = "''";
long startTime;
long endTime;
// timed operation
startTime = System.currentTimeMillis();
try {
// Delete articles index if it is exists
JestClient client = store.getClient();
DeleteIndex deleteIndex = new DeleteIndex.Builder("articles").build();
JestResult result = client.execute(deleteIndex);
responseDesc = result.getJsonString();
//System.out.println(result.getJsonString());
} catch (Exception e) {
logger.error("Indexing error", e);
}
endTime = System.currentTimeMillis();
// end of timed operation
responseTime = (endTime - startTime);
// rev 0.5 jsonObject instead of jsonPrimitive - string
String responseString = "{type: 'delete-indexes', response_time: " + responseTime + ", response_code: " + responseCode
+ ", desc: " + responseDesc + "}";
System.out.println(responseString);
return responseString;
}
}
<file_sep>package com.ibm.dashboard.store;
public class UrlStatusPersistedStoreFactory {
private static UrlStatusPersistedStore instance;
static {
CloudantUrlStatusPersistedStore curlf = new CloudantUrlStatusPersistedStore();
if(curlf.getDB() != null){
instance = curlf;
}
}
public static UrlStatusPersistedStore getInstance() {
return instance;
}
}
<file_sep># Compose for ElasticSearch Java test app
This application is designed to create index, add articles, search articles and check health of the cluster for Compose for ElasticSearch app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava and https://github.com/searchly/searchly-java-sample
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaComposeElasticSearch
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the ComposeElasticSearch service and bind it with the Java Liberty App.
## 3. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 4. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaComposeElasticSearch
random-route: true
path: target/TestJavaComposeElasticSearch.war
memory: 256M
instances: 1
name: test-java-composeelasticsearch
host: test-java-composeelasticsearch
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 5. Access the test ComposeElasticSearch application
Enter the name of the application and add the API call for the test:
https://test-java-composeelasticsearch.dys0.mybluemix.net/TestJavaComposeElasticSearch/test/elasticsearch/all
You should be seeing something like this:
```javascript
{service: 'elasticsearch', operations: [
{type: 'health', response_time: 301, response_code: 200, desc: {"cluster_name":"bmix-dal-yp-f914b69f-df93-4c56-a614-46f6d74b9480","status":"green","timed_out":false,"number_of_nodes":3,"number_of_data_nodes":3,"active_primary_shards":3,"active_shards":9,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":100.0}},
{type: 'create-indexes-articles', response_time: 311, response_code: 200, desc: {"took":23,"errors":false,"items":[{"index":{"_index":"articles","_type":"article","_id":"1","_version":11,"result":"updated","_shards":{"total":3,"successful":3,"failed":0},"created":false,"status":200}},{"index":{"_index":"articles","_type":"article","_id":"2","_version":11,"result":"updated","_shards":{"total":3,"successful":3,"failed":0},"created":false,"status":200}}]}},
{type: 'search', response_time: 178, response_code: 200, desc: {'search string':'epic', 'search result': 'The Lord of the Rings is an epic high fantasy novel written by English philologist and University of Oxford professor <NAME>. The story began as a sequel to Tolkien's 1937 children's fantasy novel The Hobbit, but eventually developed into a much larger work. It was written in stages between 1937 and 1949, much of it during World War II.[1] It is the third best-selling novel ever written, with over 150 million copies sold'}}
], response_code: 200, desc:'operations implemented CISDI/CISDI'}
```<file_sep># Testing CRUD operations from the JEE application deployed on Liberty on Bluemix with Cloudant
By following this guide, you'll set up a development environment, deploy an app locally and on Bluemix, and integrate a Bluemix database service in your app - the app tests the times of CRUD
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a [Bluemix account](https://console.ng.bluemix.net/registration/); some of the code is for Bluemix Dedicated - please modify for Bluemix Public
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone address to this repository
cd TestDashboard
```
## 2. Run the app locally using command line
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
Run the app locally on Liberty.
```
mvn install liberty:run-server
```
View your app at: http://localhost:9080/TestDashboard
## 3. Deploy to Bluemix using command line
To deploy to Bluemix using command line, it can be helpful to set up a manifest.yml file. The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup. This is also where you'll choose your URL. [Learn more...](/docs/manageapps/depapps.html#appmanifest)
The manifest.yml is provided in the sample.
```
applications:
- path: target/TestDashboard.war
memory: 512M
instances: 1
name: your-appname-here
host: your-appname-here
```
Change both the *name* and *host* to a single unique name of your choice. Note that the *host* value will be used in your public url, for example, http://your-appname-here.mybluemix.net. If you already created an app from the Bluemix UI but haven't pushed your code to it, you can use the same name value. Make sure the path points to the built application, for this example the location is `target/JavaHelloWorldApp.war`.
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
or your ```Bluemix Dedicated API```
Login to your Bluemix account
```
cf login
```
(you might need to specify ```--sso``` to indicate the Single Sign On platform in effect in your organization - the process would present you with the url to obtain a login token.
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 4. Developing and Deploying using Eclipse
IBM® Eclipse Tools for Bluemix provides plug-ins that can be installed into an existing Eclipse environment to assist in integrating the developer's integrated development environment (IDE) with Bluemix.
1. Download and install [IBM Eclipse Tools for Bluemix](https://developer.ibm.com/wasdev/downloads/#asset/tools-IBM_Eclipse_Tools_for_Bluemix).
2. Import this sample into Eclipse using `File` -> `Import` -> `Maven` -> `Existing Maven Projects` option.
3. Create a Liberty server definition:
- In the `Servers` view right-click -> `New` -> `Server`
- Select `IBM` -> `WebSphere Application Server Liberty`
- Choose `Install from an archive or a repository`
- Enter a destination path (/Users/username/liberty)
- Choose `WAS Liberty with Java EE 7 Web Profile`
- Continue the wizard with default options to Finish
4. Run your application locally on Liberty:
- Right click on the `TestDashboard` sample and select `Run As` -> `Run on Server` option
- Find and select the localhost Liberty server and press `Finish`
- In a few seconds, your application should be running at http://localhost:9080/TestDashboard/
5. Create a Bluemix server definition:
- In the `Servers` view, right-click -> `New` -> `Server`
- Select `IBM` -> `IBM Bluemix` and follow the steps in the wizard.\
- Enter your credentials and click `Next`
- Select your `org` and `space` and click `Finish`
6. Run your application on Bluemix:
- Right click on the `TestDashboard` sample and select `Run As` -> `Run on Server` option
- Find and select the `IBM Bluemix` and press `Finish`
- A wizard will guide you with the deployment options. Be sure to choose a unique `Name` for your application
- In a few minutes, your application should be running at the URL you chose.
Now you have your code running locally and on the cloud!
The `IBM Eclipse Tools for Bluemix` provides many powerful features such as incremental updates, remote debugging, pushing packaged servers, etc. [Learn more](https://console.ng.bluemix.net/docs/manageapps/eclipsetools/eclipsetools.html#eclipsetools)
## 5. Add a database
Next, we'll add a NoSQL database to this application and set up the application so that it can run locally and on Bluemix.
1. Log in to Bluemix in your Browser. Select your application and click on `Connect new` under `Connections`.
2. Select `Cloudant NoSQL DB` and Create the service.
3. Select `Restage` when prompted. Bluemix will restart your application and provide the database credentials to your application using the `VCAP_SERVICES` environment variable. This environment variable is only available to the application when it is running on Bluemix.
## 6. Use the database
We're now going to update your local code to point to this database. We'll store the credentials for the services in a properties file. This file will get used ONLY when the application is running locally. When running in Bluemix, the credentials will be read from the VCAP_SERVICES environment variable.
1. In Eclipse, open the file src/main/resources/cloudant.properties:
```
cloudant_url=
```
2. In your browser open the Bluemix UI, select your App -> Connections -> Cloudant -> View Credentials
3. Copy and paste just the `url` from the credentials to the `url` field of the `cloudant.properties` file.
4. Your Liberty server in Eclipse should automatically pick up the changes and restart the application.
View your app at: http://localhost:9080/TestDashboard/. Any names you enter into the app will now get added to the database.
Make any changes you want and re-deploy to Bluemix!
Please follow me on Twitter: @blumareks
## Changes in the current version
### 1.1 added custom tags
Following the request to clear the index.jsp page from unnecessary the custom tag RefreshTimeTag has been created
(affected files: pom.xml, web.xml, index.jsp, refreshTime.tld, RefreshTimeTag.java, presentDashboard.tld, PresentDashboardTag.java).
<file_sep># MySQL Java test app
This application is designed to undertake CRUD operations on Compose MySQL app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava.
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaMySQL
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the Compose MySQL service and bind it with the Java Liberty App.
## 2. JVM System Properties for TLS/SSL connection to Compose MySQL
Identify the Compose MySQL connection URL and Certificate - find the link at the management console.
Therefore our application will need to set several JVM system properties to ensure that the client is able to validate the TLS/SSL certificate presented by the server.
Copy the certificate between lines: ```-----BEGIN CERTIFICATE-----``` and ```-----END CERTIFICATE-----``` into the file mysqlcert.crt (I usually use ```cat > mysqlcert.crt``` and control-C to exit editing).
javax.net.ssl.trustStore: The path to a trust store containing the certificate of the signing authority
javax.net.ssl.trustStorePassword: The password to access this trust store
The trust store is typically created with the keytool command line program provided as part of the JDK. For example:
keytool -importcert -trustcacerts -file <path to certificate authority file>
-keystore <path to trust store> -storepass <<PASSWORD>>
The command for our system is the following:
create the MySQLKey store:
**keytool -importcert -trustcacerts -file ./mysqlcert.crt -keystore ./mysqlKeyStore -storepass <PASSWORD>**
Place the mysqlKeyStore at this location: GetStartedJavaMySQL/src/main/resources/mysqlKeyStore
The document after the mvn install is going to be stored at this location:
wasdev.sample.store.MySQLVisitorStore at the createClient method
- locally: /your path to the target: GetStartedJavaMySQL/target/TestJavaMySQL-1.0-SNAPSHOT/WEB-INF/classes/mysqlKeyStore
- on Bluemix (after cf push command) : /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.war/WEB-INF/classes/mysqlKeyStore
A typical application will also need to set several JVM system properties to ensure that the client presents an TLS/SSL certificate to the MySQL server:
- javax.net.ssl.keyStore The path to a key store containing the client’s TLS/SSL certificates
- javax.net.ssl.keyStorePassword The password to access this key store
## 3. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 4. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaMySQL
random-route: true
path: target/TestJavaMongo.war
memory: 256M
instances: 1
name: test-java-MySQL
host: test-java-MySQL
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 5. Access the test MySQL application
Enter the name of the application and add the API call for the test:
```https://<yourappname>.mybluemix.net/TestJavaMongo/test/mysql/all```
You should be seeing something like this:
```javascript
{service: 'mysql', operations: [
{type: 'create', response_time: 40, response_code: 200, desc: {'visitor': '1509049042749,test case: 1509049042749'}},
{type: 'read', response_time: 22, response_code: 200, desc: {'visitor id': '92'}},
{type: 'update', response_time: 108, response_code: 200, desc: {'visitor': '92,test case2: 1509049042830'}},
{type: 'delete', response_time: 11, response_code: 200, desc: { 'deleted visitor id': '92'}}
], response_code: 200, desc:'operations implemented CRUD/CRUD'}
```
<file_sep>/**
*
*/
package com.ibm.dashboard.tag;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.ibm.dashboard.UrlResponse;
import com.ibm.dashboard.UrlResponseDoc;
import com.ibm.dashboard.singleton.DashboardData;
import com.ibm.dashboard.singleton.RefreshData;
import com.ibm.dashboard.store.UrlStatusPersisted;
import com.ibm.dashboard.store.UrlStatusPersistedStore;
import com.ibm.dashboard.store.UrlStatusPersistedStoreFactory;
/**
* @author mareksadowski
*
*/
public class PresentDashboardTag extends SimpleTagSupport {
// private String refreshTime;
//// TODO: CR 1.1 custom tag to replace the code
private String NUMBER_OF_DISPLAYED_RESULTS;// = 12;
private String TRESHOLD_TO_YELLOW;// = 1000;
/**
* @param nUMBER_OF_DISPLAYED_RESULTS
* the nUMBER_OF_DISPLAYED_RESULTS to set
*/
public void setNUMBER_OF_DISPLAYED_RESULTS(String nUMBER_OF_DISPLAYED_RESULTS) {
this.NUMBER_OF_DISPLAYED_RESULTS = nUMBER_OF_DISPLAYED_RESULTS;
System.out.println(
"PresentDashboard TAG: setting NUMBER_OF_DISPLAYED_RESULTS: " + this.NUMBER_OF_DISPLAYED_RESULTS);
}
/**
* @param tRESHOLD_TO_YELLOW
* the tRESHOLD_TO_YELLOW to set
*/
public void setTRESHOLD_TO_YELLOW(String tRESHOLD_TO_YELLOW) {
this.TRESHOLD_TO_YELLOW = tRESHOLD_TO_YELLOW;
System.out.println("PresentDashboard TAG: setting TRESHOLD_TO_YELLOW: " + this.TRESHOLD_TO_YELLOW);
}
public PresentDashboardTag() {
System.out.println("PresentDashboard TAG: the constructor");
}
@Override
public void doTag() throws JspException, IOException {
// tag comes here
System.out.println("PresentDashboard TAG: do tag = start with NUMBER_OF_DISPLAYED_RESULTS = " + NUMBER_OF_DISPLAYED_RESULTS
+ "Yellow " + TRESHOLD_TO_YELLOW );
int NUMBER_OF_DISPLAYED_RESULTS = Integer.parseInt(this.NUMBER_OF_DISPLAYED_RESULTS);
int TRESHOLD_TO_YELLOW = Integer.parseInt(this.TRESHOLD_TO_YELLOW);
JspWriter out = getJspContext().getOut();
DashboardData dashboardData = DashboardData.getInstance();
RefreshData refreshData = RefreshData.getInstance();
UrlStatusPersistedStore store = UrlStatusPersistedStoreFactory.getInstance();
if (store == null) {
System.out.println("PresentDashboard TAG: no store defined! Showing instructions to create Cloudant");
out.println("<br> NO STORE DEFINED - DEFINE LOCAL STORE IN WEB-INF/CLASSES/cloudant-properties \n"
+ "<br> OR BIND THE CLOUDANT DB TO THE SERVICE IF IT IS DEPLOYED ON BLUEMIX:\n"
+ "<br> cf create-service \"cloudantNoSQLDB Dedicated\" \"Shared Dedicated\" NAME_OF_THE_CLOUDANT_SERVICE\n"
+ "<br> cf bind-service NAME_OF_THIS_APPLICATION NAME_OF_THE_CLOUDANT_SERVICE\n" + " <br><br>");
} else {
String message2Print = "The next scheduled refresh will take place at " + dashboardData.nextRun
+ " Pacific time";
if (dashboardData.nextRun != null && dashboardData.nextRun != "") {
out.println("<br><b>" + message2Print + "</b><BR>");
}
// get the _id of the record from the url parameter :
// working with the dashboarddata singleton cache instead of pulling
// the data from DB direct
out.println("<table>");
// get the singleton
// get the latest json
// parse json
// TODO do only display of data
System.out.print("Refreshed the jsp page with urls: ");
for (UrlStatusPersisted doc : dashboardData.getUrls()) {
if (doc.getUrl() != null) {
out.println("<tr><td>\n" + doc.getName() + "</td>");
try {
// iterate through the statuses
// request to show only NUMBER_OF_DISPLAYED_RESULTS
int max = (doc.urlResponses).length;
// CR rev1.0 max 12 runs
if (max > NUMBER_OF_DISPLAYED_RESULTS) {
max = NUMBER_OF_DISPLAYED_RESULTS;
System.out.println("CR - showing only first " + NUMBER_OF_DISPLAYED_RESULTS + " calls");
}
// CR rev0.4 adding time counting in minutes
long time = 0;
String userInput = doc.urlTimes[0];
String expectedPattern = "yyyy-MM-dd HH:mm:SS z"; // from
// UrlStatus
SimpleDateFormat formatter = new SimpleDateFormat(expectedPattern);
// System.out.println("now time: ");
Date datetimeZero = new Date();
Date date;
String dateString = "";
long milisecondsZero = datetimeZero.getTime();
long milisecondsTest;
for (int i = 0; i < max; i++) {
// cr rev0.4 adding time...
try {
// (2) give the formatter a String that matches
// the SimpleDateFormat pattern
userInput = doc.urlTimes[i];
// System.out.println("old call time: ");
date = formatter.parse(userInput);
// rev 1.0 setting the refresh time
DateFormat df = new SimpleDateFormat("HH:mm");
df.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
dateString = df.format(date);
// (3) prints out "Tue Sep 22 00:00:00 EDT 2009"
// System.out.println(dateString);
} catch (Exception e) {
System.out.println(e);
date = datetimeZero;
}
milisecondsTest = date.getTime();
time = (milisecondsZero - milisecondsTest) / (1000 * 60);
// skip nulls
// TODO: remove initial nulls
if (doc.urlResponses[i] == null) {
// System.out.println("skipping null values");
} else if ("HTTP/1.1 200 OK".contentEquals(doc.urlResponses[i])) {
// CR rev1.1 skip pretty when there is an
// exception
// CR rev0.4 pretty forming information about
// the call
String prettyInfo = "";
String jsonString;
jsonString = doc.urlLogTails[i].replaceAll("\"", "'");
int totalResponseTime = 0;
try {
// 1 time - in minutes from the time 0
prettyInfo = "request date: " + doc.urlTimes[i] + "\n";
// 2 info on the seperate calls
prettyInfo = prettyInfo + "operation responses for: " + "\n";
// System.out.println("ok - for :"+
// jsonString);
UrlResponseDoc urlResponseDoc = new UrlResponseDoc(jsonString);
// UrlResponse[] urlResponses =
// urlResponseDoc.getOperationArray();
UrlResponse[] urlResponses = urlResponseDoc.getUrlResponses();
for (int y = 0; y < urlResponses.length; y++) {
prettyInfo = prettyInfo + "\n";
prettyInfo = prettyInfo + urlResponses[y].getType() + "\n";
prettyInfo = prettyInfo + " - time: " + urlResponses[y].getResponse_time()
+ "\n";
prettyInfo = prettyInfo + " - code: " + urlResponses[y].getResponse_code()
+ "\n";
prettyInfo = prettyInfo + " - details:"
+ urlResponses[y].getDescString().replaceAll("\"", "'") + "\n";
totalResponseTime = totalResponseTime + urlResponses[y].getResponse_time();
}
// before info: doc.urlTimes[i] + "\n" +
// doc.urlLogTails[i]
prettyInfo = "total response time: " + totalResponseTime + "\n" + prettyInfo;
// getting out a good response
// green under the treshold
// yellow outside of the treshold
out.println("<td align=center><img src="
+ ((totalResponseTime < TRESHOLD_TO_YELLOW) ? "'./img/ok.png' alt='ok' "
: "'./img/yellow.png' alt='too long' ")
+ "title=\"" + prettyInfo + "\" /><br>" + time + "<BR>" + dateString
+ " </td>");
} catch (Exception e) {
// TODO: CR 1.1 when there is a problem with
// the parsed json (gson exception etc do
// not fail the page
// there was an exception while parsing of
// the returned json
// just mark it yellow and get the json
// without parsing
System.out.println("pretty info exception - not parsing json for log no " + i);
e.printStackTrace();
jsonString = doc.urlLogTails[i].replaceAll("\'", "\\\'");
jsonString = jsonString.replaceAll("\"", "'");
prettyInfo = jsonString;
// there is an exception - so marking it
// yellow
out.println("<td align=center><img src="
+ "'./img/yellow.png' alt='exception while parsing' " + "title=\""
+ prettyInfo + "\" /><br>" + time + "<BR>" + dateString + " </td>");
}
} else {
System.out.println("fail - for " + i);
out.println("<td align=center><img src='./img/fail.png' alt='fail' title=\""
+ doc.urlTimes[i] + "\n" + doc.urlResponses[i] + "\" /><br> " + time + "<BR>"
+ dateString + "</td>");
// System.out.println("fail - for "+i);
}
}
} finally {
// System.out.println("end");
System.out.print(".");
}
out.println("</tr>");
}
}
}
out.println("</table>");
// System.out.println("custom tag --- end");
// TODO: CR 1.1 custom table builder tag --end
}
}
<file_sep>/**
*
*/
package com.ibm.dashboard;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* @author <NAME> <EMAIL>
* @since 20170309
*
*/
public class DashboardHttpClient {
CloseableHttpClient httpClient = null;
/**
* using https connections with NoopHostnameVerifier
*/
public DashboardHttpClient(SSLContext sslContext) {
httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
}
/**
* using http connections
*/
public DashboardHttpClient() {
httpClient = HttpClients.createDefault();
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
}
<file_sep>/**
*
*/
package com.ibm.dashboard;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* @author mareksadowski
*
*/
public class UrlResponseDoc {
String service;
JsonArray operations;
int response_code;
String desc;
UrlResponse[] urlResponses;
public UrlResponse[] getUrlResponses() {
return urlResponses;
}
/**
*
*/
public UrlResponseDoc() {
// TODO Auto-generated constructor stub
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public JsonArray getOperations() {
return operations;
}
public void setOperations(JsonArray operations) {
this.operations = operations;
}
public int getResponse_code() {
return response_code;
}
public void setResponse_code(int response_code) {
this.response_code = response_code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public UrlResponse[] getOperationArray(){
Gson gson = new Gson();
UrlResponse[] urlResponses = gson.fromJson(operations, UrlResponse[].class);
//System.out.println("found urlResponses with gson : " + urlResponses.length);
return urlResponses;
}
public UrlResponseDoc (String jsonString){
Gson gson = new Gson();
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
//System.out.println(jsonObject.get("service").getAsString());
this.service = jsonObject.get("service").getAsString();
//System.out.println(jsonObject.get("operations").getAsJsonArray());
this.operations = jsonObject.get("operations").getAsJsonArray();
//System.out.println(jsonObject.get("response_code").getAsInt());
//this.response_code = jsonObject.get("response_code").getAsInt();
//this.desc = jsonObject.get("desc").getAsString();
this.urlResponses = gson.fromJson(this.operations, UrlResponse[].class);
//System.out.println("size of the responses: " +urlResponses.length);
}
}
<file_sep>/**
*
*/
package com.ibm.dashboard;
import com.ibm.dashboard.rest.UrlStatusAPI;
/**
* @author mareksadowski
*
*/
public class UrlWriteStatus {
public UrlStatus urlStatus;
public UrlStatus writeNewStatus() {
UrlStatusAPI urlStatusAPI = new UrlStatusAPI();
UrlStatus newUrlStatus = urlStatusAPI.newUrlStatus(urlStatus);
urlStatus._id = newUrlStatus._id;
urlStatus._rev = newUrlStatus._rev;
urlStatus.urlResponses = newUrlStatus.urlResponses;
urlStatus.urlTimes = newUrlStatus.urlTimes;
urlStatus.urlLogTails = newUrlStatus.urlLogTails;
urlStatus.name = newUrlStatus.name;
urlStatus.isGet = newUrlStatus.isGet;
return urlStatus;
}
}
<file_sep>package wasdev.sample.model;
import io.searchbox.annotations.JestId;
/**
* @author ferhat
*/
public class Article {
// JestId is optional, use when you want to set a property as ElasticSearch index id
@JestId
private Long id;
private String author;
private String content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
<file_sep>/**
* Copyright 2015-2016 IBM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Licensed Materials - Property of IBM
* (c) Copyright IBM Corp. 2015-2016
*/
package com.messagehub.samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
//import org.apache.log4j.Level;
//import org.apache.log4j.//logger;
import com.messagehub.samples.bluemix.BluemixEnvironment;
import com.messagehub.samples.bluemix.MessageHubCredentials;
import com.messagehub.samples.rest.RESTAdmin;
import wasdev.sample.Visitor;
/**
* Console-based sample interacting with Message Hub, authenticating with
* SASL/PLAIN over an SSL connection.
*
* @author IBM
*/
@ApplicationPath("test")
@Path("/messagehub")
public class MessageHubConsoleSample extends Application {
private static final String APP_NAME = "myapp.war";//"test-java-messagehub";
private static final String DEFAULT_TOPIC_NAME = "test-java-messagehub-topic";
private static final String ARG_CONSUMER = "-consumer";
private static final String ARG_PRODUCER_ = "-producer";
private static final String ARG_TOPIC = "-topic";
String topicName = DEFAULT_TOPIC_NAME;
String user;
String password;
String bootstrapServers = "kafka03-prod01.messagehub.services.us-south.bluemix.net:9093,kafka01-prod01.messagehub.services.us-south.bluemix.net:9093,kafka05-prod01.messagehub.services.us-south.bluemix.net:9093,kafka02-prod01.messagehub.services.us-south.bluemix.net:9093,kafka04-prod01.messagehub.services.us-south.bluemix.net:9093";// args[0];bootstrapServers
// =
// null;
String adminRestURL = "https://kafka-admin-prod01.messagehub.services.us-south.bluemix.net:443";;
String apiKey = "<KEY>";
public static String messageHubProduceMessage = "{}";
public static String messageHubConsumeMessage = "{}";
public static String responseCreateTopic = "{}";
private static Thread consumerThread = null;
private static ConsumerRunnable consumerRunnable = null;
private static Thread producerThread = null;
private static ProducerRunnable producerRunnable = null;
private static String resourceDir;
public static boolean isTestOver = false;
public void setMessageHubProduceMessage(String msg){
this.messageHubProduceMessage = msg;
}
private static void printUsage() {
System.out.println("\n" + "Usage:\n" + " java -jar build/libs/" + APP_NAME + ".jar \\\n"
+ " <kafka_brokers_sasl> <kafka_admin_url> <api_key> [" + ARG_CONSUMER + "] \\\n"
+ " [" + ARG_PRODUCER_ + "] [" + ARG_TOPIC + "]\n" + "Where:\n" + " kafka_broker_sasl\n"
+ " Required. Comma separated list of broker endpoints to connect to, for\n"
+ " example \"host1:port1,host2:port2\".\n" + " kafka_admin_url\n"
+ " Required. The URL of the Message Hub Kafka administration REST endpoint.\n" + " api_key\n"
+ " Required. A Message Hub API key used to authenticate access to Kafka.\n" + " "
+ ARG_CONSUMER + "\n"
+ " Optional. Only consume message (do not produce messages to the topic).\n"
+ " If omitted this sample will both produce and consume messages.\n" + " " + ARG_PRODUCER_
+ "\n" + " Optional. Only produce messages (do not consume messages from the\n"
+ " topic). If omitted this sample will both produce and consume messages.\n" + " "
+ ARG_TOPIC + "\n" + " Optional. Specifies the Kafka topic name to use. If omitted the\n"
+ " default used is '" + DEFAULT_TOPIC_NAME + "'\n");
}
@POST
@Path("/all")
@Produces({ "application/json" })
@Consumes("application/json")
public String runTestPost(String string) {
System.out.println("got post req + " + string);
return runTest();
}
@GET
@Path("/all")
@Produces({ "application/json" })
public String runTest() { // static void main(String args[]) {
System.out.println("--------------------\nRunning in Message Hub.");
try {
final String userDir = System.getProperty("user.dir");
final boolean isRunningInBluemix = BluemixEnvironment.isRunningInBluemix();
final Properties clientProperties = new Properties();
boolean runConsumer = true;
boolean runProducer = true;
// Check environment: Bluemix vs Local, to obtain configuration
// parameters
if (isRunningInBluemix) {
//// logger.log(Level.INFO, "Running in Bluemix mode.");
System.out.println("Running in Bluemix mode.");
// ~/app/wlp/usr/servers/defaultServer/apps/myapp.war/WEB-INF/classes
resourceDir = userDir + File.separator + "apps" + File.separator + APP_NAME + File.separator + "WEB-INF" + File.separator
+ "classes";
MessageHubCredentials credentials = BluemixEnvironment.getMessageHubCredentials();
bootstrapServers = stringArrayToCSV(credentials.getKafkaBrokersSasl());
adminRestURL = credentials.getKafkaRestUrl();
apiKey = credentials.getApiKey();
user = credentials.getUser();
password = <PASSWORD>();
} else {
// If running locally
System.out.println("Running in local mode.");
resourceDir = userDir + File.separator + "apps" + File.separator + "MessageHubLibertyApp.war"
+ File.separator + "WEB-INF" + File.separator + "classes";
user = apiKey.substring(0, 16);
password = <PASSWORD>.substring(16);
}
// inject bootstrapServers in configuration, for both consumer and
// producer
clientProperties.put("bootstrap.servers", bootstrapServers);
System.out.println("Kafka Endpoints: " + bootstrapServers);
System.out.println("Admin REST Endpoint: " + adminRestURL);
responseCreateTopic = messageHubCreateTopic();
// create the Kafka clients
if (runConsumer) {
System.out.println("starting consumer");
Properties consumerProperties = getClientConfiguration(clientProperties, "consumer.properties", user,
password);
consumerRunnable = new ConsumerRunnable(consumerProperties, topicName);
consumerThread = new Thread(consumerRunnable, "Consumer Thread");
consumerThread.start();
}
if (runProducer) {
System.out.println("starting producer");
Properties producerProperties = getClientConfiguration(clientProperties, "producer.properties", user,
password);
producerRunnable = new ProducerRunnable(producerProperties, topicName);
producerThread = new Thread(producerRunnable, "Producer Thread");
producerThread.start();
}
System.out.println("MessageHubConsoleSample will run until interrupted.");
} catch (Exception e) {
System.out.println("Exception occurred, application will terminate" + e);
System.exit(-1);
}
System.out.println("-------------------------------entering loop!");
long startTime;
long endTime;
startTime = System.currentTimeMillis();
endTime = startTime;
while(((endTime-startTime)<5000)&&(!isTestOver)){
endTime = System.currentTimeMillis();
}
isTestOver = false;
System.out.println("-------------------------------Quitting");
String response = "{service: 'message-hub', operations: [" + responseCreateTopic + ","
+ messageHubProduceMessage + "," + messageHubConsumeMessage //+ "," + messageHubDeleteTopic()
+ "]"
+ ", response_code: 200, desc:'operations implemented CrPCo/CrPCoD'}";
shutdown();
return response;
}
private String messageHubCreateTopic() {
// TODO Auto-generated method stub
long responseTime = 0;
String responseCode = "200";
String responseDesc = "''";
long startTime;
long endTime;
// Using Message Hub Admin REST API to create and list topics
// If the topic already exists, creation will be a no-op
System.out.println("Creating the topic " + topicName);
String restResponse = "";
// timed operation
startTime = System.currentTimeMillis();
try {
// TODO: get the ObjectID
// end of timed operation
restResponse = RESTAdmin.createTopic(adminRestURL, apiKey, topicName);
} catch (Exception e) {
System.out.println("setting response code to 500; Error occurred accessing the Admin REST API " + e);
responseCode = "500";
restResponse = "Error occurred accessing the Admin REST API " + e;
// The application will carry on regardless of Admin REST errors, as
// the topic may already exist
}
endTime = System.currentTimeMillis();
System.out.println("Admin REST response :" + restResponse);
try {
String topics = RESTAdmin.listTopics(adminRestURL, apiKey);
System.out.println("Admin REST Listing Topics: " + topics);
} catch (Exception e) {
System.out.println("Error occurred accessing the Admin REST API " + e);
// The application will carry on regardless of Admin REST errors, as
// the topic may already exist
}
responseTime = (endTime - startTime);
if (restResponse.length()==0) {
restResponse = "no response - the topic has been already created";
}
responseDesc = "{'Admin REST response': '" + restResponse + "'}";
String responseString = "{type: 'create topic', response_time: " + responseTime + ", response_code: " + responseCode
+ ", desc: " + responseDesc + "}";
System.out.println(responseString);
return responseString;
}
/*
* convenience method for cleanup on shutdown
*/
private static void shutdown() {
if (producerRunnable != null)
producerRunnable.shutdown();
if (consumerRunnable != null)
consumerRunnable.shutdown();
if (producerThread != null)
producerThread.interrupt();
if (consumerThread != null)
consumerThread.interrupt();
}
/*
* Return a CSV-String from a String array
*/
private static String stringArrayToCSV(String[] sArray) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sArray.length; i++) {
sb.append(sArray[i]);
if (i < sArray.length - 1)
sb.append(",");
}
return sb.toString();
}
/*
* Retrieve client configuration information, using a properties file, for
* connecting to Message Hub Kafka.
*/
static final Properties getClientConfiguration(Properties commonProps, String fileName, String user,
String password) {
Properties result = new Properties();
InputStream propsStream;
// test file system:
//resourceDir = "...GetStartedJavaMessageHub/target/TestJavaMessageHub-1.0-SNAPSHOT/WEB-INF/classes";
System.out.println("reading prop file :" + resourceDir + File.separator + fileName);
try {
propsStream = new FileInputStream(resourceDir + File.separator + fileName);
result.load(propsStream);
propsStream.close();
} catch (IOException e) {
System.out.println("Could not load properties from file");
return result;
}
System.out.println("read prop file");
result.putAll(commonProps);
// Adding in credentials for MessageHub auth
String saslJaasConfig = result.getProperty("sasl.jaas.config");
saslJaasConfig = saslJaasConfig.replace("USERNAME", user).replace("<PASSWORD>", <PASSWORD>);
result.setProperty("sasl.jaas.config", saslJaasConfig);
return result;
}
}
<file_sep>package com.ibm.dashboard.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
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 com.ibm.dashboard.singleton.RefreshData;
/**
* Servlet implementation class PingHandler
*/
@WebServlet("/PingHandler")
public class PingHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PingHandler() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException
{
// liberty <webContainer deferServletLoad="false"/>
System.out.println("----------");
System.out.println("---------- init successfully ----------");
System.out.println("----------");
// TODO: rev0.4 self schedule from DB settings
RefreshData initRefreshScheduler = RefreshData.getInstance();
System.out.println("----------");
System.out.println("---------- Refresh Scheduler initialized successfully ----------");
System.out.println("----------");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.getWriter().append("{service: 'dashboard', operations:[], response_code: 200, desc:' Served at: ").append(request.getContextPath()).append("Error: no connection to Cloudant'}");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<file_sep>/*******************************************************************************
* Copyright (c) 2017 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package wasdev.sample.store;
import java.io.IOException;
import java.util.Arrays;
import org.apache.log4j.BasicConfigurator;
import com.google.gson.JsonObject;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.cluster.Health;
public class SearchlyJestStore {
private static JestClient client;
public SearchlyJestStore() {
if (client == null) {
client = jestClient();
}
}
public JestClient getClient() {
return client;
}
/**
* https://help.compose.com/v2.0/docs/elasticsearch-connecting-to-elasticsearch
*
* TODO: remove unnecessary create the key store: keytool -importcert
* -trustcacerts -file ./searchlycert.crt -keystore ./searchlyKeyStore
* -storepass aftereight
*
*
* The document is being stored at this location: locally: /your path to the
* target:
* GetStartedJavaMongoDb/target/TestJavaMongo-1.0-SNAPSHOT/WEB-INF/classes/mongoKeyStore
* on Bluemix:
* /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.war/WEB-INF/classes/mongoKeyStore
*
*
*/
private static JestClient jestClient() {
// TODO: upgrade the code to use the VCAP certificate for MongoDB
// System.setProperty("javax.net.ssl.trustStore",
// "/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.war/WEB-INF/classes/mongoKeyStore");
// uncomment this for local deployments:
// System.setProperty("javax.net.ssl.trustStore",
// "/Volumes/WD1TB/workspaceJee/GetStartedJavaMongoDb/target/TestJavaMongo-1.0-SNAPSHOT/WEB-INF/classes/mongoKeyStore");
// System.setProperty("javax.net.ssl.trustStorePassword", "<PASSWORD>");
// System.out.println("trustStore location: " +
// System.getProperty("javax.net.ssl.trustStore"));
// System.out.println("trustStorePassword: " +
// System.getProperty("javax.net.ssl.trustStorePassword"));
String url = "";
// connectionUrl = "http://site:your-api-key@your- url.searchly.com";
// //replace with the Connection URL
if (System.getenv("VCAP_SERVICES") != null) {
// When running in Bluemix, the VCAP_SERVICES env var will have the
// credentials for all bound/connected services
// Parse the VCAP JSON structure looking for searchly.
JsonObject searchlyCredentials = VCAPHelper.getCloudCredentials("compose-for-elasticsearch");
if (searchlyCredentials == null) {
System.out.println("No searchlyCredentials service bound to this application");
return null;
}
System.out.println(searchlyCredentials);
url = searchlyCredentials.get("uri").getAsString();
System.out.println("got searchlyCredentials credentials from VCAP: " + url);
} else {
System.out.println("Running locally. Looking for credentials in mongodb.properties");
url = VCAPHelper.getLocalProperties("searchly.properties").getProperty("searchly_url");
if (url == null || url.length() == 0) {
System.out.println(
"To use a searchly, set the ElasticSearch url in src/main/resources/searchly.properties");
return null;
}
}
try {
// shows connection process
BasicConfigurator.configure();
System.out.println("Connecting to compose " + url);
// start of Jest library methods
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig.Builder(Arrays.asList(
// Compose connection strings
// "https://username:password@portal113-2.latest-elasticsearch.compose-3.composedb.com:10113",
// "https://username:password@portal164-1.latest-elasticsearch.compose-3.composedb.com:10113"
url)).multiThreaded(true).build());
// Construct a new Jest client according to configuration via
// factory
System.out.println("Connected to Searchly ");
return factory.getObject();
} catch (Exception e) {
System.out.println("Unable to connect to compose");
e.printStackTrace();
return null;
}
}
}
<file_sep>package com.ibm.dashboard.servlet;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import com.cloudant.client.org.lightcouch.NoDocumentException;
import com.ibm.dashboard.singleton.DashboardData;
import com.ibm.dashboard.store.UrlStatusPersisted;
import com.ibm.dashboard.store.UrlStatusPersistedStore;
import com.ibm.dashboard.store.UrlStatusPersistedStoreFactory;
/**
* Servlet implementation class ModifyNewUrlFormHandler
*/
@WebServlet("/ModifyUrlFormHandler")
public class ModifyNewURLFormHandler extends HttpServlet {
private static String FORWARD_TO_PAGE = "/manageUrls.jsp";
UrlStatusPersistedStore store = UrlStatusPersistedStoreFactory.getInstance();
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ModifyNewURLFormHandler() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Modifying URL in the DB- Served at: ").append(request.getContextPath());
// TODO: rev0.4 table : do we modify or delete
String paramName = "modify";
//get the parameters
String id = request.getParameter(paramName);
if (id!= null && id != "") {
System.out.println(id);
//update the db
paramName = "url." + id;
String url = request.getParameter(paramName);
paramName = "get." + id;
Boolean isGet = "true".equalsIgnoreCase(request.getParameter(paramName));
paramName = "url_name." + id;
String urlName = request.getParameter(paramName);
paramName = "json.txt." + id;
String jsonText = request.getParameter(paramName);
System.out.println("url to modify: " + url);
System.out.println("url_name to modify: " + urlName);
System.out.println("isGet to modify: " + isGet);
System.out.println("json.text to modify: " + jsonText);
if (store == null) {
System.out.println("store is null!!!");
} else {
System.out.println("the store is not null.");
try {
UrlStatusPersisted urlStatusPersisted = store.get(id);
// TODO parse the sslOn status
urlStatusPersisted.sslOn = false;
//keeping old values
//urlStatusPersisted.setUrlLogTails(emptyArray);
//urlStatusPersisted.setUrlResponses(emptyArray);
//urlStatusPersisted.setUrlTimes(emptyArray);
urlStatusPersisted.url = url;
urlStatusPersisted.name = urlName;
urlStatusPersisted.isGet = isGet;
urlStatusPersisted.jsonText = jsonText;
store.update(id, urlStatusPersisted);
System.out.println("ModifyNewURLFormHandler: updated url..." + urlName + " , id: " + id);
// TODO: reset the cache
DashboardData dashboardData = DashboardData.getInstance();
dashboardData.resetUrls();
// TODO: rev1.0 add a message: Schedule changes will take effect at XX:XX:XXX Pacific time
// get the XX:XX:XXX Pacific time from the RefreshData
String modifyMessage = "The URL modified successfully. Changes will take effect at "
+ dashboardData.nextRun + " Pacific time";
// adding session
// Retrieve the current session. Create one if not exists
HttpSession session = request.getSession(true);
//adding the message
session.setAttribute("message", modifyMessage);
} catch (NoDocumentException e) {
System.out.println(e.getError());
}
}
} else {
// TODO: rev0.4 table : do we modify or delete
paramName = "delete";
//get the parameters
id = request.getParameter(paramName);
if (id!= null && id != "") {
System.out.println("ModifyNewURLFormHandler: url to delete: " + id);
if (store == null) {
System.out.println("ModifyNewURLFormHandler: store is null!!!");
} else {
System.out.println("ModifyNewURLFormHandler: the store is not null.");
try {
store.delete(id);
System.out.println("ModifyNewURLFormHandler: deleted url...");
// TODO: reset the cache
DashboardData dashboardData = DashboardData.getInstance();
dashboardData.resetUrls();
// TODO: rev1.0 add a message: Schedule changes will take effect at XX:XX:XXX Pacific time
// get the XX:XX:XXX Pacific time from the RefreshData
String deleteMessage = "The URL deleted successfully. Changes will take effect at "
+ dashboardData.nextRun + " Pacific time";
// adding session
// Retrieve the current session. Create one if not exists
HttpSession session = request.getSession(true);
//adding the message
session.setAttribute("message", deleteMessage);
} catch (NoDocumentException e) {
System.out.println(e.getError());
}
}
} else {
System.out.println("ModifyNewURLFormHandler: something went wrong id found in delete or modify ???");
}
}
//return back to the dashboard
//getting back to the page who potentially called this servlet
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(FORWARD_TO_PAGE);
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<file_sep># Redis Java test app
This application is designed to undertake several typical operations on Compose Redis app based on the Dedicated Bluemix (public Bluemix is also considered).
1. Please follow the below steps to deploy the app.
2. Please test the app
3. Please reference the app in the Test Dashboard app.
## Prerequisites
You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a Dedicated Bluemix - also you might want to test the environment with Public Bluemix: [Bluemix account](https://console.ng.bluemix.net/registration/).
This application is based on the github.com/IBM-Bluemix/GetStartedJava.
I used also information from http://www.baeldung.com/jedis-java-redis-client-library
## 1. Clone the sample app
Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located.
```bash
git clone https://github.com/blumareks/BluemixTestDashboard
cd BluemixTestDashboard/GetStartedJavaRedis
```
## 2. Create the necessary Bluemix App and Services
Login to the Bluemix console.
Create the Java Liberty App
Create the Compose Redis service and bind it with the Java Liberty App.
## 3. Make the app locally using MAVEN
Use Maven to install dependencies and build the .war file.
```
mvn clean install
```
## 4. Deploy to Bluemix using command line
To deploy to Bluemix using command line update manifest.yml file.
The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup.
The manifest.yml is provided in the sample.
```
---
applications:
- name: TestAppJavaRedis
random-route: true
path: target/TestJavaRedis.war
memory: 256M
instances: 1
name: test-java-redis
host: test-java-redis
```
Choose your API endpoint
```
cf api <API-endpoint>
```
Replace the *API-endpoint* in the command with an API endpoint from the following list of public Bluemix locations.
* https://api.ng.bluemix.net # US South
* https://api.eu-gb.bluemix.net # United Kingdom
* https://api.au-syd.bluemix.net # Sydney
* https://api.eu-de.bluemix.net # Germany
Login to your Bluemix account
```
cf login
```
Push your application to Bluemix.
```
cf push
```
This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.
## 5. Access the test Redis application
Enter the name of the application and add the API call for the test:
https://test-java-Redis.dys0.mybluemix.net/test/redis/all
You should be seeing something like this:
```javascript
{service: 'redis', operations: [
{type: 'create', response_time: 16, response_code: 200, desc: {'visitor': '1503895681168,test case: 1503895681168'}},
{type: 'read', response_time: 9, response_code: 200, desc: {'visitor id': '1503895681168'}},
{type: 'list push', response_time: 18, response_code: 200, desc: {'visitor pushed': '1503895681168,test case2: 1503895681272'}},
{type: 'list pop', response_time: 34, response_code: 200, desc: { 'list pop visitor id': '1503895681168'}},
{type: 'test sets', response_time: 344, response_code: 200, desc: {'visitor and setTests ': '1503895681376,test case: 1503895681376 size set 4 + it is there true'}}
], response_code: 200, desc:'operations implemented CRPPS/CRPPS HTPP-S'}
```
|
a1c0b15406aa41eea3e6572b4be1382e37bb9939
|
[
"Markdown",
"Java"
] | 21
|
Markdown
|
blumareks/BluemixTestDashboard
|
d32262c5dc207e6c489912a566c2dc2f17bdf9fa
|
57ec8bcdafb1b6cdd788ed0f1765d1f3592f0e07
|
refs/heads/master
|
<file_sep>import javax.annotation.CheckForNull;
class PreferZeroLengthArrays {
public int[] foo(int i) {
return null;
}
public int[] bar(int i) {
return new int[0];
}
@CheckForNull
public int[] fooCheckForNull(int i) {
return null;
}
}
|
4048efd638b30cd8a49ee74962af177420956353
|
[
"Java"
] | 1
|
Java
|
kozhukhin/findbugs
|
3873405c415bbd31e5fc19373866b63e3946c73a
|
20ba16e5e81fedb26dbe9d8fbd6e50efd6467782
|
refs/heads/master
|
<repo_name>HighDivineFox/Posi-Chess<file_sep>/Server_Functions/user_repository.js
import axios from 'axios';
const BASE_URL = 'http://192.168.0.2:5000';
export function getUser(data) {
return axios.get(`${BASE_URL}/api/v1/user/email/${data.email}/password/${data.password}`)
.then(response => response.data)
}
export function getUserByID(ID) {
return axios.get(`${BASE_URL}/api/v1/user/id/${ID}`)
.then(response => response.data)
}
export function createUser(data) {
return axios.post(`${BASE_URL}/api/v1/user/create`, data)
.then(response => response.data)
}
export function insertNewUserPosition(data) {
return axios.post(`${BASE_URL}/api/v1/user/savePos`, data)
.then(response => response.data)
}
export function updateExistingPosition(data) {
return axios.post(`${BASE_URL}/api/v1/user/updatePos`, data)
.then(response => response.data)
}
export function getUserLookingForGame() {
return axios.get(`${BASE_URL}/api/v1/user/looking`)
.then(response => response.data)
}
export function deleteUserPosition(data) {
return axios.post(`${BASE_URL}/api/v1/user/deletePos`, data)
.then(response => response.data)
}
export function getWhitePos(ID) {
return axios.get(`${BASE_URL}/api/v1/user/id/${ID}/whitepos`)
.then(response => response.data)
}
export function userExists(email) {
return axios.get(`${BASE_URL}/api/v1/user/email/${email}`)
.then(response => response.data)
}
export function doesUserExist(username, email) {
return axios.get(`${BASE_URL}/api/v1/user/username/${username}/email/${email}`)
.then(response => response.data)
}
export function addGameToHistory(data) {
return axios.post(`${BASE_URL}/api/v1/user/addGame`, data)
.then(response => response.data)
}<file_sep>/vue.config.js
module.exports = {
pages: {
'index': {
// entry for the page
entry: './src/pages/Home/main.js',
// the source template
template: 'public/index.html',
// when using title option,
// template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
title: 'Posi-Chess',
// chunks to include on this page, by default includes
// extracted common chunks and vendor chunks.
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
signup: 'src/pages/SignUp/main.js',
posmaker: 'src/pages/PosMaker/main.js',
creategame: 'src/pages/CreateGame/main.js',
battleboard: 'src/pages/BattleBoard/main.js'
}
}<file_sep>/api/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = Schema(
{
name: {type: String},
username: {type: String, required: true},
username_lower: {type: String, required: true},
email: {type: String, required: true},
password: {type: String, required: true},
rating: {type: Number, required: true},
activeGames: {type: Array},
gameHistory: {type: Array},
savedPositions: [
{
id: Schema.Types.ObjectId,
side: String,
pos: String,
points: Number
}
],
looking_for_game: {type: Boolean, required: true}
},
{ timestamps: true }
);
const User = mongoose.model("user", UserSchema);
module.exports = User;<file_sep>/Server_Functions/game_repository.js
import axios from 'axios';
const BASE_URL = 'http://192.168.0.2:5000';
export function getGame(ID) {
return axios.get(`${BASE_URL}/api/v1/game/id/${ID}`)
.then(response => response.data)
}
export function getGameWithPlayerID(ID) {
return axios.get(`${BASE_URL}/api/v1/game/playerId/${ID}`)
.then(response => response.data)
}
export function getOpenGames() {
return axios.get(`${BASE_URL}/api/v1/game/open`)
.then(response => response.data)
}
export function postGame(data) {
return axios.post(`${BASE_URL}/api/v1/game/create`, data)
.then(response => response.data)
}
export function deleteGame(ID) {
return axios.get(`${BASE_URL}/api/v1/game/delete/${ID}`)
.then(response => response.data)
}
export function joinGame(data) {
return axios.post(`${BASE_URL}/api/v1/game/join`, data)
.then(response => response.data)
}
export function updateStartPosInGame(data) {
return axios.post(`${BASE_URL}/api/v1/game/updatePos`, data)
.then(response => response.data)
}
export function connectToGame(data) {
return axios.post(`${BASE_URL}/api/v1/game/connect`, data)
.then(response => response.data)
}
export function updateFENInGame(data) {
return axios.post(`${BASE_URL}/api/v1/game/updateFEN`, data)
.then(response => response.data)
}
export function getFENForGame(data) {
return axios.get(`${BASE_URL}/api/v1/game/getFEN/${data}`)
.then(response => response.data)
}<file_sep>/api/server.js
'use strict';
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt')
// Models
const User = require('./user')
const Game = require('./game')
mongoose.set('useFindAndModify', false)
+mongoose.connect(
'mongodb+srv://Chris:BbSXLCX6YGzZJ1Zq@<EMAIL>/chess_app?retryWrites=true&w=majority',
{ useNewUrlParser: true, useCreateIndex: true, }
);
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
/////
// USER LOGIN
/////
app.get('/api/v1/user/email/:email/password/:password', (req, res) => {
User
.find({email: req.params.email})
.exec((err, user) => {
if(err) return res.status(404).send('Unable to find user')
if(user.length == 0){
return res.status(404).send("couldn't find user")
}
bcrypt.compare(req.params.password, user[0].password, (err, result) => {
if(err) return res.status(404).send('Not found')
if(result){
return res.send(user[0])
}else{
return res.status(404).send("Unable to log in")
}
})
})
})
/////
/// GET USER BY ID
////
app.get('/api/v1/user/id/:id', (req, res) => {
User
.find({_id: req.params.id})
.exec((err, user) => {
if(err) return res.status(404).send('Unable to find user')
return res.send(user[0])
})
})
/////
/// GET USER BY EMAIL
////
app.get('/api/v1/user/email/:email', (req, res) => {
User
.find({email: req.params.email})
.exec((err, user) => {
if(err) return res.status(404).send('Unable to find user')
if(user.length > 0){
return res.send(true)
}else{
return res.send(false)
}
})
})
/////
/// GET WHITE POSITIONS BY ID
////
app.get('/api/v1/user/id/:id/whitepos', (req, res) => {
User
.find({_id: req.params.id})
.exec((err, user) => {
if(err) return res.status(404).send('Unable to find user')
return res.send(user[0].savedPositions.filter(item => item.side == 'w'))
})
})
/////
/// CREATE NEW USER
/////
app.post('/api/v1/user/create', (req, res) => {
bcrypt.hash(req.body.password, 4)
.then((newPW) => {
const newUser = new User({
name: req.body.name,
username: req.body.username,
username_lower: req.body.username.toLowerCase(),
email: req.body.email.toLowerCase(),
password: <PASSWORD>,
rating: 1200,
activeGames: [],
gameHistory: [],
savePositions: [],
looking_for_game: false
})
newUser.save((err, user) => {
if (err) return res.status(404).send('Unable to create user')
return res.send(user)
})
})
})
/////
/// GET USER THAT IS LOOKING FOR A GAME
/////
app.get('/api/v1/user/looking', (req, res) => {
User
.find({looking_for_game: true})
.limit(1)
.exec((err, user) => {
if(err) return res.status(404).send('Unable to update user')
if(user.length == 0) return res.send(null)
return res.send(user[0])
})
})
/////
/// CHECK IF USER EXISTS OR NOT
/////
app.get('/api/v1/user/username/:username/email/:email', (req, res) => {
User
.find({$or: [
{username_lower: req.params.username.toLowerCase()},
{email: req.params.email.toLowerCase()}
]})
.exec((err, result) => {
if(err) /* User not found */ return res.status(404).send(false)
return res.send(result.length > 0)
})
})
/////
/// ADD TO SAVED POSITIONS
/////
app.post('/api/v1/user/savePos', (req, res) => {
let posOBj = {
side: req.body.side,
pos: req.body.pos,
points: req.body.points
}
User.findByIdAndUpdate(req.body.user_id, {$push: {savedPositions: posOBj}})
.exec((err, newUser) => {
if(err) return res.status(404).send('Unable to update user')
return res.send(true)
})
})
/////
/// UPDATE SAVED POSITION
/////
app.post('/api/v1/user/updatePos', (req, res) => {
User.updateOne({'savedPositions._id': req.body.pos_id}, {$set: {'savedPositions.$.pos': req.body.pos, 'savedPositions.$.side': req.body.side}})
.exec((err, newPos) => {
if(err) return res.status(404).send('Unable to remove position')
return res.send(true)
})
})
/////
/// ADD GAME TO HISTORY
/////
app.post('/api/v1/user/addGame', (req, res) => {
User.findByIdAndUpdate(req.body.user_Id, {$push: {gameHistory: req.body.game_Id}})
.exec((err, newUser) => {
if(err) return res.status(404).send('Unable to add game to history')
return res.send(true)
})
})
/////
/// REMOVE SAVED POSITION
/////
app.post('/api/v1/user/deletePos', (req, res) => {
User.findByIdAndUpdate(req.body.user_id, {$pull: {savedPositions: {_id: req.body.pos_id}}})
.exec((err, removedPos) => {
if(err) return res.status(404).send('Unable to remove position')
return res.send(true)
})
})
/////
/// GET GAME BY ID
////
app.get('/api/v1/game/id/:id', (req, res) => {
Game
.find({_id: req.params.id})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to find game')
return res.send(game[0])
})
})
/////
/// GET GAME WITH PLAYER ID
////
app.get('/api/v1/game/playerId/:id', (req, res) => {
Game
.find(
{$or:[
{whitePlayer: req.params.id},
{blackPlayer: req.params.id}
]
}
)
.exec((err, games) => {
if(err) return res.status(404).send('No games with this player')
return res.send(games)
})
})
/////
/// CREATE NEW GAME
////
app.post('/api/v1/game/create/', (req, res) => {
Game
.create({
PGN: null,
FEN: null,
pointAllowance: req.body.points || 15,
whitePlayer: req.body.whitePlayer,
blackPlayer: req.body.blackPlayer,
whiteStartPos: "",
blackStartPos: "",
whitePlayerConnected: false,
blackPlayerConnected: false,
ended: false,
result: "",
whiteTime: req.body.minutes || 5,
blackTime: req.body.minutes || 5
}, (err, game) => {
if(err) return res.status(404).send('Unable to create game')
return res.send(game)
})
})
/////
/// DELETE GAME
////
app.get('/api/v1/game/delete/:id', (req, res) => {
Game
.findByIdAndDelete(req.params.id)
.exec((err, result) => {
if(err) return res.status(404).send('Unable to delete game')
return res.send(true)
})
})
/////
/// JOIN GAME
////
app.post('/api/v1/game/join', (req, res) => {
if(req.body.whitePlayer){
Game
.findByIdAndUpdate(req.body.id, {whitePlayer: req.body.whitePlayer}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to join game')
return res.send(game)
})
}else if(req.body.blackPlayer){
Game
.findByIdAndUpdate(req.body.id, {blackPlayer: req.body.blackPlayer}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to join game')
return res.send(game)
})
}
})
/////
/// UPDATE START POSITION FOR PLAYER
/////
app.post('/api/v1/game/connect', (req, res) => {
if(req.body.whitePlayer){
Game
.findByIdAndUpdate(req.body.id, {whitePlayerConnected: true}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to connect to game')
return res.send(true)
})
}else if(req.body.blackPlayer){
Game
.findByIdAndUpdate(req.body.id, {blackPlayerConnected: true}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to connect to game')
return res.send(true)
})
}
})
/////
/// UPDATE START POSITION FOR PLAYER
/////
app.post('/api/v1/game/updatePos', (req, res) => {
//console.log(req.body);
if(req.body.side == 'white'){
Game.findByIdAndUpdate(req.body.id, {whiteStartPos: req.body.pos}, {new: true})
.exec((err, updatedGame) => {
if(err) return res.status(404).send('Unable to update position')
if(updatedGame.whiteStartPos != '' && updatedGame.blackStartPos != ''){
let combinedFEN = combineFEN(updatedGame.whiteStartPos, updatedGame.blackStartPos) + ' w KQkq - 0 1'
updatedGame['FEN'] = combinedFEN
Game
.findByIdAndUpdate(req.body.id, {FEN: combinedFEN}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to update position')
return res.send(game)
})
}else{
return res.send(updatedGame)
}
})
}else{
Game.findByIdAndUpdate(req.body.id, {blackStartPos: req.body.pos})
.exec((err, updatedGame) => {
if(err) return res.status(404).send('Unable to update position')
if(updatedGame.whiteStartPos != '' && updatedGame.blackStartPos != ''){
let combinedFEN = combineFEN(updatedGame.whiteStartPos, updatedGame.blackStartPos) + ' w KQkq - 0 1'
updatedGame['FEN'] = combinedFEN
Game
.findByIdAndUpdate(req.body.id, {FEN: combinedFEN}, {new: true})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to update position')
return res.send(game)
})
}else{
return res.send(updatedGame)
}
})
}
})
var combineFEN = function(whiteHalf, blackHalf){
//console.log(blackHalf);
let blackReg = /(^.{1,}\/.{1,}\/.{1,}\/.{1,}\/).\/.\/.\//
let whiteReg = /\/8\/8\/8(\/.{1,}\/.{1,}\/.{1,}\/.{1,})$/
let b = blackHalf.match(blackReg)
let w = whiteHalf.match(whiteReg)
//console.log(b[1]);
//console.log(w[1]);
let newPos = b[1].slice(0, -1) + w[1]
//console.log(newPos);
return newPos
}
/////
/// UPDATE GAME FEN
////
app.post('/api/v1/game/updateFEN/', (req, res) => {
Game
.findByIdAndUpdate(req.body.id, {FEN: req.body.fen})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to update FEN for game')
return res.send(true)
})
})
/////
/// GET FEN FOR GAME
////
app.get('/api/v1/game/getFEN/:id', (req, res) => {
Game
.findById(req.params.id)
.exec((err, game) => {
if(err) return res.status(404).send('Unable to get FEN')
return res.send(game.FEN)
})
})
/////
/// GET GAMES WITH ONLY ONE PLAYER THAT HAVEN'T ENDED
////
app.get('/api/v1/game/open', (req, res) => {
Game
.find(
{$or:
[
{
ended: false,
whitePlayer: ''
},
{
ended: false,
blackPlayer: ''
}
]
})
.exec((err, game) => {
if(err) return res.status(404).send('Unable to find game')
return res.send(game)
})
})
const PORT = 5000;
app.listen(PORT);
console.log('api running on port ' + PORT + ': ');
|
0f03ebc19fafb150e32c7cb94b545a6ca1ec9f93
|
[
"JavaScript"
] | 5
|
JavaScript
|
HighDivineFox/Posi-Chess
|
9fd10a0b9dda617b0e12432b1d524600a340d2ed
|
1946ea8fd9d54c31429bfc81ff2e7da970d2c886
|
refs/heads/master
|
<file_sep># for utilities
matplotlib
numpy
#gnuplot
<file_sep>This is a collection of tools, common things used by packages of material science.
Vis:
Contain a collection of matplotlib, pyplot, gnuplot methods
used for ploting common results from material science simulations.
Feel free to contribute
Intall
in the future:
pip install plot_methods
<file_sep># -*- coding: utf-8 -*-
"""
setup: usage: pip install -e .[graphs]
"""
from setuptools import setup, find_packages
if __name__ == '__main__':
setup(
name='masci_tools',
version='0.2.0',
description='Tools for Materials science. Vis contains wrapers of matplotlib functionality to visualalize common material science data. Plus wrapers of visualisation for aiida-fleur workflow nodes',
url='https://github.com/JuDFTteam/masci-tools',
author='<NAME>',
author_email='<EMAIL>',
license='MIT License, see LICENSE.txt file.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Physics'
],
keywords='material science plots fitting visualization aiida dft all-electron',
packages=find_packages(),
#['src', 'tests'],
include_package_data=True,
install_requires=[
'numpy',
'matplotlib',
],
)
|
3c2a15c2b29be89a8fce25c1694a5f480b103425
|
[
"Python",
"Text",
"reStructuredText"
] | 3
|
Text
|
be-zimmermann/masci-tools
|
fe9f6f3f8920796dc2364d9a8f669038b2797f31
|
e0ed4f2732170fd9ce7c701f2ebcead77d184faf
|
refs/heads/master
|
<repo_name>darthbatman/File-Synchronizer-Windows<file_sep>/Windows/directoryTest/directoryTest/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace directoryTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\files";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
FileAttributes attr;
try
{
attr = File.GetAttributes(e.FullPath);
}
catch (Exception ex)
{
Console.WriteLine(ex);
attr = FileAttributes.NoScrubData;
}
if (attr.HasFlag(FileAttributes.NoScrubData))
{
}
else if (attr.HasFlag(FileAttributes.Directory))
{
try
{
string relPath = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
string url = "http://192.168.1.119:8080/newfolder/" + relPath;
//richTextBox1.Text = richTextBox1.Text + url + "\n";
MessageBox.Show(url);
//MessageBox.Show(relPath);
//MessageBox.Show(relPath + " vs. " + e.Name);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
else
{
try
{
using (WebClient client = new WebClient())
{
string relPath = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
byte[] response = client.UploadFile("http://192.168.1.119:8080/create/" + relPath, e.FullPath);
//richTextBox1.Text = richTextBox1.Text + "http://192.168.1.119:8080/create/" + relPath + " with file: " + e.FullPath + "\n";
string result = Encoding.UTF8.GetString(response);
Console.WriteLine(response);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
}
else if (e.ChangeType == WatcherChangeTypes.Changed)
{
FileAttributes attr;
try
{
attr = File.GetAttributes(e.FullPath);
}
catch (Exception ex)
{
Console.WriteLine(ex);
attr = FileAttributes.NoScrubData;
}
if (!attr.HasFlag(FileAttributes.Directory))
{
try
{
using (WebClient client = new WebClient())
{
string relPath = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
byte[] response = client.UploadFile("http://192.168.1.119:8080/create/" + relPath, e.FullPath);
//richTextBox1.Text = richTextBox1.Text + "http://192.168.1.119:8080/create/" + relPath + " with file: " + e.FullPath + "\n";
string result = Encoding.UTF8.GetString(response);
Console.WriteLine(response);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
}
else if (e.ChangeType == WatcherChangeTypes.Deleted)
{
if (!e.FullPath.ToString().Contains("."))
{
try
{
string relPath = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
string url = "http://192.168.1.119:8080/deletedir/" + relPath;
//richTextBox1.Text = richTextBox1.Text + url + "\n";
//MessageBox.Show(url);
//MessageBox.Show(relPath);
//MessageBox.Show(relPath + " vs. " + e.Name);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
else
{
try
{
string relPath = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
string url = "http://192.168.1.119:8080/delete/" + relPath;
//richTextBox1.Text = richTextBox1.Text + url + "\n";
//MessageBox.Show(url);
//MessageBox.Show(relPath);
//MessageBox.Show(relPath + " vs. " + e.Name);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
}
}
private void OnRenamed(object source, RenamedEventArgs e)
{
try
{
string relPathOld = (e.OldFullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
string relPathNew = (e.FullPath).Replace((Path.GetDirectoryName(Application.ExecutablePath) + "\\files\\"), "").Replace("\\", "|");
string url = "http://192.168.1.119:8080/rename/" + relPathOld + "/" + relPathNew;
//richTextBox1.Text = richTextBox1.Text + url + "\n";
//MessageBox.Show(url);
//MessageBox.Show(relPathOld + "****" + relPathNew);
//MessageBox.Show(relPath + " vs. " + e.Name);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception ex)
{
Console.WriteLine(ex);
OnChanged(source, e);
}
}
}
}
<file_sep>/Windows/directoryTest/directoryTest/bin/Debug/index.js
var app = require("express")();
var http = require("http").Server(app);
var fs = require("fs-extra");
var path = require('path');
var chokidar = require('chokidar');
var busboy = require('connect-busboy');
var mkdirp = require('mkdirp');
app.use(busboy());
app.use(require("express").static(path.join(__dirname, 'public')));
app.get("/", function(req, res){
res.send("<h1>Welcome to homeFileSyncTest</h1>");
});
app.post("/create/:relpath", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
//console.log(req.params.relpath.toString().replace(/\|/g, "\\"));
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
//console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + (req.params.relpath.toString().replace(/\|/g, "\\")));
file.pipe(fstream);
fstream.on('close', function () {
//console.log("Upload Finished of " + filename);
res.send('create complete'); //where to go next
});
});
});
app.post("/newdir", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
//console.log("Uploading: " + filename);
mkdirp(__dirname + "/files/" + filename.split('.')[0], function(err) {
//console.log(__dirname + "/" + filename.split('.')[0]);
});
res.send("new dir");
});
});
app.get("/newfolder/:folder", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
//console.log(req.params.folder);
//console.log(req.params.folder.toString().replace(/\|/g, "\\"));
mkdirp(__dirname + "/files/" + req.params.folder.toString().replace(/\|/g, "\\"), function(err) {
//console.log(__dirname + "/" + req.params.folder.toString().replace(/\|/g, "\\"));
res.send("new folder");
});
});
app.get("/rename/:oldfilename/:newfilename", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
//console.log(req.params.oldfilename.toString().replace(/\|/g, "\\") + " should be renamed to " + req.params.newfilename.toString().replace(/\|/g, "\\"));
fs.rename(__dirname + "/files/" + req.params.oldfilename.toString().replace(/\|/g, "\\"), __dirname + "/files/" + req.params.newfilename.toString().replace(/\|/g, "\\"), function(err){
//console.log("renamed");
});
res.send("rename");
});
app.get("/delete/:filename", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
//console.log(req.params.filename.toString().replace(/\|/g, "\\") + " should be deleted");
fs.unlink(__dirname + "/files/" + req.params.filename.toString().replace(/\|/g, "\\"), function(err){
if (!err) {
//console.log("deleted");
}
else {
//console.log(err);
}
});
res.send("delete");
});
app.get("/deletedir/:foldername", function(req, res){
console.log(req.protocol + '://' + req.get('host') + req.originalUrl);
//console.log("delete " + req.params.foldername.toString().replace(/\|/g, "\\"));
deleteFolderRecursive(__dirname + "/files/" + req.params.foldername.toString().replace(/\|/g, "\\"));
res.send("delete dir");
});
var deleteFolderRecursive = function(path){
if (fs.existsSync(path)){
fs.readdirSync(path).forEach(function(file, index){
var curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()){
deleteFolderRecursive(curPath);
}
else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
http.listen(8080, function(){
console.log("Listening on *:8080");
});<file_sep>/README.md
# File-Synchronizer-Windows
Synchronizes files between computers or folders. For Windows.
|
bb2a73f1b7d47f33f5f64626bb0da94d27c98cb5
|
[
"JavaScript",
"C#",
"Markdown"
] | 3
|
C#
|
darthbatman/File-Synchronizer-Windows
|
8a1dca2d353fd5a4e9e1c1b3e527a843a29cc36a
|
9a6b1709e1bb4631d831ae5e0a9d00a5d13abd70
|
refs/heads/master
|
<repo_name>Vasserman2000/angular-2-play-ground<file_sep>/src/app/child-two.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'child-two',
template: `
<span id="data">Child two says: this is from child one: {{ data }}</span>
`,
styles: ['#data {color: blue; font-weight: bold;}']
})
export class ChildTwo implements OnInit{
@Input() ChildOneToChildTwo : string;
data : string = 'data' ;
message: string = 'Hello dear brother!! How are you?';
ngOnInit() {
this.data = this.ChildOneToChildTwo;
}
sum (num1: number, num2: number) : number {
if (num1 && num2) {
return num1 + num2;
} else {
return 0;
}
}
}
<file_sep>/src/app/app.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<child-one
[parentToChildOne]="title"
[num1]="x"
[num2]="y"
(message)='readMessageFromChildOne($event)'></child-one>
<br>
<strong>X</strong>: {{x}}<br>
<strong>Y</strong>: {{y}}
`,
styles: []
})
export class AppComponent {
title = 'שלום';
x: number = 4;
y: number = 9;
constructor () {
setInterval(() => {
this.x++;
this.y++;
}, 1000);
}
readMessageFromChildOne(event) {
alert(event);
}
}
<file_sep>/src/app/child-one.component.ts
import { Component, Input, OnInit, OnChanges, SimpleChange, Output, EventEmitter, ViewChild } from '@angular/core';
import { ChildTwo } from './child-two.component';
@Component({
selector: 'child-one',
template: `
<span id="name">Child one says: this is from parent: {{ title }}</span> <br>
<button (click)="sendMessageToParent()">Click me to see the message from child 1</button>
<br>
<child-two [ChildOneToChildTwo]="title" #brother></child-two>
<br>
<p>{{brother.message}}</p>
<p>Sum result from brother component: {{sumResult}}
`,
styles: ['#name {color: red; font-weight: bold;}']
})
export class ChildOne implements OnInit, OnChanges {
@Input() parentToChildOne : string;
@Input() num1 : number;
@Input() num2 : number;
@Output() message = new EventEmitter<string>();
@ViewChild(ChildTwo) private brother: ChildTwo;
sumResult: number;
title : string = 'Page' ;
changeLog: string[] = [];
constructor() {
}
ngOnInit() {
this.title = this.parentToChildOne;
console.log(this.title);
this.sumResult = this.brother.sum(8, 13);
}
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
let log: string[] = [];
for (let propName in changes) {
let changedProp = changes[propName];
let to = JSON.stringify(changedProp.currentValue);
if (changedProp.isFirstChange()) {
log.push(`Initial value of ${propName} set to ${to}`);
} else {
let from = JSON.stringify(changedProp.previousValue);
log.push(`${propName} changed from ${from} to ${to}`);
}
}
this.changeLog.push(log.join(', '));
}
sendMessageToParent() {
this.message.emit('Hello dear parent, this is the message from your first child!');
}
}
|
e95d02af008c08bc912b651dcaed895297b06460
|
[
"TypeScript"
] | 3
|
TypeScript
|
Vasserman2000/angular-2-play-ground
|
8723423226d5a59d31e0d97fcb5d7ee8b44e8e44
|
2746b2c2bf1656407d2dadaff14b029502ab5bb8
|
refs/heads/master
|
<repo_name>vans0011/mp2-lab4-queue<file_sep>/test/test_queue.cpp
#include <gtest.h>
#include "tqueue.h"
TEST(TQueue, can_create_queue_with_positive_length)
{
ASSERT_NO_THROW(TQueue q1(5));
}
TEST(TQueue, cant_create_queue_with_negative_length)
{
ASSERT_ANY_THROW(TQueue q1(-5););
}
TEST(TQueue, get_element_is_correct)
{
TQueue q1(5);
q1.Put(1);
q1.Put(2);
ASSERT_EQ(1, q1.Get());
}
TEST(TQueue, can_get_element)
{
TQueue q1(5);
q1.Put(1);
ASSERT_NO_THROW(q1.Get());
}
TEST(TQueue, top_element_is_different_after_get)
{
TQueue q1(5);
q1.Put(1);
q1.Put(2);
q1.Get();
ASSERT_EQ(2, q1.TopElem());
}
TEST(TQueue, get_element_after_get_and_put_is_correct)
{
TQueue q1(5);
q1.Put(1);
q1.Put(2);
q1.Put(3);
q1.Get();
q1.Get();
q1.Get();
q1.Put(10);
ASSERT_EQ(10, q1.Get());
}
TEST(TQueue, top_elem_doesnt_delete_element)
{
TQueue q1(5);
q1.Put(1);
q1.Put(2);
q1.TopElem();
ASSERT_EQ(1, q1.TopElem());
}
TEST(TQueue, can_put_element)
{
TQueue q1(5);
ASSERT_NO_THROW(q1.Put(1));
}
TEST(TQueue, can_put_multiple_times)
{
TQueue q1(5);
q1.Put(1);
q1.Put(2);
q1.Put(3);
ASSERT_NO_THROW(q1.Put(2));
}
TEST(TQueue, put_element_is_correct)
{
TQueue q1(5);
q1.Put(1);
ASSERT_EQ(1, q1.Get());
}
TEST(TQueue, element_cant_change_when_put_element_in_full_queue)
{
TQueue q1(2);
q1.Put(1);
q1.Put(2);
q1.Put(3);
q1.Get();
ASSERT_EQ(2, q1.TopElem());
}
<file_sep>/src/tproc.cpp
#include <iostream>
#include "tproc.h"
using namespace std;
TProc::TProc(double q) :q2(q)
{}
bool TProc::IsFree()
{
return state;
}
bool TProc::IsDone()
{
double r = (rand() / (double)(RAND_MAX + 1));
if (r <= q2)
return 1;
else
return 0;
}
void TProc::StartJob()
{
state = 0;
}
void TProc::EndJob()
{
state = 1;
}<file_sep>/include/tqueue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include "tstack.h"
class TQueue : public TStack
{
public:
int Li;
int Hi;
TQueue(int Size = DefMemSize);
~TQueue() {};
TData Get();
void Put(const TData &Val);
TData TopElem();
int GetNextIndex(int ind);
};
#endif <file_sep>/src/tqueue.cpp
#include "tqueue.h"
using namespace std;
TQueue::TQueue(int Size) :TStack(Size), Li(-1), Hi(-1)
{}
TData TQueue::Get()
{
if (pMem == nullptr)
SetRetCode(DataNoMem);
else if (IsEmpty())
SetRetCode(DataEmpty);
else
{
--DataCount;
Li = GetNextIndex(Li);
return pMem[Li];
}
}
void TQueue::Put(const TData &Val)
{
if (pMem == nullptr)
SetRetCode(DataNoMem);
else if (IsFull())
SetRetCode(DataFull);
else
{
++DataCount;
Hi = GetNextIndex(Hi);
pMem[Hi] = Val;
}
}
TData TQueue::TopElem()
{
if (pMem == nullptr)
{
SetRetCode(DataNoMem);
return -1;
}
else if (IsEmpty())
{
SetRetCode(DataEmpty);
return -1;
}
else
{
return pMem[GetNextIndex(Li)];
}
}
int TQueue::GetNextIndex(int index)
{
return (index + 1) % MemSize;
}<file_sep>/samples/main.cpp
#include <iostream>
#include "tqueue.h"
#include "tjobstream.h"
#include "tproc.h"
using namespace std;
int main()
{
int tactNum = 100, qSize = 10;
double q1 = 0.5, q2 = 0.3 ;
TJobStream w(q1);
TProc p(q2);
TQueue q(qSize);
int Alltasks = 0;
int DoneTasks = 0;
int NotFitJobs = 0;
int DownT = 0;
int UnprocessedTask = 0;
for (int i = 0; i < tactNum; i++){
if (w.NewJob()) {
Alltasks++;
if (q.IsFull()){
NotFitJobs++;
}
else{
q.Put(w.GetNum());
}
}
if (p.IsFree())
{
if (q.IsEmpty())
{
DownT++;
}
else{
q.Get();
p.StartJob();
}
}
else{
if (p.IsDone())
{
p.EndJob();
DoneTasks++;
if (q.IsEmpty())
DownT++;
else
{
q.Get();
p.StartJob();
}
}
}
}
while (!q.IsEmpty()){
UnprocessedTask++;
q.Get();
}
cout << "All jobs: " << Alltasks << endl;
cout << "Jobs Completed: " << DoneTasks << ", that is " << ((double)DoneTasks / (double)Alltasks) * 100 << "%" << endl;
cout << "Jobs rejected: " << NotFitJobs << ", that is " << (double)NotFitJobs / (double)Alltasks * 100 << "%" << endl;
cout << "Jobs unprocessed:" << UnprocessedTask << ", that is " << (double)UnprocessedTask / (double)Alltasks * 100 << "%" << endl;
cout << "Time for 1 job:" << (double)tactNum / (double)DoneTasks << " tacts" << endl;
cout << "Processor downtime:" << DownT << ", that is " << (double)DownT / (double)tactNum * 100 << "%" << endl;
return 0;
}<file_sep>/src/tjobstream.cpp
#include "tjobstream.h"
#include <iostream>
using namespace std;
TJobStream::TJobStream(double q) : q1(q)
{}
bool TJobStream::NewJob()
{
double r = (rand() / (double)(RAND_MAX + 1));
if (r <= q1)
{
jobNum++;
return 1;
}
else
return 0;
}
int TJobStream::GetNum()
{
return jobNum;
}<file_sep>/include/tjobstream.h
#ifndef __JOBSTREAM_H__
#define __JOBSTREAM_H__
class TJobStream
{
public:
double q1;
int jobNum = 1;
TJobStream(double q = 0.5);
bool NewJob();
int GetNum();
};
#endif<file_sep>/include/tproc.h
#ifndef __PROC_H__
#define __PROC_H__
class TProc {
private:
double q2;
bool state; // 1 = free, 0 = busy
public:
TProc(double q = 0.5);
bool IsFree();
bool IsDone();
void StartJob();
void EndJob();
};
#endif<file_sep>/src/tstack.cpp
#include <iostream>
#include "tstack.h"
using namespace std;
TStack::TStack(int Size) : TDataRoot(Size), top(-1)
{}
void TStack::Put(const TData &Val)
{
if (pMem == nullptr)
SetRetCode(DataNoMem);
else if (IsFull())
SetRetCode(DataFull);
else
{
pMem[++top] = Val;
DataCount++;
}
}
TData TStack::Get()
{
if (pMem == nullptr)
SetRetCode(DataNoMem);
else if (IsEmpty())
SetRetCode(DataEmpty);
else
{
DataCount--;
return pMem[top--];
}
}
TData TStack::TopElem()
{
if (pMem == nullptr)
{
SetRetCode(DataNoMem);
return -1;
}
else if (IsEmpty())
{
SetRetCode(DataEmpty);
return -1;
}
else
return pMem[top];
}
int TStack::IsValid()
{
return GetRetCode();
}
void TStack::Print()
{
for (int i = 0; i<DataCount; i++)
cout << pMem[i] << " ";
cout << endl;
}
|
96b145f4c98cb0da35bf9c41cfc0f36bcea5be1e
|
[
"C++"
] | 9
|
C++
|
vans0011/mp2-lab4-queue
|
4480f720854d6cec7076db827f928a2ae3bae7dc
|
213dbc58185cee90655832ec5bad06701320f30e
|
refs/heads/master
|
<file_sep>#ifndef INTERSECTIONS_H
#define INTERSECTIONS_H
#include "Math.h"
#include "Object.h"
#include <iostream>
using namespace std;
struct Ray
{
XMFLOAT3 origin;
XMFLOAT3 direction;
Ray(XMFLOAT3 origin, XMFLOAT3 direction)
{
this->origin = origin;
this->direction = direction;
}
};
struct Sphere
{
XMFLOAT3 center;
float radius;
Sphere(XMFLOAT3 center, float radius)
{
this->center = center;
this->radius = radius;
}
};
struct Plane
{
DirectX::XMFLOAT3 normal;
float d;
Plane()
{
this->normal = XMFLOAT3(0, 0, 0);
this->d = 0.0f;
};
Plane(XMFLOAT3 normal, float d)
{
this->normal = normal;
this->d = d;
}
};
struct Triangle
{
XMFLOAT3 p0, p1, p2;
Triangle(XMFLOAT3 p0, XMFLOAT3 p1, XMFLOAT3 p2)
{
this->p0 = p0;
this->p1 = p1;
this->p2 = p2;
}
};
static bool RayVsSphere(Ray& ray, Sphere& sphere, float& distance)
{
bool hit = false;
XMFLOAT3 v = Subtract3(ray.origin, sphere.center);
float b = DotProduct3(ray.direction, v);
float c = DotProduct3(v, v) - sphere.radius*sphere.radius;
float discriminant = b*b - c;
//Discriminant has to be > 0 to avoid complex numbers
if (discriminant > 0.0f)
{
//Calculate both points of intersection.
float returnValue = -1.0f;
float t1 = -b + sqrt(discriminant);
float t2 = -b - sqrt(discriminant);
if (t1 < t2 && t1 > 0)
returnValue = t1;
else
returnValue = t2;
distance = returnValue;
hit = true;
}
return hit;
}
static bool RaySphereIntersect(XMFLOAT3 rayOrigin, XMFLOAT3 rayDirection, float radius, float& distance)
{
bool hit = false;
// Calculate the a, b, and c coefficients.
float a = (rayDirection.x * rayDirection.x) + (rayDirection.y * rayDirection.y) + (rayDirection.z * rayDirection.z);
float b = ((rayDirection.x * rayOrigin.x) + (rayDirection.y * rayOrigin.y) + (rayDirection.z * rayOrigin.z)) * 2.0f;
float c = ((rayOrigin.x * rayOrigin.x) + (rayOrigin.y * rayOrigin.y) + (rayOrigin.z * rayOrigin.z)) - (radius * radius);
// Find the discriminant.
float discriminant = (b * b) - (4 * a * c);
// if discriminant is negative the picking ray missed the sphere, otherwise it intersected the sphere.
if (discriminant > 0.0f)
{
//Calculate both points of intersection.
float returnValue = -1.0f;
float t1 = -b + sqrt(discriminant);
float t2 = -b - sqrt(discriminant);
if (t1 < t2 && t1 > 0)
returnValue = t1;
else
returnValue = t2;
distance = returnValue;
hit = true;
}
return hit;
}
static bool RayVsTriangle(Ray& ray, Triangle& triangle)
{
float ALMOST_INFINITY = 10000000000000000.0f;
float EXTREMELY_SMALL = 0.00000000000000001f;
bool hit = false;
XMFLOAT3 e1 = Subtract3(triangle.p1, triangle.p0);
XMFLOAT3 e2 = Subtract3(triangle.p2, triangle.p0);
XMFLOAT3 m = CrossProduct3(ray.direction, e2);
//e1*(d x e2) = determinant
float det = DotProduct3(e1, m);
if (det < -EXTREMELY_SMALL || det > EXTREMELY_SMALL)
{
float f = 1 / det;
XMFLOAT3 s = Subtract3(ray.origin, triangle.p0);
// 1/det * det(s,d,e2)
float u = f * DotProduct3(s, m);
if (u > 0.0f)
{
XMFLOAT3 n = CrossProduct3(s, e1);
// 1/det * det(s,d,e1)
float v = f * DotProduct3(ray.direction, n);
if (v > 0.0f && u + v < 1.0f)
{
// 1/det * det(d,e1,e2)
float w = f * DotProduct3(e2, n);
//Intersects at (u,v,w)
hit = true;
}
}
}
return hit;
}
static float PlaneVsPoint(Plane plane, XMFLOAT3 point)
{
return plane.normal.x*point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.d;
}
#endif
<file_sep>#include "BoundingBox.h"
using namespace std;
using namespace DirectX;
BoundingBox::BoundingBox()
{
this->position = XMFLOAT2(0, 0);
this->size = XMFLOAT2(0, 0);
}
BoundingBox::BoundingBox(XMFLOAT2 position, XMFLOAT2 size)
{
this->position = position;
this->size = size;
}
BoundingBox::~BoundingBox()
{
}
XMFLOAT2 BoundingBox::GetPosition()
{
return position;
}
XMFLOAT2 BoundingBox::GetSize()
{
return size;
}
BoundingBox BoundingBox::GetChildBoundingBox(int childQuadrant)
{
XMFLOAT2 childPosition;
XMFLOAT2 childSize = XMFLOAT2(size.x / 2, size.y / 2);
switch (childQuadrant)
{
case 0:
childPosition = XMFLOAT2(position.x + size.x / 2, position.y + size.y / 2);
break;
case 1:
childPosition = XMFLOAT2(position.x, position.y + size.y / 2);
break;
case 2:
childPosition = XMFLOAT2(position.x, position.y);
break;
case 3:
childPosition = XMFLOAT2(position.x + size.x / 2, position.y);
break;
default:
break;
}
return BoundingBox(childPosition, childSize);
}<file_sep>#pragma once
#include <DirectXMath.h>
struct VertexPosUV
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 uv;
};
struct Vertex
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 uv;
DirectX::XMFLOAT3 normal;
};<file_sep>#pragma once
#include "ShaderBase.h"
using namespace DirectX;
class ShaderShadowMap
{
private:
struct MatrixBuffer
{
XMMATRIX lightWVP;
XMFLOAT3 lightPos;
float padding;
};
int width, height;
ID3D11Texture2D* shadowMap;
ID3D11DepthStencilView* shadowMapDepthView;
ID3D11ShaderResourceView* shadowMapSRV;
D3D11_VIEWPORT shadowMapViewport;
float shadowMapBias;
ID3D11RasterizerState* rasterizerState;
ID3D11DepthStencilState* depthStencilState;
ID3D11VertexShader* vertexShader;
ID3D11Buffer* matrixBuffer;
ID3D11InputLayout* inputLayout;
public:
ShaderShadowMap(ID3D11Device* device, LPCWSTR vertexShaderFilename, int width, int height, float bias);
virtual ~ShaderShadowMap();
void UseShader(ID3D11DeviceContext* deviceContext);
void SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& lightWVP, XMFLOAT3 lightPos);
ID3D11ShaderResourceView* GetShadowSRV();
int GetSize();
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <windows.h>
#include <stdexcept>
class Timer
{
private:
INT64 frequency;
float ticksPerMs;
INT64 startTime;
float frameTime;
public:
Timer();
~Timer();
void Update();
float GetTime();
};
<file_sep>#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <DirectXMath.h>
#include "Object.h"
#include "BoundingBox.h"
#include "ShaderDefault.h"
#include "Intersections.h"
class Quadtree
{
private:
class Node
{
public:
Node();
~Node();
Node* child[4];
std::vector<Object*> objects;
};
Node* root;
BoundingBox rootBoundingBox;
const int MAX_DEPTH = 4;
public:
Quadtree(BoundingBox rootBoundingBox);
Quadtree(ID3D11Device* device, std::string filename);
~Quadtree();
void Render(ID3D11DeviceContext* deviceContext, ShaderDefault* shader, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix);
void Render(ID3D11DeviceContext* deviceContext, Node* currentNode, BoundingBox box, ShaderDefault* shader, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, int& modelsRendered);
private:
void Clean(Node* currentNode);
Node* ReadNode(ID3D11Device* device, std::ifstream& file);
int PlanesVsPoints(Plane planes[], DirectX::XMFLOAT3 points[]);
};
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <d3dcompiler.h>
#include <stdexcept>
#include "Deferred.h"
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dcompiler.lib")
class D3DClass
{
private:
IDXGISwapChain* swapChain;
ID3D11Device* device;
ID3D11DeviceContext* deviceContext;
ID3D11RenderTargetView* renderTargetView;
D3D11_VIEWPORT viewport;
Deferred* deferredShader;
ID3D11DepthStencilView* depthStencilView;
ID3D11Texture2D* depthStencilBuffer;
ID3D11RasterizerState* rasterState;
ID3D11RasterizerState* rasterNoCullingState;
ID3D11DepthStencilState* depthStencilState;
ID3D11DepthStencilState* depthDisabledStencilState;
ID3D11BlendState* alphaEnableBlendingState;
ID3D11BlendState* alphaDisableBlendingState;
DirectX::XMMATRIX projectionMatrix;
DirectX::XMMATRIX worldMatrix;
DirectX::XMMATRIX orthoMatrix;
public:
D3DClass(int screenWidth, int screenHeight, HWND hwnd, bool fullscreen, float screenDepth, float screenNear);
~D3DClass();
void BeginScene(float red, float green, float blue, float alpha);
void EndScene();
ID3D11Device* GetDevice();
ID3D11DeviceContext* GetDeviceContext();
void GetProjectionMatrix(DirectX::XMMATRIX& projectionMatrix);
void GetWorldMatrix(DirectX::XMMATRIX& worldMatrix);
void GetOrthoMatrix(DirectX::XMMATRIX& orthoMatrix);
ID3D11ShaderResourceView* GetDeferredSRV(int viewNumber);
void ActivateDeferredShading();
void TurnZBufferON();
void TurnZBufferOFF();
void TurnAlphaBlendingON();
void TurnAlphaBlendingOFF();
void TurnCullingON();
void TurnCullingOFF();
void SetBackBufferRenderTarget();
void ResetViewport();
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#include "ShaderDefault.h"
using namespace DirectX;
using namespace std;
ShaderDefault::ShaderDefault(ID3D11Device* device,
LPCWSTR vertexShaderFilename,
LPCWSTR pixelShaderFilename
) : ShaderBase(device)
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
CreateMandatoryShaders(device, vertexShaderFilename, pixelShaderFilename, inputDesc, ARRAYSIZE(inputDesc));
D3D11_BUFFER_DESC matrixBufferDesc;
HRESULT hr;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
}
ShaderDefault::~ShaderDefault()
{
matrixBuffer->Release();
}
void ShaderDefault::UseShader(ID3D11DeviceContext* deviceContext)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(hullShader, nullptr, 0);
deviceContext->DSSetShader(domainShader, nullptr, 0);
deviceContext->GSSetShader(geometryShader, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
}
void ShaderDefault::SetMatrices(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
XMMATRIX wvp = worldMatrix * viewMatrix * projectionMatrix;
wvp = XMMatrixTranspose(wvp);
XMMATRIX wm = XMMatrixTranspose(worldMatrix);
XMMATRIX vm = XMMatrixTranspose(viewMatrix);
XMMATRIX pm = XMMatrixTranspose(projectionMatrix);
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->world = wm;
matrixDataBuffer->view = vm;
matrixDataBuffer->projection = pm;
matrixDataBuffer->wvp = wvp;
deviceContext->Unmap(matrixBuffer, 0);
int bufferNumber = 0;
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
deviceContext->IASetInputLayout(inputLayout);
}
void* ShaderDefault::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShaderDefault::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#pragma once
#include "Object.h"
#include <DirectXMath.h>
#include "Intersections.h"
using namespace DirectX;
using namespace std;
class ObjectIntersection : public Object
{
private:
XMFLOAT3 position;
XMFLOAT3 scaling;
Sphere* intersectionSphere;
bool updateWorld;
public:
ObjectIntersection();
ObjectIntersection(ID3D11Device* device, string modelFilename, XMFLOAT3 position, XMFLOAT3 scaling, XMMATRIX& world);
virtual ~ObjectIntersection();
XMFLOAT3 GetPosition();
void SetPosition(XMFLOAT3 newPos);
XMFLOAT3 GetScaling();
void SetScaling(XMFLOAT3 newScaling);
Sphere* GetIntersectionSphere();
void Update();
};
<file_sep>#include "ParticleEmitter.h"
using namespace std;
using namespace DirectX;
ParticleEmitter::ParticleEmitter(ID3D11Device* device, std::string textureFilename) : ObjectBase()
{
texture = new Texture(textureFilename, device);
//Test particles
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 30; j++)
{
particles.push_back(new Particle(XMFLOAT3(2.0f*i, rand()%100+1.0f, 2.0f*j), XMFLOAT3(0, -50, 0), XMFLOAT3(0, 0, 0)));
}
}
particleData.clear();
for (unsigned int i = 0; i < particles.size(); i++)
{
particleData.push_back(particles.at(i)->GetPosition());
}
D3D11_BUFFER_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(XMFLOAT3) * particleData.size();
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = particleData.data();
device->CreateBuffer(&bufferDesc, &data, &vertexBuffer);
vertexCount = particleData.size();
}
ParticleEmitter::~ParticleEmitter()
{
for (unsigned int i = 0; i < particles.size(); i++)
{
delete particles.at(i);
}
}
void ParticleEmitter::Render(ID3D11DeviceContext* deviceContext)
{
UINT32 vertexSize = sizeof(XMFLOAT3);
UINT32 offset = 0;
ID3D11ShaderResourceView* textureView = GetTexture();
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &vertexSize, &offset);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
deviceContext->PSSetShaderResources(0, 1, &textureView);
deviceContext->Draw(vertexCount, 0);
}
void ParticleEmitter::Update(ID3D11DeviceContext* deviceContext, float frameTime)
{
//Update the particleData
particleData.clear();
for (unsigned int i = 0; i < particles.size(); i++)
{
Particle* currentParticle = particles.at(i);
currentParticle->Update(frameTime);
if (!currentParticle->IsAlive())
{
XMFLOAT3 oldPosition = currentParticle->GetPosition();
delete currentParticle;
particles[i] = new Particle(XMFLOAT3(oldPosition.x, rand() % 100 + 100.0f, oldPosition.z), XMFLOAT3(0, -50, 0), XMFLOAT3(0, 0, 0));
}
particleData.push_back(currentParticle->GetPosition());
}
vertexCount = particleData.size();
//Update the buffer
D3D11_MAPPED_SUBRESOURCE mappedResource;
deviceContext->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
memcpy(mappedResource.pData, particleData.data(), sizeof(XMFLOAT3)*particleData.size());
deviceContext->Unmap(vertexBuffer, 0);
}
<file_sep>#include "InputHandler.h"
#include <iostream>
using namespace std;
using namespace DirectX;
InputHandler::InputHandler(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
HRESULT result;
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
mousePos = XMFLOAT2(0.0f, 0.0f);
//Initialize the main direct input interface
result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&directInput, NULL);
if (FAILED(result))
{
throw runtime_error("Could not initialize main direct input interface");
}
//Initialize the interface for the keyboard
result = directInput->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
if (FAILED(result))
{
throw runtime_error("Could not initialize the keyboard");
}
keyboard->SetDataFormat(&c_dfDIKeyboard);
keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
result = keyboard->Acquire();
if (FAILED(result))
{
throw runtime_error("Could not aquire the keyboard");
}
// Initialize the direct input interface for the mouse.
result = directInput->CreateDevice(GUID_SysMouse, &mouse, NULL);
if (FAILED(result))
{
throw runtime_error("Could not initialize the mouse");
}
mouse->SetDataFormat(&c_dfDIMouse);
mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
result = mouse->Acquire();
if (FAILED(result))
{
throw runtime_error("Could not aquire the mouse");
}
}
InputHandler::~InputHandler()
{
if (directInput)
{
directInput->Release();
directInput = nullptr;
}
if (keyboard)
{
keyboard->Unacquire();
keyboard->Release();
keyboard = nullptr;
}
if (mouse)
{
mouse->Unacquire();
mouse->Release();
mouse = nullptr;
}
}
void InputHandler::Update()
{
bool result = false;
result = ReadKeyboard();
if (!result)
return;
result = ReadMouse();
if (!result)
return;
ProcessInput();
}
bool InputHandler::ReadKeyboard()
{
HRESULT result;
bool r = false;
//Read the keyboard device
result = keyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);
//If the keyboard was lost or not acquired, try to get control back
if (FAILED(result))
{
if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
{
keyboard->Acquire();
}
}
else
{
r = true;
}
return r;
}
bool InputHandler::ReadMouse()
{
HRESULT result;
bool r = false;
//Read the mouse device
result = mouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mouseState);
//If the mouse was lost or not acquired, try to get control back
if (FAILED(result))
{
if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
{
mouse->Acquire();
}
}
else
{
r = true;
}
return r;
}
void InputHandler::ProcessInput()
{
// Update the location of the mouse cursor
mousePos.x += mouseState.lX;
mousePos.y += mouseState.lY;
//Ensure the mousePos is limited to the bounds of the window
if (mousePos.x < 0) { mousePos.x = 0; }
if (mousePos.y < 0) { mousePos.y = 0; }
if (mousePos.x > screenWidth) { mousePos.x = (float)screenWidth; }
if (mousePos.y > screenHeight) { mousePos.y = (float)screenHeight; }
//GER GLOBAL POSITION, INTE FÖR SJÄLVA FÖNSTRET. FIXA
LPPOINT point = new POINT();
GetCursorPos(point);
mousePos.x = point->x;
mousePos.y = point->y;
delete point;
}
XMFLOAT2 InputHandler::GetMouseLocation()
{
return mousePos;
}
bool InputHandler::Escape()
{
bool pressed = false;
if (keyboardState[DIK_ESCAPE] & 0x80)
{
pressed = true;
}
return pressed;
}
bool InputHandler::W()
{
bool pressed = false;
if (keyboardState[DIK_W] & 0x80)
{
pressed = true;
}
return pressed;
}
bool InputHandler::A()
{
bool pressed = false;
if (keyboardState[DIK_A] & 0x80)
{
pressed = true;
}
return pressed;
}
bool InputHandler::S()
{
bool pressed = false;
if (keyboardState[DIK_S] & 0x80)
{
pressed = true;
}
return pressed;
}
bool InputHandler::D()
{
bool pressed = false;
if (keyboardState[DIK_D] & 0x80)
{
pressed = true;
}
return pressed;
}
XMFLOAT2 InputHandler::HandleMouse()
{
DIMOUSESTATE mouseCurrState;
mouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
//If these values are changed it means that actual mouse movement happened.
XMFLOAT2 lxly(1000000.0f, 1000000.0f);
//Check if the state of the mouse has changed since last time.
if ((mouseCurrState.lX != mouseState.lX) || (mouseCurrState.lY != mouseState.lY))
{
lxly.x = (float)mouseState.lX;
lxly.y = (float)mouseState.lY;
}
return lxly;
}
bool InputHandler::LMB()
{
bool down = false;
// Check if the left mouse button is currently pressed.
if (mouseState.rgbButtons[0] & 0x80)
{
down = true;
}
return down;
}
<file_sep>#pragma once
#include "ShaderBase.h"
#include <stdexcept>
#include "Light.h"
using namespace DirectX;
class ShaderTerrain : public ShaderBase
{
private:
struct MatrixBuffer
{
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
DirectX::XMMATRIX wvp;
};
struct GSBuffer
{
DirectX::XMMATRIX viewMatrix;
DirectX::XMFLOAT3 camPos;
float padding;
};
ID3D11Buffer* matrixBuffer;
ID3D11Buffer* gsBuffer;
ID3D11SamplerState* samplerState;
public:
ShaderTerrain(ID3D11Device* device, LPCWSTR vsFilename, LPCWSTR psFilename, LPCWSTR gsFilename);
virtual ~ShaderTerrain();
virtual void UseShader(ID3D11DeviceContext* deviceContext);
void SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix,
XMMATRIX& projectionMatrix, ID3D11ShaderResourceView** textures, XMFLOAT3 camPos);
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <DirectXMath.h>
class Light
{
private:
DirectX::XMFLOAT4 ambientColor;
DirectX::XMFLOAT4 diffuseColor;
DirectX::XMFLOAT3 direction;
public:
Light(DirectX::XMFLOAT4 ambientColor, DirectX::XMFLOAT4 diffuseColor, DirectX::XMFLOAT3 direction);
~Light();
DirectX::XMFLOAT4 GetAmbientColor();
DirectX::XMFLOAT4 GetDiffuseColor();
DirectX::XMFLOAT3 GetDirection();
void SetAmbientColor(float red, float green, float blue, float alpha);
void SetDiffuseColor(float red, float green, float blue, float alpha);
void SetDirection(float x, float y, float z);
};
<file_sep>#pragma once
#include "VertexTypes.h"
#include <Windows.h>
#include <d3d11.h>
#include <stdexcept>
class OrthoWindow
{
private:
int vertexCount;
int indexCount;
ID3D11Buffer* vertexBuffer;
ID3D11Buffer* indexBuffer;
void InitializeBuffers(ID3D11Device* device, int windowWidth, int windowHeight);
public:
OrthoWindow(ID3D11Device* device, int windowWidth, int windowHeight);
~OrthoWindow();
void Render(ID3D11DeviceContext* deviceContext);
int GetIndexCount();
};
<file_sep>#include "ShaderParticles.h"
using namespace DirectX;
using namespace std;
ShaderParticles::ShaderParticles(ID3D11Device* device,
LPCWSTR vertexShaderFilename,
LPCWSTR pixelShaderFilename,
LPCWSTR geometryShaderFilename
) : ShaderBase(device)
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
CreateMandatoryShaders(device, vertexShaderFilename, pixelShaderFilename, inputDesc, ARRAYSIZE(inputDesc));
//Create geomtery shader
HRESULT hr;
ID3DBlob* pGS = nullptr;
ID3DBlob* errorMessage = nullptr;
hr = D3DCompileFromFile(geometryShaderFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "gs_4_0", NULL, NULL, &pGS, &errorMessage);
if (FAILED(hr))
{
if (errorMessage)
{
throw runtime_error(string(static_cast<const char *>(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()));
}
else
{
throw runtime_error("No such file");
}
}
device->CreateGeometryShader(pGS->GetBufferPointer(), pGS->GetBufferSize(), nullptr, &geometryShader);
D3D11_BUFFER_DESC matrixBufferDesc;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
}
ShaderParticles::~ShaderParticles()
{
}
void ShaderParticles::UseShader(ID3D11DeviceContext* deviceContext)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(hullShader, nullptr, 0);
deviceContext->DSSetShader(domainShader, nullptr, 0);
deviceContext->GSSetShader(geometryShader, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
}
void ShaderParticles::SetMatrices(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, XMFLOAT3 campos)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
XMMATRIX wvp = worldMatrix * viewMatrix * projectionMatrix;
wvp = XMMatrixTranspose(wvp);
XMMATRIX wm = XMMatrixTranspose(worldMatrix);
XMMATRIX vm = XMMatrixTranspose(viewMatrix);
XMMATRIX pm = XMMatrixTranspose(projectionMatrix);
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->world = wm;
matrixDataBuffer->view = vm;
matrixDataBuffer->projection = pm;
matrixDataBuffer->wvp = wvp;
matrixDataBuffer->campos = campos;
deviceContext->Unmap(matrixBuffer, 0);
int bufferNumber = 0;
deviceContext->GSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
deviceContext->IASetInputLayout(inputLayout);
}
void* ShaderParticles::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShaderParticles::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "Light.h"
using namespace DirectX;
Light::Light(XMFLOAT4 ambientColor, XMFLOAT4 diffuseColor, XMFLOAT3 direction)
{
this->ambientColor = ambientColor;
this->diffuseColor = diffuseColor;
this->direction = direction;
}
Light::~Light()
{
}
void Light::SetAmbientColor(float red, float green, float blue, float alpha)
{
ambientColor = XMFLOAT4(red, green, blue, alpha);
}
void Light::SetDiffuseColor(float red, float green, float blue, float alpha)
{
diffuseColor = XMFLOAT4(red, green, blue, alpha);
}
void Light::SetDirection(float x, float y, float z)
{
direction = XMFLOAT3(x, y, z);
}
XMFLOAT4 Light::GetAmbientColor()
{
return ambientColor;
}
XMFLOAT4 Light::GetDiffuseColor()
{
return diffuseColor;
}
XMFLOAT3 Light::GetDirection()
{
return direction;
}<file_sep>#pragma once
#include <DirectXMath.h>
class Particle
{
private:
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 velocity;
DirectX::XMFLOAT3 acceleration;
bool alive;
public:
Particle( DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 0, 0),
DirectX::XMFLOAT3 velocity = DirectX::XMFLOAT3(0, 0, 0),
DirectX::XMFLOAT3 acceleration = DirectX::XMFLOAT3(0, 0, 0)
);
~Particle();
void Update(float frameTime);
DirectX::XMFLOAT3 GetPosition();
bool IsAlive();
};
<file_sep>#include "Quadtree.h"
using namespace std;
using namespace DirectX;
Quadtree::Node::Node()
{
for (int i = 0; i < 4; i++)
{
child[i] = nullptr;
}
}
Quadtree::Node::~Node()
{
for (vector<Object*>::iterator i = objects.begin(); i != objects.end(); ++i)
{
delete *i;
}
}
Quadtree::Quadtree(ID3D11Device* device, std::string filename)
{
ifstream file(filename);
if (file.good())
{
XMFLOAT2 position;
XMFLOAT2 size;
file >> position.x >> position.y >> size.x >> size.y;
rootBoundingBox = BoundingBox(position, size);
root = ReadNode(device, file);
}
file.close();
}
Quadtree::~Quadtree()
{
Clean(root);
}
void Quadtree::Render(ID3D11DeviceContext* deviceContext, ShaderDefault* shader, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix)
{
int modelsRendered = 0;
Render(deviceContext, root, rootBoundingBox, shader, viewMatrix, projectionMatrix, modelsRendered);
cout << "Models rendered: " << modelsRendered << endl;
}
void Quadtree::Render(ID3D11DeviceContext* deviceContext, Node* currentNode, BoundingBox box, ShaderDefault* shader, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, int& modelsRendered)
{
Plane planes[6];
XMFLOAT4X4 m;
XMMATRIX tempMatrix = XMMatrixMultiply(viewMatrix, projectionMatrix);
XMStoreFloat4x4(&m, tempMatrix);
//Left
planes[0].normal.x = -(m._14 + m._11);
planes[0].normal.y = -(m._24 + m._21);
planes[0].normal.z = -(m._34 + m._31);
planes[0].d = -(m._44 + m._41);
//Right
planes[1].normal.x = -(m._14 - m._11);
planes[1].normal.y = -(m._24 - m._21);
planes[1].normal.z = -(m._34 - m._31);
planes[1].d = -(m._44 - m._41);
//Top
planes[2].normal.x = -(m._14 - m._12);
planes[2].normal.y = -(m._24 - m._22);
planes[2].normal.z = -(m._34 - m._32);
planes[2].d = -(m._44 - m._42);
//Bottom
planes[3].normal.x = -(m._14 + m._12);
planes[3].normal.y = -(m._24 + m._22);
planes[3].normal.z = -(m._34 + m._32);
planes[3].d = -(m._44 + m._42);
//Near
planes[4].normal.x = -(m._14 + m._13);
planes[4].normal.y = -(m._24 + m._23);
planes[4].normal.z = -(m._34 + m._33);
planes[4].d = -(m._44 + m._43);
//Far
planes[5].normal.x = -(m._14 - m._13);
planes[5].normal.y = -(m._24 - m._23);
planes[5].normal.z = -(m._34 - m._33);
planes[5].d = -(m._44 - m._43);
//Normalize
for (int i = 0; i < 6; i++)
{
XMVECTOR lengthVector = XMVector3Length(XMLoadFloat3(&planes[i].normal));
XMFLOAT3 length;
XMStoreFloat3(&length, lengthVector);
float denom = 1.0f / length.x;
planes[i].normal.x *= denom;
planes[i].normal.y *= denom;
planes[i].normal.z *= denom;
planes[i].d *= denom;
}
//Calculate the 8 points of the bounding box
XMFLOAT3 points[8];
XMFLOAT2 pos = box.GetPosition();
XMFLOAT2 size = box.GetSize();
float height = 64.0f;
points[0].x = pos.x;
points[0].y = 0;
points[0].z = pos.y;
points[1].x = pos.x + size.x;
points[1].y = 0;
points[1].z = pos.y;
points[2].x = pos.x;
points[2].y = 0;
points[2].z = pos.y + size.y;
points[3].x = pos.x + size.x;
points[3].y = 0;
points[3].z = pos.y + size.y;
points[4].x = pos.x;
points[4].y = height;
points[4].z = pos.y;
points[5].x = pos.x + size.x;
points[5].y = height;
points[5].z = pos.y;
points[6].x = pos.x;
points[6].y = height;
points[6].z = pos.y + size.y;
points[7].x = pos.x + size.x;
points[7].y = height;
points[7].z = pos.y + size.y;
int frustumIntersection = PlanesVsPoints(planes, points);
if (frustumIntersection <= 0) //If box is inside or intersecting the frustum
{
for (vector<Object*>::iterator i = currentNode->objects.begin(); i != currentNode->objects.end(); ++i)
{
XMMATRIX world;
(*i)->GetWorldMatrix(world);
shader->SetMatrices(deviceContext, world, viewMatrix, projectionMatrix);
(*i)->Render(deviceContext);
modelsRendered++;
}
for (int i = 0; i < 4; i++)
{
if (currentNode->child[i])
{
Render(deviceContext, currentNode->child[i], box.GetChildBoundingBox(i), shader, viewMatrix, projectionMatrix, modelsRendered);
}
}
}
}
int Quadtree::PlanesVsPoints(Plane planes[], DirectX::XMFLOAT3 points[])
{
int insideFrustumCount = 0;
for (int i = 0; i < 6; i++)
{
int insidePlaneCount = 0;
int isAllInside = 1;
for (int j = 0; j < 8; j++)
{
if (PlaneVsPoint(planes[i], points[j]) > 0)
{
isAllInside = 0;
insidePlaneCount++;
}
}
if (insidePlaneCount == 8)
{
//All points outside of frustum
return 1;
}
insideFrustumCount += isAllInside;
}
if (insideFrustumCount == 6)
{
//All points are within the frustum
return -1;
}
//The frustum is intersecting the bounding box
return 0;
}
void Quadtree::Clean(Node* currentNode)
{
if (currentNode)
{
for (int i = 0; i < 4; i++)
{
Clean(currentNode->child[i]);
}
delete currentNode;
currentNode = nullptr;
}
}
Quadtree::Node* Quadtree::ReadNode(ID3D11Device* device, std::ifstream& file)
{
string command;
Node* currentNode = new Node();
while (!file.eof())
{
file >> command;
if (command == "o")
{
string objectFilename;
XMFLOAT4X4 worldTransform;
file >> objectFilename;
file >> worldTransform.m[0][0] >> worldTransform.m[0][1] >> worldTransform.m[0][2] >> worldTransform.m[0][3]
>> worldTransform.m[1][0] >> worldTransform.m[1][1] >> worldTransform.m[1][2] >> worldTransform.m[1][3]
>> worldTransform.m[2][0] >> worldTransform.m[2][1] >> worldTransform.m[2][2] >> worldTransform.m[2][3]
>> worldTransform.m[3][0] >> worldTransform.m[3][1] >> worldTransform.m[3][2] >> worldTransform.m[3][3];
currentNode->objects.push_back(new Object(device, objectFilename, XMLoadFloat4x4(&worldTransform)));
}
else if (command == "c")
{
int childNum;
file >> childNum;
currentNode->child[childNum] = ReadNode(device, file);
}
else if (command == "e")
{
return currentNode;
}
}
}
<file_sep>#include "Texture.h"
using namespace std;
using namespace DirectX;
Texture::Texture(std::string filename, ID3D11Device* device)
{
ifstream file(filename, ios_base::binary);
if (file.good())
{
vector<unsigned char> data;
//Get the filesize in bytes
file.seekg(0, file.end);
unsigned int size = (unsigned int)file.tellg();
file.seekg(0, file.beg);
data.resize(size);
//Assume texture is always square and RGBA format
width = height = (int)sqrt(size / 4);
//Read the whole file into the vector
file.read((char*)&data[0], data.size());
file.close();
//Create texture buffer
D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.MiscFlags = 0;
textureDesc.CPUAccessFlags = 0;
ID3D11Texture2D* pTexture = nullptr;
D3D11_SUBRESOURCE_DATA subresourceData;
ZeroMemory(&subresourceData, sizeof(subresourceData));
subresourceData.pSysMem = (void*)&data[0];
subresourceData.SysMemPitch = width * 4 * sizeof(char);
device->CreateTexture2D(&textureDesc, &subresourceData, &pTexture);
D3D11_SHADER_RESOURCE_VIEW_DESC resViewDesc;
ZeroMemory(&resViewDesc, sizeof(resViewDesc));
resViewDesc.Format = textureDesc.Format;
resViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
resViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
resViewDesc.Texture2D.MostDetailedMip = 0;
device->CreateShaderResourceView(pTexture, &resViewDesc, &texture);
pTexture->Release();
}
else
{
throw runtime_error("Failed to load texture: " + filename);
texture = nullptr;
}
}
Texture::~Texture()
{
texture->Release();
}
ID3D11ShaderResourceView* Texture::GetTexture() const
{
return texture;
}
<file_sep>#include "ShaderTerrain.h"
#include <iostream>
using namespace DirectX;
using namespace std;
ShaderTerrain::ShaderTerrain(ID3D11Device* device, LPCWSTR vsFilename, LPCWSTR psFilename, LPCWSTR gsFilename)
: ShaderBase(device)
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
CreateMandatoryShaders(device, vsFilename, psFilename, inputDesc, ARRAYSIZE(inputDesc));
D3D11_BUFFER_DESC matrixBufferDesc;
HRESULT hr;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
if (FAILED(hr))
{
throw runtime_error("Could not create MatrixBuffer");
}
D3D11_BUFFER_DESC gsBufferDesc;
// Setup the description of the dynamic constant buffer that is in the geometry shader.
// Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
gsBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
gsBufferDesc.ByteWidth = sizeof(GSBuffer);
gsBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
gsBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
gsBufferDesc.MiscFlags = 0;
gsBufferDesc.StructureByteStride = 0;
//Create the gsBuffer pointer so we can access the geometry shader constant buffer from within this class.
hr = device->CreateBuffer(&gsBufferDesc, NULL, &gsBuffer);
if (FAILED(hr))
{
throw runtime_error("Could not create gsBuffer");
}
D3D11_SAMPLER_DESC samplerDesc;
// Create a texture sampler state description.
//samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 4;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
hr = device->CreateSamplerState(&samplerDesc, &samplerState);
if (FAILED(hr))
{
throw runtime_error("Could not create SamplerState");
}
//Create geometry shader.
ID3DBlob* errorMessage = nullptr;
ID3DBlob* pPS = nullptr;
hr = D3DCompileFromFile(gsFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "gs_4_0", NULL, NULL, &pPS, &errorMessage);
if (FAILED(hr))
{
if (errorMessage)
{
throw runtime_error(string(static_cast<const char *>(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()));
}
else
{
throw runtime_error("No such file");
}
}
device->CreateGeometryShader(pPS->GetBufferPointer(), pPS->GetBufferSize(), nullptr, &geometryShader);
pPS->Release();
}
ShaderTerrain::~ShaderTerrain()
{
}
void ShaderTerrain::UseShader(ID3D11DeviceContext* deviceContext)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(hullShader, nullptr, 0);
deviceContext->DSSetShader(domainShader, nullptr, 0);
deviceContext->GSSetShader(geometryShader, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
deviceContext->IASetInputLayout(inputLayout);
}
void ShaderTerrain::SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, ID3D11ShaderResourceView** textures, XMFLOAT3 camPos)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
int bufferNumber;
XMMATRIX wvp = worldMatrix * viewMatrix * projectionMatrix;
wvp = XMMatrixTranspose(wvp);
XMMATRIX wm = XMMatrixTranspose(worldMatrix);
XMMATRIX vm = XMMatrixTranspose(viewMatrix);
XMMATRIX pm = XMMatrixTranspose(projectionMatrix);
///////////////////////////////////////////////// Matrix buffer, PS /////////////////////////////////////////////////
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->world = wm;
matrixDataBuffer->view = vm;
matrixDataBuffer->projection = pm;
matrixDataBuffer->wvp = wvp;
deviceContext->Unmap(matrixBuffer, 0);
bufferNumber = 0;
//Set matrix buffer to the vertex shader
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
/////////////////////////////////////////////////// GSBuffer, GS ///////////////////////////////////////////////////
hr = deviceContext->Map(gsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
GSBuffer* gsDataBuffer = (GSBuffer*)mappedResource.pData;
//Copy the data into the constant buffer.
gsDataBuffer->camPos = camPos;
gsDataBuffer->viewMatrix = viewMatrix;
deviceContext->Unmap(gsBuffer, 0);
bufferNumber = 0;
//Set matrix buffer to the vertex shader
deviceContext->GSSetConstantBuffers(bufferNumber, 1, &gsBuffer);
deviceContext->PSSetSamplers(0, 1, &samplerState);
deviceContext->PSSetShaderResources(0, 4, textures);
}
void* ShaderTerrain::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShaderTerrain::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "ShaderUv.h"
using namespace DirectX;
ShaderUv::ShaderUv() : ShaderBase()
{
}
ShaderUv::~ShaderUv()
{
}
bool ShaderUv::Initialize(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "UVCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
if (!this->ShaderBase::Initialize(device, hwnd, inputDesc, ARRAYSIZE(inputDesc), vsFilename, psFilename))
{
return false;
}
D3D11_BUFFER_DESC matrixBufferDesc;
HRESULT hr;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
if (FAILED(hr))
{
return false;
}
return true;
}
void ShaderUv::UseShader(ID3D11DeviceContext* deviceContext, ID3D11Buffer* vertexBuffer, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projMatrix)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBuffer* matrixDataBuffer;
unsigned int bufferNumber;
XMMATRIX wm = XMMatrixTranspose(worldMatrix);
XMMATRIX vm = XMMatrixTranspose(viewMatrix);
XMMATRIX pm = XMMatrixTranspose(projMatrix);
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->world = wm;
matrixDataBuffer->view = vm;
matrixDataBuffer->projection = pm;
deviceContext->Unmap(matrixBuffer, 0);
bufferNumber = 0;
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(nullptr, nullptr, 0);
deviceContext->DSSetShader(nullptr, nullptr, 0);
deviceContext->GSSetShader(nullptr, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
}
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <windows.h>
class Camera
{
private:
DirectX::XMFLOAT3 positionXYZ;
DirectX::XMFLOAT3 rotationXYZ;
DirectX::XMMATRIX viewMatrix;
public:
Camera();
~Camera();
void SetPosition(DirectX::XMFLOAT3 newPos);
void SetRotation(DirectX::XMFLOAT3 newRot);
DirectX::XMFLOAT3 GetPosition();
DirectX::XMFLOAT3 GetRotation();
void GetViewMatrix(DirectX::XMMATRIX& viewMatrix);
void Update();
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <string>
#include <vector>
#include <fstream>
#include "ObjectBase.h"
class Object : public ObjectBase
{
private:
std::vector<DirectX::XMFLOAT3> vertices;
std::vector<DirectX::XMFLOAT2> uvs;
std::vector<DirectX::XMFLOAT3> normals;
std::vector<Vertex> faces;
public:
Object(ID3D11Device* device, std::string modelFilename, DirectX::XMMATRIX& worldMatrix);
virtual ~Object();
virtual void Render(ID3D11DeviceContext* deviceContext);
};
<file_sep>#include "Position.h"
#include <iostream>
using namespace DirectX;
using namespace std;
Position::Position(XMFLOAT3 startPos, XMFLOAT3 startRot)
{
position = startPos;
rotation = startRot;
frameTime = 0;
forwardSpeed = 0;
backwardSpeed = 0;
leftSpeed = 0;
rightSpeed = 0;
}
Position::~Position()
{
}
void Position::SetPosition(XMFLOAT3 pos)
{
position = pos;
}
void Position::SetRotation(XMFLOAT3 rot)
{
rotation = rot;
}
void Position::SetY(float y)
{
position.y = y;
}
XMFLOAT3 Position::GetPosition()
{
return position;
}
XMFLOAT3 Position::GetRotation()
{
return rotation;
}
void Position::SetFrameTime(float frameTime)
{
this->frameTime = frameTime;
}
void Position::LookAround(XMFLOAT2 lxly)
{
//If no mouse-movement occurred the InputHandler will return 1000000.0f for both x and y,
//therefore nothing is done when these values show up
if (lxly.x < 1000000.0f && lxly.y < 1000000.0f)
{
rotation.y += lxly.x * LOOK_SPEED;
rotation.x += lxly.y * LOOK_SPEED;
////Keep y-rotation within 360-bounds
if (rotation.y < 0.0f)
{
rotation.y += 360.0f;
}
else if (rotation.y > 360.0f)
{
rotation.y = 0;
}
//Lock x-rotation to given bounds otherwise the camera can be turned upside-down
if (rotation.x < -VIEW_BOUNDS_X)
{
rotation.x = -VIEW_BOUNDS_X;
}
else if (rotation.x > VIEW_BOUNDS_X)
{
rotation.x = VIEW_BOUNDS_X;
}
}
}
void Position::MoveForward(bool keyDown)
{
//Update the forward speed movement. If the key is down, accelerate.
if (keyDown)
{
forwardSpeed += frameTime * ACCELERATION;
if (forwardSpeed > (frameTime * SPEED_MULTIPLIER))
{
forwardSpeed = frameTime * SPEED_MULTIPLIER;
}
}
else //If the key is not down, decelerate.
{
forwardSpeed -= frameTime * DECELERATION;
if (forwardSpeed < 0.0f)
{
forwardSpeed = 0.0f;
}
}
float radians = XMConvertToRadians(rotation.y);
//Update the position.
position.x += sinf(radians) * forwardSpeed;
position.z += cosf(radians) * forwardSpeed;
}
void Position::MoveBackward(bool keyDown)
{
//Update the forward speed movement. If the key is down, accelerate.
if (keyDown)
{
backwardSpeed += frameTime * ACCELERATION;
if (backwardSpeed > (frameTime * SPEED_MULTIPLIER))
{
backwardSpeed = frameTime * SPEED_MULTIPLIER;
}
}
else //If the key is not down, decelerate.
{
backwardSpeed -= frameTime * DECELERATION;
if (backwardSpeed < 0.0f)
{
backwardSpeed = 0.0f;
}
}
float radians = XMConvertToRadians(rotation.y);
//Update the position.
position.x -= sinf(radians) * backwardSpeed;
position.z -= cosf(radians) * backwardSpeed;
}
void Position::MoveLeft(bool keyDown)
{
//Update the left speed movement. If the key is down, accelerate.
if (keyDown)
{
leftSpeed += frameTime * ACCELERATION;
if (leftSpeed > (frameTime * SPEED_MULTIPLIER))
{
leftSpeed = frameTime * SPEED_MULTIPLIER;
}
}
else //If the key is not down, decelerate.
{
leftSpeed -= frameTime * DECELERATION;
if (leftSpeed < 0.0f)
{
leftSpeed = 0.0f;
}
}
//rotation.y gives forward-direction. -90 gives left
float radians = XMConvertToRadians(rotation.y - 90.0f);
//Update the position.
position.x += sinf(radians) * leftSpeed;
position.z += cosf(radians) * leftSpeed;
}
void Position::MoveRight(bool keyDown)
{
//Update the right speed movement. If the key is down, accelerate.
if (keyDown)
{
rightSpeed += frameTime * ACCELERATION;
if (rightSpeed > (frameTime * SPEED_MULTIPLIER))
{
rightSpeed = frameTime * SPEED_MULTIPLIER;
}
}
else //If the key is not down, decelerate.
{
rightSpeed -= frameTime * DECELERATION;
if (rightSpeed < 0.0f)
{
rightSpeed = 0.0f;
}
}
//rotation.y gives forward-direction. +90 gives right
float radians = XMConvertToRadians(rotation.y + 90.0f);
//Update the position.
position.x += sinf(radians) * rightSpeed;
position.z += cosf(radians) * rightSpeed;
}<file_sep>Core techniques
================================================================================
Deferred rendering and lighting Jonas X
Geometry
================================================================================
Height-map terrain rendering, user can walk on the terrain. Jonas X
Parsing and rendering of an existing model format (OBJ, FBX, Collada, etc.). Mattias X
Texturing and lightning
================================================================================
Blend-mapping Mattias X
Projection techniques
================================================================================
Shadow maps Jonas /
Acceleration techniques
================================================================================
View frustum culling against a quadtree Mattias X
Back-face culling using geometry shader Jonas X
Other techniques
================================================================================
Particle system with billboarded particles Mattias X
Water-effect Jonas -
Picking Jonas X<file_sep>#include "OrthoWindow.h"
using namespace std;
using namespace DirectX;
OrthoWindow::OrthoWindow(ID3D11Device* device, int windowWidth, int windowHeight)
{
vertexCount = 0;
indexCount = 0;
InitializeBuffers(device, windowWidth, windowHeight);
}
OrthoWindow::~OrthoWindow()
{
if (vertexBuffer)
{
vertexBuffer->Release();
vertexBuffer = nullptr;
}
if (indexBuffer)
{
indexBuffer->Release();
indexBuffer = nullptr;
}
}
void OrthoWindow::InitializeBuffers(ID3D11Device* device, int windowWidth, int windowHeight)
{
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
//Screen coordinates of the window
float left = -1.0f;
float right = 1.0f;
float top = 1.0f;
float bottom = -1.0f;
vertexCount = 6;
indexCount = vertexCount;
VertexPosUV* vertices = new VertexPosUV[vertexCount];
unsigned long* indices = new unsigned long[indexCount];
// First triangle
vertices[0].pos = XMFLOAT3(left, top, 0.0f); // Top left
vertices[0].uv = XMFLOAT2(0.0f, 0.0f);
vertices[1].pos = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[1].uv = XMFLOAT2(1.0f, 1.0f);
vertices[2].pos = XMFLOAT3(left, bottom, 0.0f); // Bottom left
vertices[2].uv = XMFLOAT2(0.0f, 1.0f);
// Second triangle
vertices[3].pos = XMFLOAT3(left, top, 0.0f); // Top left
vertices[3].uv = XMFLOAT2(0.0f, 0.0f);
vertices[4].pos = XMFLOAT3(right, top, 0.0f); // Top right
vertices[4].uv = XMFLOAT2(1.0f, 0.0f);
vertices[5].pos = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[5].uv = XMFLOAT2(1.0f, 1.0f);
//Load the index array with data
for (int i = 0; i < indexCount; i++)
{
indices[i] = i;
}
//Description of the vertex buffer
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexPosUV) * vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
//Create vertex buffer
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);
if (FAILED(result))
{
throw runtime_error("Error creating vertex buffer in OrthoWindow");
}
//Description of the index buffer
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
//Create the index buffer
result = device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);
if (FAILED(result))
{
throw runtime_error("Error creating index buffer in OrthoWindow");
}
delete[] vertices;
vertices = nullptr;
delete[] indices;
indices = nullptr;
}
void OrthoWindow::Render(ID3D11DeviceContext* deviceContext)
{
unsigned int stride = sizeof(VertexPosUV);
unsigned int offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
deviceContext->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
int OrthoWindow::GetIndexCount()
{
return indexCount;
}
<file_sep>#pragma once
#include "ObjectBase.h"
#include "Texture.h"
#include "Particle.h"
#include <string>
#include <vector>
class ParticleEmitter : public ObjectBase
{
private:
std::vector<DirectX::XMFLOAT3> particleData;
std::vector<Particle*> particles;
public:
ParticleEmitter(ID3D11Device* device, std::string textureFilename);
virtual ~ParticleEmitter();
virtual void Render(ID3D11DeviceContext* deviceContext);
virtual void Update(ID3D11DeviceContext* deviceContext, float frameTime);
};
<file_sep>#include "Object.h"
#include "Texture.h"
using namespace std;
using namespace DirectX;
Object::Object(ID3D11Device* device, std::string modelFilename, DirectX::XMMATRIX& worldMatrix) : ObjectBase(worldMatrix)
{
bool result = true;
ifstream file(modelFilename);
if (file.good())
{
while (!file.eof())
{
string command;
file >> command;
if (command == "v")
{
XMFLOAT3 tempVertex;
file >> tempVertex.x;
file >> tempVertex.y;
file >> tempVertex.z;
tempVertex.z *= -1.0f;
vertices.push_back(tempVertex);
}
else if (command == "vt")
{
XMFLOAT2 tempUv;
file >> tempUv.x;
file >> tempUv.y;
tempUv.y = 1.0f - tempUv.y;
uvs.push_back(tempUv);
}
else if (command == "vn")
{
XMFLOAT3 tempNormal;
file >> tempNormal.x;
file >> tempNormal.y;
file >> tempNormal.z;
tempNormal.z *= -1.0f;
normals.push_back(tempNormal);
}
else if (command == "f")
{
int vertexIndex[3];
int uvIndex[3];
int normalIndex[3];
for (int i = 0; i < 3; i++)
{
file >> vertexIndex[i];
//Check if we can load UV coordinates
if (file.peek() == '/')
{
file.get();
file >> uvIndex[i];
//Check if we can load normals
if (file.peek() == '/')
{
file.get();
file >> normalIndex[i];
}
}
}
for (int i = 2; i >= 0; i--)
{
Vertex tempVertex;
tempVertex.pos = vertices[vertexIndex[i] - 1];
tempVertex.uv = uvs[uvIndex[i] - 1];
tempVertex.normal = normals[normalIndex[i] - 1];
faces.push_back(tempVertex);
}
}
else if (command == "mtllib")
{
string materialFilename;
file >> materialFilename;
ifstream materialFile(materialFilename);
if (materialFile.good())
{
string mtlCommand;
while (!materialFile.eof())
{
materialFile >> mtlCommand;
if (mtlCommand == "map_Kd")
{
string textureFilename;
materialFile >> textureFilename;
texture = new Texture(textureFilename, device);
}
else //Unknown command, ignore it
{
string tempString;
getline(materialFile, tempString);
}
}
materialFile.close();
}
else
{
throw runtime_error("Failed to load material file: " + materialFilename);
}
}
else //Unknown command, ignore it
{
string tempString;
getline(file, tempString);
}
}
}
else
{
throw runtime_error("Failed to load file: " + modelFilename);
}
file.close();
D3D11_BUFFER_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.ByteWidth = sizeof(Vertex) * faces.size();
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = faces.data();
device->CreateBuffer(&bufferDesc, &data, &vertexBuffer);
vertexCount = faces.size();
}
Object::~Object()
{
}
void Object::Render(ID3D11DeviceContext* deviceContext)
{
UINT32 vertexSize = sizeof(Vertex);
UINT32 offset = 0;
ID3D11ShaderResourceView* textureView = GetTexture();
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &vertexSize, &offset);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->PSSetShaderResources(0, 1, &textureView);
deviceContext->Draw(vertexCount, 0);
}
<file_sep>#include <windows.h>
#include "System.h"
#include <crtdbg.h>
#include "Console.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
srand((unsigned)time(NULL));
RedirectIOToConsole();
System* system;
try
{
system = new System(false, false, 1440, 900);
system->Run();
delete system;
}
catch (exception& e)
{
MessageBoxA(NULL, e.what(), "Error", MB_ICONERROR | MB_OK);
}
return 0;
}
<file_sep>#include "Terrain.h"
#include <iostream>
using namespace DirectX;
using namespace std;
Terrain::Terrain(ID3D11Device* device, char* heightMapName, float normalizeFactor, string blendMapFilename, string grassTextureFilename, string stoneTextureFilename, string sandTextureFilename)
{
indexBuffer = nullptr;
vertexBuffer = nullptr;
vertexCount = 0;
indexCount = 0;
bool result = true;
texture[0] = new Texture(blendMapFilename, device);
texture[1] = new Texture(grassTextureFilename, device);
texture[2] = new Texture(stoneTextureFilename, device);
texture[3] = new Texture(sandTextureFilename, device);
//Load, normalize, calculate normals and calculate texture coordinates for the heightmap
result = LoadHeightMap(heightMapName);
if (!result)
throw runtime_error("LoadHeightMap Error");
NormalizeHeightMap(normalizeFactor);
CalculateNormals();
CalculateTextureCoordinates();
//Initialize the vertex and index buffer that holds the geometry for the terrain.
InitializeBuffers(device);
}
Terrain::~Terrain()
{
if (indexBuffer)
{
indexBuffer->Release();
indexBuffer = nullptr;
}
if (vertexBuffer)
{
vertexBuffer->Release();
vertexBuffer = nullptr;
}
if (heightMap)
{
delete[] heightMap;
heightMap = nullptr;
}
if (texture[0])
{
delete texture[0];
texture[0] = nullptr;
}
if (texture[1])
{
delete texture[1];
texture[1] = nullptr;
}
if (texture[2])
{
delete texture[2];
texture[2] = nullptr;
}
if (texture[3])
{
delete texture[3];
texture[3] = nullptr;
}
}
void Terrain::Render(ID3D11DeviceContext* deviceContext)
{
SetBuffers(deviceContext);
deviceContext->DrawIndexed(vertexCount, 0,0);
}
int Terrain::GetIndexCount()
{
return indexCount;
}
float Terrain::GetY(float x, float z)
{
float returnValue = 0.0f;
//Normalizing with bilinear interpolation
if (x <= terrainWidth-2 && z <= terrainHeight-2 && x >= 0 + 1 && z >= 0 + 1)
{
int x1, x2, z1, z2;
float q11, q12, q21, q22;
x1 = (int)floor(x);
x2 = (int)floor(x+1);
z1 = (int)floor(z);
z2 = (int)floor(z+1);
q11 = GetHeightAt(x1, z1);
q12 = GetHeightAt(x1, z2);
q21 = GetHeightAt(x2, z1);
q22 = GetHeightAt(x2, z2);
returnValue = (1.0f / ((x2 - x1)*(z2 - z1)))*(q11*(x2 - x)*(z2 - z) +
q21*(x - x1)*(z2 - z) +
q12*(x2 - x)*(z - z1) +
q22*(x - x1)*(z - z1));
}
return returnValue;
}
float Terrain::GetHeightAt(int x, int z)
{
return heightMap[(terrainHeight * z) + x].y;
}
ID3D11ShaderResourceView** Terrain::GetTextures()
{
textureArray[0] = texture[0]->GetTexture();
textureArray[1] = texture[1]->GetTexture();
textureArray[2] = texture[2]->GetTexture();
textureArray[3] = texture[3]->GetTexture();
return textureArray;
}
bool Terrain::LoadHeightMap(char* filename)
{
FILE* filePtr;
int error;
unsigned int count;
BITMAPFILEHEADER bitmapFileHeader;
BITMAPINFOHEADER bitmapInfoHeader;
int imageSize;
unsigned char* bitmapImage;
unsigned char height;
// Open the height map file in binary
error = fopen_s(&filePtr, filename, "rb");
if (error != 0)
{
return false;
}
//Read file and info headers
count = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr);
if (count != 1)
{
return false;
}
count = fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);
if (count != 1)
{
return false;
}
//Allocate the memory needed for the heightmap
terrainWidth = bitmapInfoHeader.biWidth;
terrainHeight = bitmapInfoHeader.biHeight;
imageSize = terrainWidth * terrainHeight * 3;
bitmapImage = new unsigned char[imageSize];
if (!bitmapImage)
{
return false;
}
//Read the file
fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);
count = fread(bitmapImage, 1, imageSize, filePtr);
if (count != imageSize)
{
return false;
}
//Close the file
error = fclose(filePtr);
if (error != 0)
{
return false;
}
heightMap = new HeightMap[terrainWidth * terrainHeight];
if (!heightMap)
{
return false;
}
int k = 0;
int index = 0;
//Read the image data into the height map
for (int j = 0; j < terrainHeight; j++)
{
for (int i = 0; i < terrainWidth; i++)
{
height = bitmapImage[k];
index = (terrainHeight * j) + i;
heightMap[index].x = (float)i;
heightMap[index].y = (float)height;
heightMap[index].z = (float)j;
k += 3;
}
}
delete[] bitmapImage;
bitmapImage = nullptr;
return true;
}
void Terrain::NormalizeHeightMap(float factor)
{
//Simple normalizing by a given number
for (int i = 0; i < terrainHeight; i++)
{
for (int j = 0; j < terrainWidth; j++)
{
heightMap[(terrainHeight * i) + j].y /= factor;
}
}
}
void Terrain::CalculateNormals()
{
int index1, index2, index3, index, count;
float vertex1[3], vertex2[3], vertex3[3], vector1[3], vector2[3], sum[3], length;
// Create a temporary array to hold the un-normalized normal vectors.
float3* normals = new float3[(terrainHeight - 1) * (terrainWidth - 1)];
// Go through all the faces in the mesh and calculate their normals.
for (int j = 0; j < (terrainHeight - 1); j++)
{
for (int i = 0; i < (terrainWidth - 1); i++)
{
index1 = (j * terrainHeight) + i;
index2 = (j * terrainHeight) + (i + 1);
index3 = ((j + 1) * terrainHeight) + i;
//Get three vertices from the face.
vertex1[0] = heightMap[index1].x;
vertex1[1] = heightMap[index1].y;
vertex1[2] = heightMap[index1].z;
vertex2[0] = heightMap[index2].x;
vertex2[1] = heightMap[index2].y;
vertex2[2] = heightMap[index2].z;
vertex3[0] = heightMap[index3].x;
vertex3[1] = heightMap[index3].y;
vertex3[2] = heightMap[index3].z;
// Calculate the two vectors for this face.
vector1[0] = vertex1[0] - vertex3[0];
vector1[1] = vertex1[1] - vertex3[1];
vector1[2] = vertex1[2] - vertex3[2];
vector2[0] = vertex3[0] - vertex2[0];
vector2[1] = vertex3[1] - vertex2[1];
vector2[2] = vertex3[2] - vertex2[2];
index = (j * (terrainHeight - 1)) + i;
// Calculate the cross product of those two vectors to get the un-normalized value for this face normal.
normals[index].x = (vector1[1] * vector2[2]) - (vector1[2] * vector2[1]);
normals[index].y = (vector1[2] * vector2[0]) - (vector1[0] * vector2[2]);
normals[index].z = (vector1[0] * vector2[1]) - (vector1[1] * vector2[0]);
}
}
//Go through all the vertices and take an average of each face normal
//that the vertex touches to get the averaged normal for that vertex.
for (int j = 0; j < terrainHeight; j++)
{
for (int i = 0; i < terrainWidth; i++)
{
sum[0] = 0.0f;
sum[1] = 0.0f;
sum[2] = 0.0f;
count = 0;
// Bottom left face
if (((i - 1) >= 0) && ((j - 1) >= 0))
{
index = ((j - 1) * (terrainHeight - 1)) + (i - 1);
sum[0] += normals[index].x;
sum[1] += normals[index].y;
sum[2] += normals[index].z;
count++;
}
// Bottom right face
if ((i < (terrainWidth - 1)) && ((j - 1) >= 0))
{
index = ((j - 1) * (terrainHeight - 1)) + i;
sum[0] += normals[index].x;
sum[1] += normals[index].y;
sum[2] += normals[index].z;
count++;
}
// Upper left face
if (((i - 1) >= 0) && (j < (terrainHeight - 1)))
{
index = (j * (terrainHeight - 1)) + (i - 1);
sum[0] += normals[index].x;
sum[1] += normals[index].y;
sum[2] += normals[index].z;
count++;
}
// Upper right face
if ((i < (terrainWidth - 1)) && (j < (terrainHeight - 1)))
{
index = (j * (terrainHeight - 1)) + i;
sum[0] += normals[index].x;
sum[1] += normals[index].y;
sum[2] += normals[index].z;
count++;
}
//Average of the faces touching this vertex.
sum[0] = (sum[0] / (float)count);
sum[1] = (sum[1] / (float)count);
sum[2] = (sum[2] / (float)count);
length = sqrt((sum[0] * sum[0]) + (sum[1] * sum[1]) + (sum[2] * sum[2]));
//index to the vertex location in the height map array
index = (j * terrainHeight) + i;
// Normalize the final shared normal for this vertex and store it in the height map array.
heightMap[index].nx = (sum[0] / length);
heightMap[index].ny = (sum[1] / length);
heightMap[index].nz = (sum[2] / length);
}
}
delete[] normals;
normals = nullptr;
}
void Terrain::CalculateTextureCoordinates()
{
float incrementValue = (float)TEXTURE_REPEAT / (float)terrainWidth;
int incrementCount = terrainWidth / TEXTURE_REPEAT;
float tuCoordinate = 0.0f;
float tvCoordinate = 1.0f;
int tuCount = 0;
int tvCount = 0;
//Loop through heightmap and calculate texture coordinates for each vertex
for (int i = 0; i < terrainHeight; i++)
{
for (int j = 0; j < terrainWidth; j++)
{
//Store the texture coordinate in the height map
heightMap[(terrainHeight * i) + j].tu = tuCoordinate;
heightMap[(terrainHeight * i) + j].tv = tvCoordinate;
tuCoordinate += incrementValue;
tuCount++;
// Check if at the far right end of the texture. If so, start from the left
if (tuCount == incrementCount)
{
tuCoordinate = 0.0f;
tuCount = 0;
}
}
tvCoordinate -= incrementValue;
tvCount++;
// Check if at the top of the texture. If so, start from the bottom
if (tvCount == incrementCount)
{
tvCoordinate = 1.0f;
tvCount = 0;
}
}
}
void Terrain::InitializeBuffers(ID3D11Device* device)
{
HRESULT result;
int index1, index2, index3, index4;
vertexCount = (terrainWidth - 1) * (terrainHeight - 1) * 6;
indexCount = vertexCount;
Vertex* vertices = new Vertex[vertexCount];
unsigned long* indices = new unsigned long[indexCount];
int index = 0;
float tu = 0.0f;
float tv = 0.0f;
//Load the vertex and index array with the terrain data.
for (int i = 0; i < (terrainHeight - 1); i++)
{
for (int j = 0; j < (terrainWidth - 1); j++)
{
index1 = (terrainHeight * i) + j; //Bottom left
index2 = (terrainHeight * i) + (j + 1); //Bottom right
index3 = (terrainHeight * (i + 1)) + j; //Upper left
index4 = (terrainHeight * (i + 1)) + (j + 1); //Upper right
// Upper left
tv = heightMap[index3].tv;
//Cover the top edge
if (tv == 1.0f)
tv = 0.0f;
vertices[index].pos = XMFLOAT3(heightMap[index3].x, heightMap[index3].y, heightMap[index3].z);
vertices[index].uv = XMFLOAT2(heightMap[index3].tu, tv);
vertices[index].normal = XMFLOAT3(heightMap[index3].nx, heightMap[index3].ny, heightMap[index3].nz);
indices[index] = index;
index++;
// Upper right
tu = heightMap[index4].tu;
tv = heightMap[index4].tv;
//Cover the top and right edge
if (tu == 0.0f)
tu = 1.0f;
if (tv == 1.0f)
tv = 0.0f;
vertices[index].pos = XMFLOAT3(heightMap[index4].x, heightMap[index4].y, heightMap[index4].z);
vertices[index].uv = XMFLOAT2(tu, tv);
vertices[index].normal = XMFLOAT3(heightMap[index4].nx, heightMap[index4].ny, heightMap[index4].nz);
indices[index] = index;
index++;
// Bottom left
vertices[index].pos = XMFLOAT3(heightMap[index1].x, heightMap[index1].y, heightMap[index1].z);
vertices[index].uv = XMFLOAT2(heightMap[index1].tu, heightMap[index1].tv);
vertices[index].normal = XMFLOAT3(heightMap[index1].nx, heightMap[index1].ny, heightMap[index1].nz);
indices[index] = index;
index++;
// Bottom left
vertices[index].pos = XMFLOAT3(heightMap[index1].x, heightMap[index1].y, heightMap[index1].z);
vertices[index].uv = XMFLOAT2(heightMap[index1].tu, heightMap[index1].tv);
vertices[index].normal = XMFLOAT3(heightMap[index1].nx, heightMap[index1].ny, heightMap[index1].nz);
indices[index] = index;
index++;
// Upper right
tu = heightMap[index4].tu;
tv = heightMap[index4].tv;
//Cover the top and right edge.
if (tu == 0.0f)
tu = 1.0f;
if (tv == 1.0f)
tv = 0.0f;
vertices[index].pos = XMFLOAT3(heightMap[index4].x, heightMap[index4].y, heightMap[index4].z);
vertices[index].uv = XMFLOAT2(tu, tv);
vertices[index].normal = XMFLOAT3(heightMap[index4].nx, heightMap[index4].ny, heightMap[index4].nz);
indices[index] = index;
index++;
// Bottom right
tu = heightMap[index2].tu;
// Cover the right edge.
if (tu == 0.0f)
tu = 1.0f;
vertices[index].pos = XMFLOAT3(heightMap[index2].x, heightMap[index2].y, heightMap[index2].z);
vertices[index].uv = XMFLOAT2(tu, heightMap[index2].tv);
vertices[index].normal = XMFLOAT3(heightMap[index2].nx, heightMap[index2].ny, heightMap[index2].nz);
indices[index] = index;
index++;
}
}
D3D11_BUFFER_DESC vertexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData;
//Description of the vertex buffer
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
//Create the vertex buffer
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);
D3D11_BUFFER_DESC indexBufferDesc;
D3D11_SUBRESOURCE_DATA indexData;
//Description of the index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);
delete[] vertices;
vertices = nullptr;
delete[] indices;
indices = nullptr;
}
void Terrain::SetBuffers(ID3D11DeviceContext* deviceContext)
{
UINT32 vertexSize = sizeof(Vertex);
UINT32 offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &vertexSize, &offset);
deviceContext->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <Windows.h>
#include <d3dcompiler.h>
#include <string>
#include <fstream>
class ShaderBase
{
protected:
ID3D11VertexShader* vertexShader;
ID3D11PixelShader* pixelShader;
ID3D11HullShader* hullShader;
ID3D11GeometryShader* geometryShader;
ID3D11DomainShader* domainShader;
ID3D11InputLayout* inputLayout;
unsigned int vertexSize;
public:
ShaderBase(ID3D11Device* device);
virtual ~ShaderBase();
void CreateMandatoryShaders(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename, D3D11_INPUT_ELEMENT_DESC* inputDesc, unsigned int inputDescSize);
};
<file_sep>#include "ShaderShadowMap.h"
#include <string>
#include <fstream>
using namespace std;
ShaderShadowMap::ShaderShadowMap(ID3D11Device* device, LPCWSTR vertexShaderFilename, int width, int height, float bias)
{
D3D11_RASTERIZER_DESC rasterDesc;
D3D11_DEPTH_STENCIL_DESC depthDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_FRONT;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
//Create rasterizer state
device->CreateRasterizerState(&rasterDesc, &rasterizerState);
depthDesc.DepthEnable = true;
depthDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
depthDesc.StencilEnable = false;
depthDesc.StencilReadMask = 0xFF;
depthDesc.StencilWriteMask = 0xFF;
depthDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the depth stencil state.
device->CreateDepthStencilState(&depthDesc, &depthStencilState);
HRESULT hr;
ID3DBlob* errorMessage = nullptr;
//Create vertex shader
ID3DBlob* pVS = nullptr;
hr = D3DCompileFromFile(vertexShaderFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_4_0", NULL, NULL, &pVS, &errorMessage);
if (FAILED(hr))
{
if (errorMessage)
{
throw runtime_error(string(static_cast<const char *>(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()));
}
else
{
throw runtime_error("No such file");
}
}
device->CreateVertexShader(pVS->GetBufferPointer(), pVS->GetBufferSize(), nullptr, &vertexShader);
//Create vertex layout
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
device->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), pVS->GetBufferPointer(), pVS->GetBufferSize(), &inputLayout);
pVS->Release();
D3D11_BUFFER_DESC matrixBufferDesc;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
this->width = width;
this->height = height;
this->shadowMapBias = bias;
D3D11_TEXTURE2D_DESC texDesc;
ZeroMemory(&texDesc, sizeof(D3D11_TEXTURE2D_DESC));
texDesc.Width = width;
texDesc.Height = height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R32_TYPELESS;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_DEPTH_STENCIL;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
hr = device->CreateTexture2D(&texDesc, nullptr, &shadowMap);
if (FAILED(hr))
{
throw std::runtime_error("Shadow map 1");
}
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
dsvDesc.Flags = 0;
dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Texture2D.MipSlice = 0;
hr = device->CreateDepthStencilView(shadowMap, &dsvDesc, &shadowMapDepthView);
if (FAILED(hr))
{
throw std::runtime_error("Shadow map 2");
}
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
srvDesc.Format = DXGI_FORMAT_R32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
srvDesc.Texture2D.MostDetailedMip = 0;
hr = device->CreateShaderResourceView(shadowMap, &srvDesc, &shadowMapSRV);
if (FAILED(hr))
{
throw std::runtime_error("Shadow map 3");
}
shadowMapViewport.Width = (FLOAT)width;
shadowMapViewport.Height = (FLOAT)height;
shadowMapViewport.MinDepth = 0.0f;
shadowMapViewport.MaxDepth = 1.0f;
shadowMapViewport.TopLeftX = 0;
shadowMapViewport.TopLeftY = 0;
}
ShaderShadowMap::~ShaderShadowMap()
{
rasterizerState->Release();
depthStencilState->Release();
vertexShader->Release();
matrixBuffer->Release();
inputLayout->Release();
shadowMap->Release();
shadowMapDepthView->Release();
shadowMapSRV->Release();
}
void ShaderShadowMap::UseShader(ID3D11DeviceContext* deviceContext)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(nullptr, nullptr, 0);
deviceContext->DSSetShader(nullptr, nullptr, 0);
deviceContext->GSSetShader(nullptr, nullptr, 0);
deviceContext->PSSetShader(nullptr, nullptr, 0);
deviceContext->RSSetViewports(1, &shadowMapViewport);
deviceContext->OMSetRenderTargets(0, nullptr, shadowMapDepthView);
deviceContext->OMSetDepthStencilState(depthStencilState, 1);
deviceContext->RSSetState(rasterizerState);
deviceContext->ClearDepthStencilView(shadowMapDepthView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
void ShaderShadowMap::SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& lightWVP, XMFLOAT3 lightPos)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
XMMATRIX lWVP = XMMatrixTranspose(lightWVP);
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->lightWVP = lWVP;
matrixDataBuffer->lightPos = lightPos;
deviceContext->Unmap(matrixBuffer, 0);
int bufferNumber = 0;
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
deviceContext->IASetInputLayout(inputLayout);
}
ID3D11ShaderResourceView* ShaderShadowMap::GetShadowSRV()
{
return shadowMapSRV;
}
int ShaderShadowMap::GetSize()
{
//Square texture. height = width
return height;
}
void* ShaderShadowMap::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShaderShadowMap::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#pragma once
#define DIRECTINPUT_VERSION 0x0800
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
#include <dinput.h>
#include <Windows.h>
#include <DirectXMath.h>
#include <stdexcept>
class InputHandler
{
private:
IDirectInput8* directInput;
IDirectInputDevice8* keyboard;
IDirectInputDevice8* mouse;
unsigned char keyboardState[256];
DIMOUSESTATE mouseState;
int screenWidth;
int screenHeight;
DirectX::XMFLOAT2 mousePos;
bool ReadKeyboard();
bool ReadMouse();
void ProcessInput();
public:
InputHandler(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight);
~InputHandler();
void Update();
DirectX::XMFLOAT2 GetMouseLocation();
bool Escape();
bool W();
bool A();
bool S();
bool D();
bool LMB();
//Returns lX and lY from the mouse state
DirectX::XMFLOAT2 HandleMouse();
};
<file_sep>#include "System.h"
System::System(bool fullscreen, bool showCursor, int screenWidth, int screenHeight)
{
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
this->fullscreen = fullscreen;
this->showCursor = showCursor;
InitializeWindows();
//Create and initialize the application
application = new Application(hinstance, hwnd, screenWidth, screenHeight);
}
System::~System()
{
delete application;
ShutdownWindows();
}
void System::Run()
{
MSG msg;
bool result;
bool done = false;
ZeroMemory(&msg, sizeof(MSG));
while (!done)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (msg.message == WM_QUIT)
{
done = true;
}
else
{
result = Update();
if (!result)
{
done = true;
}
}
}
}
bool System::Update()
{
bool result = true;
//SetCursorPos(realScreenWidth / 2, realScreenHeight / 2);
result = application->Update();
if (!result)
return false;
return result;
}
LRESULT CALLBACK System::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
return DefWindowProc(hwnd, umsg, wparam, lparam);
}
void System::InitializeWindows()
{
WNDCLASSEX wc;
DEVMODE dmScreenSettings;
int posX, posY;
applicationHandle = this;
hinstance = GetModuleHandle(NULL);
applicationName = L"3DProject";
//Setup the windows class with default settings.
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hinstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = applicationName;
wc.cbSize = sizeof(WNDCLASSEX);
RegisterClassEx(&wc);
//Setup the screen settings depending on whether it is running in full screen or in windowed mode.
if (fullscreen)
{
//Determine the resolution of the screen.
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
//If full screen set the screen to maximum size of the users desktop and 32bit.
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth;
dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
posX = 0;
posY = 0;
}
else //If windowed
{
//Place the window in the middle of the screen.
posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
realScreenHeight = GetSystemMetrics(SM_CYSCREEN);
realScreenWidth = GetSystemMetrics(SM_CXSCREEN);
}
hwnd = CreateWindowEx(WS_EX_APPWINDOW, applicationName, applicationName,
WS_OVERLAPPEDWINDOW | CW_USEDEFAULT | CW_USEDEFAULT,
posX, posY, screenWidth, screenHeight, NULL, NULL, hinstance, NULL);
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
ShowCursor(showCursor);
}
void System::ShutdownWindows()
{
ShowCursor(true);
if (fullscreen)
{
ChangeDisplaySettings(NULL, 0);
}
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
SetCursorPos(screenWidth / 2, screenHeight / 2);
DestroyWindow(hwnd);
hwnd = NULL;
UnregisterClass(applicationName, hinstance);
hinstance = NULL;
applicationHandle = NULL;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)
{
switch (umessage)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
default:
{
return applicationHandle->MessageHandler(hwnd, umessage, wparam, lparam);
}
}
}<file_sep>#include "Particle.h"
using namespace DirectX;
Particle::Particle(XMFLOAT3 position, XMFLOAT3 velocity, XMFLOAT3 acceleration)
{
this->position = position;
this->velocity = velocity;
this->acceleration = acceleration;
}
Particle::~Particle()
{
}
void Particle::Update(float frameTime)
{
float factor = frameTime / 1000;
XMVECTOR tempPosition = XMLoadFloat3(&position);
XMVECTOR tempVelocity = XMLoadFloat3(&velocity);
XMVECTOR tempAcceleration = XMLoadFloat3(&acceleration);
tempVelocity += tempAcceleration * factor;
tempPosition += tempVelocity * factor;
XMStoreFloat3(&position, tempPosition);
XMStoreFloat3(&velocity, tempVelocity);
XMStoreFloat3(&acceleration, tempAcceleration);
alive = position.y > -10;
}
XMFLOAT3 Particle::GetPosition()
{
return position;
}
bool Particle::IsAlive()
{
return alive;
}
<file_sep>#pragma once
#include "ShaderBase.h"
class ShaderUv : public ShaderBase
{
private:
struct MatrixBuffer
{
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
};
ID3D11Buffer* matrixBuffer;
public:
ShaderUv();
virtual ~ShaderUv();
virtual bool Initialize(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename);
virtual void UseShader(ID3D11DeviceContext* deviceContext, ID3D11Buffer* vertexBuffer, DirectX::XMMATRIX& worldMatrix, DirectX::XMMATRIX& viewMatrix, DirectX::XMMATRIX& projMatrix);
};
<file_sep>#include "Timer.h"
using namespace std;
Timer::Timer()
{
// Check to see if this system supports high performance timers
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
if (frequency == 0)
{
throw runtime_error("Could not initialize Timer");
}
ticksPerMs = (float)(frequency / 1000);
QueryPerformanceCounter((LARGE_INTEGER*)&startTime);
}
Timer::~Timer()
{
}
void Timer::Update()
{
INT64 currentTime;
float timeDifference;
QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); //Query the current time
timeDifference = (float)(currentTime - startTime); //Difference in time since the last time-query
frameTime = timeDifference / ticksPerMs; //Time difference over the timer speed resolution give frameTime
startTime = currentTime; //Restart the timer
}
float Timer::GetTime()
{
return frameTime;
}
<file_sep>#pragma once
#include "ShaderBase.h"
class ShaderParticles : public ShaderBase
{
private:
struct MatrixBuffer
{
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
DirectX::XMMATRIX wvp;
DirectX::XMFLOAT3 campos;
};
ID3D11Buffer* matrixBuffer;
public:
ShaderParticles(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename, LPCWSTR geometryShaderFilename);
virtual ~ShaderParticles();
virtual void UseShader(ID3D11DeviceContext* deviceContext);
void SetMatrices(ID3D11DeviceContext* deviceContext, DirectX::XMMATRIX& worldMatrix, DirectX::XMMATRIX& viewMatrix, DirectX::XMMATRIX& projectionMatrix, DirectX::XMFLOAT3 campos);
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <DirectXMath.h>
class BoundingBox
{
private:
DirectX::XMFLOAT2 position;
DirectX::XMFLOAT2 size;
public:
BoundingBox();
BoundingBox(DirectX::XMFLOAT2 position, DirectX::XMFLOAT2 size);
~BoundingBox();
DirectX::XMFLOAT2 GetPosition();
DirectX::XMFLOAT2 GetSize();
BoundingBox GetChildBoundingBox(int childQuadrant);
};
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <Windows.h>
#include <d3dcompiler.h>
#include <string>
#include <fstream>
class Deferred
{
private:
//Diffuse, Normal and WorldPosition (used the shadow mapping)
static const int BUFFER_COUNT = 3;
int textureWidth;
int textureHeight;
ID3D11Texture2D* renderTargetTextureArray[BUFFER_COUNT];
ID3D11RenderTargetView* renderTargetViewArray[BUFFER_COUNT];
ID3D11ShaderResourceView* shaderResourceViewArray[BUFFER_COUNT];
ID3D11Texture2D* depthStencilBuffer;
ID3D11DepthStencilView* depthStencilView;
D3D11_VIEWPORT viewport;
void InitializeBuffers(ID3D11Device* device);
public:
Deferred(ID3D11Device* device, int textureWidth, int textureHeight);
virtual ~Deferred();
void SetRenderTargets(ID3D11DeviceContext* deviceContext);
void ClearRenderTargets(ID3D11DeviceContext* deviceContext, float r, float g, float b, float a);
ID3D11ShaderResourceView* GetShaderResourceView(int viewNumber);
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <windows.h>
#include <stdexcept>
#include "D3DClass.h"
#include "VertexTypes.h"
#include "Camera.h"
#include "Terrain.h"
#include "Light.h"
#include "InputHandler.h"
#include "Timer.h"
#include "Position.h"
#include "OrthoWindow.h"
#include "Object.h"
#include "ObjectBase.h"
#include "ObjectIntersection.h"
#include "ParticleEmitter.h"
#include "Light.h"
#include "Quadtree.h"
#include "ShadowLight.h"
#include "ShaderParticles.h"
#include "ShaderBase.h"
#include "ShaderDefault.h"
#include "ShaderTerrain.h"
#include "ShaderLight.h"
#include "ShaderShadowMap.h"
class Application
{
private:
const float HEIGHT_FROM_GROUND = 5.0f;
const int NUM_SPHERES = 4;
int screenWidth;
int screenHeight;
bool moveRightOrLeft; //true = right movement
//OBJECTS
D3DClass* Direct3D;
Camera* camera;
Terrain* terrain;
Position* position;
InputHandler* input;
Timer* timer;
OrthoWindow* orthoWindow;
//MODELS
ObjectBase* particleEmitter;
ObjectBase** spheres;
ObjectBase* sphere;
Quadtree* modelQuadtree;
//SHADERS
ShaderDefault* modelShader;
ShaderParticles* particleShader;
ShaderTerrain* terrainShader;
ShaderLight* lightShader;
ShaderShadowMap* shadowMapShader;
//OTHER
Light* light;
ShadowLight* shadowLight;
void HandleMovement(float frameTime);
void CreateShaders();
void RenderToTexture();
bool RenderGraphics();
bool TestIntersections(ObjectIntersection* object, float& distance);
Ray GetRay();
public:
Application(HINSTANCE hInstance, HWND hwnd, int screenWidth, int screenHeight);
~Application();
bool Update();
};
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <stdexcept>
#include <windows.h>
#include "VertexTypes.h"
#include "Texture.h"
class Terrain
{
private:
//For our texture-blending to work this has to be set to 1.
//If no blending is used then repeating texture works
const int TEXTURE_REPEAT = 1;
struct float3
{
float x, y, z;
};
struct HeightMap
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
};
int terrainWidth;
int terrainHeight;
int vertexCount;
int indexCount;
HeightMap* heightMap;
ID3D11Buffer* vertexBuffer;
ID3D11Buffer* indexBuffer;
Texture* texture[4];
ID3D11ShaderResourceView* textureArray[4];
void InitializeBuffers(ID3D11Device* device);
void SetBuffers(ID3D11DeviceContext* deviceContext);
bool LoadHeightMap(char* filename);
void NormalizeHeightMap(float factor);
void CalculateNormals();
void CalculateTextureCoordinates();
float GetHeightAt(int x, int z);
public:
Terrain(ID3D11Device* device, char* heightMapName, float normalizeFactor, std::string blendMapFilename, std::string grassTextureFilename, std::string stoneTextureFilename, std::string sandTextureFilename);
~Terrain();
void Render(ID3D11DeviceContext* deviceContext);
float GetY(float x, float z);
int GetIndexCount();
ID3D11ShaderResourceView** GetTextures();
};
<file_sep>#include "Application.h"
#include <iostream>
#include <DirectXCollision.h>
#include <DirectXMath.h>
using namespace DirectX;
using namespace std;
Application::Application(HINSTANCE hInstance, HWND hwnd, int screenWidth, int screenHeight)
{
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
moveRightOrLeft = true;
float screenDepth = 1000.0f;
float screenNear = 0.1f;
Direct3D = new D3DClass(screenWidth, screenHeight, hwnd, false, screenDepth, screenNear);
timer = new Timer();
input = new InputHandler(hInstance, hwnd, screenWidth, screenHeight);
position = new Position(XMFLOAT3(170.0f, 15.0f, 50.0f), XMFLOAT3(0.0f, 0.0f, 0.0f));
camera = new Camera();
camera->SetPosition(position->GetPosition());
camera->SetRotation(position->GetRotation());
terrain = new Terrain( Direct3D->GetDevice(), "assets/textures/terrain/heightmap02.bmp", 7.0f,
"assets/textures/terrain/blendmap.raw",
"assets/textures/terrain/grass.raw",
"assets/textures/terrain/stone.raw",
"assets/textures/terrain/sand.raw");
particleEmitter = new ParticleEmitter(Direct3D->GetDevice(), "assets/textures/dollar.raw");
spheres = new ObjectBase*[NUM_SPHERES];
for (int i = 0; i < NUM_SPHERES; i++)
{
XMFLOAT3 pos((float)(170 + (i * 20 + 5 * i)), 20, 170);
XMFLOAT3 scale((float)(4 + i*i), (float)(4 + i*i), (float)(4 + i*i));
spheres[i] = new ObjectIntersection(Direct3D->GetDevice(), "assets/models/sphere3.obj", pos, scale, XMMatrixIdentity());
}
XMMATRIX tempWorldMatrix = XMMatrixIdentity();
sphere = new ObjectIntersection(Direct3D->GetDevice(), "assets/models/sphere3.obj", XMFLOAT3(350, 15, 128), XMFLOAT3(5, 5, 5), tempWorldMatrix);
modelQuadtree = new Quadtree(Direct3D->GetDevice(), "assets/map/tree.txt");
// Initialize the light object.
XMFLOAT4 ambient(0.05f, 0.05f, 0.05f, 1.0f);
XMFLOAT4 diffuse(1.0f, 1.0f, 1.0f, 1.0f);
XMFLOAT3 direction(0.0f, -0.6f, 0.75f);
orthoWindow = new OrthoWindow(Direct3D->GetDevice(), screenWidth, screenHeight);
XMFLOAT3 position(256.0f, 56.0f, -26.0f);
shadowLight = new ShadowLight(ambient, diffuse, position, XMFLOAT3(256.0f, 0.0f, 256.0f));
shadowLight->CreateProjectionMatrix(screenDepth, screenNear);
shadowLight->CreateViewMatrix();
light = new Light(ambient, diffuse, shadowLight->GetDirection());
XMFLOAT3 dir = shadowLight->GetDirection();
light->SetDirection(dir.x, dir.y, dir.z);
CreateShaders();
}
Application::~Application()
{
//OBJECTS
if (Direct3D)
{
delete Direct3D;
Direct3D = nullptr;
}
if (camera)
{
delete camera;
camera = nullptr;
}
if (terrain)
{
delete terrain;
terrain = nullptr;
}
if (timer)
{
delete timer;
timer = nullptr;
}
if (input)
{
delete input;
input = nullptr;
}
if (input)
{
delete input;
input = nullptr;
}
if (position)
{
delete position;
position = nullptr;
}
if (light)
{
delete light;
light = nullptr;
}
if (orthoWindow)
{
delete orthoWindow;
orthoWindow = nullptr;
}
if (shadowLight)
{
delete shadowLight;
shadowLight = nullptr;
}
//MODELS
if (particleEmitter)
{
delete particleEmitter;
particleEmitter = nullptr;
}
if (spheres)
{
for (int i = 0; i < NUM_SPHERES; i++)
{
delete spheres[i];
}
delete[] spheres;
}
if (sphere)
{
delete sphere;
}
if (modelQuadtree)
{
delete modelQuadtree;
modelQuadtree = nullptr;
}
//SHADERS
if (modelShader)
{
delete modelShader;
modelShader = nullptr;
}
if (particleShader)
{
delete particleShader;
particleShader = nullptr;
}
if (lightShader)
{
delete lightShader;
lightShader = nullptr;
}
if (terrainShader)
{
delete terrainShader;
terrainShader = nullptr;
}
if (shadowMapShader)
{
delete shadowMapShader;
shadowMapShader = nullptr;
}
}
bool Application::Update()
{
bool result = true;
////Updates moving light. Temporary.
//XMFLOAT3 pos = shadowLight->GetPosition();
//if (moveRightOrLeft)
//{
// pos.x += 0.6f;
// if (pos.x > 300)
// {
// moveRightOrLeft = false;
// }
//}
//else
//{
// pos.x -= 0.6f;
// if (pos.x < 0)
// {
// moveRightOrLeft = true;
// }
//}
//shadowLight->SetPosition(pos);
//shadowLight->CreateViewMatrix();
//((ObjectIntersection*)sphere)->SetPosition(pos);
timer->Update();
float frameTime = timer->GetTime();
input->Update();
HandleMovement(frameTime);
//Update the camera. viewMatrix gets updated here.
camera->Update();
particleEmitter->Update(Direct3D->GetDeviceContext(), frameTime);
if (!result)
{
return false;
}
for (int i = 0; i < NUM_SPHERES; i++)
{
((ObjectIntersection*)spheres[i])->Update();
}
((ObjectIntersection*)sphere)->Update();
result = RenderGraphics();
//Check if the user pressed escape and wants to exit the application.
if (input->Escape())
{
result = false;
}
return result;
}
void Application::HandleMovement(float frameTime)
{
bool keyDown;
position->SetFrameTime(frameTime);
//Handle the input.
keyDown = input->W();
position->MoveForward(keyDown);
keyDown = input->A();
position->MoveLeft(keyDown);
keyDown = input->S();
position->MoveBackward(keyDown);
keyDown = input->D();
position->MoveRight(keyDown);
position->LookAround(input->HandleMouse());
//Get the view point position/rotation.
XMFLOAT3 pos = position->GetPosition();
XMFLOAT3 rot = position->GetRotation();
//Locking the Y-position to the ground
pos.y = terrain->GetY(pos.x, pos.z) + HEIGHT_FROM_GROUND;
// Set the position of the camera.
camera->SetPosition(pos);
camera->SetRotation(rot);
keyDown = input->LMB();
if (keyDown)
{
float closestDist = 9999999.0f;
float distance = -1.0f;
int closestIndex = -1;
bool intersect = false;
for (int i = 0; i < NUM_SPHERES; i++)
{
intersect = TestIntersections((ObjectIntersection*)spheres[i], distance);
if (intersect)
{
if (distance < closestDist)
{
closestDist = distance;
closestIndex = i;
}
}
}
if (closestIndex > -1)
{
XMFLOAT3 p = ((ObjectIntersection*)spheres[closestIndex])->GetPosition();
((ObjectIntersection*)spheres[closestIndex])->SetPosition(XMFLOAT3(p.x, p.y + 10, p.z));
}
distance = -1;
intersect = TestIntersections((ObjectIntersection*)sphere, distance);
if (intersect)
{
cout << "INTERSECT" << endl;
XMFLOAT3 p = camera->GetPosition();
((ObjectIntersection*)sphere)->SetPosition(XMFLOAT3(p.x, p.y, p.z));
}
}
}
Ray Application::GetRay()
{
XMVECTOR pickRayInViewSpacePos = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR pickRayInViewSpaceDir = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
//Transform ray from view to world space
XMMATRIX invView;
XMVECTOR matInvDeter;
XMMATRIX v;
camera->GetViewMatrix(v);
invView = XMMatrixInverse(&matInvDeter, v);
XMVECTOR pickRayInWorldSpacePos = XMVector3TransformCoord(pickRayInViewSpacePos, invView);
XMVECTOR pickRayInWorldSpaceDir = XMVector3TransformNormal(pickRayInViewSpaceDir, invView);
XMFLOAT3 ro;
XMFLOAT3 rd;
XMStoreFloat3(&ro, pickRayInWorldSpacePos);
XMStoreFloat3(&rd, pickRayInWorldSpaceDir);
Ray r(ro, rd);
return r;
}
bool Application::TestIntersections(ObjectIntersection* object, float& distance)
{
bool intersect = false;
Ray r = GetRay();
RayVsSphere(r, *object->GetIntersectionSphere(), distance);
if (distance > 0)
{
intersect = true;
}
return intersect;
//XMVECTOR origin = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
//XMVECTOR dir = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
//XMMATRIX viewMx;
//camera->GetViewMatrix(viewMx);
//XMMATRIX modelMx;
//object->GetWorldMatrix(modelMx);
//XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(viewMx), viewMx);
//XMMATRIX invModel = XMMatrixInverse(&XMMatrixDeterminant(modelMx), modelMx);
//XMMATRIX toLocal = invView * invModel;
//origin = XMVector3TransformCoord(origin, toLocal);
//dir = XMVector3TransformNormal(dir, toLocal);
//dir = XMVector3Normalize(dir);
//XMMATRIX w, v, p;
//Direct3D->GetProjectionMatrix(p);
//camera->GetViewMatrix(v);
//object->GetWorldMatrix(w);
//XMVECTOR o = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
//XMVECTOR d = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f);
//o = XMVector3Unproject(o, 0, 0, screenWidth, screenHeight, 0, 1, p, v, w);
//d = XMVector3Unproject(d, 0, 0, screenWidth, screenHeight, 0, 1, p, v, w);
//XMFLOAT3 ro;
//XMFLOAT3 rd;
//XMStoreFloat3(&ro, o);
//XMStoreFloat3(&rd, d);
//DirectX::BoundingSphere b;
//b.Center = object->GetIntersectionSphere()->center;
//b.Radius = object->GetIntersectionSphere()->radius;
//intersect = b.Intersects(o, d, distance);
}
bool Application::RenderGraphics()
{
bool result = true;
XMMATRIX view, projection, lightVP;
shadowLight->GetViewMatrix(view);
shadowLight->GetProjectionMatrix(projection);
lightVP = XMMatrixMultiply(view, projection);
RenderToTexture();
Direct3D->BeginScene(0.2f, 0.4f, 1.0f, 1.0f);
Direct3D->TurnZBufferOFF();
orthoWindow->Render(Direct3D->GetDeviceContext());
lightShader->SetBuffers(Direct3D->GetDeviceContext(),
Direct3D->GetDeferredSRV(0), Direct3D->GetDeferredSRV(1), shadowMapShader->GetShadowSRV(),
Direct3D->GetDeferredSRV(2), shadowLight->GetDirection(), lightVP, shadowMapShader->GetSize());
lightShader->Draw(Direct3D->GetDeviceContext(), orthoWindow->GetIndexCount());
Direct3D->TurnZBufferON();
Direct3D->EndScene();
return result;
}
void Application::RenderToTexture()
{
XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
Direct3D->GetWorldMatrix(worldMatrix);
camera->GetViewMatrix(viewMatrix);
Direct3D->GetProjectionMatrix(projectionMatrix);
///*Uncomment to render from the view of the light*/
//shadowLight->GetViewMatrix(viewMatrix);
//shadowLight->GetProjectionMatrix(projectionMatrix);
////////////////////////////////////////////////////////////////////////// Render to shadow map //////////////////////////////////////////////////////////////////////////
shadowMapShader->UseShader(Direct3D->GetDeviceContext());
XMMATRIX lightView, lightProj, world, wvp;
XMFLOAT3 lightPos = shadowLight->GetPosition();
shadowLight->GetViewMatrix(lightView);
shadowLight->GetProjectionMatrix(lightProj);
XMMATRIX vp = lightView * lightProj;
for (int i = 0; i < NUM_SPHERES; i++)
{
spheres[i]->GetWorldMatrix(world);
wvp = world * vp;
shadowMapShader->SetBuffers(Direct3D->GetDeviceContext(), wvp, shadowLight->GetPosition());
spheres[i]->Render(Direct3D->GetDeviceContext());
}
sphere->GetWorldMatrix(world);
wvp = world * vp;
shadowMapShader->SetBuffers(Direct3D->GetDeviceContext(), wvp, shadowLight->GetPosition());
sphere->Render(Direct3D->GetDeviceContext());
//////////////////////////////////////////////////////////////////// Render scene with deferred shading ////////////////////////////////////////////////////////////////////
Direct3D->ActivateDeferredShading();
//Turns culling OFF to show that the terrain shader has its own backface culling in the geometry shader
Direct3D->TurnCullingOFF();
//Render terrain
terrainShader->UseShader(Direct3D->GetDeviceContext());
terrainShader->SetBuffers(Direct3D->GetDeviceContext(), worldMatrix, viewMatrix, projectionMatrix, terrain->GetTextures(), camera->GetPosition());
terrain->Render(Direct3D->GetDeviceContext());
Direct3D->TurnCullingON();
//Render objects
modelShader->UseShader(Direct3D->GetDeviceContext());
modelQuadtree->Render(Direct3D->GetDeviceContext(), modelShader, viewMatrix, projectionMatrix);
sphere->GetWorldMatrix(world);
modelShader->SetMatrices(Direct3D->GetDeviceContext(), world, viewMatrix, projectionMatrix);
sphere->Render(Direct3D->GetDeviceContext());
for (int i = 0; i < NUM_SPHERES; i++)
{
spheres[i]->GetWorldMatrix(world);
modelShader->SetMatrices(Direct3D->GetDeviceContext(), world, viewMatrix, projectionMatrix);
spheres[i]->Render(Direct3D->GetDeviceContext());
}
//Render particles
particleShader->UseShader(Direct3D->GetDeviceContext());
particleShader->SetMatrices(Direct3D->GetDeviceContext(), XMMatrixTranslation(128 - 30, 1, 64 - 30), viewMatrix, projectionMatrix, camera->GetPosition());
particleEmitter->Render(Direct3D->GetDeviceContext());
//Deactivate deferred shading. Activates forward shading again
Direct3D->SetBackBufferRenderTarget();
Direct3D->ResetViewport();
}
void Application::CreateShaders()
{
modelShader = new ShaderDefault(Direct3D->GetDevice(), L"assets/shaders/ShaderUvVS.hlsl", L"assets/shaders/ShaderUvPS.hlsl");
particleShader = new ShaderParticles(Direct3D->GetDevice(), L"assets/shaders/ShaderParticlesVS.hlsl", L"assets/shaders/ShaderParticlesPS.hlsl", L"assets/shaders/ShaderParticlesGS.hlsl");
terrainShader = new ShaderTerrain(Direct3D->GetDevice(), L"assets/shaders/TerrainVS.hlsl", L"assets/shaders/TerrainPS.hlsl", L"assets/shaders/TerrainGS.hlsl");
lightShader = new ShaderLight(Direct3D->GetDevice(), L"assets/shaders/LightVS.hlsl", L"assets/shaders/LightPS.hlsl");
shadowMapShader = new ShaderShadowMap(Direct3D->GetDevice(), L"assets/shaders/ShadowMapVS.hlsl", 2048, 2048, 0.0001f);
}
<file_sep>#ifndef MATH_H
#define MATH_H
#include <DirectXMath.h>
using namespace DirectX;
static float DotProduct3(XMFLOAT3 v1, XMFLOAT3 v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
static XMFLOAT3 CrossProduct3(XMFLOAT3 v1, XMFLOAT3 v2)
{
return XMFLOAT3(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
}
static XMFLOAT3 Subtract3(XMFLOAT3 v1, XMFLOAT3 v2)
{
return XMFLOAT3(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
}
#endif<file_sep>#include "ObjectBase.h"
using namespace std;
using namespace DirectX;
ObjectBase::ObjectBase()
{
/*XMStoreFloat4x4(&worldMatrix, XMMatrixIdentity());*/
}
ObjectBase::ObjectBase(DirectX::XMMATRIX& worldMatrix)
{
this->worldMatrix = worldMatrix;
}
ObjectBase::~ObjectBase()
{
if (vertexBuffer)
vertexBuffer->Release();
delete texture;
}
void ObjectBase::Update(ID3D11DeviceContext* deviceContext, float frameTime)
{
}
ID3D11Buffer* ObjectBase::GetVertexBuffer() const
{
return vertexBuffer;
}
ID3D11ShaderResourceView* ObjectBase::GetTexture() const
{
return texture->GetTexture();
}
void ObjectBase::GetWorldMatrix(XMMATRIX& worldMatrix) const
{
worldMatrix = this->worldMatrix;
}
void* ObjectBase::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ObjectBase::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include "VertexTypes.h"
#include "Texture.h"
using namespace DirectX;
class ObjectBase
{
protected:
ID3D11Buffer* vertexBuffer;
Texture* texture;
int vertexCount;
XMMATRIX worldMatrix;
public:
ObjectBase(DirectX::XMMATRIX& worldMatrix);
ObjectBase();
virtual ~ObjectBase();
virtual void Render(ID3D11DeviceContext* deviceContext) = 0;
virtual void Update(ID3D11DeviceContext* deviceContext, float frameTime);
ID3D11Buffer* GetVertexBuffer() const;
ID3D11ShaderResourceView* GetTexture() const;
void GetWorldMatrix(DirectX::XMMATRIX& worldMatrix) const;
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <DirectXMath.h>
class Position
{
private:
const float ACCELERATION = 0.001f;
const float DECELERATION = 0.0007f;
const float SPEED_MULTIPLIER = 0.03f;
const float LOOK_SPEED = 0.5f;
const float VIEW_BOUNDS_X = 75.0f;
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 rotation;
float frameTime;
float forwardSpeed;
float backwardSpeed;
float leftSpeed;
float rightSpeed;
public:
Position(DirectX::XMFLOAT3 startPos, DirectX::XMFLOAT3 startRot);
~Position();
void SetPosition(DirectX::XMFLOAT3 pos);
void SetRotation(DirectX::XMFLOAT3 rot);
void SetY(float y);
DirectX::XMFLOAT3 GetPosition();
DirectX::XMFLOAT3 GetRotation();
void SetFrameTime(float frameTime);
void MoveForward(bool keyDown);
void MoveBackward(bool keyDown);
void MoveLeft(bool keyDown);
void MoveRight(bool keyDown);
void LookAround(DirectX::XMFLOAT2 lxly);
};
<file_sep>#include "ObjectIntersection.h"
ObjectIntersection::ObjectIntersection(ID3D11Device* device, string modelFilename, XMFLOAT3 position, XMFLOAT3 scaling, XMMATRIX& world)
: Object(device, modelFilename, world)
{
this->position = position;
this->scaling = scaling;
worldMatrix = XMMatrixScaling(scaling.x, scaling.y, scaling.z) * XMMatrixTranslation(position.x, position.y, position.z);
updateWorld = false;
intersectionSphere = new Sphere(position, scaling.x);
}
ObjectIntersection::~ObjectIntersection()
{
delete intersectionSphere;
intersectionSphere = nullptr;
}
//This could be called only when SET functions are called, but if there are objects with continuous movement it has to be called each frame
void ObjectIntersection::Update()
{
if (updateWorld)
{
worldMatrix = XMMatrixScaling(scaling.x, scaling.y, scaling.z)*XMMatrixTranslation(position.x, position.y, position.z);
intersectionSphere->center = position;
updateWorld = false;
}
if (position.y > intersectionSphere->radius + 10)
{
position.y--;
updateWorld = true;
}
}
XMFLOAT3 ObjectIntersection::GetPosition()
{
return position;
}
void ObjectIntersection::SetPosition(XMFLOAT3 newPos)
{
position = newPos;
updateWorld = true;
}
XMFLOAT3 ObjectIntersection::GetScaling()
{
return scaling;
}
void ObjectIntersection::SetScaling(XMFLOAT3 newScaling)
{
scaling = newScaling;
updateWorld = true;
}
Sphere* ObjectIntersection::GetIntersectionSphere()
{
return intersectionSphere;
}
<file_sep>#pragma once
#include <DirectXMath.h>
using namespace DirectX;
class ShadowLight
{
private:
XMMATRIX viewMatrix;
XMMATRIX projectionMatrix;
XMFLOAT4 ambientColor;
XMFLOAT4 diffuseColor;
XMFLOAT3 position;
XMFLOAT3 lookAt;
public:
ShadowLight();
ShadowLight(XMFLOAT4 ambient, XMFLOAT4 diffuse, XMFLOAT3 position, XMFLOAT3 lookAt);
~ShadowLight();
XMFLOAT4 GetAmbientColor();
XMFLOAT4 GetDiffuseColor();
XMFLOAT3 GetPosition();
void SetAmbientColor(XMFLOAT4 ambient);
void SetDiffuseColor(XMFLOAT4 diffuse);
void SetPosition(XMFLOAT3 position);
void SetLookAt(XMFLOAT3 lookAt);
void CreateViewMatrix();
void CreateProjectionMatrix(float screenDepth, float screenNear);
void GetViewMatrix(XMMATRIX& viewMatrix);
void GetProjectionMatrix(XMMATRIX& projectionMatrix);
XMFLOAT3 GetDirection();
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include "ShaderBase.h"
using namespace DirectX;
class ShaderLight : public ShaderBase
{
private:
struct LightBufferPS
{
DirectX::XMMATRIX lightVP;
DirectX::XMFLOAT3 lightDirection;
int size;
};
ID3D11SamplerState* sampleState;
ID3D11Buffer* lightBuffer;
void SetLightBuffer(ID3D11DeviceContext* deviceContext, DirectX::XMFLOAT3 lightDirection, int shadowMapSize, XMMATRIX& lightVP);
public:
ShaderLight(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename);
virtual ~ShaderLight();
void SetBuffers(ID3D11DeviceContext* deviceContext,
ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalTexture, ID3D11ShaderResourceView* shadowTexture, ID3D11ShaderResourceView* worldPosTexture,
DirectX::XMFLOAT3 lightDirection, XMMATRIX& lightWVP, int shadowMapSize);
virtual void Draw(ID3D11DeviceContext* deviceContext, int indexCount);
};
<file_sep>#include "ShadowLight.h"
ShadowLight::ShadowLight()
{
//If default constructed object should be used, then all values have to be set by the SET functions.
}
ShadowLight::ShadowLight(XMFLOAT4 ambient, XMFLOAT4 diffuse, XMFLOAT3 position, XMFLOAT3 lookAt)
{
ambientColor = ambient;
diffuseColor = diffuse;
this->position = position;
this->lookAt = lookAt;
}
ShadowLight::~ShadowLight()
{
}
XMFLOAT4 ShadowLight::GetAmbientColor()
{
return ambientColor;
}
XMFLOAT4 ShadowLight::GetDiffuseColor()
{
return diffuseColor;
}
XMFLOAT3 ShadowLight::GetPosition()
{
return position;
}
void ShadowLight::SetAmbientColor(XMFLOAT4 ambient)
{
ambientColor = ambient;
}
void ShadowLight::SetDiffuseColor(XMFLOAT4 diffuse)
{
diffuseColor = diffuse;
}
void ShadowLight::SetPosition(XMFLOAT3 position)
{
this->position = position;
}
void ShadowLight::SetLookAt(XMFLOAT3 lookAt)
{
this->lookAt = lookAt;
}
void ShadowLight::CreateViewMatrix()
{
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, .0f);
XMVECTOR pos = XMVectorSet(position.x, position.y, position.z, .0f);
XMVECTOR look = XMVectorSet(lookAt.x, lookAt.y, lookAt.z, .0f);
viewMatrix = XMMatrixLookAtLH(pos, look, up);
}
void ShadowLight::CreateProjectionMatrix(float screenDepth, float screenNear)
{
//Field of view and screen aspect for square light
float fov = (float)XM_PI / 2.0f;
float screenAspect = 1.0f;
projectionMatrix = XMMatrixPerspectiveFovLH(fov, screenAspect, screenNear, screenDepth);
}
void ShadowLight::GetViewMatrix(XMMATRIX& viewMatrix)
{
viewMatrix = this->viewMatrix;
}
void ShadowLight::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = this->projectionMatrix;
}
XMFLOAT3 ShadowLight::GetDirection()
{
XMFLOAT3 dir(lookAt.x - position.x, lookAt.y - position.y, lookAt.z - position.z);
float length = sqrt((dir.x * dir.x) + (dir.y * dir.y) + (dir.z * dir.z));
dir.x = dir.x / length;
dir.y = dir.y / length;
dir.z = dir.z / length;
return dir;
}
void* ShadowLight::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShadowLight::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "Deferred.h"
using namespace std;
using namespace DirectX;
Deferred::Deferred(ID3D11Device* device, int textureWidth, int textureHeight)
{
this->textureWidth = textureWidth;
this->textureHeight = textureHeight;
InitializeBuffers(device);
}
Deferred::~Deferred()
{
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
if (depthStencilBuffer)
{
depthStencilBuffer->Release();
depthStencilBuffer = nullptr;
}
for (int i = 0; i < BUFFER_COUNT; i++)
{
if (shaderResourceViewArray[i])
{
shaderResourceViewArray[i]->Release();
shaderResourceViewArray[i] = nullptr;
}
if (renderTargetViewArray[i])
{
renderTargetViewArray[i]->Release();
renderTargetViewArray[i] = nullptr;
}
if (renderTargetTextureArray[i])
{
renderTargetTextureArray[i]->Release();
renderTargetTextureArray[i] = nullptr;
}
}
}
void Deferred::InitializeBuffers(ID3D11Device* device)
{
HRESULT result;
D3D11_TEXTURE2D_DESC textureDesc;
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));
//Render target texture description
textureDesc.Width = textureWidth;
textureDesc.Height = textureHeight;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
//Create the render target textures
for (int i = 0; i < BUFFER_COUNT; i++)
{
result = device->CreateTexture2D(&textureDesc, NULL, &renderTargetTextureArray[i]);
if (FAILED(result))
{
throw runtime_error("Error creating render target textures");
}
}
//Description of the render target view.
renderTargetViewDesc.Format = textureDesc.Format;
renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
renderTargetViewDesc.Texture2D.MipSlice = 0;
//Create the render target views
for (int i = 0; i < BUFFER_COUNT; i++)
{
result = device->CreateRenderTargetView(renderTargetTextureArray[i], &renderTargetViewDesc, &renderTargetViewArray[i]);
if (FAILED(result))
{
throw runtime_error("Error creating render target views");
}
}
//Description of the shader resource view
shaderResourceViewDesc.Format = textureDesc.Format;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;
//Create the shader resource views
for (int i = 0; i < BUFFER_COUNT; i++)
{
result = device->CreateShaderResourceView(renderTargetTextureArray[i], &shaderResourceViewDesc, &shaderResourceViewArray[i]);
if (FAILED(result))
{
throw runtime_error("Error creating shader resource views");
}
}
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
//Description of the depth buffer
depthBufferDesc.Width = textureWidth;
depthBufferDesc.Height = textureHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// Create the texture for the depth buffer
result = device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);
if (FAILED(result))
{
throw runtime_error("Error creating texture for the depth buffer");
}
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
//Stencil view description.
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
//Create the depth stencil view
result = device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView);
if (FAILED(result))
{
throw runtime_error("Error creating depth stencil view");
}
//Viewport for rendering
viewport.Width = (float)textureWidth;
viewport.Height = (float)textureHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
}
void Deferred::SetRenderTargets(ID3D11DeviceContext* deviceContext)
{
//Bind the render target view array and depth stencil buffer to the output render pipeline
deviceContext->OMSetRenderTargets(BUFFER_COUNT, renderTargetViewArray, depthStencilView);
deviceContext->RSSetViewports(1, &viewport);
}
void Deferred::ClearRenderTargets(ID3D11DeviceContext* deviceContext, float r, float g, float b, float a)
{
float color[4] = { r, g, b, a };
//Clear the render target buffers
for (int i = 0; i < BUFFER_COUNT; i++)
{
deviceContext->ClearRenderTargetView(renderTargetViewArray[i], color);
}
deviceContext->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
return;
}
ID3D11ShaderResourceView* Deferred::GetShaderResourceView(int viewNumber)
{
return shaderResourceViewArray[viewNumber];
}
void* Deferred::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void Deferred::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "ShaderBase.h"
using namespace std;
ShaderBase::ShaderBase(ID3D11Device* device)
{
vertexShader = nullptr;
hullShader = nullptr;
pixelShader = nullptr;
geometryShader = nullptr;
domainShader = nullptr;
}
ShaderBase::~ShaderBase()
{
if (vertexShader)
vertexShader->Release();
if (pixelShader)
pixelShader->Release();
if (hullShader)
hullShader->Release();
if (geometryShader)
geometryShader->Release();
if (domainShader)
domainShader->Release();
}
void ShaderBase::CreateMandatoryShaders(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename, D3D11_INPUT_ELEMENT_DESC* inputDesc, unsigned int inputDescSize)
{
HRESULT hr;
ID3DBlob* errorMessage = nullptr;
//Create vertex shader
ID3DBlob* pVS = nullptr;
hr = D3DCompileFromFile(vertexShaderFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_4_0", NULL, NULL, &pVS, &errorMessage);
if (FAILED(hr))
{
if (errorMessage)
{
throw runtime_error(string(static_cast<const char *>(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()));
}
else
{
throw runtime_error("No such file");
}
}
device->CreateVertexShader(pVS->GetBufferPointer(), pVS->GetBufferSize(), nullptr, &vertexShader);
//Create vertex layout
device->CreateInputLayout(inputDesc, inputDescSize, pVS->GetBufferPointer(), pVS->GetBufferSize(), &inputLayout);
pVS->Release();
//Create pixel shader.
ID3DBlob* pPS = nullptr;
hr = D3DCompileFromFile(pixelShaderFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_4_0", NULL, NULL, &pPS, &errorMessage);
if (FAILED(hr))
{
if (errorMessage)
{
throw runtime_error(string(static_cast<const char *>(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()));
}
else
{
throw runtime_error("No such file");
}
}
device->CreatePixelShader(pPS->GetBufferPointer(), pPS->GetBufferSize(), nullptr, &pixelShader);
pPS->Release();
}
<file_sep>#include "Camera.h"
using namespace DirectX;
Camera::Camera()
{
}
Camera::~Camera()
{
}
void Camera::SetPosition(XMFLOAT3 newPos)
{
positionXYZ = newPos;
}
void Camera::SetRotation(XMFLOAT3 newRot)
{
rotationXYZ = newRot;
}
XMFLOAT3 Camera::GetPosition()
{
return positionXYZ;
}
XMFLOAT3 Camera::GetRotation()
{
return rotationXYZ;
}
void Camera::GetViewMatrix(XMMATRIX& viewMatrix)
{
viewMatrix = this->viewMatrix;
}
void Camera::Update()
{
XMMATRIX rotationMatrix;
XMVECTOR up = { { 0.0f, 1.0f, 0.0f } };
XMVECTOR position = { { positionXYZ.x, positionXYZ.y, positionXYZ.z } };
XMVECTOR lookAt = { { 0.0f, 0.0f, 1.0f } };
rotationMatrix = XMMatrixRotationRollPitchYaw(XMConvertToRadians(rotationXYZ.x), XMConvertToRadians(rotationXYZ.y), XMConvertToRadians(rotationXYZ.z));
lookAt = XMVector3TransformCoord(lookAt, rotationMatrix);
up = XMVector3TransformCoord(up, rotationMatrix);
lookAt = position + lookAt;
viewMatrix = XMMatrixLookAtLH(position, lookAt, up);
}
void* Camera::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void Camera::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "D3DClass.h"
using namespace DirectX;
using namespace std;
D3DClass::D3DClass(int screenWidth, int screenHeight, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
HRESULT result;
ID3D11Texture2D* backBufferPtr;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_RASTERIZER_DESC rasterDesc;
D3D11_RASTERIZER_DESC rasterNoCullingDesc;
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
D3D11_BLEND_DESC blendStateDescription;
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
// Initialize the swap chain description.
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = screenWidth;
swapChainDesc.BufferDesc.Height = screenHeight;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hwnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
if (fullscreen)
{
swapChainDesc.Windowed = false;
}
else
{
swapChainDesc.Windowed = true;
}
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;
//Create the swap chain, device, and device context
result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &deviceContext);
if (FAILED(result))
{
throw std::runtime_error("Could not create swap buffer");
}
//Get the pointer to the back buffer
result = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if (FAILED(result))
{
throw std::runtime_error("Could not get swap chain pointer");
}
// Create the render target view with the back buffer pointer
result = device->CreateRenderTargetView(backBufferPtr, NULL, &renderTargetView);
if (FAILED(result))
{
throw std::runtime_error("CreateRenderTargetView error");
}
backBufferPtr->Release();
backBufferPtr = 0;
// Initialize the description of the depth buffer.
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
result = device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);
if (FAILED(result))
{
throw std::runtime_error("Depth buffer error");
}
// Initialize the description of the stencil state.
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the depth stencil state.
result = device->CreateDepthStencilState(&depthStencilDesc, &depthStencilState);
if (FAILED(result))
{
throw std::runtime_error("Depth stencil error");
}
// Set the depth stencil state.
deviceContext->OMSetDepthStencilState(depthStencilState, 1);
// Initialize the depth stencil view.
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
result = device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView);
if (FAILED(result))
{
throw std::runtime_error("Depth stencil view error");
}
//Bind the render target view and depth stencil buffer to the output render pipeline.
deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
//Setup the raster description which will determine how and what polygons will be drawn
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
//Create the rasterizer state from the description
result = device->CreateRasterizerState(&rasterDesc, &rasterState);
if (FAILED(result))
{
throw std::runtime_error("Resterizer state error 1");
}
deviceContext->RSSetState(rasterState);
rasterNoCullingDesc.AntialiasedLineEnable = false;
rasterNoCullingDesc.CullMode = D3D11_CULL_NONE;
rasterNoCullingDesc.DepthBias = 0;
rasterNoCullingDesc.DepthBiasClamp = 0.0f;
rasterNoCullingDesc.DepthClipEnable = true;
rasterNoCullingDesc.FillMode = D3D11_FILL_SOLID;
rasterNoCullingDesc.FrontCounterClockwise = false;
rasterNoCullingDesc.MultisampleEnable = false;
rasterNoCullingDesc.ScissorEnable = false;
rasterNoCullingDesc.SlopeScaledDepthBias = 0.0f;
result = device->CreateRasterizerState(&rasterNoCullingDesc, &rasterNoCullingState);
if (FAILED(result))
{
throw std::runtime_error("Resterizer state error 2");
}
//Setup the viewport for rendering
viewport.Width = (float)screenWidth;
viewport.Height = (float)screenHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
deviceContext->RSSetViewports(1, &viewport);
// Create the matrices for 3D rendering.
projectionMatrix = XMMatrixPerspectiveFovLH(XM_PI * 0.45f, (float)screenWidth / (float)screenHeight, screenNear, screenDepth);
worldMatrix = XMMatrixIdentity();
// Create an orthographic projection matrix for 2D rendering.
orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
result = device->CreateDepthStencilState(&depthDisabledStencilDesc, &depthDisabledStencilState);
if (FAILED(result))
{
throw std::runtime_error("Depth stencil state error");
}
//Clear the blend state description.
ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
result = device->CreateBlendState(&blendStateDescription, &alphaEnableBlendingState);
if (FAILED(result))
{
throw std::runtime_error("Blend state error");
}
blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
result = device->CreateBlendState(&blendStateDescription, &alphaDisableBlendingState);
if (FAILED(result))
{
throw std::runtime_error("Blend state error 2");
}
deferredShader = new Deferred(device, screenWidth, screenHeight);
}
D3DClass::~D3DClass()
{
if (swapChain)
swapChain->SetFullscreenState(false, NULL);
if (alphaEnableBlendingState)
{
alphaEnableBlendingState->Release();
alphaEnableBlendingState = nullptr;
}
if (alphaDisableBlendingState)
{
alphaDisableBlendingState->Release();
alphaDisableBlendingState = nullptr;
}
if (depthDisabledStencilState)
{
depthDisabledStencilState->Release();
depthDisabledStencilState = nullptr;
}
if (rasterState)
{
rasterState->Release();
rasterState = nullptr;
}
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
if (depthStencilState)
{
depthStencilState->Release();
depthStencilState = nullptr;
}
if (renderTargetView)
{
renderTargetView->Release();
renderTargetView = nullptr;
}
if (deviceContext)
{
deviceContext->Release();
deviceContext = nullptr;
}
if (device)
{
device->Release();
device = nullptr;
}
if (swapChain)
{
swapChain->Release();
swapChain = nullptr;
}
if (deferredShader)
{
delete deferredShader;
deferredShader = nullptr;
}
}
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
float color[4];
color[0] = red;
color[1] = green;
color[2] = blue;
color[3] = alpha;
deviceContext->ClearRenderTargetView(renderTargetView, color);
deviceContext->OMSetDepthStencilState(depthStencilState, 1);
deviceContext->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
void D3DClass::EndScene()
{
swapChain->Present(0, 0);
}
ID3D11Device* D3DClass::GetDevice()
{
return device;
}
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
return deviceContext;
}
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = this->projectionMatrix;
}
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
worldMatrix = this->worldMatrix;
}
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
orthoMatrix = this->orthoMatrix;
}
void D3DClass::TurnZBufferON()
{
deviceContext->OMSetDepthStencilState(depthStencilState, 1);
}
void D3DClass::TurnZBufferOFF()
{
deviceContext->OMSetDepthStencilState(depthDisabledStencilState, 1);
}
void D3DClass::SetBackBufferRenderTarget()
{
deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
}
void D3DClass::ResetViewport()
{
deviceContext->RSSetViewports(1, &viewport);
}
void D3DClass::TurnAlphaBlendingON()
{
float blendFactor[4];
blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;
deviceContext->OMSetBlendState(alphaEnableBlendingState, blendFactor, 0xffffffff);
}
void D3DClass::TurnAlphaBlendingOFF()
{
float blendFactor[4];
blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;
deviceContext->OMSetBlendState(alphaDisableBlendingState, blendFactor, 0xffffffff);
}
void D3DClass::TurnCullingON()
{
deviceContext->RSSetState(rasterState);
}
void D3DClass::TurnCullingOFF()
{
deviceContext->RSSetState(rasterNoCullingState);
}
ID3D11ShaderResourceView* D3DClass::GetDeferredSRV(int viewNumber)
{
return deferredShader->GetShaderResourceView(viewNumber);
}
void D3DClass::ActivateDeferredShading()
{
deferredShader->ClearRenderTargets(deviceContext, 0.2f, 0.4f, 1.0f, 1.0f);
deferredShader->SetRenderTargets(deviceContext);
}
void* D3DClass::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void D3DClass::operator delete(void* p)
{
_mm_free(p);
}
<file_sep>#include "ShaderLight.h"
using namespace std;
using namespace DirectX;
ShaderLight::ShaderLight(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename)
: ShaderBase(device)
{
HRESULT result;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC lightBufferDesc;
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
CreateMandatoryShaders(device, vertexShaderFilename, pixelShaderFilename, inputDesc, ARRAYSIZE(inputDesc));
//Texture sampler state description
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
//Create the texture sampler state
result = device->CreateSamplerState(&samplerDesc, &sampleState);
if (FAILED(result))
{
throw runtime_error("Error creating sampler state");
}
// Description of the light constant buffer in the pixel shader.
lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBufferPS);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightBufferDesc.MiscFlags = 0;
lightBufferDesc.StructureByteStride = 0;
//Create light buffer pointer so the values withing the shader can be changed
result = device->CreateBuffer(&lightBufferDesc, NULL, &lightBuffer);
if (FAILED(result))
{
throw runtime_error("Error creating ligth buffer");
}
}
ShaderLight::~ShaderLight()
{
if (lightBuffer)
{
lightBuffer->Release();
lightBuffer = nullptr;
}
if (sampleState)
{
sampleState->Release();
sampleState = nullptr;
}
}
void ShaderLight::SetBuffers(ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView* colorTexture,
ID3D11ShaderResourceView* normalTexture, ID3D11ShaderResourceView* shadowTexture, ID3D11ShaderResourceView* worldPosTexture, DirectX::XMFLOAT3 lightDirection, XMMATRIX& lightVP, int shadowMapSize)
{
//Update light constant buffer
SetLightBuffer(deviceContext, lightDirection, shadowMapSize, lightVP);
//Set shader texture resources in the pixel shader
deviceContext->PSSetShaderResources(0, 1, &colorTexture);
deviceContext->PSSetShaderResources(1, 1, &normalTexture);
deviceContext->PSSetShaderResources(2, 1, &shadowTexture);
deviceContext->PSSetShaderResources(3, 1, &worldPosTexture);
}
void ShaderLight::Draw(ID3D11DeviceContext* deviceContext, int indexCount)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(hullShader, nullptr, 0);
deviceContext->DSSetShader(domainShader, nullptr, 0);
deviceContext->GSSetShader(geometryShader, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
deviceContext->IASetInputLayout(inputLayout);
deviceContext->PSSetSamplers(0, 1, &sampleState);
//Unlike the other shaders who lets the objects draw themselves, after activating the shader and setting all values and data, this shader has to render the whole scene
//since the objects have already drawn themselves to the buffer used in ShaderDeferred
deviceContext->DrawIndexed(indexCount, 0, 0);
}
void ShaderLight::SetLightBuffer(ID3D11DeviceContext* deviceContext, XMFLOAT3 lightDirection, int shadowMapSize, XMMATRIX& lightVP)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
unsigned int bufferNumber = 0;
XMMATRIX lvp = XMMatrixTranspose(lightVP);
//Lock the light constant buffer so it can be written to.
result = deviceContext->Map(lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
throw runtime_error("Could not Map light buffer in ShaderLight");
}
LightBufferPS* lightData = (LightBufferPS*)mappedResource.pData;
//Copy the lighting variables into the constant buffer
lightData->lightVP = lvp;
lightData->lightDirection = lightDirection;
lightData->size = shadowMapSize;
deviceContext->Unmap(lightBuffer, 0);
//Set light buffer in pixel shader with updated values
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &lightBuffer);
}
<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <string>
#include <vector>
#include <fstream>
class Texture
{
private:
ID3D11ShaderResourceView* texture;
int width;
int height;
public:
Texture(std::string filename, ID3D11Device* device);
~Texture();
ID3D11ShaderResourceView* GetTexture() const;
};
<file_sep>#pragma once
#include "ShaderBase.h"
class ShaderDefault : public ShaderBase
{
private:
struct MatrixBuffer
{
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX projection;
DirectX::XMMATRIX wvp;
};
ID3D11Buffer* matrixBuffer;
public:
ShaderDefault(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename);
virtual ~ShaderDefault();
virtual void UseShader(ID3D11DeviceContext* deviceContext);
void SetMatrices(ID3D11DeviceContext* deviceContext, DirectX::XMMATRIX& worldMatrix, DirectX::XMMATRIX& viewMatrix, DirectX::XMMATRIX& projectionMatrix);
//Without overloading these the 16B alignment of an XMMATRIX is not guaranteed, which could possibly cause access violation
void* operator new(size_t i);
void operator delete(void* p);
};
<file_sep>#pragma once
#include <windows.h>
#include <stdexcept>
#include "Application.h"
class System
{
private:
LPCWSTR applicationName;
HINSTANCE hinstance;
HWND hwnd;
Application* application;
int screenWidth;
int screenHeight;
bool fullscreen;
bool showCursor;
int realScreenWidth;
int realScreenHeight;
bool Update();
void InitializeWindows();
void ShutdownWindows();
public:
System(bool fullscreen = false, bool showCursor = true, int screenWidth = 1000, int screenHeight = 800);
~System();
void Run();
LRESULT CALLBACK MessageHandler(HWND, UINT, WPARAM, LPARAM);
};
static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
static System* applicationHandle = nullptr;
|
15c24740464ef0675459ac4aa48f5df68722f73e
|
[
"C",
"Text",
"C++"
] | 59
|
C++
|
lunderot/3DProject
|
ebdace1508d9d6c749e25088d93d06f204e17aed
|
ca9006480b056b003813ae8e293b8f3db801604b
|
refs/heads/master
|
<file_sep>## [1.1.1](https://github.com/etclabscore/react-monaco-editor/compare/1.1.0...1.1.1) (2020-12-07)
### Bug Fixes
* bump monaco to 0.21.2 to get bug fix for monaco.languages.json.jsonDefaults ([041dd99](https://github.com/etclabscore/react-monaco-editor/commit/041dd995fb6ee6788a9b3e39166d558af79f2ddc))
# [1.1.0](https://github.com/etclabscore/react-monaco-editor/compare/1.0.4...1.1.0) (2020-12-05)
### Features
* update monaco to 0.21.0 ([bfa4db2](https://github.com/etclabscore/react-monaco-editor/commit/bfa4db260997c407d9b1ec79653622c461b90130))
## [1.0.4](https://github.com/etclabscore/react-monaco-editor/compare/1.0.3...1.0.4) (2020-03-09)
### Bug Fixes
* **README:** update readme about how monaco editor is loaded ([c5488e6](https://github.com/etclabscore/react-monaco-editor/commit/c5488e65b6060bb771358542c81ac800245b6270))
* **README:** update steps to include monaco-editor-webpack-plugin ([1a35297](https://github.com/etclabscore/react-monaco-editor/commit/1a3529795f5c717906ff3e04ed361ee8b638801f))
* options parameter ([da4bacb](https://github.com/etclabscore/react-monaco-editor/commit/da4bacb8abd765cf68fb1fc71837d3ab7a87c4c9))
## [1.0.3](https://github.com/etclabscore/react-monaco-editor/compare/1.0.2...1.0.3) (2019-12-13)
### Bug Fixes
* **README:** use rescript utils to prepend webpack plugin ([c3dcd88](https://github.com/etclabscore/react-monaco-editor/commit/c3dcd8827c88f50848f8bfee1e6d4cd623d651bf))
* dont update if not changed for read only ([2eae929](https://github.com/etclabscore/react-monaco-editor/commit/2eae929e98a57a4f4630b5b213a9e24b961c7b55))
## [1.0.2](https://github.com/etclabscore/react-monaco-editor/compare/1.0.1...1.0.2) (2019-12-13)
### Bug Fixes
* tsconfig ([30c5463](https://github.com/etclabscore/react-monaco-editor/commit/30c54637338ef91b368cab54084ffcdbceda778c))
* **README:** add import to component code example ([30f249d](https://github.com/etclabscore/react-monaco-editor/commit/30f249d6b105a041d8c1f17a06296af367b017e4))
## [1.0.1](https://github.com/etclabscore/react-monaco-editor/compare/1.0.0...1.0.1) (2019-12-13)
### Bug Fixes
* **build:** issue with tsconfig ([debd480](https://github.com/etclabscore/react-monaco-editor/commit/debd4807d61c4b0d06088285e62587a4e8fd9cb3))
* **release:** remove github pages release ([b61e13d](https://github.com/etclabscore/react-monaco-editor/commit/b61e13d59b781bb74b0f818b0d3c83aa7ae79e77))
# 1.0.0 (2019-12-13)
### Bug Fixes
* **README:** add example component usage ([6d48d83](https://github.com/etclabscore/react-monaco-editor/commit/6d48d83bf754b8158bb51e55176cb7007c918b66))
* **REAMDE:** update js code syntax ([e17a3a8](https://github.com/etclabscore/react-monaco-editor/commit/e17a3a8779579ad13f8aed5916808089a9d137b0))
<file_sep>import MonacoEditor from "./MonacoEditor";
export default MonacoEditor;
<file_sep># React Monaco Editor
Monaco Editor Wrapper for integration with react + webpack. Based on [SurenAt93/monaco-react/](https://github.com/SurenAt93/monaco-react/) but does not load from a CDN. It loads monaco via `monaco-editor-webpack-plugin` and gives installation instructions for a new or existing project via `rescripts`.
## Setup in a new create-react-app project
### 1. Install deps
```
npm install @etclabscore/react-monaco-editor --save
```
```sh
npm install @rescripts/cli @rescripts/utilities --save-dev
```
```sh
npm install monaco-editor-webpack-plugin --save-dev
```
### 2. Replace `react-scripts` calls with `rescripts` calls
`package.json`
```diff
{
"name": "built-with-rescripts",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.6.1",
"react-dom": "^16.6.1",
"react-scripts": "2.1.1"
}
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-env": "^0.0.10"
}
"scripts": {
- "start": "react-scripts start",
+ "start": "rescripts start",
- "build": "react-scripts build",
+ "build": "rescripts build",
- "test": "react-scripts test",
+ "test": "rescripts test",
- "eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
```
### 3. Add new file called in root of your project called rescript-monaco.js
```js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const { prependWebpackPlugin } = require("@rescripts/utilities");
module.exports = function override(config, env) {
return prependWebpackPlugin(new MonacoWebpackPlugin({
// available options are documented at https://github.com/Microsoft/monaco-editor-webpack-plugin#options
languages: ["json"]
}), config);
}
```
### 4. Define a 'rescripts' field and specify the rescript-monaco.js
`package.json`
```diff
{
"name": "built-with-rescripts",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.6.1",
"react-dom": "^16.6.1",
"react-scripts": "2.1.1"
}
"devDependencies": {
"@rescripts/cli": "^0.1.0"
}
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
+ "rescripts": [
+ "rescript-monaco"
+ ]
}
```
### 5. Use the component:
```js
import MonacoEditor from "@etclabscore/react-monaco-editor";
const MyComponent = ({value}) => {
const handleEditorDidMount = (editor) => {
}
const handleChange = (ev, value) => {
}
return (
<MonacoEditor
height="100vh"
value={value}
editorDidMount={handleEditorDidMount}
language="json"
onChange={handleChange}
/>
);
}
```
### Contributing
How to contribute, build and release are outlined in [CONTRIBUTING.md](CONTRIBUTING.md), [BUILDING.md](BUILDING.md) and [RELEASING.md](RELEASING.md) respectively. Commits in this repository follow the [CONVENTIONAL_COMMITS.md](CONVENTIONAL_COMMITS.md) specification.
|
5d9e24006ac9c66724e4838cc96243b9f83b2526
|
[
"Markdown",
"TypeScript"
] | 3
|
Markdown
|
etclabscore/react-monaco-editor
|
b9aefc3e0fb502d4d74f5e2677f85b7b6024f233
|
d547b4c423eae1494438cd8ca4fdc614f65f87b6
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { MeasurmentSystemService } from '../../services/measurment-system.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html'
})
export class HeaderComponent implements OnInit {
private isCollapsed: boolean = true;
private system: any;
constructor(private systemService: MeasurmentSystemService) { }
ngOnInit() {
this.system = this.systemService.getSystem();
}
changeSystem(newSystem: string) {
this.systemService.setSystem(newSystem);
localStorage['system'] = newSystem;
}
}
<file_sep>import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
import { MeasurmentSystemService } from '../../../services/measurment-system.service';
@Component({
selector: 'trail-width',
templateUrl: './trail-width.component.html',
styleUrls: ['./trail-width.component.css']
})
export class TrailWidthComponent implements OnInit {
@Input() widths: any[];
@Output() selectedWidth = new EventEmitter();
private system: any;
constructor(private systemService: MeasurmentSystemService) { }
ngOnInit() {
this.system = this.systemService.getSystem();
}
selectWidth(id) {
this.selectedWidth.emit(id);
}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class MeasurmentSystemService {
private system: any = {};
constructor() {
this.system.type = localStorage['system'] ? localStorage['system'] : 'metric';
this.system.notation = this.system.type == 'metric' ? 'm' : '"';
}
getSystem() {
return this.system;
}
setSystem(type: string) {
this.system.type = type;
this.system.notation = type == 'metric' ? 'm' : '"';
}
}
<file_sep>import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[centered]'
})
export class CenteredDirective {
constructor(private element: ElementRef) {
element.nativeElement.style.textAlign = 'center';
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { CollapseModule, DropdownModule } from 'ng2-bootstrap';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { CriteriaComponent } from './components/criteria/criteria.component';
import { ResultComponent } from './components/result/result.component';
import { UnitPipe } from './pipes/unit.pipe';
import { MeasurmentSystemService } from './services/measurment-system.service';
import { DataService } from './services/data.service';
import { TrailWidthComponent } from './components/criteria/trail-width/trail-width.component';
import { CenteredDirective } from './directives/centered.directive';
import { TreadSurfaceComponent } from './components/criteria/tread-surface/tread-surface.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
CriteriaComponent,
ResultComponent,
UnitPipe,
TrailWidthComponent,
CenteredDirective,
TreadSurfaceComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
CollapseModule.forRoot(),
DropdownModule.forRoot()
],
providers: [
MeasurmentSystemService, DataService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Injectable } from '@angular/core';
var model = require('../data.json');
@Injectable()
export class DataService {
private data: any = model;
public getSurfaces(): any[] {
return this.data['tread-surface'];
}
public getWidths(): any[] {
return this.data['trail-width'];
}
}
<file_sep>import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'tread-surface',
templateUrl: './tread-surface.component.html',
styleUrls: ['./tread-surface.component.css']
})
export class TreadSurfaceComponent {
@Input() surfaces: any[];
@Output() selectedSurface = new EventEmitter();
selectSurface(id) {
this.selectedSurface.emit(id);
}
}
<file_sep>import { TrailRatingsPage } from './app.po';
describe('trail-ratings App', function() {
let page: TrailRatingsPage;
beforeEach(() => {
page = new TrailRatingsPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('app works!');
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-criteria',
templateUrl: './criteria.component.html'
})
export class CriteriaComponent implements OnInit {
private widths: any[];
private surfaces: any[];
private selectedWidth: number;
private selectedSurface: number;
constructor(private data: DataService) { }
ngOnInit() {
this.widths = this.data.getWidths();
this.surfaces = this.data.getSurfaces();
}
selectWidth(id) {
this.selectedWidth = id;
}
selectSurface(id) {
this.selectedSurface = id;
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'unit'
})
export class UnitPipe implements PipeTransform {
transform(value: number, system: string): number {
if (system == 'metric') {
return value / 39.3700787;
}
return value;
}
}
|
ce1127957434ff37adbf5fd423bb51c25df8c2f5
|
[
"TypeScript"
] | 10
|
TypeScript
|
pufanalexandru/trail-ratings
|
02fb997e48e5e6e0e61bccb2c5e10226104747f5
|
825e4a4cf759e27f91c516cadb74294de8fe9299
|
refs/heads/master
|
<repo_name>stuffandahalf/qol-utils<file_sep>/README.md
# qol-utils
A series of scripts I use to simplify my workflow. Typically saved as ~/bin
<file_sep>/pokebox-counter.py
#!/usr/bin/env python
from __future__ import print_function
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main(args):
if len(args) != 2:
eprint(args[0] + ' requires one argument')
return 1
num = int(args[1]) - 1
box = (num // 30) + 1
offset = num % 30
print('BOX ' + str(box) + ' OFFSET ' + str(offset + 1))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
<file_sep>/sysinfo.sh
#!/bin/sh
watch "echo 'CPU Frequency'; \
lscpu | grep MHz; echo ''; \
sensors"
|
fe444ef0f50bd270496de4216019f4d9568498be
|
[
"Markdown",
"Python",
"Shell"
] | 3
|
Markdown
|
stuffandahalf/qol-utils
|
cfd47d1d659d0a30e852be5f6d6b2b54b4fe6183
|
634ac2f250a5e865abb7e1b11b6c22f90f89b1f7
|
refs/heads/master
|
<repo_name>mchung/bootup<file_sep>/slicehost/add_vhost.rb
#!/usr/bin/env ruby
require 'erb'
require 'optparse'
require 'pp'
help = <<HELP
$0 is a friendly VirtualHost generating script
Basic Command Line Usage:
#{__FILE__} --host=foo.com --ports=5000-5010
Options:
HELP
DOMAIN = {}
opts = OptionParser.new do |opts|
opts.banner = help
opts.on("--host [host]", "Hostname") do |host|
DOMAIN[:host] = host
end
opts.on("--ports [ports]", "Proxy ports") do |ports|
s, f = ports.split("-").collect{|x| x.to_i}
DOMAIN[:ports] = (s..f).to_a
end
end
opts.parse!
template = ERB.new(File.read("~/bootup/config/etc/apache/sites-available/apache-site.conf"))
`mkdir -p /var/local/#{DOMAIN[:host]}/shared/log`
`mkdir -p /var/local/#{DOMAIN[:host]}/shared/config`
`chown -R app:app /var/local/#{DOMAIN[:host]}`
template.run(binding)
<file_sep>/slicehost/10-misc.sh
#
# Ubuntu 8.0.4
#
# Installs miscellaneous packages (Ubuntu / Rubygems)
#
aptitude update -y
aptitude install -y locate git-core git-doc tree emacs22-nox screen nmap sqlite3 libsqlite3-dev libxml2 libxml2-dev libxslt1.1 libxslt1-dev subversion ssl-cert
updatedb
gem update
gem install rake hpricot rack libxml-ruby nokogiri
<file_sep>/slicehost/36-passenger.sh
#
# Ubuntu 8.0.4
#
# Installs Phusion Passenger (mod_rails).
# Also adds a user called "app" that your Rails application runs as
#
PASSENGER_VER=2.2.11
if [ ! -n "$SERVERNAME" ]
then
echo "Must set 'ServerName' for Apache"
echo "SERVERNAME=example.com `basename $0`"
exit
fi
export USERNAME=app
sh add_user.sh
gem install passenger -v $PASSENGER_VER
passenger-install-apache2-module -a
echo "\
ServerName $SERVERNAME
LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-$PASSENGER_VER/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-$PASSENGER_VER
PassengerRuby /usr/local/bin/ruby
" >> /etc/apache2/apache2.conf
<file_sep>/slicehost/05-ruby.sh
#
# Ubuntu 8.0.4
#
# Compiles Ruby 1.8.7-p72 and Rubygems 1.3.2 from source
#
aptitude update -y
aptitude install -y libssl-dev libreadline5-dev zlib1g-dev
# Download Ruby from source, compile, and install.
RUBY_VER=1.8.7-p174
RUBY_PKG=ruby-$RUBY_VER
RUBY_URL=ftp://ftp.ruby-lang.org/pub/ruby/1.8/$RUBY_PKG.tar.gz
cd /usr/local/src
wget $RUBY_URL
tar zxvf $RUBY_PKG.tar.gz
cd $RUBY_PKG
./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr
make -j4
make install
# Download Rubygems from source, compile, and install
RUBYGEM_VER=1.3.6
ASSET_ID=69365
RUBYGEM_PKG=rubygems-$RUBYGEM_VER
RUBYGEM_URL=http://rubyforge.org/frs/download.php/$ASSET_ID/$RUBYGEM_PKG.tgz
cd /usr/local/src
wget $RUBYGEM_URL
tar zxvf $RUBYGEM_PKG.tgz
cd $RUBYGEM_PKG
ruby setup.rb
<file_sep>/slicehost/20-mysql.sh
#
# Ubuntu 8.0.4
#
# Installs MySQL packages. Installs MySQL gem if Rubygems is installed
#
# TODO: How to set root password non-interactively?
#
aptitude update -y
MY_VER=5.1
aptitude install -y mysql-server-$MY_VER mysql-client-$MY_VER libmysqlclient15-dev
if [ -e "`which gem`" ]
then
# install mysql gem
gem install mysql
fi
# TODO: Create a default cnf file
# sudo cp custom.cnf /etc/mysql/my.cnf
# restart to load changes
service mysql restart
# secure mysql
mysql_secure_installation<file_sep>/slicehost/26-nginx.sh
#
# Ubuntu 8.0.4
#
# Installs Nginx
#
aptitude update -y
aptitude install -y nginx
service nginx restart
<file_sep>/slicehost/40-rails-apps.sh
#
# Ubuntu 8.0.4
#
# Setups Rails directory (Not entirely useful, yet)
#
export USERNAME=app
sh add_user.sh
mkdir -p /var/local
chown app:app /var/local
<file_sep>/slicehost/50-gsl.sh
#
# Ubuntu 8.0.4
#
# Installs GSL with Ruby bindings
#
aptitude update -y
aptitude install -y gsl-bin libgsl0-dev
# Download GSL from source, compile, and install.
GSL_VER=1.10.3
GSL_PKG=rb-gsl-$GSL_VER
GSL_URL=http://rubyforge.org/frs/download.php/28909/$GSL_PKG.tar.gz
cd /usr/local/src
wget $GSL_URL
tar zxvf $GSL_PKG.tar.gz
cd $GSL_PKG
ruby setup.rb config
ruby setup.rb setup
ruby setup.rb install
<file_sep>/slicehost/45-sendmail.sh
#
# Ubuntu 8.0.4
#
# Installs Sendmail.
#
aptitude update -y
aptitude install -y sendmail
<file_sep>/slicehost/35-mongrel.sh
#
# Ubuntu 8.0.4
#
# Installs mongrel.
#
gem install mongrel mongrel_cluster <file_sep>/slicehost/01-iptables.sh
#
# Ubuntu 8.0.4
#
# Update iptables
#
iptables-restore < ~/bootup/config/etc/iptables.up.rules
iptables-save > /etc/iptables.up.rules
perl -pi.bak -e "s/iface lo inet loopback/iface lo inet loopback\npre-up iptables-restore < \/etc\/iptables.up.rules/gi;"
/etc/network/interfaces
<file_sep>/slicehost/slicedns.rb
#!/usr/bin/env ruby
require 'rubygems'
require 'active_resource'
#
# This script was taken from http://github.com/postpostmodern/slicehost-dns/tree/master on Jan 22, 2009
#
# Get your API key from your SliceManager here:
# https://manage.slicehost.com/api/
# and put it here:
API_PASSWORD = YAML::load_file(File.dirname(__FILE__) + '/../config/slicehost.yml')[:api_password]
raise "Couldn't find ../config/slicehost.yml" unless API_PASSWORD
unless ARGV.size == 2 && ARGV[1].end_with?('.')
puts "Usage: #{__FILE__} slice domain.com."
exit
end
# Get command line arguments
slice_name = ARGV.shift
zone_name = ARGV.shift
# Address class is required for Slice class
class Address < String; end
# Define the ActiveResource classes
class Slice < ActiveResource::Base
self.site = "https://#{API_PASSWORD}@api.slicehost.com/"
def self.find_by_name(name)
Slice.find(:first, :params => { :name => name })
end
end
class Zone < ActiveResource::Base
self.site = "https://#{API_PASSWORD}@api.slicehost.com/"
def records
Record.find(:all, :params => { :zone_id => self.id })
end
def self.exists?(name)
!Zone.find(:all, :params => { :origin => name }).empty?
end
def self.find_by_name(name)
Zone.find(:first, :params => { :origin => name })
end
end
class Record < ActiveResource::Base
self.site = "https://#{API_PASSWORD}@api.slicehost.com/"
end
# Method to add a new record based on a hash
def create_record(r, defaults)
rec = Record.new(defaults.merge(r))
rec.save
puts notice(rec)
end
# Prints the record's details
def notice(r)
' | ' + r.name.to_s.ljust(30) +
' | ' + r.record_type.to_s.ljust(5) +
' | ' + r.aux.to_s.rjust(4) +
' | ' + r.data.to_s.ljust(34) +
' | '
end
# Find the IP address of the slice
slice = Slice.find_by_name(slice_name)
# Bail if the slice name doesn't work out
if slice.nil?
puts "\nSlice not found. :( "
puts "Aborted."
exit
end
slice_ip = slice.ip_address
# Check if zone exists
if Zone.exists?(zone_name)
puts "\nA zone for #{zone_name} already exists."
print "Cancel or Overwrite? [Co] "
input = STDIN.gets.chomp.strip
# Respond accordingly
if input.downcase == 'o'
Zone.find_by_name(zone_name).destroy
else
puts " Cancelled"
exit
end
end
# Create new zone
z = Zone.new(:origin => zone_name, :ttl => 43200)
z.save
# Record definitions
defaults = { :zone_id => z.id, :ttl => 43200 }
a_records = [
{ :record_type => 'A', :name => zone_name, :data => slice_ip },
{ :record_type => 'A', :name => "*.#{zone_name}", :data => slice_ip }
]
google_mx = [
{ :record_type => 'MX', :name => zone_name, :aux => 10, :data => 'ASPMX.L.GOOGLE.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 20, :data => 'ALT1.ASPMX.L.GOOGLE.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 20, :data => 'ALT2.ASPMX.L.GOOGLE.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 30, :data => 'ASPMX2.GOOGLEMAIL.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 30, :data => 'ASPMX3.GOOGLEMAIL.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 30, :data => 'ASPMX4.GOOGLEMAIL.COM.' },
{ :record_type => 'MX', :name => zone_name, :aux => 30, :data => 'ASPMX5.GOOGLEMAIL.COM.' }
]
google_cname = [
{ :record_type => 'CNAME', :name => 'mail', :data => 'ghs.google.com.' },
{ :record_type => 'CNAME', :name => 'start', :data => 'ghs.google.com.' },
{ :record_type => 'CNAME', :name => 'docs', :data => 'ghs.google.com.' },
{ :record_type => 'CNAME', :name => 'calendar', :data => 'ghs.google.com.' }
]
google_srv = [
{ :record_type => 'SRV', :name => "_xmpp-server._tcp.#{zone_name}", :aux => 5, :data => '0 5269 xmpp-server.l.google.com.'},
{ :record_type => 'SRV', :name => "_xmpp-server._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server1.l.google.com.'},
{ :record_type => 'SRV', :name => "_xmpp-server._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server2.l.google.com.'},
{ :record_type => 'SRV', :name => "_xmpp-server._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server3.l.google.com.'},
{ :record_type => 'SRV', :name => "_xmpp-server._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server4.l.google.com.'},
{ :record_type => 'SRV', :name => "_jabber._tcp.#{zone_name}", :aux => 5, :data => '0 5269 xmpp-server.l.google.com.'},
{ :record_type => 'SRV', :name => "_jabber._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server1.l.google.com.'},
{ :record_type => 'SRV', :name => "_jabber._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server2.l.google.com.'},
{ :record_type => 'SRV', :name => "_jabber._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server3.l.google.com.'},
{ :record_type => 'SRV', :name => "_jabber._tcp.#{zone_name}", :aux => 20, :data => '0 5269 xmpp-server4.l.google.com.'}
]
ns_records = [
{ :record_type => 'NS', :name => zone_name, :data => 'ns1.slicehost.net.' },
{ :record_type => 'NS', :name => zone_name, :data => 'ns2.slicehost.net.' },
{ :record_type => 'NS', :name => zone_name, :data => 'ns3.slicehost.net.' }
]
# DO IT!!
puts "\nCreating A records..."
a_records.each do |r|
create_record(r, defaults)
end
puts "\nCreating NS records..."
ns_records.each do |r|
create_record(r, defaults)
end
# Ask to add Google records
print "\nAdd records for Google Apps? [Yn] "
input = STDIN.gets.chomp.strip
# Respond accordingly
unless input.downcase == "n"
puts "\nCreating Google MX records..."
google_mx.each do |r|
create_record(r, defaults)
end
puts "\nCreating Google SRV records..."
google_srv.each do |r|
create_record(r, defaults)
end
puts "\nCreating Google CNAME records..."
google_cname.each do |r|
create_record(r, defaults)
end
end
# Finally, let everyone know we're finished
puts "\nALL DONE!"
<file_sep>/slicehost/Rakefile
# TODO Make this work.
desc "Setup core"
task "setup-core" do
`sh 00-core.sh`
`sh 10-misc.sh`
end
desc "Setup Ruby & Rubygems"
task "setup-ruby" => ["setup-core"] do
`sh 05-ruby.sh`
end
desc "Setup everything"
task "setup-all" => ["setup-core", "setup-ruby"]<file_sep>/slicehost/add_wp.rb
#!/usr/bin/env ruby
#
# Adds a WordPress instance
#
require 'erb'
require 'optparse'
require 'pp'
help = <<HELP
#{__FILE__} adds a WordPress site
Basic Command Line Usage:
#{__FILE__} --wordpress=foo.com
Options:
HELP
WORDPRESS = {}
optparse = OptionParser.new do |opts|
opts.banner = help
opts.on("--wordpress WORDPRESS", "Mandatory domain.tld") do |arg|
WORDPRESS[:wpdom] = arg
end
opts.on("--dbname DBNAME", "Mandatory dbname") do |arg|
WORDPRESS[:dbname] = arg
end
opts.on("--dbuser DBUSER", "Mandatory dbuser") do |arg|
WORDPRESS[:dbuser] = arg
end
opts.on("--dbpass DBPASS", "Mandatory dbpass") do |arg|
WORDPRESS[:dbpass] = arg
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end.parse!
wpdom = WORDPRESS[:wpdom]
dbname = WORDPRESS[:dbname]
dbuser = WORDPRESS[:dbuser]
dbpass = WORDPRESS[:dbpass]
raise "Requires --wordpress, --dbname, --dbuser, --dbpass" unless wpdom && dbname && dbuser && dbpass
puts "mkdir -p /var/local/wp/#{wpdom}/{public,private,log,backup}"
puts ""
puts "Copy nginx-wp to /var/local/wp/#{wpdom}/private/nginx"
puts ""
puts "ln -s /var/local/wp/#{wpdom}/private/nginx /etc/nginx/sites-enabled/#{wpdom}"
puts ""
puts "make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/ssl/certs/selfsigned.pem # Use ^h to backspace"
puts ""
puts "cd /var/local/wp/#{wpdom}/private"
puts "openssl genrsa -des3 -out #{wpdom}.key 1024"
puts "openssl req -new -key #{wpdom}.key -out #{wpdom}.csr"
puts "cp #{wpdom}.key #{wpdom}.key.orig"
puts "openssl rsa -in #{wpdom}.key.orig -out #{wpdom}.key"
puts "openssl x509 -req -days 3650 -in #{wpdom}.csr -signkey #{wpdom}.key -out #{wpdom}.crt"
puts "cp #{wpdom}.crt /etc/ssl/certs/"
puts "cp #{wpdom}.key /etc/ssl/private/"
puts "service nginx restart"
puts ""
cat =<<EOF
CREATE DATABASE #{dbname};
GRANT ALL ON #{dbname}.* TO #{dbuser}@localhost IDENTIFIED BY "#{dbpass}"
EOF
# cat > /tmp/mysql.sql <<EOF
puts "/var/local/wp/#{wpdom}/private/mysql"
puts cat
puts "mysql -u root -p < /tmp/mysql.sql"
puts ""
puts "cd /var/local/wp/#{wpdom}/public"
puts "svn co http://svn.automattic.com/wordpress/tags/2.9.2 ."
puts "chown -R app:app /var/local/wp/#{wpdom}"
puts "chmod -R 755 /var/local/wp/#{wpdom}"
puts "chmod -R -s /var/local/wp/#{wpdom}"
puts ""
puts "Setup wordpress"
puts "Add to wp-config.php"
puts "define('FORCE_SSL_LOGIN', true);"
puts "define('FORCE_SSL_ADMIN', true);"
puts ""<file_sep>/slicehost/55-imagemagick.sh
#
# Ubuntu 8.0.4
#
# Installs ImageMagick. Installs rmagick gem if Rubygems is installed
#
aptitude update -y
aptitude install -y imagemagick libmagick9-dev
if [ -e "`which gem`" ]
then
gem install rmagick
fi
<file_sep>/slicehost/15-postgresql.sh
#
# Ubuntu 8.0.4
#
# Installs PostgreSQL packages. Installs pg gem if Rubygems is installed
#
# PGPASSWORD=<PASSWORD> sh 15-setup-postgresql.sh
#
if [ ! -n "$PGPASSWORD" ]
then
echo "Must set 'admin' password for PostgreSQL"
echo "PGPASSWORD=<PASSWORD>z `basename $0`"
exit
fi
aptitude update -y
PG_VER=8.4
PGCONFDIR=/etc/postgresql/$PG_VER/main/
aptitude install -y postgresql-$PG_VER postgresql-server-dev-$PG_VER postgresql-contrib-$PG_VER
# log and monitoring for pgAdmin
sudo su postgres -c psql < /usr/share/postgresql/$PG_VER/contrib/adminpack.sql
# modify settings
perl -pi.bak -e "s/#listen_addresses = 'localhost'/listen_addresses = '*'/gi; \
s/#password_encryption/password_encryption/gi" \
$PGCONFDIR/postgresql.conf
# add addresses
echo "\
# p \n\
hostssl all all 172.16.58.3/32 md5 \n\
# m \n\
hostssl all all 172.16.31.10/32 md5 \n\
# o \n\
hostssl all all 192.168.127.12/32 md5 \n\
" >> /etc/postgresql/$PG_VER/main/pg_hba.conf
# restart to load changes
pg_ctlcluster $PG_VER main restart
# create an 'admin' PostgreSQL user
cat > /tmp/postgres.sql <<EOF
CREATE ROLE admin
LOGIN ENCRYPTED PASSWORD '$<PASSWORD>'
SUPERUSER INHERIT CREATEDB CREATEROLE;
EOF
sudo su postgres -c psql template1 < /tmp/postgres.sql
rm /tmp/postgres.sql
if [ -e "`which gem`" ]
then
# install pg gem
gem install pg
fi
<file_sep>/slicehost/30-memcached.sh
#
# Ubuntu 8.0.4
#
# Installs memcached. Installs memcache-client gem if Rubygems is installed
#
aptitude update -y
aptitude install -y memcached
if [ -e "`which gem`" ]
then
gem install memcache-client
fi<file_sep>/slicehost/00-core.sh
#
# Ubuntu 8.0.4
#
# Installs core development packages and users
#
aptitude update -y
aptitude install -y build-essential gcc g++
# setup timezone
ln -sf /usr/share/zoneinfo/America/Phoenix /etc/localtime
# add admin user
export USERNAME=admin
sh add_user.sh
echo "$USERNAME\tALL=(ALL) ALL" >> /etc/sudoers
cd ~
mkdir -p .ssh
touch .ssh/authorized_keys
chmod 700 .ssh/
chmod 600 .ssh/authorized_keys
echo
echo "Copying authorized_keys"
echo
# TODO Use relative paths instead of absolute. dirname? pwd?
cp ~/bootup/config/root_authorized_keys ~/.ssh/authorized_keys
echo
echo "For security reasons, you must manually set a password for the 'admin' user."
echo<file_sep>/slicehost/60-php.sh
#
# Ubuntu 8.0.4
#
# Installs PHP
#
aptitude update -y
aptitude install -y php5-common php5-cgi php5-mysql php5-cli php5-gd
cp ~/bootup/config/etc/init.d/php-fastcgi /etc/init.d/php-fastcgi
chmod 755 /etc/init.d/php-fastcgi
cp ~/bootup/config/etc/default/php-fastcgi /etc/default/php-fastcgi
cp ~/bootup/config/etc/nginx/fastcgi_params /etc/nginx/fastcgi_params
/etc/init.d/php-fastcgi start
update-rc.d php-fastcgi defaults
# /etc/init.d/nginx restart
# /etc/init.d/apache restart<file_sep>/slicehost/56-image-science.sh
#
# Ubuntu 8.0.4
#
# Installs FreeImage. Installs image_science gem if Rubygems is installed
#
aptitude update -y
aptitude install -y libfreeimage-dev libfreeimage3
if [ -e "`which gem`" ]
then
gem install image_science xml-simple builder mime-types
fi
<file_sep>/slicehost/25-apache.sh
#
# Ubuntu 8.0.4
#
# Installs Apache
#
aptitude update -y
aptitude install -y apache2 apache2-prefork-dev libapr1-dev
MODS="rewrite.load proxy.conf proxy.load proxy_balancer.load proxy_http.load"
for mod in $MODS
do
ln -s /etc/apache2/mods-available/$mod /etc/apache2/mods-enabled/$mod
done
apache2ctl -k graceful<file_sep>/slicehost/add_user.sh
#
# Ubuntu 8.0.4
#
# Create users
#
if [ ! -n "$USERNAME" ]
then
echo "Must set the username"
echo "USERNAME=mchung sh `basename $0`"
exit
fi
useradd -m -d /home/$USERNAME -s /bin/bash $USERNAME
mkdir /home/$USERNAME/.ssh
cp ~/bootup/config/default_authorized_keys /home/$USERNAME/.ssh/authorized_keys
chmod 700 /home/$USERNAME/.ssh/
chmod 600 /home/$USERNAME/.ssh/authorized_keys
chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh/
|
35503921c9624e550547eb845980ee4d2f3db67b
|
[
"Ruby",
"Shell"
] | 22
|
Ruby
|
mchung/bootup
|
1682c520fe2081534578f9341252aaf21f52462d
|
970a61231c77b463375527694312e90d9f11739d
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include "omp.h"
#include "CycleTimer.h"
extern void mandelbrotSerial(
float x0, float y0, float x1, float y1,
int width, int height,
int startRow, int numRows,
int startCol, int totalColumns,
int maxIterations,
int output[]);
//
// MandelbrotThread --
//
// Multi-threaded implementation of mandelbrot set image generation.
// Multi-threading performed via pthreads.
void mandelbrotOmp(
int numThreads,
float x0, float y0, float x1, float y1,
int width, int height,
int maxIterations, int output[])
{
const static int MAX_THREADS = 32;
if (numThreads > MAX_THREADS)
{
fprintf(stderr, "Error: Max allowed threads is %d\n", MAX_THREADS);
exit(1);
}
#pragma omp parallel num_threads(numThreads)
{
int threadId = omp_get_thread_num();
double startTime = CycleTimer::currentSeconds();
int rows = 0, columns = 0;
int chunk = 5;
for (int i = 0; i < height; i += chunk) {
rows = height - i < chunk ? height - i : chunk;
for (int j = chunk*threadId; j < width; j += chunk*numThreads) {
columns = width - j < chunk ? width - j : chunk;
mandelbrotSerial(x0, y0, x1, y1, width, height,i, rows, j, columns, maxIterations, output);
}
}
double endTime = CycleTimer::currentSeconds();
//printf("[Thread# %d]:\t\t[%.3f] ms\n",threadId , (endTime-startTime) * 1000);
}
}
|
293591c37106cdd07200ec302b9e09ff3ebb1836
|
[
"C++"
] | 1
|
C++
|
ashish-17/mandelbrot
|
e781c5d497ab9c97f7223c6df4123c887862224d
|
f7710206aa02e72853f4812e91671d04b5bc03c3
|
refs/heads/master
|
<repo_name>half2me/cryptocard<file_sep>/Dockerfile
FROM gradle:4.6.0-jdk8
ADD . /home/gradle
<file_sep>/settings.gradle
rootProject.name = 'cryptocard'
include 'applet'
<file_sep>/applet/src/main/java/applet/ECCryptoCard.java
package applet;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
public class ECCryptoCard extends CryptoCard {
KeyPair newKey() {
return new KeyPair(KeyPair.ALG_EC_FP, KeyBuilder.LENGTH_EC_F2M_163);
//signature = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false);
}
/**
* Installs this applet.
* @param bArray the array containing installation parameters
* @param bOffset the starting offset in bArray
* @param bLength the length in bytes of the parameter data in bArray
*/
public static void install(byte[] bArray, short bOffset, byte bLength){
new ECCryptoCard();
}
}
<file_sep>/applet/src/test/java/tests/AppletTest.java
package tests;
import applet.CryptoCard;
import applet.ECCryptoCard;
import com.licel.jcardsim.base.Simulator;
import javacard.framework.AID;
import org.junit.Assert;
import org.testng.annotations.*;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
/**
* Example test class for the applet
* Note: If simulator cannot be started try adding "-noverify" JVM parameter
*
* @author xsvenda, <NAME> (ph4r05)
*/
public class AppletTest {
private Simulator simulator;
private byte[] appletAIDBytes;
private AID appletAID;
public AppletTest() {
this.simulator = new Simulator();
this.appletAIDBytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
this.appletAID = new AID(this.appletAIDBytes, (short) 0, (byte) this.appletAIDBytes.length);
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
this.simulator.installApplet(appletAID, ECCryptoCard.class);
simulator.selectApplet(appletAID);
}
@AfterMethod
public void tearDownMethod() throws Exception {
simulator.reset();
}
// Example test
@Test
public void testGetPubKey() {
byte[] resp = simulator.transmitCommand((new CommandAPDU(0x00, 0x00, 0x00, 0x00)).getBytes());
byte[] resp2 = simulator.transmitCommand((new CommandAPDU(0x00, 0x00, 0x00, 0x00)).getBytes());
assert Arrays.equals(resp, resp2);
}
}
<file_sep>/build.gradle
group 'com.github.half2me'
version '1.0-SNAPSHOT'
<file_sep>/applet/src/main/java/applet/CryptoCard.java
package applet;
import javacard.framework.*;
import javacard.security.*;
public abstract class CryptoCard extends Applet implements ISO7816 {
// Key
protected KeyPair kp;
// Signature scratchpad
private byte[] scratchpad;
protected CryptoCard() {
scratchpad = new byte[256];
kp = newKey();
kp.genKeyPair();
register();
}
abstract KeyPair newKey();
/**
* Processes an incoming APDU.
* @see APDU
* @param apdu the incoming APDU
* @exception ISOException with the response bytes per ISO 7816-4
*/
public void process(APDU apdu) {
byte buffer[] = apdu.getBuffer();
if (this.selectingApplet()) { return; } // APDU was just selecting our application
switch (buffer[ISO7816.OFFSET_INS]) {
case 0x00:
sendPublicKey(apdu);
return;
case 0x01:
// Sign data
return;
default:
ISOException.throwIt (ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void sendPublicKey(APDU apdu) {
byte buffer[] = apdu.getBuffer();
PublicKey pk = kp.getPublic();
byte type = pk.getType();
short size = pk.getSize();
}
}
|
11d5a2840401ac885e756322ac55fa8e97a57ebe
|
[
"Java",
"Dockerfile",
"Gradle"
] | 6
|
Dockerfile
|
half2me/cryptocard
|
d29914868ba036b4169239c4377eb9dab8ddb5ce
|
97ac7d4345076c8000af0eb7ad28fe92f04d2b31
|
refs/heads/master
|
<repo_name>Akelan/TiMPlab-3-<file_sep>/.gitignore
/** @file derevo.cpp */
#include <iostream>
using namespace std;
void obhP (int node, int n, int *aa) /// functia obhoda v pramom poryadke (obhP), param: koren', kol-vp uzlov, massiv dereva
{///
cout<<node+1<<" ";///raspechatyvaem koren'
int *b=new int[n];///sozdaem dop massiv B
for (int i=0; i<n; i++)
b[i]=0;///zapolnaem 0
for (int i=0; i<n; i++)
if (aa[i]==node+1)
b[i]=aa[i];///esly est' dety y korna, zapisyvaem ih v b
for (int i=0; i<n; i++)
if (b[i]!=0) obhP(i,n,aa);///esly kakoi-libo element v b neraven 0, to vasyvaem obhO podavay koren'=nomery ne nylevogo elementa b
return;
}///
void obhO (int node, int n, int *aa) /// functia obhoda v obratnom poryadke (obhO), param: koren', kol-vp uzlov, massiv dereva
{///
int *b=new int[n];///tot ge algoritm, no raspechatka proishodit esly massiv b togdestvennyi 0
for (int i=0; i<n; i++)
b[i]=0;
for (int i=0; i<n; i++)
if (aa[i]==node+1)
b[i]=aa[i];
for (int i=0; i<n; i++)
if (b[i]!=0) obhO(i,n,aa);
cout<<node+1<<" ";
return;
}///
void obhS (int node, int n, int *aa) /// functia obhoda v simmetricnom poryadke (obhS), param: koren', kol-vp uzlov, massiv dereva
{
int *b=new int[n];
for (int i=0; i<n; i++)///tot ge algoritm v nachale
b[i]=0;
for (int i=0; i<n; i++)
if (aa[i]==node+1)
b[i]=aa[i];
for (int i=0; i<n; i++)
if (b[i]!=0) obhS(i,n,aa);///esly massiv b togdestvennyi 0
int k=0;
for (int i=0; i<n; i++)///esly y elementa net detei pechataem ego
if (aa[i]==node+1) k++;
if (k==0)
cout<<node+1<<" ";
if ((aa[node-1]!=aa[node])&(aa[node]!=0))///posle pervogo rebenka pechtaem roditela
cout<<aa[node]<<" ";
return;
}///
int main(void)/// functia main
{
int n;
cout<<"vvedite kol-vo yzlov=";
cin>>n;
cout<<"\n";
int *a=new int[n];
cout<<"vvedite elementy: ";
for (int i=0; i<n; i++)
{
cin>>a[i];
}///vvodim derevo
///vysyvaem funcii dla ego raspechatki
cout<<"\n pramoi obhod \n";
obhP(0,n,a);
cout<<"\n obratnyi obhod \n";
obhO(0,n,a);
cout<<"\n simmetricnyi obhod \n";
obhS(0,n,a);
return 0;
}
|
b5984d7c84f9f1815002865c7943e24611f22018
|
[
"C++"
] | 1
|
C++
|
Akelan/TiMPlab-3-
|
34a6ed5e5f8ece35c3f90899a09f8e226fe78c32
|
0e448c8db9dc002e7f4f6761a5bc27d4c25ca3cd
|
refs/heads/master
|
<file_sep>app.controller("shoppingItem", function($scope, $http, $location) {
$http.get("./templates/data.json")
.then(function(data) {
$scope.items = data.data
})
$scope.Range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
$scope.basket={}
$scope.subtotal = 0
$scope.addToCart = function(itemid, item, quantity) {
if (!$scope.basket[itemid]) {
$scope.basket[itemid] = 0
}
$scope.basket[itemid] += Number(quantity)
$scope.subtotal += (item.price / 100) * Number(quantity)
$scope.quantity = 1;
$scope.iteminbag= Object.keys($scope.basket).length
console.log($scope.basket[itemid]);
console.log($scope.basket);
}
$scope.checkout= function(){
console.log("cart");
$location.path('/cart/')
}
});
<file_sep>app.filter('price', function () {
return function (input) {
return (input/100)
};
})
|
c29979e585ef8d68287d490ebea6a04aa5f836aa
|
[
"JavaScript"
] | 2
|
JavaScript
|
NavidFa/shopping-cart
|
2b97f627012240ba5abbc47f798db98050ce1c27
|
3ca612cb48c5eae510fcab2ec65d701da905c4cb
|
refs/heads/master
|
<repo_name>Surajchopra/Session-2<file_sep>/JSON.R
library(rjson) # load package rjson
json1 <- fromJSON("text1.json") # import the first file as text1
json2 <- fromJSON("text2.json") # import the first file as text2
json3 <- fromJSON("text3.json") # import the first file as text3
# print all the JSON files.
print(json1)
print(json2)
print(json3)
# convert the JSON into data frame.
json_data <- data.frame(json1, json2, json3)
json_data
2. #2. Parse the following JSON into a data frame
js<-'{ "name": null, "release_date_local": null, "title": "3 (2011)",
# "opening_weekend_take": 1234, "year": 2011, "release_date_wide": "2011-09-16", "gross": 59954 }'
library(RJSONIO)
require(RJSONIO)
js <- '{ "name": null, "release_date_local": null, "title": "3 (2011)",
+ "opening_weekend_take": 1234, "year": 2011, "release_date_wide": "2011-09-16", "gross": 59954 }'
js <- fromJSON(js)
js
# use do.call function to convert the JSON into data frame.
do.call("cbind", js)
3. # 3. Write a script for variable binning using R.
x <- c(4,7,9,1,10,15,18,109,3,160,100,16,120,22,2,23,16,17)
binned.x <- as.factor(ifelse(x>50, "10+",x))
binned.x
|
5a981751bbd2059c36e6a25f56e6f763ed6250c7
|
[
"R"
] | 1
|
R
|
Surajchopra/Session-2
|
b95e8c02ecbeccd3fedb28fa8bb8e0106de22cb1
|
cbf9ec0d93abaa42b6ee4bf4c3dcdc4400458632
|
refs/heads/master
|
<repo_name>FalsEDarKNess/Book-Library<file_sep>/database/seeds/TownshipSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Township;
class TownshipSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$township = ['Hlaing','Dagon','Mayangone'];
foreach ($township as $row) {
Township::create(["name"=>$row]);
}
}
}
<file_sep>/routes/web.php
<?php
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('/', 'MainController@home')->name('homepage');
Route::get('about', 'MainController@about')->name('aboutpage');
Route::get('contact', 'MainController@contact')->name('contactpage');
Route::get('books', 'MainController@books')->name('bookspage');
Route::get('action', 'MainController@action')->name('actionpage');
Route::get('newarrivel', 'MainController@newarrivel')->name('newarrivelpage');
Route::get('classic', 'MainController@classic')->name('classicpage');
Route::get('education', 'MainController@education')->name('educationpage');
Route::get('free', 'MainController@free')->name('freepage');
Route::get('funny', 'MainController@funny')->name('funnypage');
Route::get('horror', 'MainController@horror')->name('horrorpage');
Route::get('romance', 'MainController@romance')->name('romancepage');
Route::get('knowledge', 'MainController@knowledge')->name('knowledgepage');
// Working with data in blade file
Route::get('service','MainController@service')->name('servicepage');
//CRUD for student table
Route::resource('student','StudentController'); // resource (get/post/put/delete)
<file_sep>/app/Http/Controllers/MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MainController extends Controller
{
public function home($value='')
{
return view('home');
}
public function about($value='')
{
return view('about');
}
public function contact($value='')
{
return view('contact');
}
public function books($value='')
{
return view('books');
}
public function action($value='')
{
return view('action');
}
public function newarrivel($value='')
{
return view('newarrivel');
}
public function classic($value='')
{
return view('classic');
}
public function education($value='')
{
return view('education');
}
public function free($value='')
{
return view('free');
}
public function funny($value='')
{
return view('funny');
}
public function horror($value='')
{
return view('horror');
}
public function romance($value='')
{
return view('romance');
}
public function knowledge($value='')
{
return view('knowledge');
}
public function service($value='')
{
//string
//return view('service',['name'=>'<NAME>']);
//array of arrays
$students = array(
array('name'=>'mgmg','age'=>26),
array('name'=>'SuSu','age'=>23)
);
//dd($students); //var_dump();die();
//may be array of objects
return view('service',['a'=>$students]);
}
}
|
f136820e12c3872765c753547195fb5349cabeaf
|
[
"PHP"
] | 3
|
PHP
|
FalsEDarKNess/Book-Library
|
0910d89a6effcff8db4c21b2f5f1efb3a7ef9a34
|
1273460bec2c7d2789e0129fecc9929112c75116
|
refs/heads/master
|
<repo_name>beneggett/coin_payments<file_sep>/lib/coin_payments/api.rb
module CoinPayments
class Api
URL_ENDPOINT = ENV.fetch("COIN_PAYMENTS_BASE_URL", "https://www.coinpayments.net/api.php")
API_VERSION = ENV.fetch("COIN_PAYMENTS_API_VERSION", "1")
include HTTParty
def post(body, openstruct: true)
response = self.class.post(URL_ENDPOINT, body: modify_body(body), timeout: 30, headers: modify_headers(body))
if response["error"] == "ok"
if openstruct
JSON::parse(response["result"].to_json, object_class: OpenStruct)
else
response
end
else
OpenStruct.new response
end
end
### Informational Commands
## Get Basic Account Info
# CoinPayments::Api.new.get_basic_account_info
def get_basic_account_info
body = {cmd: "get_basic_info"}
post body
end
# Convert epoch time, fwiw: Time.at response.time_joined
## Get Exchange Rates / Supported Coins
# CoinPayments::Api.new.get_exchange_rates
# CoinPayments::Api.new.get_exchange_rates accepted: true
# CoinPayments::Api.new.get_exchange_rates accepted: true, accepted_only: true
def get_exchange_rates(options = {})
body = {
cmd: "rates"
}
body[:short] = 1 if options[:short]
body[:accepted] = 1 if options[:accepted]
response = post body, openstruct: false
if options[:accepted_only]
response.to_h.delete_if { |_k, v| v[:accepted] == 0 }
else
response.to_h
end
end
## Get Coin Balances
# CoinPayments::Api.new.get_coin_balances
# CoinPayments::Api.new.get_coin_balances all: true
def get_coin_balances(options = {})
body = {
cmd: "balances"
}
body[:all] = 1 if options[:all]
post body
end
## Get Deposit Address
# CoinPayments::Api.new.get_deposit_address
def get_deposit_address(currency = "BTC")
body = {
cmd: "get_deposit_address",
currency: currency
}
post body
end
### Receiving Payments
## Create Transaction
# CoinPayments::Api.new.create_transaction amount: 10, currency1: "USD", currency2: "BTC", buyer_email: "<EMAIL>", buyer_name: "<NAME>"
def create_transaction(options = {})
required_params = %i( amount currency1 currency2 buyer_email)
required_params_present = required_params.all? { |e| options.keys.include?(e) }
raise "Required Argument Error. Must include #{required_params.join(', ')}" unless required_params_present
body = {
cmd: "create_transaction",
amount: options[:amount],
currency1: options[:currency1],
currency2: options[:currency2],
buyer_email: options[:buyer_email],
}
body[:buyer_name] = options[:buyer_name] if options[:buyer_name]
body[:item_name] = options[:item_name] if options[:item_name]
body[:item_number] = options[:item_number] if options[:item_number]
body[:invoice] = options[:invoice] if options[:invoice]
body[:custom] = options[:custom] if options[:custom]
body[:address] = options[:address] if options[:address]
body[:ipn_url] = options[:ipn_url] if options[:ipn_url]
post body
end
## Callback Addresses
# CoinPayments::Api.new.callback_addresses
def callback_addresses(options = {})
body = {
cmd: "get_callback_address",
currency: options.fetch(:currency, "BTC")
}
body[:ipn_url] = options[:ipn_url] if options[:ipn_url]
post body
end
## Get TX Info
# CoinPayments::Api.new.get_tx_info "CPCK5DNHP28DYY3GMWBTWLOIZM"
# CoinPayments::Api.new.get_tx_info "CPCK5DNHP28DYY3GMWBTWLOIZM", "CPCK5OLFDULWTYNDW7UQ0LYE2D" # Multiple lookup, don't recommend as it returns funny & they don't like more than 25
def get_tx_info(*transaction_ids)
cmd = if transaction_ids.size > 1
"get_tx_info_multi"
else
"get_tx_info"
end
body = {
cmd: cmd,
txid: transaction_ids.join('|'),
# full: 0 # I don't see any practical use for this
}
post body, openstruct: cmd != "get_tx_info_multi"
end
## Get TX List
# CoinPayments::Api.new.get_tx_list
# CoinPayments::Api.new.get_tx_list limit: 5
# CoinPayments::Api.new.get_tx_list limit: 5, start: 5
# CoinPayments::Api.new.get_tx_list newer: (Time.now - 1800).to_i
def get_tx_list(options = {})
body = {
cmd: "get_tx_ids"
}
body[:limit] = [options[:limit].to_i, 100].min if options[:limit] # limit The maximum number of transaction IDs to return from 1-100. (default: 25)
body[:start] = options[:start] if options[:start] # start What transaction # to start from (for iteration/pagination.) (default: 0, starts with your newest transactions.)
body[:newer] = options[:newer] if options[:newer] # newer Return transactions started at the given Unix timestamp or later. (default: 0)
body[:all] = options[:all] if options[:all] # By default we return an array of TX IDs where you are the seller for use with get_tx_info_multi or get_tx_info. If all is set to 1 returns an array with TX IDs and whether you are the seller or buyer for the transaction.
post body
end
### Withdrawals/Transfers
## Create Transfer
# CoinPayments::Api.new.create_transfer amount: 0.005, currency: "BTC", merchant: "1bf1c996fd6781bd4aabec78dda6250d"
def create_transfer(options = {})
required_params = %i( amount currency)
required_params_present = required_params.all? { |e| options.keys.include?(e) }
raise "Required Argument Error. Must include #{required_params.join(', ')}" unless required_params_present
mutually_exclusive_params = %i( merchant pbntag)
mutually_exclusive_params_present = mutually_exclusive_params.any? { |e| options.keys.include?(e) }
raise "Required Argument Error. Must include one of #{mutually_exclusive_params.join(', ')}" unless required_params_present
body = {
cmd: "create_transfer",
amount: options[:amount],
currency: options[:currency],
}
body[:merchant] = options[:merchant] if options[:merchant]
body[:pbntag] = options[:pbntag] if options[:pbntag]
body[:auto_confirm] = 1 if options[:auto_confirm]
post body
end
## Create Withdrawal / Mass Withdrawal
# CoinPayments::Api.new.create_withdrawal
def create_withdrawal
# body = {
# cmd: "create_withdrawal"
# }
end
## Convert Coins
# CoinPayments::Api.new.convert_coins
def convert_coins
# body = {
# cmd: "convert_coins"
# }
end
## Conversion Limits
# CoinPayments::Api.new.conversion_limits
def conversion_limits
# body = {
# cmd: "conversion_limits"
# }
end
## Get Withdrawal History
# CoinPayments::Api.new.get_withdrawal_history
def get_withdrawal_history
# body = {
# cmd: "get_withdrawal_history"
# }
end
## Get Withdrawal Info
# CoinPayments::Api.new.get_withdrawal_info
def get_withdrawal_info
# body = {
# cmd: "get_withdrawal_info"
# }
end
## Get Conversion Info
# CoinPayments::Api.new.get_conversion_info
def get_conversion_info
# body = {
# cmd: "get_conversion_info"
# }
end
### PayByName
## Get Profile Information
# CoinPayments::Api.new.get_profile_information
def get_profile_information
# body = {
# cmd: "get_profile_information"
# }
end
## Get Tag List
# CoinPayments::Api.new.get_tag_list
def get_tag_list
# body = {
# cmd: "get_tag_list"
# }
end
## Update Tag Profile
# CoinPayments::Api.new.update_tag_profile
def update_tag_profile
# body = {
# cmd: "update_tag_profile"
# }
end
## Claim Tag
# CoinPayments::Api.new.claim_tag
def claim_tag
# body = {
# cmd: "claim_tag"
# }
end
private
def modify_body(body)
default_params = {
version: API_VERSION,
key: ENV.fetch("COIN_PAYMENTS_PUBLIC_KEY", 'not-implemented')
}
default_params.merge body
end
def modify_headers(body)
required_params = {
version: API_VERSION,
key: ENV.fetch("COIN_PAYMENTS_PUBLIC_KEY", 'not-implemented'),
}.merge(body)
headers = {
'Content-Type' => "application/x-www-form-urlencoded",
'Content-transfer-encoding' => 'text',
}
headers["HMAC"] = hmac_encrypt(required_params)
headers
end
def hmac_encrypt(required_params)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha512'), ENV.fetch("COIN_PAYMENTS_PRIVATE_KEY", 'not-implemented'), HTTParty::HashConversions.to_params(required_params))
end
end
end
<file_sep>/test/coin_payments_test.rb
require "test_helper"
class CoinPaymentsTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::CoinPayments::VERSION
end
def test_it_does_something_useful
assert false
end
end
<file_sep>/lib/coin_payments.rb
# require "active_support/all"
require "httparty"
require "ostruct"
require "coin_payments/api"
require "coin_payments/version"
module CoinPayments
end
<file_sep>/README.md
# CoinPayments
Fully Implements the CoinPayments API in Ruby.
CoinPayments is an integrated payment gateway for cryptocurrencies such as Bitcoin and Litecoin. There are Over 1040 Supported Coins available. You can accept all 1040 supported coins or just one.
This gem will make it dead simple to work with CoinPayments API set & integrate it into any Ruby Project.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'coin_payments'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install coin_payments
## Usage
You'll first need to create a CoinPayments.net account to get started. If you don't have one, please consider creating one through my affiliate link: https://www.coinpayments.net/index.php?ref=1bf1c996fd6781bd4aabec78dda6250c
Or if you don't want to sign up through my link, feel free to sign up at https://www.coinpayments.net
There are many [tools for Merchants available](https://www.coinpayments.net/merchant-tools). We are going to focus on the API integrations.
There are two sides we'll need to concern ourselves:
1. Utilizing the API to manage payments & accounts
2. Creating a webhook or Instant Payment Notification (IPN)
### Utilizing the API
The only setup needed is to go to the [API Keys page and generate an API key](https://www.coinpayments.net/index.php?cmd=acct_api_keys). You will be given a private and public key used to authenticate your API calls. Make sure you don't share your private key with any 3rd parties!
Note: You must click 'Edit Permissions' to enable most commands
You will need to set the following environment variables in your app, and the rest will work automatically
```
COIN_PAYMENTS_PUBLIC_KEY: "your-public-api-key"
COIN_PAYMENTS_PRIVATE_KEY: "your-private-api-key"
```
Once those are set, you are now ready to utilize the API.
Available features have been implemented per the Features chart below
## Features
Implemented APIs from [CoinPayments API Docs](https://www.coinpayments.net/apidoc-intro)
| API | Docs | Implemented? | Priority |
| --- | --- | --- | --- |
| **Informational Commands** |
| Get Basic Account Info | [📚](https://www.coinpayments.net/apidoc-get-basic-info) | ✅ | 👍 |
| Get Exchange Rates / Supported Coins | [📚](https://www.coinpayments.net/apidoc-rates) | ✅ | 👍 |
| Get Coin Balances | [📚](https://www.coinpayments.net/apidoc-balances) | ✅ | 👍 |
| Get Deposit Address | [📚](https://www.coinpayments.net/apidoc-get-deposit-address) | ✅ | 👍 |
| **Receiving Payments** |
| Create Transaction | [📚](https://www.coinpayments.net/apidoc-create-transaction) | ✅ | 👍 |
| Callback Addresses | [📚](https://www.coinpayments.net/apidoc-get-callback-address) | ✅ | 👍 |
| Get TX Info | [📚](https://www.coinpayments.net/apidoc-get-tx-info) | ✅ | 👍 |
| Get TX List | [📚](https://www.coinpayments.net/apidoc-get-tx-ids) | ✅ | 👍 |
| **Withdrawals/Transfers** |
| Create Transfer | [📚](https://www.coinpayments.net/apidoc-create-transfer) | ✅ | 👌 |
| Create Withdrawal / Mass Withdrawal | [📚](https://www.coinpayments.net/apidoc-create-withdrawal) | ❌ | 👌 |
| Convert Coins | [📚](https://www.coinpayments.net/apidoc-convert) | ❌ | 👌 |
| Conversion Limits | [📚](https://www.coinpayments.net/apidoc-convert-limits) | ❌ | 👌 |
| Get Withdrawal History | [📚](https://www.coinpayments.net/apidoc-get-withdrawal-history) | ❌ | 👌 |
| Get Withdrawal Info | [📚](https://www.coinpayments.net/apidoc-get-withdrawal-info) | ❌ | 👌 |
| Get Conversion Info | [📚](https://www.coinpayments.net/apidoc-get-conversion-info) | ❌ | 👌 |
| **$PayByName** |
| Get Profile Information | [📚](https://www.coinpayments.net/apidoc-get-pbn-info) | ❌ | 👎 |
| Get Tag List | [📚](https://www.coinpayments.net/apidoc-get-pbn-list) | ❌ | 👎 |
| Update Tag Profile | [📚](https://www.coinpayments.net/apidoc-update-pbn-tag) | ❌ | 👎 |
| Claim Tag | [📚](https://www.coinpayments.net/apidoc-claim-pbn-tag) | ❌ | 👎 |
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/beneggett/coin_payments. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
## Code of Conduct
Everyone interacting in the CoinPayments project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/beneggett/coin_payments/blob/master/CODE_OF_CONDUCT.md).
|
a8b59a9055452268c9115783baab1b3eb6eebbff
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
beneggett/coin_payments
|
982d5e3fd42713dd4881065f15ddd77c2e00f8e2
|
61ded764f12f214ea9bcb8ae9f78b59b60095573
|
refs/heads/master
|
<repo_name>J0P/harjoitus-16<file_sep>/harj16.cpp
/*********************
* Tehtävä: <NAME>
* Tekijä: <NAME>
* Kuvaus: Ohjelma kysyy tietosi ja tulostaa ne
* PVM: 24.10.2014
* Versio: 1.0
*********************/
#include <iostream>
using namespace std;
struct ASD
{
char etu[25], suku[25];
int km, pn, kn;
};
int main()
{
int luku = 5;
ASD tiedot1 = { "Mikko", "Mikkonen", 70, 40100, 1800};
ASD tiedot2;
cout << "Anna etu- ja sukunimesi: " << endl;
cin >> ws >> tiedot2.etu >> ws >> tiedot2.suku;
cout << "Anna koulumatkasi pituus (km): " << endl;
cin >> tiedot2.km;
cout << "Anna postinumerosi: " << endl;
cin >> tiedot2.pn;
cout << "Anna kengannumerosi: " << endl;
cin >> tiedot2.kn;
cout << "Tietosi: " << endl << tiedot2.etu << " " << tiedot2.suku << endl << "Koulumatka: " << tiedot2.km << "km" << endl << "Postinumero: " << tiedot2.pn << endl << "Kengannumero: " << tiedot2.kn << endl;
return 0;
}
|
532c8d9b7ef365d98e71ab1c08997e2853bb31c7
|
[
"C++"
] | 1
|
C++
|
J0P/harjoitus-16
|
435213657469a9c91352fb67296f6aa7f0531b24
|
a2db4ed2218a74de81f68f37a673488c863a3704
|
refs/heads/master
|
<repo_name>erickfama/Emotions<file_sep>/README.md
# Emotions
Analysis of emotions of the audience in pieces of Chopin, Mozart and Voiles.
<file_sep>/chopin_mozart_voiles.R
#############################################################
### Chopin, Mozart and Voiles emotions survey data bases ###
#############################################################
library(ggplot2)
library(tidyverse)
# Crear vectores de sinonimos
calma <- c('tranquilidad|Tranquilidad|Armonia|Paz|Quietud|Sosiego|Placidez|Relajacion|Serenidad|Descanso|Equilibrio|Inocencia|Libertad|Ligereza|Orden|Organizacion|Refelxion|Reflexion|InCalma|Calma? ')
tension <- c('Intranquilidad|Impaciencia|Ansiedad|Inquietud|Desasosiego|Alerta|Angustia|Descontrol|Tension|Estres|Nerviosismo|Sobresalto|Sosobra')
alegria <- c('alegria|Regocijo|Jubilo|Entusiasmo|Exaltacion|Felicidad|Festividad|Jugueton|Optimismo')
tristeza <- c('Pesar|Nostalgia|Nolstalgia|Tostalgia|Melancolia|Soledad|Depresion|Anoranza|Desolacion')
compasion <- c('Agradecimiento|Apertura|Comprension|Introspeccion')
certeza <- c('Claridad|Seguridad|Esperanza|Resolucion|Aceptacion|Encuentro|Expectativa|Persistencia')
duda <- c('Incertidumbre|Duda|Desesperanza|Misterio|Suspenso')
placer <- c('Suavidad|Gusto|Contemplacion|Finesa|Pureza')
dolor <- c('Amargura|Congoja|Drama|Separacion')
amor <- c('Ternura|Compania|Romanticismo')
diversion <- c('Sorpresa|sorpresa|Distraccion|Juego|Asombro|Experimentacion|Flexibilidad')
aburrimiento <- c('Desesperacion|Monotonia')
frustracion <- c('Decepcion|Fracaso')
valor <- c('Arrojo|Emprendimiento|Valentia')
miedo <- c('Sospecha|Temor')
agrado <- c('Bienestar|Amabilidad|Exotismo|Gracia|Sencillez')
desagrado <- c('Desencanto|Incomodidad')
deseo <- c('Interes|Anhelo|Busqueda|Ensonacion')
entusiasmo <- c('Curiosidad|Dedicacion|Descubrimiento|Empuje|Intriga|Motivacion|Pasion')
apatia <- c('Pereza|Recogimiento')
vigor <- c('Fortaleza|Energia|Fuerza|Concentracion|Resiliencia')
altivez <- c('Altaneria|Decencia|Pedanteria|Picardia|Poder')
humillacion <- c('Resignacion')
# Vector de sinonimos
sinonimos <- c(calma, tension, alegria, tristeza, compasion, certeza, duda, placer,
dolor, amor, diversion, aburrimiento, frustracion, valor, miedo,
agrado, desagrado, deseo, entusiasmo, apatia, vigor, altivez, humillacion)
# Vector de reemplazo
replaces <- c('Calma', 'Tension', 'Alegria', 'Tristeza', 'Compasion', 'Certeza', 'Duda', 'Placer',
'Dolor', 'Amor', 'Diversion', 'Aburrimiento', 'Frustracion', 'Valor', 'Miedo',
'Agrado', 'Desagrado', 'Deseo', 'Entusiasmo', 'Apatia', 'Vigor', 'Altivez','Humillacion')
----------- ### Chopin ### -----------
chopin_df <- read.csv('C:/Users/Erick/Documents/projects/emociones/db/chopin.csv',
header = TRUE)
# Enlistar las emociones
list_emotions_chopin <- strsplit(as.character(chopin_df$resumen), ' ')
# Anadir columna que cuente el numero de emociones por participante
chopin_df <- chopin_df %>%
mutate(n_emociones = unlist(lapply(lapply(list_emotions_chopin, unique),length)))
# Obtener vector que contenga todo el listado de emociones (respuestas)
emotions_chopin <- unlist(strsplit(as.character(chopin_df$resumen), ' '))
n <- c(seq(1, length(sinonimos), 1)) # vector guia
# Reemplazar sinonimos
for(i in n){
emotions_chopin <- str_replace_all(emotions_chopin, sinonimos[i], replaces[i])
}
emotions_chopin <- replace(emotions_chopin,
emotions_chopin == 'InCalma', # Cambiar valor erroneo
'Calma')
# Crear vector de emociones unicas
unique_emotions_chopin <- sort(unique(emotions_chopin))
# Crear data frame de frecuencias de emociones
chopin_emotions <- as.data.frame(table(emotions_chopin))
# Grafica de frecuencia
chopin_emotions %>%
ggplot(aes(x= Freq, y = reorder(emotions_chopin, -Freq), fill = Freq)) +
geom_bar(stat = 'identity') +
scale_fill_gradient(name = 'Frecuencia', low = 'lightblue', high = 'royalblue4') +
scale_x_continuous(breaks = c(seq(0, 100, 10))) +
labs( x = 'Frecuencia', y = 'Emociones',
title = 'Emociones Resumidas Chopin')
----------- ### Mozart ### -----------
mozart_df <- read.csv('C:/Users/Erick/Documents/projects/emociones/db/mozart.csv',
header = TRUE)
# Enlistar las emociones
list_emotions_mozart <- strsplit(as.character(mozart_df$resumen), ' ')
# Anadir columna que cuente el numero de emociones por participante
mozart_df <- mozart_df %>%
mutate(n_emociones = unlist(lapply(lapply(list_emotions_mozart, unique),length)))
# Obtener que contenga todo el listado de emociones (respuestas)
emotions_mozart <- (unlist(strsplit(as.character(mozart_df$resumen), ' ')))
# Eliminar 'Sin respuesta'
emotions_mozart <- emotions_mozart[! emotions_mozart %in% c('Sin', 'respuesta')]
# Reemplazar sinonimos
for(i in n){
emotions_mozart <- str_replace_all(emotions_mozart, sinonimos[i], replaces[i])
}
emotions_mozart <- replace(emotions_mozart,
emotions_mozart == 'InCalma', # Cambiar valor erroneo
'Calma')
# Crear vector de emociones unicas
unique_emotions_mozart <- sort(unique(emotions_mozart))
# Crear data frame de frecuencias de emociones
mozart_emotions <- as.data.frame(table(emotions_mozart))
# Grafica de frecuencia
mozart_emotions %>%
ggplot(aes(x= Freq, y = reorder(emotions_mozart, -Freq), fill = Freq)) +
geom_bar(stat = 'identity') +
scale_fill_gradient(name = 'Frecuencia', low = 'burlywood1', high = 'firebrick1') +
scale_x_continuous(breaks = c(seq(0, 60, 5))) +
labs( x = 'Frecuencia', y = 'Emociones',
title = 'Emociones Resumidas Mozart')
----------- ### Voiles ### -----------
voiles_df <- read.csv('C:/Users/Erick/Documents/projects/emociones/db/voiles.csv',
header = TRUE)
# Enlistar las emociones
list_emotions_voiles <- strsplit(as.character(voiles_df$resumen), ' ')
# Anadir columna que cuente el numero de emociones por participante
voiles_df <- voiles_df %>%
mutate(n_emociones = unlist(lapply(lapply(list_emotions_voiles, unique),length)))
# Obtener vector de emociones que contenga todo el listado de emociones (respuestas)
emotions_voiles <- unlist(strsplit(as.character(voiles_df$resumen), ' ')) # Emociones Raw
# Reemplazar sinonimos
for(i in n){
emotions_voiles <- str_replace_all(emotions_voiles, sinonimos[i], replaces[i])
}
emotions_voiles <- str_replace(emotions_voiles,
'InCalma', # Cambiar valor erroneo
'Calma')
# Crear vector de emociones unicas
unique_emotions_voiles <- sort(unique(emotions_voiles))
# Crear data frame de frecuencias de emociones
voiles_emotions <- as.data.frame(table(emotions_voiles))
# histograma de frecuencia
voiles_emotions %>%
ggplot(aes(x= Freq, y = reorder(emotions_voiles, -Freq), fill = Freq)) +
geom_bar(stat = 'identity') +
scale_fill_gradient(name = 'Frecuencia', low = 'pink', high = 'purple') +
scale_x_continuous(breaks = c(seq(0, 40, 5))) +
labs( x = 'Frecuencia', y = 'Emociones',
title = 'Emociones Resumidas Voiles')
### Emociones de los tres compositores ###
# Unir emociones chopin - mozart
all_emotions <- merge(chopin_emotions, mozart_emotions,
by.x = 'emotions_chopin',
by.y = 'emotions_mozart',
all.x = TRUE,
all.y = TRUE,
suffixes = c('chopin', 'mozart'),
no.dups = TRUE)
# Unir emociones chopin, mozart - voiles
all_emotions <- merge(all_emotions, voiles_emotions,
by.x = 'emotions_chopin',
by.y = 'emotions_voiles',
all.x = TRUE,
all.y = TRUE,
suffixes = c('all' , 'voiles'),
no.dups = TRUE)
# Cambiar NAs a 0
all_emotions[is.na(all_emotions)] <- 0
# Cambiar nombres de columnas para el nuevo df
colnames(all_emotions)[c(1, 2, 3, 4)] <- c('emotions',
'chopin',
'mozart',
'voiles')
# Lista de emociones basada en el apendice (Flores y Diaz, 2001)
emotions_list <- as.data.frame(sort((all_emotions$emotions))) # No se presento ira, aversion y agotamiento
|
529f4d908c66fa03d01a50ceb248e6016cdf7a58
|
[
"Markdown",
"R"
] | 2
|
Markdown
|
erickfama/Emotions
|
200f5d2f1b68cf9c347a6e170c2e58a39df8eb9b
|
4e97e9b2ea71edc0025e5f79ab2f73cb45e7c6ae
|
refs/heads/master
|
<repo_name>abigartist/wuziqi2020<file_sep>/stack.cpp
//
// Created by 20694 on 2020/6/13.
//
#include "stack.h"
extern int player;
void push(stack*s,point p0){
s->p[s->top].x=p0.x;
s->p[s->top].y=p0.y;
s->p[s->top].score=p0.score;
s->top++;
}
point top(stack*s){
s->top--;
return s->p[s->top];
}
bool is_empty(stack*s){
return s->top==0;
}
void pop(stack*s){
s->top--;
}
void init(stack*s){
s->top=0;
initialization(s->p);
}
void pop_stack(int i, stack &best_nodes, int &pawn_score,point*p,int color) {
if(color!=player) {
if (pawn_score < p[i].score) {
if (is_empty(&best_nodes)) {
push(&best_nodes, p[i]);
} else {
while (!is_empty(&best_nodes)) {
pop(&best_nodes);
}
push(&best_nodes, p[i]);
}
pawn_score = p[i].score;
}
}
if(color==player){
if (pawn_score > p[i].score) {
if (is_empty(&best_nodes)) {
push(&best_nodes, p[i]);
} else {
while (!is_empty(&best_nodes)) {
pop(&best_nodes);
}
push(&best_nodes, p[i]);
}
pawn_score = p[i].score;
}
}
}<file_sep>/pawn_score.h
//
// Created by 20694 on 2020/5/12.
//
#ifndef GOBANG_PAWN_SCORE_H
#define GOBANG_PAWN_SCORE_H
const int w5=10000;
const int a4=1000;
const int d4=550;
const int a3=500;
const int d3=250;
const int a2=200;
const int d2=100;
#include "main.h"
int win5(const int*left,const int*right,int length,int color);
int alive4(const int*left,const int*right,int length,int color);
int alive3(const int *left,const int *right,int length,int color);
int alive2(const int *left,const int *right,int length,int color);
int dead4(const int *left,const int *right,int length,int color);
int dead3(const int *left,const int *right,int length,int color);
int dead2(const int *left,const int *right,int length,int color);
#endif //GOBANG_PAWN_SCORE_H
<file_sep>/main.cpp
#include "main.h"
#include <windows.h>
#include <conio.h>
point best;
int board[col][row]={
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
};
int is_empty[row][col]={empty};
int player={black};
int xp,yp;
int PointFlag=0;
int main(int argc,char *argv[]){
SetConsoleTitle("GoBang");
ShadowWindowLine("GoBang GAME",2,18,12,26,yes,red);
ShadowWindowLine("press any key to start",20,18,40,23,no,blue);
_getch();
ShadowWindowLine("Game processing!",20,8,40,16,yes,blue);
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); // 获取标准输入设备句柄
INPUT_RECORD inRec;
DWORD res;
COORD zero={0,0};
COORD ai={0,0};
while (1)
{
ReadConsoleInput(hInput, &inRec, 1, &res);
if (inRec.EventType == MOUSE_EVENT) //鼠标左键
{
if(inRec.Event.MouseEvent.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),zero);
printf("x-%2dy-%2d",inRec.Event.MouseEvent.dwMousePosition.Y,inRec.Event.MouseEvent.dwMousePosition.X);
Sleep(100);
}
if(inRec.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED){
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),inRec.Event.MouseEvent.dwMousePosition);
xp=inRec.Event.MouseEvent.dwMousePosition.Y;
yp=inRec.Event.MouseEvent.dwMousePosition.X;
if(board[xp][yp]!=empty){ continue;}
board[xp][yp]=1;
PointFlag=1;
if(xp<1||xp>=16||yp<1||yp>=16) { continue;}
if(is_end(xp,yp,1)){
ShadowWindowLine("you win!",20,2,30,6,yes,red);
_getch();
break;
}
printf("x");
Sleep(100);
}
if(PointFlag==1)
{
max_min(2,2);
board[best.x][best.y]=2;
if(is_end(best.x,best.y,2)){
ShadowWindowLine("you lose",20,2,30,6,yes,blue);
_getch();
break;
}
ai={(short)(best.y),(short)best.x};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),ai);
printf("o");
PointFlag=0;
}
}
}
// int l=is_end(1,1,black);
// printf("%d",l);
return 0;
}
<file_sep>/stack.h
//
// Created by 20694 on 2020/6/13.
//
#ifndef GOBANG_STACK_H
#define GOBANG_STACK_H
#include "main.h"
typedef struct STACK{
point p[square];
int top;
int cap;
}stack;
void push(stack*s,point p0);
void pop(stack*s);
void init(stack*s);
bool is_empty(stack*s);
point top(stack*s);
void pop_stack(int i, stack &best_nodes, int &pawn_score,point*p,int color);
#endif //GOBANG_STACK_H
<file_sep>/max_min.cpp
//
// Created by 20694 on 2020/5/26.
//
#include "max_min.h"
extern int board[col][row];
extern int player;
extern point best;
int Max(int x, int y){
if(x>y){return x;}
else return y;
}
void initialization(point*p0){
for(int i=0;i<square;i++){
p0[i].x=p0[i].y=p0[i].score=0;
}
}
int Min(int x,int y){
if(x>y){return y;}
else return x;
}
int find_point(point*p){
int cnt=0;
initialization(p);
for(int i=1;i<col;i++)
for(int j=1;j<row;j++)
{
if(board[i][j]==empty){
p[cnt].x=i;
p[cnt].y=j;
cnt++;
}
}
return cnt;
}
int max_min(int deep,int color) {
int alpha=min,beta=max;
point p[square];
stack best_nodes;
init(&best_nodes);
int color_, length, score, pawn_score;
pawn_score = score = length = 0;
length = find_point(p);
if (length == 0) { exit(0); }
color_ = get_color_(color);
if(color!=player) {pawn_score = min;}
else {pawn_score=max;}
for (int i = 0; i < length; i++) {
board[p[i].x][p[i].y] = color;
if(color!=player){
if(deep==1){score=state_score(p[i].x,p[i].y,color);}
else score=max_min(deep-1,color_);
if(score>beta) {
board[p[i].x][p[i].y] = empty;
return max;
}
}else{
if(deep==1){score=-state_score(p[i].x,p[i].y,color);}
else score=max_min(deep-1,color_);
if(score<alpha) {
board[p[i].x][p[i].y] = empty;
return min;
}
}
p[i].score = score;
pop_stack(i, best_nodes, pawn_score, p, color);
board[p[i].x][p[i].y] = empty;
}
if (!is_empty(&best_nodes)) {
point pr;
pr = top(&best_nodes);
best = pr;
if(color==player){alpha=pr.score;}
else{beta=pr.score;}
return pr.score;
}
if (deep == 4) { best = top(&best_nodes); }
return pawn_score;
}<file_sep>/print.h
//
// Created by 20694 on 2020/6/17.
//
#ifndef GOBANG_PRINT_H
#define GOBANG_PRINT_H
#include <windows.h>
#include <conio.h>
#include <cstdio>
#include <string>
#include <cstring>
using std::string;
enum {yes,no};
enum {red,blue};
void ShadowWindowLine(const char* s,int left,int top,int right,int bottom,int shadow,int color);
int is_end(int x,int y,int color);
void MouseEvent();
#endif //GOBANG_PRINT_H
<file_sep>/state.h
//
// Created by 20694 on 2020/5/10.
//
#ifndef GOBANG_STATE_H
#define GOBANG_STATE_H
#include "main.h"
#include "pawn_score.h"
typedef struct Dir{
int x;
int y;
}dir;
bool is_in_board(int x,int y);
dir next_point(dir p,dir d,int des);
#endif //GOBANG_STATE_H
<file_sep>/print.cpp
//
// Created by 20694 on 2020/6/17.
//
#include "print.h"
#include <windows.h>
HANDLE hin;
void ShadowWindowLine(const char* s,int left,int top,int right,int bottom,int shadow,int color){
HANDLE hout =GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bInfo;
SMALL_RECT rc;
WORD att0,att1,attText;
int i,chNum=strlen(s);
GetConsoleScreenBufferInfo(hout,&bInfo);
rc.Left=left;
rc.Top=top;
rc.Right=rc.Left+chNum;
rc.Bottom=rc.Top+4;
att0=BACKGROUND_INTENSITY;
if(color==red){att1=FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE;}
if(color==blue){att1=FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE;}
attText=FOREGROUND_RED |FOREGROUND_INTENSITY;
COORD posShadow={(short)(rc.Left+1),(short)(rc.Top+1)},posText={(short)(rc.Left),(short)(rc.Top)};
DWORD a= NULL;
if(shadow==yes){
for(i=0;i<5;i++){
FillConsoleOutputAttribute(hout, att0,chNum+4, posShadow,&a);
posShadow.Y++;
}
}
for (i=0;i<5;i++)
{
FillConsoleOutputAttribute(hout, att1,chNum + 4, posText, &a);
posText.Y++;
}
posText.X=rc.Left+2;
posText.Y=rc.Top+2;
WriteConsoleOutputCharacter(hout,s,strlen(s),posText, &a);
SetConsoleTextAttribute(hout,bInfo.wAttributes);
}
<file_sep>/pawn_score.cpp
//
// Created by 20694 on 2020/5/12.
//
//w5,a4,a3,a2,a1,d4,d3,d2,d1,
//w5=a4=a3=a2=a1=d4=d3=d2=d1=0
#include "pawn_score.h"
int win5(const int *left, const int *right, int length, int color){
if(5==length) {
return w5;
}
else return 0;
}
int alive4(const int *left,const int *right,int length,int color){
int color_;
color_ = get_color_(color);
if(length!=4||left[1]==color_||right[1]==color_) return 0;
else return a4;
}
int dead4(const int *left,const int *right,int length,int color){
int color_;
color_ = get_color_(color);
switch (length){
case 4:{
if(left[1]==color_&&right[1]==color_) return 0;
else{
return d4;
}
}
case 3:{
if((left[1]==empty&&left[2]==color)||(right[1]==empty&&right[2]==color)){
return d4;
}else return 0;
}
case 2:{
if((left[1]==empty&&left[2]==color&&left[3]==color)||(right[1]==empty&&right[2]==color&&right[3]==color)){
return d4;
}else return 0;
}
default:return 0;
}
}
int alive3(const int *left,const int *right,int length,int color){
switch(length){
case 2:{
if((left[2]==empty&&left[1]==empty&&right[1]==empty&&right[2]==color&&right[3]==empty)||(right[2]==empty&&right[1]==empty&&left[1]==empty&&left[2]==color&&left[3]==empty)){
return a3;
}else return 0;
}
case 3:{
if(left[1]==empty&&right[1]==empty&&left[2]==empty&&right[2]==empty){
return a3;
}
else return 0;
}
default:return 0;
}
}
int dead3(const int *left,const int *right,int length,int color){
int color_;
color_=get_color_(color);
switch(length){
case 1:{
if((left[1]==color_&&right[1]==empty&&right[2]==color&&right[3]==color)||(right[1]==color_&&left[1]==empty&&left[2]==color&&left[3]==color)||(left[1]==empty&&left[2]==color&&left[3]==empty&&left[4]==color)||(right[1]==empty&&right[2]==color&&right[3]==empty&&right[4]==color)||(left[1]==empty&&right[1]==empty&&left[2]==color&&right[2]==color)){
return d3;
}else return 0;
}
case 2:{
if((left[1]==color_&&right[1]==empty&&right[2]==color)||(right[1]==color_&&left[1]==empty&&left[2]==color)||(left[1]==empty&&right[1]==empty&&right[2]==empty&&right[3]==color&&right[4]==color)||(right[1]==empty&&left[1]==empty&&left[2]==empty&&left[3]==color&&left[4]==color)){
return d3;
}else return 0;
}
case 3:{
if(left[1]==color_||right[1]==color_||(left[1]==empty&&right[1]==empty&&left[2]==color_&&right[2]==color_)){
return d3;
}else return 0;
}
default:return 0;
}
}
int alive2(const int *left,const int *right,int length,int color){
switch (length){
case 1:{
if((left[1]==empty&&right[1]==empty&&right[2]==color&&right[3]==empty)||(right[1]==empty&&left[1]==empty&&left[2]==color&&left[3]==empty)||(left[1]==empty&&right[1]==empty&&right[2]==empty&&right[3]==color)||(right[1]==empty&&left[1]==empty&&left[2]==empty&&left[3]==color)){
return a2;
}else return 0;
}
case 2:{
if(left[1]==empty&&right[1]==empty&&(left[2]==empty||right[2]==empty)){
return a2;
}else return 0;
}
default:return 0;
}
}
int dead2(const int *left,const int *right,int length,int color){
int color_;
color_=get_color_(color);
switch(length){
case 1:{
if((left[1]==color_&&right[1]==empty&&right[2]==color&&right[3]==empty)||(right[1]==color_&&left[1]==empty&&left[2]==color&&left[3]==empty)||(left[1]==color_&&right[1]==empty&&right[2]==empty&&right[3]==color)||(right[1]==color_&&left[1]==empty&&left[2]==empty&&left[3]==color)){
return d2;
}else return 0;
}
case 2:{
if((left[1]==color&&right[1]==empty)||(left[1]==empty&&right[1]==color)){
return d2;
}else return 0;
}
default:return 0;
}
}<file_sep>/max_min.h
//
// Created by 20694 on 2020/5/26.
//
#ifndef GOBANG_MAX_MIN_H
#define GOBANG_MAX_MIN_H
#include "main.h"
#include "stack.h"
#define min -100000000
#define max 100000000
int find_point(point*p);
int Min(int x,int y);
int Max(int x, int y);
#endif //GOBANG_MAX_MIN_H
<file_sep>/main.h
//
// Created by 20694 on 2020/5/10.
//
#ifndef GOBANG_MAIN_H
#define GOBANG_MAIN_H
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cassert>
using std::cin;
using std::cout;
using std::string;
#define black 1
#define white 2
#define empty 0
#define row 16
#define col 16
#define square 225
#define Number_of_layers 4
enum {yes,no};
enum {red,blue};
typedef struct Point{
int x;
int y;
int score;
}point;
void initialization(point*p0);
int state_score(int x,int y,int color);
int get_color_(int color);
int max_min(int deep,int color);
int is_end(int x,int y,int color);
void print();
void ShadowWindowLine(const char* s,int left,int top,int right,int bottom,int shadow,int color);
#endif //GOBANG_MAIN_H
<file_sep>/state.cpp
//
// Created by 20694 on 2020/5/10.
//
#include "state.h"
extern int board[row][col];
extern int is_empty[row][col];
extern int player;
dir da={1,0};
dir db={0,1};
dir dc={1,1};
dir dd={-1,1};
//评估棋型
bool is_in_board(int x,int y){
return !(x > 15 || y > 15 || x < 1 || y < 1);
}
int get_color_(int color) {
int color_;
if(white == color){
color_=black;
}else{
color_=white;
}
return color_;
}
dir next_point(dir p,dir d,int des){
dir p_;
p_.x=p.x+des*d.x;
p_.y=p.y+des*d.y;
return p_;
}
int is_end(int x,int y,int color){
int l;
dir Dir,point,point_;
point.x=x;point.y=y;
Dir.x=Dir.y=0;
for(int d=1;d<=4;d++) {
l = 1;
switch (d) {
case 1:
Dir = da;
break;
case 2:
Dir = db;
break;
case 3:
Dir = dc;
break;
case 4:
Dir = dd;
break;
default:
break;
}
point_ = next_point(point, Dir, 1);
while (is_in_board(point_.x, point_.y) && board[point_.x][point_.y] == color) {
l++;
point_ = next_point(point_, Dir, 1);
}
point_ = next_point(point, Dir, -1);
while (is_in_board(point_.x, point_.y) && board[point_.x][point_.y] == color) {
l++;
point_ = next_point(point_, Dir, -1);
}
if(l==5) return 1;
}
return 0;
}
int state_score(int x,int y,int color){
int left[5]={0};int right[5]={0};int d,cnt,l,color_,score;
color_=get_color_(color);
score=cnt=0;
dir Dir,point,point_,le,ri;
point.x=x;point.y=y;
Dir.x=Dir.y=ri.x=ri.y=le.x=le.y=0;
for(d=1;d<=4;d++){
l=1;
switch (d){
case 1: Dir=da;
break;
case 2: Dir=db;
break;
case 3: Dir=dc;
break;
case 4: Dir=dd;
break;
default:break;
}
point_=next_point(point,Dir,1);
while(is_in_board(point_.x,point_.y)&&board[point_.x][point_.y]==color){
l++;
ri=point_;
point_=next_point(point_,Dir,1);
}
point_=next_point(point,Dir,-1);
while(is_in_board(point_.x,point_.y)&&board[point_.x][point_.y]==color){
l++;
le=point_;
point_=next_point(point_,Dir,-1);
}
for(cnt=1;cnt<=4;cnt++){
point_=next_point(ri,Dir,cnt);
if(is_in_board(point_.x,point_.y)){
right[cnt]=board[point_.x][point_.y];
}else{
right[cnt]=color_;
}
point_=next_point(le,Dir,-cnt);
if(is_in_board(point_.x,point_.y)){
right[cnt]=board[point_.x][point_.y];
}else{
right[cnt]=color_;
}
}
while(true){
if(win5(left,right,l,color)){
score+=win5(left,right,l,color);
break;
}
if(alive4(left,right,l,color)){
score+=alive4(left,right,l,color);
break;
}
if(dead4(left,right,l,color)){
score+=dead4(left,right,l,color);
break;
}
if(alive3(left,right,l,color)){
score+=alive3(left,right,l,color);
break;
}
if(dead3(left,right,l,color)){
score+=dead3(left,right,l,color);
break;
}
if(alive2(left,right,l,color)){
score+=alive2(left,right,l,color);
break;
}
if(dead2(left,right,l,color)){
score+=dead2(left,right,l,color);
break;
}
else break;
}
}
return score;
}
|
3b0c4cab29fcbda8698d616ba5a574a6dbf097b2
|
[
"C",
"C++"
] | 12
|
C++
|
abigartist/wuziqi2020
|
1ede71e071892b8a437cd4eaa8bc3c05edbe3ca5
|
31af9de8b7d462dd284188e9b545e6726ee71ae7
|
refs/heads/master
|
<repo_name>wilhelmberg/delete-directory-tree<file_sep>/delete-directory-tree/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace delete_directory_tree {
class Program {
private static bool _Quiet = false;
private static long _CntAllFiles = 0;
private static long _CntErrorFiles = 0;
private static long _CntAllDirs = 0;
private static long _CntErrorDirs = 0;
static int Main(string[] args) {
if (null == args || args.Length < 1 || args.Length > 2) {
writeError("delete-directory-tree [/Q] <directory>");
return 1;
}
string dir = string.Empty;
if (2 == args.Length && !"/Q".Equals(args[0], StringComparison.OrdinalIgnoreCase)) {
writeError("[{0}]: unknown parameter", args[0]);
return 1;
} else if (2 == args.Length && "/Q".Equals(args[0], StringComparison.OrdinalIgnoreCase)) {
_Quiet = true;
dir = args[1];
} else {
dir = args[0];
}
string fullPath = new DirectoryInfo(dir).FullName;
if (!Directory.Exists(dir)) {
writeError("[{0}] does not exist!", fullPath);
return 0;
}
try {
if (_Quiet) { Console.WriteLine( "[{0}]", fullPath ); }
return DeleteFilesAndFoldersRecursively(dir) ? 0 : 1;
}
catch (Exception e) {
writeError(e.Message);
return 1;
}
finally {
//show summary, repeat base dir name if not quiet
if (!_Quiet) { Console.WriteLine( "[{0}]", fullPath ); }
string msg = string.Format(
//"{0,7:#######} folders - {1,7:#######} with error, {2,7:#######} files - {3,7:#######} with error"
"{0,7} folders {1,7} with error, {2,7} files {3,7} with error"
, _CntAllDirs
, _CntErrorDirs
, _CntAllFiles
, _CntErrorFiles
);
if (_CntErrorDirs > 0 || _CntErrorFiles > 0) {
writeError(msg);
} else {
Console.WriteLine(msg);
}
}
}
public static bool DeleteFilesAndFoldersRecursively(string target_dir) {
bool fileSuccess = true;
foreach (string file in Directory.GetFiles(target_dir)) {
_CntAllFiles++;
if (!deleteFile(file)) {
fileSuccess = false;
_CntErrorFiles++;
}
}
bool dirSuccess = true;
foreach (string subDir in Directory.GetDirectories(target_dir)) {
bool tmpSuccess = DeleteFilesAndFoldersRecursively(subDir);
if (!tmpSuccess) { dirSuccess = false; }
}
// This makes the difference between whether it works or not.
Thread.Sleep(10);
_CntAllDirs++;
if (!deleteDir(target_dir)) {
dirSuccess = false;
_CntErrorDirs++;
}
return (fileSuccess && dirSuccess);
}
public static bool deleteFile(string file) {
for (int i = 0; i < 3; i++) {
try {
//another way to reset attributes:
//FileSystemInfo fsi = new FileSystemInfo(pathToFile);
//fsi.Attributes = FileAttributes.Normal;
//or
//File.SetAttributes(pathToFile, FileAttributes.Normal);
//File.Delete(pathToFile);
FileInfo f = new FileInfo(file);
f.Attributes = f.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
f.Delete();
return true;
}
catch (Exception e) {
writeError("[{0}]: {1}", file, e.Message);
Thread.Sleep(100);
}
}
return false;
}
public static bool deleteDir(string dir) {
for (int i = 0; i < 3; i++) {
try {
if (!_Quiet) { Console.WriteLine("[{0}] deleting ...", dir); }
//Directory.Delete( dir );
DirectoryInfo d = new DirectoryInfo(dir);
d.Attributes = d.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
d.Delete();
return true;
}
catch (Exception e) {
writeError("[{0}]: {1}", dir, e.Message.Trim());
Thread.Sleep(100);
}
}
return false;
}
public static void writeError(string msg, params object[] args) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg, args);
Console.ResetColor();
}
}
}
<file_sep>/delete-directory-tree-cpp/delete-directory-tree-cpp.cpp
// delete-directory-tree-cpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
using std::cout;
#if defined(UNICODE)
#define _tcout std::wcout
#else
#define _tcout std::cout
#endif
bool _Quiet = false;
long _CntAllFiles = 0;
long _CntErrorFiles = 0;
long _CntAllDirs = 0;
long _CntErrorDirs = 0;
//based on:
//How to Delete Directories Recursively with Win32
//http://blog.nuclex-games.com/2012/06/how-to-delete-directories-recursively-with-win32/
class SearchHandleScope {
/// <summary>Initializes a new search handle closer</summary>
/// <param name="searchHandle">Search handle that will be closed on destruction</param>
public: SearchHandleScope(HANDLE searchHandle) :
searchHandle(searchHandle) {
}
/// <summary>Closes the search handle</summary>
public: ~SearchHandleScope() {
::FindClose(this->searchHandle);
}
/// <summary>Search handle that will be closed when the instance is destroyed</summary>
private: HANDLE searchHandle;
};
/// <summary>Recursively deletes the specified directory and all its contents</summary>
/// <param name="path">Absolute path of the directory that will be deleted</param>
/// <remarks>
/// The path must not be terminated with a path separator.
/// </remarks>
bool recursiveDeleteDirectory(const std::wstring &path) {
std::wstring allFilesMask;
if (0 == path.compare(path.size() - 1, 1, _T("\\"))) {
allFilesMask = _T("*");
} else {
allFilesMask = _T("\\*");
}
WIN32_FIND_DATAW findData;
bool dirSuccess = true;
bool fileSuccess = true;
bool returnValue = true;
// First, delete the contents of the directory, recursively for subdirectories
std::wstring searchMask = path + allFilesMask;
HANDLE searchHandle = ::FindFirstFileExW(
searchMask.c_str()
, FindExInfoBasic
, &findData
, FindExSearchNameMatch
, nullptr
, 0
);
if (searchHandle == INVALID_HANDLE_VALUE) {
DWORD lastError = ::GetLastError();
if (lastError != ERROR_FILE_NOT_FOUND) { // or ERROR_NO_MORE_FILES, ERROR_NOT_FOUND?
_tcout << _T("Directory [") << path << _T("] does not exist!") << std::endl;
return 0;
}
}
// Did this directory have any contents? If so, delete them first
if (searchHandle != INVALID_HANDLE_VALUE) {
SearchHandleScope scope(searchHandle);
for (;;) {
// Do not process the obligatory '.' and '..' directories
//if (findData.cFileName[0] != '.') { //also exlcudes .files e.g. .gitignore
if (0 != _wcsicmp(findData.cFileName, _T(".")) && 0 != _wcsicmp(findData.cFileName, _T(".."))) {
bool isDirectory =
((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) ||
((findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0);
// Subdirectories need to be handled by deleting their contents first
std::wstring filePath = path + L'\\' + findData.cFileName;
if (isDirectory) {
returnValue = recursiveDeleteDirectory(filePath);
} else {
_CntAllFiles++;
bool tmpFileSuccess = true;
//remove readonly attribute
SetFileAttributes(filePath.c_str(), GetFileAttributes(filePath.c_str()) & ~FILE_ATTRIBUTE_READONLY);
//Try 3 times to delete the file. Wait in between
for (int i = 0; i < 3; i++) {
BOOL result = ::DeleteFileW(filePath.c_str());
if (result == TRUE) {
tmpFileSuccess = true;
break;
} else {
tmpFileSuccess = false;
if (0 == i) { _CntErrorFiles++; }
_tcout << filePath << _T(": Could not delete file") << std::endl;
Sleep(100);
}
}
if (!tmpFileSuccess) { fileSuccess = false; }
}
}
// Advance to the next file in the directory
BOOL result = ::FindNextFileW(searchHandle, &findData);
if (result == FALSE) {
DWORD lastError = ::GetLastError();
if (lastError != ERROR_NO_MORE_FILES) {
_tcout << _T("Error enumerating directory") << std::endl;
}
break; // All directory contents enumerated and deleted
}
} // for
}
//Seems that this is the important step:
//maybe the searchHandle needs some time to be released
Sleep(10);
if (!_Quiet) { _tcout << path << " deleting ..." << std::endl; }
_CntAllDirs++;
//The directory is empty, we can now safely remove it
//Try 3 times to delete the directory. Wait in between
for (int i = 0; i < 3; i++) {
BOOL result = ::RemoveDirectory(path.c_str());
//_tcout << _T("RemoveDirectory [") << i << _T("] ") << path << ": " << result << std::endl;
if (result == TRUE) {
dirSuccess = true;
break;
} else {
dirSuccess = false;
if (0 == i) { _CntErrorDirs++; }
_tcout << path << _T(": Could not remove directory") << std::endl;
Sleep(100);
}
}
return (fileSuccess && dirSuccess && returnValue) ? true : false;
}
int _tmain(int argc, _TCHAR* argv[]) {
//_tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
//for (int i = 0; i < argc; i++) { _tcout << i << _T(" ") << argv[i] << std::endl; }
if (argc < 2 || argc > 3) {
_tcout << _T("delete-directory-tree [/Q] <directory>") << std::endl;
return 1;
}
std::wstring dir;
if (3 == argc && 0 != _wcsicmp(_T("/Q"), (argv[1]))) {
_tcout << (argv[1]) << _T(" unknown parameter") << std::endl;
return 1;
} else if (3 == argc && 0 == _wcsicmp(_T("/Q"), (argv[1]))) {
//_tcout << _T("QUIET TRUE") << std::endl;
_Quiet = true;
dir = argv[2];
} else {
dir = argv[1];
}
try {
bool returnValue = recursiveDeleteDirectory(dir);
_tcout << _CntAllDirs << _T(" directories") << std::endl;
_tcout << _CntAllFiles << _T(" files") << std::endl;
_tcout << _CntErrorDirs << _T(" directories with error") << std::endl;
_tcout << _CntErrorFiles << _T(" files with error") << std::endl;
return returnValue ? 0 : 1;
}
catch (...) {
_tcout << "unknown EXCEPTION" << std::endl;
return 1;
}
}
<file_sep>/README.md
delete-directory-tree
=====================
Delete directory tree on Windows
|
7a5e4954056d49b9d57e42944dfd44a61e4d761f
|
[
"Markdown",
"C#",
"C++"
] | 3
|
C#
|
wilhelmberg/delete-directory-tree
|
420c4f8499d799a3f041b1770fa5363673fd1e28
|
282835bb1385ee2c0f9a43bb1d66c5f27e01de43
|
refs/heads/master
|
<file_sep>#include "RP1210ProtocolModel.h"
#include <QSettings>
RP1210ProtocolModel::RP1210ProtocolModel(QObject *parent)
: QAbstractListModel(parent)
{
RawProtocolMap.clear();
IndexList.clear();
}
RP1210ProtocolModel::~RP1210ProtocolModel()
{
RawProtocolMap.clear();
IndexList.clear();
}
Rp1210Protocol* RP1210ProtocolModel::GetProtocol(int index)
{
if (0 <= index && index < IndexList.size())
{
int protocolId = IndexList[index];
return &(RawProtocolMap[protocolId]);
}
return 0;
}
void RP1210ProtocolModel::IniProtocolList(class QSettings* VenderIni, QList<Rp1210Device>& DeviceList)
{
RawProtocolMap.clear();
IndexList.clear();
QStringList ProtocolStrList = VenderIni->value("/VendorInformation/Protocols").toStringList();
for (int i = 0; i < ProtocolStrList.size(); ++i)
{
QString temp = "/ProtocolInformation" + ProtocolStrList[i];
Rp1210Protocol protocol;
protocol.ProtocolID = ProtocolStrList[i].toInt();
protocol.ProtocolName = VenderIni->value(temp + "/ProtocolString").toString();
protocol.ProtocolParam = VenderIni->value(temp + "/ProtocolParams").toString();
protocol.ProtocolSpeed = VenderIni->value(temp + "/ProtocolSpeed").toStringList();
QStringList DeviceIdList = VenderIni->value(temp + "/Devices").toStringList();
for (int i = 0; i < DeviceIdList.size(); ++i)
{
int DeviceId = DeviceIdList[i].toInt();
protocol.DeviceIDs.append(DeviceId);
for (int j = 0; j < DeviceList.size(); ++j)
{
if (DeviceList[j].DeviceID == DeviceId)
DeviceList[j].Protocols.append(protocol.ProtocolID);
}
}
RawProtocolMap.insert(protocol.ProtocolID, protocol);
}
}
void RP1210ProtocolModel::SetProtocolList(QList<int>* list)
{
beginResetModel();
if (list)
IndexList = *list;
else
IndexList.clear();
endResetModel();
}
int RP1210ProtocolModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const
{
return IndexList.size();
}
QVariant RP1210ProtocolModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= IndexList.count())
return QVariant();
if (role == Qt::DisplayRole)
{
int protocolId = IndexList[index.row()];
return RawProtocolMap[protocolId].ProtocolName;
}
else
return QVariant();
}
<file_sep>#ifndef RP1210DeviceModel_h__
#define RP1210DeviceModel_h__
// 4/16/2017 : ZH : 设备列表
#include <QAbstractListModel>
struct Rp1210Device
{
int DeviceID; // 设备号
QString DeviceName; // 设备名称
QString DeviceParam; // 设备参数
int MultiCANChannels;
int MultiJ1939Channels;
int MultiISO15765Channels;
QList<int> Protocols; // 支持的协议列表
};
class RP1210DeviceModel : public QAbstractListModel
{
Q_OBJECT
public:
RP1210DeviceModel(QObject *parent);
~RP1210DeviceModel();
QList<Rp1210Device>& GetDeviceList();
QList<int>* GetProtocolList(int index);
void InitDeviceList(class QSettings* VenderIni);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
private:
QList<Rp1210Device> DeviceList;
};
#endif // RP1210DeviceModel_h__
<file_sep>#include "RP1210ReadThread.h"
#include "RP1210Core.h"
RP1210ReadThread::RP1210ReadThread(RP1210Core* core, QObject *parent)
:QThread(parent)
,rp1210Core(core)
,NeedExit(false)
{
}
RP1210ReadThread::~RP1210ReadThread()
{
}
void RP1210ReadThread::SetNeedExit(bool needExit)
{
NeedExit = needExit;
}
void RP1210ReadThread::run()
{
unsigned char RxBuffer[MAX_J1939_MESSAGE_LENGTH + 256] = { 0 };
short retVal = 0;
while (true)
{
if (!rp1210Core) break;
if (NeedExit) break;
memset(RxBuffer, 0x00, sizeof(RxBuffer));
retVal = rp1210Core->ReadMessge((char*)&RxBuffer[0], sizeof(RxBuffer), NON_BLOCKING_IO);
if (retVal > 0)
{ // 4/23/2017 : ZH : 读取到消息
emit MsgReady(QByteArray((char*)(&RxBuffer[0]), retVal));
}
else if (retVal == 0)
{ // 4/23/2017 : ZH : 暂时没有消息
QThread::msleep(10);
}
else
{ // 4/23/2017 : ZH : 发生错误
emit ErrorOccurred(retVal*(-1));
break;
}
}
}
<file_sep>#include "RP1210MsgParser.h"
#include <QDir>
#include <QFile>
#include <QDateTime>
#include <QCoreApplication>
#include <QMessageBox>
RP1210MsgParser::RP1210MsgParser(QObject *parent)
: QAbstractTableModel(parent)
{
j1939MsgList.clear();
// 测试代码
//char tmp1[] = { 0x04,0xF6,0xFE,0x29,0xF1,0xFE,0x00,0x06,0x00,0xFF,0xFC,0x00,0x00,0xFC,0xFF,0x00,0x00,0xFF };
char tmp[] = { 0x00,0x00,0x00,0x00,0xF1,0xFE,0x00,0x06,0x00,0xFF,0xFC,0x00,0x00,0xFC,0xFF,0x00,0x00,0xFF };
QByteArray arr(tmp, sizeof(tmp));
for (int i = 0; i < 100; ++i)
{
j1939MsgList.append(J1939Message(arr, false));
arr[3] = arr[3] + 1;
}
}
RP1210MsgParser::~RP1210MsgParser()
{
j1939MsgList.clear();
}
int RP1210MsgParser::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return j1939MsgList.size();
}
int RP1210MsgParser::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 7;
}
QVariant RP1210MsgParser::data(const QModelIndex& index, int role) const
{
if (index.row() >= j1939MsgList.size())
return QVariant();
// 对齐方式
if (role == Qt::TextAlignmentRole)
{
if (index.column() == 6)
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
else
return QVariant(Qt::AlignCenter);
}
if (role == Qt::DisplayRole)
{
const J1939Message& msg = j1939MsgList[index.row()];
msg.GetTimeStamp();
switch (index.column())
{
case 0:
return QVariant(msg.GetTimeStamp());
case 1:
if (msg.GetEchoByte() == -1)
return QVariant("*");
else
return QVariant(msg.GetEchoByte());
case 2:
return QVariant(msg.GetPGN());
case 3:
return QVariant(msg.GetPriority());
case 4:
return QVariant(tr("%1").arg(msg.GetSA(),2,16,QChar('0')).toUpper());
case 5:
return QVariant(tr("%1").arg(msg.GetTA(), 2,16,QChar('0')).toUpper());
case 6:
return QVariant(msg.GetMsgDataString());
default:
return QVariant();
}
}
return QVariant();
}
QVariant RP1210MsgParser::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Vertical)
return QVariant();
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
case 0:
return QVariant("TimeStamp");
case 1:
return QVariant("Echo");
case 2:
return QVariant("PGN");
case 3:
return QVariant("Priority");
case 4:
return QVariant("SA");
case 5:
return QVariant("TA");
case 6:
return QVariant("DATA");
default:
return QVariant();
break;
}
}
return QVariant();
}
QString RP1210MsgParser::GetMessageString(int row)
{
return j1939MsgList.at(row).GetRawMsgString();
}
void RP1210MsgParser::ClearAllMessage()
{
beginResetModel();
j1939MsgList.clear();
endResetModel();
}
void RP1210MsgParser::DeleteMessage(QModelIndexList& msgs)
{
QMap<int, int>rowMap;
for each(QModelIndex msg in msgs)
{
rowMap.insert(msg.row(), 0);
}
QMapIterator<int, int> it(rowMap);
it.toBack();
// 利用QMap是存储数据是有序的,并且不会重复存储key值。
beginResetModel();
while (it.hasPrevious())
{
it.previous();
j1939MsgList.removeAt(it.key());
}
endResetModel();
}
void RP1210MsgParser::OnMessage(QByteArray data)
{
J1939Message msg(data, false);
beginInsertRows(QModelIndex(), j1939MsgList.size(), j1939MsgList.size());
j1939MsgList.push_back(msg);
endInsertRows();
}
<file_sep>
#ifndef RP1210MsgParser_h__
#define RP1210MsgParser_h__
#include <QAbstractTableModel>
#include "MessageDef.h"
// 4/23/2017 : ZH : 消息保存与解析 --> 目前只支持J1939消息
class RP1210MsgParser : public QAbstractTableModel
{
Q_OBJECT
public:
RP1210MsgParser(QObject *parent);
~RP1210MsgParser();
// 4/23/2017 : ZH : QAbstractTableModel重载
int rowCount(const QModelIndex &parent)const override;
int columnCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex& index, int role)const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
public:
QString GetMessageString(int row);
void ClearAllMessage();
void DeleteMessage(QModelIndexList& msgs);
public slots:
// 4/23/2017 : ZH : 接收并解析消息
void OnMessage(QByteArray data);
private:
// 4/23/2017 : ZH : 保存消息
QList<J1939Message> j1939MsgList;
};
#endif // RP1210MsgParser_h__
<file_sep>
#ifndef RP1210IniData_h__
#define RP1210IniData_h__
// 4/16/2017 : ZH : 负责RP1210协议涉及到的所有ini文件的数据读取工作
#include <QObject>
#include <QSettings>
#include <QStringListModel>
#include "RP1210DeviceModel.h"
#include "RP1210ProtocolModel.h"
class RP1210IniData : public QObject
{
Q_OBJECT
public:
~RP1210IniData();
static RP1210IniData* GetInistance();
public:
void ReadMainIniFile();
QStringListModel* GetVenderModel();
RP1210DeviceModel* GetDeviceModel();
RP1210ProtocolModel* GetProtocolModel();
QStringListModel* GetBaudRateModel();
public:
QString GetVenderDllPath(int index);
int GetDeviceId(int index);
QString GetProtocolName(int index);
QString GetBaudRate(int index);
public slots:
void OnVenderChanged(QString VenderName);
void OnDeviceChanged(int index);
void OnProtocolChanged(int index);
signals:
void LogMsg(QString Msg);
private:
RP1210IniData(QObject *parent);
QString MainIniPath;
QString VenderIniPath;
QString VenderDllPath;
QSettings* MainIni;
QSettings* VenderIni;
QStringListModel* VenderModel;
RP1210DeviceModel* DeviceModel;
RP1210ProtocolModel* ProtocolModel;
QStringListModel* BaudRateModel;
static RP1210IniData* TheInstance;
};
#endif // RP1210IniData_h__
<file_sep>#include "RP1210IniData.h"
#include <QStringListModel>
RP1210IniData::RP1210IniData(QObject *parent)
: QObject(parent)
{
MainIniPath = "C:\\Windows\\RP121032.ini";
VenderIniPath = "";
VenderDllPath = "";
MainIni = new QSettings(MainIniPath, QSettings::IniFormat, this);
VenderIni = 0;
VenderModel = new QStringListModel(this);
DeviceModel = new RP1210DeviceModel(this);
ProtocolModel = new RP1210ProtocolModel(this);
BaudRateModel = new QStringListModel(this);
}
RP1210IniData* RP1210IniData::TheInstance = 0;
RP1210IniData::~RP1210IniData()
{
}
RP1210IniData* RP1210IniData::GetInistance()
{
if (!TheInstance)
TheInstance = new RP1210IniData(0);
return TheInstance;
}
void RP1210IniData::ReadMainIniFile()
{
QStringList VenderList = MainIni->value("/RP1210Support/APIImplementations").toStringList();
VenderModel->setStringList(VenderList);
}
QStringListModel* RP1210IniData::GetVenderModel()
{
return VenderModel;
}
RP1210DeviceModel* RP1210IniData::GetDeviceModel()
{
return DeviceModel;
}
RP1210ProtocolModel* RP1210IniData::GetProtocolModel()
{
return ProtocolModel;
}
QStringListModel* RP1210IniData::GetBaudRateModel()
{
return BaudRateModel;
}
QString RP1210IniData::GetVenderDllPath(int index)
{
QModelIndex ModelIndex = VenderModel->index(index);
QString VenderName = VenderModel->data(ModelIndex, Qt::DisplayRole).toString();
QString VenderDllPath;
QString CpuAbi = QSysInfo::currentCpuArchitecture();
if (CpuAbi == "i386")
VenderDllPath = "C:\\Windows\\System32\\" + VenderName + ".dll";
else
VenderDllPath = "C:\\Windows\\SysWOW64\\" + VenderName + ".dll";
return VenderDllPath;
}
//QString RP1210IniData::GetVenderName(int index)
//{
// QModelIndex ModelIndex = VenderModel->index(index);
// return VenderModel->data(ModelIndex, Qt::DisplayRole).toString();
//}
int RP1210IniData::GetDeviceId(int index)
{
return DeviceModel->GetDeviceList().at(index).DeviceID;
}
QString RP1210IniData::GetProtocolName(int index)
{
QModelIndex ModelIndex = ProtocolModel->index(index);
return ProtocolModel->data(ModelIndex, Qt::DisplayRole).toString();
}
QString RP1210IniData::GetBaudRate(int index)
{
QModelIndex ModelIndex = BaudRateModel->index(index);
return BaudRateModel->data(ModelIndex, Qt::DisplayRole).toString();
}
void RP1210IniData::OnVenderChanged(QString VenderName)
{
VenderIniPath = "C:\\Windows\\" + VenderName + ".ini";
VenderDllPath = "C:\\Windows\\SysWOW64" + VenderName + ".dll";
if (VenderIni)
{
delete VenderIni;
VenderIni = 0;
}
VenderIni = new QSettings(VenderIniPath, QSettings::IniFormat, this);
DeviceModel->InitDeviceList(VenderIni);
ProtocolModel->IniProtocolList(VenderIni, DeviceModel->GetDeviceList());
}
void RP1210IniData::OnDeviceChanged(int index)
{
QList<int>* protocolList = DeviceModel->GetProtocolList(index);
ProtocolModel->SetProtocolList(protocolList);
}
void RP1210IniData::OnProtocolChanged(int index)
{
Rp1210Protocol* protocol = ProtocolModel->GetProtocol(index);
if(protocol)
BaudRateModel->setStringList(protocol->ProtocolSpeed);
}
<file_sep>#pragma once
#include <QDialog>
#include "ui_J1939FilterWindow.h"
class J1939FilterWindow : public QDialog
{
Q_OBJECT
public:
J1939FilterWindow(QWidget *parent = Q_NULLPTR);
~J1939FilterWindow();
void SetRp1210Core(class RP1210Core* core);
private:
Ui::J1939FilterWindow ui;
class RP1210Core* rp1210Core;
protected slots:
void OnSetFilterType();
void OnSetPassAll();
void OnSetDiscardAll();
void OnSetFilter();
void OnCancel();
void OnCheckBoxChanged(bool);
private:
// 4/19/2017 : ZH : 私有,辅助函数,建立信号槽连接
void InitSignalConnection();
unsigned char GetFilterFlags();
};
<file_sep>#ifndef RP1210MsgLogger_h__
#define RP1210MsgLogger_h__
#include <QObject>
//5/2/2017 ZH :消息记录
class RP1210MsgLogger : public QObject
{
Q_OBJECT
public:
RP1210MsgLogger(bool startLog = false,QObject *parent = 0);
~RP1210MsgLogger();
public:
//5/2/2017 ZH :是否在做日志
bool IsLog() const;
//5/2/2017 ZH :开始做日志
void StartLog();
//5/2/2017 ZH :停止做日志
void StopLog();
public slots:
//5/2/2017 ZH :
void LogToFile(QString msg);
void LogToFile(class J1939Message const* msg);
private:
class QFile* logFile;
};
#endif // RP1210MsgLogger_h__<file_sep>#include "RP1210Window.h"
#include "RP1210IniData.h"
#include "RP1210Core.h"
#include "J1939FilterWindow.h"
#include "RP1210ReadThread.h"
#include "RP1210MsgParser.h"
#include <QClipboard>
#include <QMessageBox>
#include <QScrollBar>
RP1210Window::RP1210Window(QWidget *parent)
: QDialog(parent)
,J1939FilterDialog(0)
{
ui.setupUi(this);
IniData = RP1210IniData::GetInistance();
IniData->ReadMainIniFile();
rp1210Core = RP1210Core::GetInstance();
rp1210ReadThread = new RP1210ReadThread(rp1210Core, this);
SetUpTableView();
connect(IniData, SIGNAL(LogMsg(QString)), this, SLOT(OnLogMsg(QString)));
connect(rp1210Core, SIGNAL(LogMsg(QString)), this, SLOT(OnLogMsg(QString)),Qt::QueuedConnection);
connect(ui.checkBoxAutoBaudRate, SIGNAL(toggled(bool)), this,SLOT(OnAutoBaudRate(bool)));
connect(ui.pushButtonConnect, SIGNAL(clicked()), this, SLOT(OnConnect()));
connect(ui.pushButtonDisConnect, SIGNAL(clicked()), this, SLOT(OnDisConnect()));
connect(ui.pushButtonFilter, SIGNAL(clicked()), this, SLOT(OnFilterWindow()));
connect(ui.pushButtonClearLog, SIGNAL(clicked()), this, SLOT(OnClearLog()));
connect(ui.comboBoxVendor, SIGNAL(currentIndexChanged(QString)), IniData, SLOT(OnVenderChanged(QString)));
connect(ui.comboBoxDevice, SIGNAL(currentIndexChanged(int)), IniData, SLOT(OnDeviceChanged(int)));
connect(ui.comboBoxProtocol, SIGNAL(currentIndexChanged(int)), IniData, SLOT(OnProtocolChanged(int)));
ui.comboBoxVendor->setModel(IniData->GetVenderModel());
ui.comboBoxDevice->setModel(IniData->GetDeviceModel());
ui.comboBoxProtocol->setModel(IniData->GetProtocolModel());
ui.comboBoxBaudRate->setModel(IniData->GetBaudRateModel());
ui.pushButtonConnect->setEnabled(true);
ui.pushButtonDisConnect->setEnabled(false);
}
RP1210Window::~RP1210Window()
{
if (IniData)
delete IniData;
if (rp1210Core)
delete rp1210Core;
IniData = 0;
rp1210Core = 0;
}
void RP1210Window::OnAutoBaudRate(bool bAuto)
{
if (ui.checkBoxAutoBaudRate->isChecked())
{
ui.comboBoxBaudRate->setEnabled(false);
}
else
{
ui.comboBoxBaudRate->setEnabled(true);
}
}
void RP1210Window::OnConnect()
{
QString dllPath = IniData->GetVenderDllPath(ui.comboBoxVendor->currentIndex());
DWORD dwError = rp1210Core->LoadRp1210DLL(dllPath);
if (!dwError) // 4/16/2017 : ZH : dwError == 0 --> Load Success
{
// 4/18/2017 : ZH : 设备ID和协议字符串
int DeviceID = IniData->GetDeviceId(ui.comboBoxDevice->currentIndex());
QString Protocol = GetProtocolString();
short ErrorCode = rp1210Core->ClientConnect(DeviceID, Protocol);
if (ErrorCode != NO_ERRORS) return;
// 4/18/2017 : ZH : 如果是J1939协议
rp1210Core->ClaimJ1939Address(J1939_OFFBOARD_DIAGNOSTICS_TOOL_1);
// 4/23/2017 : ZH : 设置过滤器为全部通过
rp1210Core->SetAllFilterStatesToPass();
// 4/23/2017 : ZH : 开启读取线程
rp1210ReadThread->SetNeedExit(false);
rp1210ReadThread->start();
ui.pushButtonConnect->setEnabled(false);
ui.pushButtonDisConnect->setEnabled(true);
}
else
{
QMessageBox::critical(this, tr("Can not load RP1210 DLL"), tr("Load %1 failed! Error code = %2").arg(dllPath).arg(dwError));
}
}
void RP1210Window::OnDisConnect()
{
rp1210ReadThread->SetNeedExit(true);
short ErrorCode = rp1210Core->ClientDisconnect();
if (ErrorCode == NO_ERRORS)
{
ui.pushButtonConnect->setEnabled(true);
ui.pushButtonDisConnect->setEnabled(false);
}
}
void RP1210Window::OnClearLog()
{
ui.textBrowserLogMsg->clear();
// 4/23/2017 : ZH : 测试代码
char tmp3[] = { 0x04,0xF6,0xFE,0x50,0xF1,0xFE,0x00,0x06,0x00,0xFF,0xFC,0x00,0x00,0xFC,0xFF,0x00,0x00,0xFF };
QByteArray arr3(tmp3, sizeof(tmp3));
msgParser->OnMessage(arr3);
}
void RP1210Window::OnFilterWindow()
{
if (!J1939FilterDialog)
{
SetUpFilterWindow();
}
J1939FilterDialog->show();
J1939FilterDialog->raise();
J1939FilterDialog->activateWindow();
}
void RP1210Window::OnSelectionChanged(QItemSelection selected, QItemSelection deSelected)
{
QItemSelectionModel* selectionModel = ui.tableViewMsg->selectionModel();
QModelIndexList selectedRows = selectionModel->selectedRows();
if (!selectedRows.empty()) //4/28/2017 ZH :有选中项
{
copyAction->setEnabled(true);
deleteAction->setEnabled(true);
logtoFileAction->setEnabled(true);
}
else //4/28/2017 ZH :无选中项
{
copyAction->setEnabled(false);
deleteAction->setEnabled(false);
logtoFileAction->setEnabled(false);
}
}
void RP1210Window::OnScrollRangeChanged(int min, int max)
{
ui.tableViewMsg->verticalScrollBar()->setValue(max);
}
void RP1210Window::OnSelectAll()
{
QItemSelectionModel* selectionModel = ui.tableViewMsg->selectionModel();
QModelIndex topLeft = msgParser->index(0, 0, QModelIndex());
QModelIndex bottomRight = msgParser->index(msgParser->rowCount(QModelIndex())-1, msgParser->columnCount(QModelIndex())-1,QModelIndex());
QItemSelection selection(topLeft, bottomRight);
selectionModel->select(selection, QItemSelectionModel::Select);
}
void RP1210Window::OnClearAll()
{
msgParser->ClearAllMessage();
}
void RP1210Window::OnDelete()
{
QItemSelectionModel* selectionModel = ui.tableViewMsg->selectionModel();
QModelIndexList selectedRows = selectionModel->selectedRows();
msgParser->DeleteMessage(selectedRows);
}
void RP1210Window::OnCopy()
{
QItemSelectionModel* selectionModel = ui.tableViewMsg->selectionModel();
QModelIndexList selectedRows = selectionModel->selectedRows();
QString strTemp = "";
for each (QModelIndex item in selectedRows)
{
strTemp += (msgParser->GetMessageString(item.row())+"\r\n");
}
QClipboard* clipBoard = QApplication::clipboard();
clipBoard->setText(strTemp);
}
void RP1210Window::OnLogtoFile()
{
bool isChecked = logtoFileAction->isChecked();
if (isChecked)
{
}
else
{
}
}
void RP1210Window::OnLogMsg(QString Msg)
{
ui.textBrowserLogMsg->append(Msg);
}
QString RP1210Window::GetProtocolString()
{
QString ProtocolName = IniData->GetProtocolName(ui.comboBoxProtocol->currentIndex());
if (!(ui.checkBoxAutoBaudRate->isChecked()))
{
QString BaudRate = IniData->GetBaudRate(ui.comboBoxBaudRate->currentIndex());
return QString("%1:Baud=%2").arg(ProtocolName).arg(BaudRate);
}
else
{
return QString("%1:Baud=Auto").arg(ProtocolName);
}
}
void RP1210Window::SetUpFilterWindow()
{
J1939FilterDialog = new J1939FilterWindow(this);
J1939FilterDialog->SetRp1210Core(rp1210Core);
}
void RP1210Window::SetUpTableView()
{
// 绑定model 和view
msgParser = new RP1210MsgParser(this);
ui.tableViewMsg->setModel(msgParser);
connect(rp1210ReadThread, &RP1210ReadThread::MsgReady, msgParser, &RP1210MsgParser::OnMessage, Qt::QueuedConnection);
//4/27/2017 ZH :表格视图的上下文菜单
selectAllAction = new QAction(tr("Select All"), this);
clearAllAction = new QAction(tr("Clear All"), this);
copyAction = new QAction(tr("Copy"), this);
deleteAction = new QAction(tr("Delete"), this);
logtoFileAction = new QAction(tr("Log to file"), this);
logtoFileAction->setCheckable(true);
logtoFileAction->setChecked(true);
separator01Action = new QAction(this);
separator02Action = new QAction(this);
separator01Action->setSeparator(true);
separator02Action->setSeparator(true);
ui.tableViewMsg->addAction(selectAllAction);
ui.tableViewMsg->addAction(clearAllAction);
ui.tableViewMsg->addAction(separator01Action);
ui.tableViewMsg->addAction(copyAction);
ui.tableViewMsg->addAction(deleteAction);
ui.tableViewMsg->addAction(separator02Action);
ui.tableViewMsg->addAction(logtoFileAction);
ui.tableViewMsg->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(selectAllAction, &QAction::triggered, this, &RP1210Window::OnSelectAll);
connect(clearAllAction, &QAction::triggered, this, &RP1210Window::OnClearAll);
connect(copyAction, &QAction::triggered, this, &RP1210Window::OnCopy);
connect(deleteAction, &QAction::triggered, this, &RP1210Window::OnDelete);
connect(logtoFileAction, &QAction::triggered, this, &RP1210Window::OnLogtoFile);
connect(ui.tableViewMsg->verticalScrollBar(), &QScrollBar::rangeChanged, this, &RP1210Window::OnScrollRangeChanged);
connect(ui.tableViewMsg->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RP1210Window::OnSelectionChanged);
}
<file_sep>
#ifndef RP1210ProtocolModel_h__
#define RP1210ProtocolModel_h__
// 4/16/2017 : ZH : 协议列表
#include <QAbstractListModel>
#include "RP1210DeviceModel.h"
struct Rp1210Protocol
{
int ProtocolID; // 编号
QString ProtocolName; // 名称
QString ProtocolParam; // 参数
QStringList ProtocolSpeed; // 速度
QList<int> DeviceIDs; // 支持的设备号列表
};
class RP1210ProtocolModel : public QAbstractListModel
{
Q_OBJECT
public:
RP1210ProtocolModel(QObject *parent);
~RP1210ProtocolModel();
Rp1210Protocol* GetProtocol(int index);
void IniProtocolList(class QSettings* VenderIni, QList<Rp1210Device>& DeviceList);
void SetProtocolList(QList<int>* list);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
private:
QMap<int, Rp1210Protocol> RawProtocolMap;
QList<int> IndexList;
};
#endif // RP1210ProtocolModel_h__
<file_sep>
#ifndef MessageDef_h__
#define MessageDef_h__
// 4/23/2017 : ZH : RP1210协议中涉及到的各种消息的定义
#include <QString>
#include <QByteArray>
// 4/23/2017 : ZH : 消息基类
class MessageBase
{
public:
MessageBase(QByteArray rawMsg,bool useEcho = false);
~MessageBase();
QString ByteArrayToQString(QByteArray arr) const;
// 4/23/2017 : ZH : 把RawMsg中的每个字节都格式化为16进制形式组成的字符串
QString GetRawMsgString();
QString GetRawMsgString()const;
// 4/23/2017 : ZH : 子类必须实现的接口,子类可能有不同的转成字符串的样子
virtual QString GetMsgDataString()const = 0;
// 4/23/2017 : ZH : 获取时间戳
unsigned int GetTimeStamp() const;
// 4/23/2017 : ZH : 获取Echo字节
char GetEchoByte() const;
protected:
unsigned int TimeStamp; // 时间戳 : 4字节,大端存储
unsigned char Echo; // echo标记:只有当IsEcho为True的时候才有效
QByteArray Data; // 消息载荷
bool UseEcho; // 是否含使用echo标记
QByteArray RawMsg; // 最原始的消息
QString RawMsgStr; // 字符串形式
};
class J1939Message : public MessageBase
{
public:
J1939Message(QByteArray rawMsg, bool useEcho = false);
~J1939Message();
public:
int GetPGN() const;
unsigned char GetPriority() const;
unsigned char GetSA() const;
unsigned char GetTA() const;
QByteArray GetJ1939Data() const;
QString GetMsgDataString()const override;
protected:
int PGN; // PGN:三个字节,小端存储
unsigned char Priority; // Priority:一个字节
unsigned char SA; // SA:一个字节
unsigned char TA; // TA:一个字节
QByteArray J1939Data; // J1939消息数据
};
#endif // MessageDef_h__<file_sep>
#ifndef RP1210_h__
#define RP1210_h__
// 2017/04/16 : ZH : RP1210协议头文件,定义协议文档中规定的数据
#include <windows.h>
//-----------------------------------------------------------------------------------------------------
// RP1210 RP1210_SendCommand Defines ( From RP1210 Document )
//-----------------------------------------------------------------------------------------------------
typedef unsigned char U8;
#define RP1210_Reset_Device 0
#define RP1210_Set_All_Filters_States_to_Pass 3
#define RP1210_Set_Message_Filtering_For_J1939 4
#define RP1210_Set_Message_Filtering_For_CAN 5
#define RP1210_Set_Message_Filtering_For_J1708 7
#define RP1210_Set_Message_Filtering_For_J1850 8
#define RP1210_Set_Message_Filtering_For_ISO15765 9
#define RP1210_Generic_Driver_Command 14
#define RP1210_Set_J1708_Mode 15
#define RP1210_Echo_Transmitted_Messages 16
#define RP1210_Set_All_Filters_States_to_Discard 17
#define RP1210_Set_Message_Receive 18
#define RP1210_Protect_J1939_Address 19
#define RP1210_Set_Broadcast_For_J1708 20
#define RP1210_Set_Broadcast_For_CAN 21
#define RP1210_Set_Broadcast_For_J1939 22
#define RP1210_Set_Broadcast_For_J1850 23
#define RP1210_Set_J1708_Filter_Type 24
#define RP1210_Set_J1939_Filter_Type 25
#define RP1210_Set_CAN_Filter_Type 26
#define RP1210_Set_J1939_Interpacket_Time 27
#define RP1210_SetMaxErrorMsgSize 28
#define RP1210_Disallow_Further_Connections 29
#define RP1210_Set_J1850_Filter_Type 30
#define RP1210_Release_J1939_Address 31
#define RP1210_Set_ISO15765_Filter_Type 32
#define RP1210_Set_Broadcast_For_ISO15765 33
#define RP1210_Set_ISO15765_Flow_Control 34
#define RP1210_Clear_ISO15765_Flow_Control 35
#define RP1210_Set_ISO15765_Link_Type 36
#define RP1210_Set_J1939_Baud 37
#define RP1210_Set_ISO15765_Baud 38
#define RP1210_Set_BlockTimeout 215
#define RP1210_Set_J1708_Baud 305
//-----------------------------------------------------------------------------------------------------
// RP1210 Constants - Check RP1210 document for any updates.
//-----------------------------------------------------------------------------------------------------
#define BIT0 1 // Bit 0 - Used for masking bits
#define BIT1 2 // Bit 1 - Used for masking bits
#define BIT2 4 // Bit 2 - Used for masking bits
#define BIT3 8 // Bit 3 - Used for masking bits
#define BIT4 16 // Bit 4 - Used for masking bits
#define BIT5 32 // Bit 5 - Used for masking bits
#define BIT6 64 // Bit 6 - Used for masking bits
#define BIT7 128 // Bit 7 - Used for masking bits
#define CONNECTED 1 // Connection state = Connected
#define NOT_CONNECTED -1 // Connection state = Disconnected
#define FILTER_PASS_NONE 0 // Filter state = DISCARD ALL MESSAGES
#define FILTER_PASS_SOME 1 // Filter state = PASS SOME
#define FILTER_PASS_ALL 2 // Filter state = PASS ALL
#define NULL_WINDOW 0 // Windows 3.1 is no longer supported.
#define BLOCKING_IO 1 // For Blocking calls to send/read.
#define NON_BLOCKING_IO 0 // For Non-Blocking calls to send/read.
#define BLOCK_INFINITE 0 // For Non-Blocking calls to send/read.
#define BLOCK_UNTIL_DONE 0 // J1939 Address claim, wait until done
#define RETURN_BEFORE_COMPLETION 2 // J1939 Address claim, don't wait
#define CONVERTED_MODE 1 // J1708 RP1210Mode="Converted"
#define RAW_MODE 0 // J1708 RP1210Mode="Raw"
//4/14/2017 ZH :消息最大长度
#define MAX_J1708_MESSAGE_LENGTH 508 // Maximum size of J1708 message (+1)
#define MAX_J1939_MESSAGE_LENGTH 1796 // Maximum size of J1939 message (+1)
#define MAX_ISO15765_MESSAGE_LENGTH 4108 // Maximum size of ISO15765 message (+1)
#define ECHO_OFF 0x00 // EchoMode
#define ECHO_ON 0x01 // EchoMode
#define RECEIVE_ON 0x01 // Set Message Receive
#define RECEIVE_OFF 0x00 // Set Message Receive
#define ADD_LIST 0x01 // Add a message to the list.
#define VIEW_B_LIST 0x02 // View an entry in the list.
#define DESTROY_LIST 0x03 // Remove all entries in the list.
#define REMOVE_ENTRY 0x04 // Remove a specific entry from the list.
#define LIST_LENGTH 0x05 // Returns number of items in list.
//4/14/2017 ZH :J1939过滤器相关
#define FILTER_PGN 0x00000001 // Setting of J1939 filters
#define FILTER_PRIORITY 0x00000002 // Setting of J1939 filters
#define FILTER_SOURCE 0x00000004 // Setting of J1939 filters
#define FILTER_DESTINATION 0x00000008 // Setting of J1939 filters
#define FILTER_INCLUSIVE 0x00 // FilterMode
#define FILTER_EXCLUSIVE 0x01 // FilterMode
//4/14/2017 ZH :J1939地址相关
#define SILENT_J1939_CLAIM 0x00 // Claim J1939 Address
#define PASS_J1939_CLAIM_MESSAGES 0x01 // Claim J1939 Address
#define J1939_GLOBAL_ADDRESS 255
#define J1939_OFFBOARD_DIAGNOSTICS_TOOL_1 249
#define J1939_OFFBOARD_DIAGNOSTICS_TOOL_2 250
#define J1587_OFFBOARD_DIAGNOSTICS_TOOL_1 172
//4/14/2017 ZH :波特率相关
#define CHANGE_BAUD_NOW 0x00 // Change Baud
#define MSG_FIRST_CHANGE_BAUD 0x01 // Change Baud
#define RP1210_BAUD_9600 0x00 // Change Baud
#define RP1210_BAUD_19200 0x01 // Change Baud
#define RP1210_BAUD_38400 0x02 // Change Baud
#define RP1210_BAUD_57600 0x03 // Change Baud
#define RP1210_BAUD_125k 0x04 // Change Baud
#define RP1210_BAUD_250k 0x05 // Change Baud
#define RP1210_BAUD_500k 0x06 // Change Baud
#define RP1210_BAUD_1000k 0x07 // Change Baud
//4/14/2017 ZH :CAN和ISO15765相关
#define STANDARD_CAN 0x00 // Filters
#define EXTENDED_CAN 0x01 // Filters
#define STANDARD_CAN_ISO15765_EXTENDED 0x02 // 11-bit with ISO15765 extended address
#define EXTENDED_CAN_ISO15765_EXTENDED 0x03 // 29-bit with ISO15765 extended address
#define STANDARD_MIXED_CAN_ISO15765 0x04 // 11-bit identifier with mixed addressing
#define ISO15765_ACTUAL_MESSAGE 0x00 // ISO15765 ReadMessage - type of data
#define ISO15765_CONFIRM 0x01 // ISO15765 ReadMessage - type of data
#define ISO15765_FF_INDICATION 0x02 // ISO15765 ReadMessage - type of data
#define LINKTYPE_GENERIC_CAN 0x00 // Set_ISO15765_Link_Type argument
#define LINKTYPE_J1939_ISO15765_2_ANNEX_A 0x01 // Set_ISO15765_Link_Type argument
#define LINKTYPE_J1939_ISO15765_3 0x02 // Set_ISO15765_Link_Type argument
#ifndef TRUE
#define TRUE 0x01
#define FALSE 0x00
#endif
//-----------------------------------------------------------------------------------------------------
// RP1210 Return Definitions 返回值定义
//-----------------------------------------------------------------------------------------------------
#define NO_ERRORS 0
#define ERR_DLL_NOT_INITIALIZED 128
#define ERR_INVALID_CLIENT_ID 129
#define ERR_CLIENT_ALREADY_CONNECTED 130
#define ERR_CLIENT_AREA_FULL 131
#define ERR_FREE_MEMORY 132
#define ERR_NOT_ENOUGH_MEMORY 133
#define ERR_INVALID_DEVICE 134
#define ERR_DEVICE_IN_USE 135
#define ERR_INVALID_PROTOCOL 136
#define ERR_TX_QUEUE_FULL 137
#define ERR_TX_QUEUE_CORRUPT 138
#define ERR_RX_QUEUE_FULL 139
#define ERR_RX_QUEUE_CORRUPT 140
#define ERR_MESSAGE_TOO_LONG 141
#define ERR_HARDWARE_NOT_RESPONDING 142
#define ERR_COMMAND_NOT_SUPPORTED 143
#define ERR_INVALID_COMMAND 144
#define ERR_TXMESSAGE_STATUS 145
#define ERR_ADDRESS_CLAIM_FAILED 146
#define ERR_CANNOT_SET_PRIORITY 147
#define ERR_CLIENT_DISCONNECTED 148
#define ERR_CONNECT_NOT_ALLOWED 149
#define ERR_CHANGE_MODE_FAILED 150
#define ERR_BUS_OFF 151
#define ERR_COULD_NOT_TX_ADDRESS_CLAIMED 152
#define ERR_ADDRESS_LOST 153
#define ERR_CODE_NOT_FOUND 154
#define ERR_BLOCK_NOT_ALLOWED 155
#define ERR_MULTIPLE_CLIENTS_CONNECTED 156
#define ERR_ADDRESS_NEVER_CLAIMED 157
#define ERR_WINDOW_HANDLE_REQUIRED 158
#define ERR_MESSAGE_NOT_SENT 159
#define ERR_MAX_NOTIFY_EXCEEDED 160
#define ERR_MAX_FILTERS_EXCEEDED 161
#define ERR_HARDWARE_STATUS_CHANGE 162
#define ERR_FIRMWARE_BEING_UPDATED 193
#define ERR_INI_FILE_NOT_IN_WIN_DIR 202
#define ERR_INI_SECTION_NOT_FOUND 204
#define ERR_INI_KEY_NOT_FOUND 205
#define ERR_INVALID_KEY_STRING 206
#define ERR_DEVICE_NOT_SUPPORTED 207
#define ERR_INVALID_PORT_PARAM 208
#define ERR_COMMAND_TIMED_OUT 213
#define ERR_OS_NOT_SUPPORTED 220
#define ERR_COMMAND_QUEUE_IS_FULL 222
#define ERR_CANNOT_SET_CAN_BAUDRATE 224
#define ERR_CANNOT_CLAIM_BROADCAST_ADDRESS 225
#define ERR_OUT_OF_ADDRESS_RESOURCES 226
#define ERR_ADDRESS_RELEASE_FAILED 227
#define ERR_COMM_DEVICE_IN_USE 230
#define ERR_DATA_LINK_CONFLICT 441
#define ERR_ADAPTER_NOT_RESPONDING 453
#define ERR_CAN_BAUD_SET_NONSTANDARD 454
#define ERR_MULTIPLE_CONNECTIONS_NOT_ALLOWED_NOW 455
#define ERR_J1708_BAUD_SET_NONSTANDARD 456
#define ERR_J1939_BAUD_SET_NONSTANDARD 457
#define ERR_ISO15765_BAUD_SET_NONSTANDARD 458
//-----------------------------------------------------------------------------------------------------
// Used to help in unpacking bytes from unsigned 2 and 4-byte integer values. 用来帮助解析消息的各种宏~~
//-----------------------------------------------------------------------------------------------------
#define HIWORD_OF_INT4( x ) ( ( x >> 16 ) & 0xFFFF )
#define LOWORD_OF_INT4( x ) ( x & 0x0000FFFF )
#define HIBYTE_OF_WORD( x ) ( ( x >> 8 ) & 0xFF )
#define LOBYTE_OF_WORD( x ) ( x & 0x00FF )
#define HINIBBLE_OF_CHAR( x ) ( ( x & 0xF0 ) >> 4 )
#define LONIBBLE_OF_CHAR( x ) ( x & 0x0F )
#define BYTE0_OF_INT4( x ) LOBYTE_OF_WORD( LOWORD_OF_INT4( x ) )
#define BYTE1_OF_INT4( x ) HIBYTE_OF_WORD( LOWORD_OF_INT4( x ) )
#define BYTE2_OF_INT4( x ) LOBYTE_OF_WORD( HIWORD_OF_INT4( x ) )
#define BYTE3_OF_INT4( x ) HIBYTE_OF_WORD( HIWORD_OF_INT4( x ) )
//-----------------------------------------------------------------------------------------------------
// RP1210 Defined Function Prototypes 导出函数声明
//-----------------------------------------------------------------------------------------------------
#define DLLEXPORT __declspec( dllexport )
#ifdef __cplusplus
extern "C" {
#endif
short DLLEXPORT WINAPI RP1210_ClientConnect(
HWND hwndClient,
short nDeviceId,
char *fpchProtocol,
long lSendBuffer,
long lReceiveBuffer,
short nIsAppPacketizingIncomingMsgs
);
short DLLEXPORT WINAPI RP1210_ClientDisconnect(
short nClientID
);
short DLLEXPORT WINAPI RP1210_SendMessage(
short nClientID,
char *fpchClientMessage,
short nMessageSize,
short nNotifyStatusOnTx,
short nBlockOnSend
);
short DLLEXPORT WINAPI RP1210_ReadMessage(
short nClientID,
char *fpchAPIMessage,
short nBufferSize,
short nBlockOnSend
);
short DLLEXPORT WINAPI RP1210_SendCommand(
short nCommandNumber,
short nClientID,
char *fpchClientCommand,
short nMessageSize
);
void DLLEXPORT WINAPI RP1210_ReadVersion(
char *fpchDLLMajorVersion,
char *fpchDLLMinorVersion,
char *fpchAPIMajorVersion,
char *fpchAPIMinorVersion
);
short DLLEXPORT WINAPI RP1210_ReadDetailedVersion(
short nClientID,
char *fpchAPIVersionInfo,
char *fpchDLLVersionInfo,
char *fpchFWVersionInfo
);
short DLLEXPORT WINAPI RP1210_GetHardwareStatus(
short nClientID,
char *fpchClientInfo,
short nInfoSize,
short nBlockOnRequest
);
short DLLEXPORT WINAPI RP1210_GetErrorMsg(
short err_code,
char *fpchMessage
);
short DLLEXPORT WINAPI RP1210_GetLastErrorMsg(
short err_code,
int *SubErrorCode,
char *fpchDescription,
short nClientID
);
#ifdef __cplusplus
}
#endif
//-----------------------------------------------------------------------------------------------------
// RP1210 Function Type Definitions 函数指针类型定义
//-----------------------------------------------------------------------------------------------------
typedef short (WINAPI *fxRP1210_ClientConnect)(HWND, short, char *, long, long, short);
typedef short (WINAPI *fxRP1210_ClientDisconnect)(short);
typedef short (WINAPI *fxRP1210_SendMessage)(short, char *, short, short, short);
typedef short (WINAPI *fxRP1210_ReadMessage)(short, char *, short, short);
typedef short (WINAPI *fxRP1210_SendCommand)(short, short, char *, short);
typedef short (WINAPI *fxRP1210_ReadVersion)(char *, char *, char *, char *);
typedef short (WINAPI *fxRP1210_ReadDetailedVersion)(short, char *, char *, char *);
typedef short (WINAPI *fxRP1210_GetHardwareStatus)(short, char *, short, short);
typedef short (WINAPI *fxRP1210_GetErrorMsg)(short, char *);
typedef short (WINAPI *fxRP1210_GetLastErrorMsg)(short, int *, char *, short);
#endif // RP1210_h__<file_sep>
#ifndef RP1210ReadThread_h__
#define RP1210ReadThread_h__
#include <QThread>
// 4/22/2017 : ZH : 消息读取线程
class RP1210Core;
class RP1210ReadThread : public QThread
{
Q_OBJECT
public:
RP1210ReadThread(RP1210Core* core,QObject *parent);
~RP1210ReadThread();
void SetNeedExit(bool needExit);
protected:
void run() Q_DECL_OVERRIDE;
private:
bool NeedExit; // 是否需要退出
RP1210Core* rp1210Core; // rp1210
signals:
void MsgReady(QByteArray data); // 有消息
void ErrorOccurred(short ErrorCode); // 读取失败
};
#endif // RP1210ReadThread_h__
<file_sep>#include "J1939FilterWindow.h"
#include "RP1210Core.h"
J1939FilterWindow::J1939FilterWindow(QWidget *parent)
: QDialog(parent)
,rp1210Core(0)
{
ui.setupUi(this);
InitSignalConnection();
OnCheckBoxChanged(true);
}
J1939FilterWindow::~J1939FilterWindow()
{
}
void J1939FilterWindow::SetRp1210Core(class RP1210Core* core)
{
rp1210Core = core;
}
void J1939FilterWindow::OnSetFilterType()
{
if (rp1210Core && ui.groupBoxFilterType->isChecked())
{
unsigned char FilterType;
if (ui.radioButtonInclusive->isChecked())
FilterType = FILTER_INCLUSIVE;
else
FilterType = FILTER_EXCLUSIVE;
rp1210Core->SetJ1919FilterType(FilterType);
}
}
void J1939FilterWindow::OnSetPassAll()
{
if (rp1210Core)
{
rp1210Core->SetAllFilterStatesToPass();
}
}
void J1939FilterWindow::OnSetDiscardAll()
{
if (rp1210Core)
{
rp1210Core->SetAllFilterStatesToDiscard();
}
}
void J1939FilterWindow::OnSetFilter()
{
if (rp1210Core)
{
unsigned char Flags = GetFilterFlags();
unsigned char PGN[3] = { 0 };
memset(PGN, 0x00, sizeof(PGN));
PGN[0] = ui.lineEditPGNByte0->text().toInt(0, 16);
PGN[1] = ui.lineEditPGNByte1->text().toInt(0, 16);
PGN[2] = ui.lineEditPGNByte2->text().toInt(0, 16);
unsigned char Priority = ui.lineEditPriority->text().toInt();
unsigned char SA = ui.lineEditSA->text().toInt();
unsigned char TA = ui.lineEditTA->text().toInt();
rp1210Core->SetMessageFilterForJ1939(Flags, PGN, Priority, SA, TA);
}
}
void J1939FilterWindow::OnCancel()
{
close();
}
void J1939FilterWindow::OnCheckBoxChanged(bool )
{
if (ui.checkBoxPGN->isChecked())
ui.groupBoxPGN->setEnabled(true);
else
ui.groupBoxPGN->setEnabled(false);
if (ui.checkBoxPriority->isChecked())
ui.lineEditPriority->setEnabled(true);
else
ui.lineEditPriority->setEnabled(false);
if (ui.checkBoxSA->isChecked())
ui.lineEditSA->setEnabled(true);
else
ui.lineEditSA->setEnabled(false);
if (ui.checkBoxTA->isChecked())
ui.lineEditTA->setEnabled(true);
else
ui.lineEditTA->setEnabled(false);
}
void J1939FilterWindow::InitSignalConnection()
{
connect(ui.pushButtonSetType, SIGNAL(clicked()), this, SLOT(OnSetFilterType()));
connect(ui.pushButtonPassAll, SIGNAL(clicked()), this, SLOT(OnSetPassAll()));
connect(ui.pushButtonDiscardAll, SIGNAL(clicked()), this, SLOT(OnSetDiscardAll()));
connect(ui.pushButtonSetFilter, SIGNAL(clicked()), this, SLOT(OnSetFilter()));
connect(ui.pushButtonCancel, SIGNAL(clicked()), this, SLOT(OnCancel()));
}
unsigned char J1939FilterWindow::GetFilterFlags()
{
unsigned char Flags = 0x00;
if (ui.checkBoxPGN->isChecked())
Flags |= FILTER_PGN;
if (ui.checkBoxPriority->isChecked())
Flags |= FILTER_PRIORITY;
if (ui.checkBoxSA->isChecked())
Flags |= FILTER_SOURCE;
if (ui.checkBoxTA->isChecked())
Flags |= FILTER_DESTINATION;
return Flags;
}
<file_sep>#include "RP1210DeviceModel.h"
#include <QSettings>
RP1210DeviceModel::RP1210DeviceModel(QObject *parent)
: QAbstractListModel(parent)
{
DeviceList.clear();
}
RP1210DeviceModel::~RP1210DeviceModel()
{
DeviceList.clear();
}
QList<Rp1210Device>& RP1210DeviceModel::GetDeviceList()
{
return DeviceList;
}
QList<int>* RP1210DeviceModel::GetProtocolList(int index)
{
if (0 <= index && index < DeviceList.size())
{
return &(DeviceList[index].Protocols);
}
return 0;
}
void RP1210DeviceModel::InitDeviceList(QSettings* VenderIni)
{
beginResetModel();
DeviceList.clear();
QStringList DeviceStrList = VenderIni->value("/VendorInformation/Devices").toStringList();
for (int i = 0; i < DeviceStrList.count(); ++i)
{
QString temp = "/DeviceInformation" + DeviceStrList[i];
Rp1210Device device;
device.DeviceID = VenderIni->value(temp + "/DeviceID").toInt();
device.DeviceName = VenderIni->value(temp + "/DeviceName").toString();
device.DeviceParam = VenderIni->value(temp + "/DeviceParams").toString();
device.MultiCANChannels = VenderIni->value(temp + "/MultiCANChannels").toInt();
device.MultiJ1939Channels = VenderIni->value(temp + "/MultiJ1939Channels").toInt();
device.MultiISO15765Channels = VenderIni->value(temp + "/MultiISO15765Channels").toInt();
DeviceList.append(device);
}
endResetModel();
}
int RP1210DeviceModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const
{
return DeviceList.count();
}
QVariant RP1210DeviceModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= DeviceList.count())
return QVariant();
if (role == Qt::DisplayRole)
return QString("%1 -- %2").arg(DeviceList.at(index.row()).DeviceID).arg(DeviceList.at(index.row()).DeviceName);
else
return QVariant();
}
<file_sep>#include "RP1210Core.h"
#include <QMessageBox>
RP1210Core::RP1210Core(QObject *parent)
: QObject(parent)
, pRP1210_ClientConnect(0)
, pRP1210_ClientDisconnect(0)
, pRP1210_ReadMessage(0)
, pRP1210_SendMessage(0)
, pRP1210_SendCommand(0)
, pRP1210_ReadVersion(0)
, pRP1210_ReadDetailedVersion(0)
, pRP1210_GetHardwareStatus(0)
, pRP1210_GetErrorMsg(0)
, pRP1210_GetLastErrorMsg(0)
, hRP1210DLL(0)
{
}
RP1210Core* RP1210Core::GetInstance()
{
if (!theRp1210Instance)
theRp1210Instance = new RP1210Core(0);
return theRp1210Instance;
}
RP1210Core::~RP1210Core()
{
UnLoadRp1210DLL();
}
DWORD RP1210Core::LoadRp1210DLL(QString DLLPath)
{
#ifdef UNICODE
hRP1210DLL = LoadLibrary(DLLPath.toStdWString().c_str());
DWORD dwError = GetLastError();
#else
hRP1210DLL = LoadLibrary(DLLPath.toStdString().c_str());
#endif
if(hRP1210DLL == NULL)
{
emit LogMsg(tr("Failed to load %1,dwError = %2.").arg(DLLPath).arg(dwError));
return dwError;
}
// 4/16/2017 : ZH : 导出函数
pRP1210_ClientConnect = (fxRP1210_ClientConnect)GetProcAddress(hRP1210DLL, "RP1210_ClientConnect");
pRP1210_ClientDisconnect = (fxRP1210_ClientDisconnect)GetProcAddress(hRP1210DLL, "RP1210_ClientDisconnect");
pRP1210_ReadMessage = (fxRP1210_ReadMessage)GetProcAddress(hRP1210DLL, "RP1210_ReadMessage");
pRP1210_SendMessage = (fxRP1210_SendMessage)GetProcAddress(hRP1210DLL, "RP1210_SendMessage");
pRP1210_SendCommand = (fxRP1210_SendCommand)GetProcAddress(hRP1210DLL, "RP1210_SendCommand");
pRP1210_ReadVersion = (fxRP1210_ReadVersion)GetProcAddress(hRP1210DLL, "RP1210_ReadVersion");
pRP1210_ReadDetailedVersion = (fxRP1210_ReadDetailedVersion)GetProcAddress(hRP1210DLL, "RP1210_ReadDetailedVersion");
pRP1210_GetHardwareStatus = (fxRP1210_GetHardwareStatus)GetProcAddress(hRP1210DLL, "RP1210_GetHardwareStatus");
pRP1210_GetErrorMsg = (fxRP1210_GetErrorMsg)GetProcAddress(hRP1210DLL, "RP1210_GetErrorMsg");
pRP1210_GetLastErrorMsg = (fxRP1210_GetLastErrorMsg)GetProcAddress(hRP1210DLL, "RP1210_GetLastErrorMsg");
if (NULL == pRP1210_ClientConnect) { emit LogMsg( "\nError: Could not find procedure RP1210_ClientConnect in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_ClientDisconnect) { emit LogMsg( "\nError: Could not find procedure RP1210_ClientDisconnect in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_ReadMessage) { emit LogMsg( "\nError: Could not find procedure RP1210_ReadMessage in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_SendMessage) { emit LogMsg( "\nError: Could not find procedure RP1210_SendMessage in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_SendCommand) { emit LogMsg( "\nError: Could not find procedure RP1210_SendCommand in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_ReadVersion) { emit LogMsg( "\nError: Could not find procedure RP1210_ReadVersion in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_GetHardwareStatus) { emit LogMsg( "\nError: Could not find procedure RP1210_GetHardwareStatus in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_GetErrorMsg) { emit LogMsg( "\nError: Could not find procedure RP1210_GetErrorMsg in DLL!\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_ReadDetailedVersion) { emit LogMsg( "\nWarning: Could not find procedure RP1210_ReadDetailedVersion in DLL.\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
if (NULL == pRP1210_GetLastErrorMsg) { emit LogMsg( "\nWarning: Could not find procedure RP1210_GetLastErrorMsg in DLL.\n"); FreeLibrary(hRP1210DLL);hRP1210DLL = 0 ; return dwError; }
emit LogMsg(tr("load %1 success!").arg(DLLPath));
return 0;
}
void RP1210Core::UnLoadRp1210DLL()
{
if (hRP1210DLL)
{
pRP1210_ClientConnect = 0;
pRP1210_ClientDisconnect = 0;
pRP1210_ReadMessage = 0;
pRP1210_SendMessage = 0;
pRP1210_SendCommand = 0;
pRP1210_ReadVersion = 0;
pRP1210_ReadDetailedVersion = 0;
pRP1210_GetHardwareStatus = 0;
pRP1210_GetErrorMsg = 0;
pRP1210_GetLastErrorMsg = 0;
FreeLibrary(hRP1210DLL);
hRP1210DLL = 0;
}
}
short RP1210Core::ClientConnect(short DeviceId, QString Protocol, long SendBufferLen /*= 0*/, long ReceiveBufferLen /*= 0*/, bool IsAppPacketizingIncomingMsgs /*= false*/)
{
short temp = 0;
if (IsAppPacketizingIncomingMsgs)
temp = 1;
ClientID = pRP1210_ClientConnect(NULL_WINDOW, DeviceId, (char*)(Protocol.toStdString().c_str()), SendBufferLen, ReceiveBufferLen, temp);
if (ClientID >= 0 && ClientID <= 127)
{
emit LogMsg(tr("RP1210_ClientConnect with DeviceID = %1,%2 success! ClientID = %3.").arg(DeviceId).arg(Protocol).arg(ClientID));
return NO_ERRORS;
}
QString ErrorString = QString(tr("Call RP1210_ClientConnect with DeviceID = %1,%2 failded!\r\n%3.").arg(DeviceId).arg(Protocol).arg(GetErrorMsg(ClientID)));
emit LogMsg(ErrorString);
QMessageBox::critical(0, tr("RP1210 API failed!"), ErrorString);
return ClientID;
}
short RP1210Core::ClientDisconnect()
{
short ErrorCode = pRP1210_ClientDisconnect(ClientID);
if (ErrorCode != NO_ERRORS)
{
QString ErrorString = QString(tr("Call RP1210_ClientDisconnect with ClientID = %1 failed!\r\n%2.").arg(ClientID).arg(GetErrorMsg(ErrorCode)));
emit LogMsg(ErrorString);
QMessageBox::critical(0, tr("RP1210 API failed!"),ErrorString);
return ErrorCode;
}
emit LogMsg("RP1210_ClientDisconnect...");
return ErrorCode;
}
short RP1210Core::SendCommand(short CommandNumber, char* ClientCommand, short MsgSize)
{
short ErrorCode = pRP1210_SendCommand(CommandNumber, ClientID, ClientCommand, MsgSize);
if (ErrorCode != NO_ERRORS)
{
QString ErrorString = QString(tr("Call RP1210_SendCommand with CommandNumber = %1 ,MsgSize = %2 failed!\r\n%3.").arg(CommandNumber).arg(MsgSize).arg(GetErrorMsg(ErrorCode)));
emit LogMsg(ErrorString);
QMessageBox::critical(0, tr("RP1210 API failed!"), ErrorString);
return ErrorCode;
}
emit LogMsg(tr("RP1210_SendCommand with CommandNumber %1,MsgSize %2").arg(CommandNumber).arg(MsgSize));
return ErrorCode;
}
short RP1210Core::ReadMessge(char* RxBuffer, short BufferSize, short BlockOnSend)
{
short retVal = pRP1210_ReadMessage(ClientID, RxBuffer, BufferSize, BlockOnSend);
// 4/22/2017 : ZH : 读取成功或者暂时没有消息
if (retVal >= 0)
return retVal;
QString ErrorString = QString(tr("Call RP1210_ReadMessage with ClientID = %1 failed!\r\n%2.").arg(ClientID).arg(GetErrorMsg(retVal*-1)));
emit LogMsg(ErrorString);
return retVal;
}
QString RP1210Core::GetErrorMsg(short ErrorID)
{
char szTemp[100] = { 0 };
memset(szTemp, 0x00, sizeof(szTemp));
if (ErrorID < 0)
ErrorID = (-1 * ErrorID);
pRP1210_GetErrorMsg(ErrorID, szTemp);
return QString("ErrorID = %1;Msg = %2").arg(ErrorID).arg(szTemp);
}
// 4/19/2017 : ZH : claim address for j1939 protocol
short RP1210Core::ClaimJ1939Address(unsigned char ToolAddress)
{
// 4/19/2017 : ZH : 别特么问为啥这样,我特么也是从示例代码中抄来的,没时间研究J1939/81文档了~~~
// J1939 "NAME" for this sample source code application ( see J1939/81 )
// Self Configurable = 0 = NO
// Industry Group = 0 = GLOBAL
// Vehicle System = 0 = Non-Specific
// Vehicle System Instance = 0 = First Diagnostic PC
// Reserved = 0 = Must be zero
// Function = 129 = Offboard Service Tool
// Function Instance = 0 = First Offboard Service Tool
// Manufacturer Code = 11 = Dearborn Group, Inc.
// Manufacturer Identity = 0 = Dearborn Group, Inc. Sample Source Code
const unsigned char ucJ1939Name[8] = { 0x00, 0x00, 0x60, 0x01, 0x00, 0x81, 0x00, 0x00 };
unsigned char TxBuffer[32] = {0};
memset(TxBuffer, 0x00, sizeof(TxBuffer));
TxBuffer[0] = ToolAddress; // 设备地址
TxBuffer[1] = ucJ1939Name[0]; // 名称?
TxBuffer[2] = ucJ1939Name[1];
TxBuffer[3] = ucJ1939Name[2];
TxBuffer[4] = ucJ1939Name[3];
TxBuffer[5] = ucJ1939Name[4];
TxBuffer[6] = ucJ1939Name[5];
TxBuffer[7] = ucJ1939Name[6];
TxBuffer[8] = ucJ1939Name[7];
TxBuffer[9] = BLOCK_UNTIL_DONE; // 调用标记
// 4/19/2017 : ZH : 发送数据
short ErrorCode = SendCommand(RP1210_Protect_J1939_Address, (char*)TxBuffer, 10);
return ErrorCode;
}
// 4/19/2017 : ZH : Set filters for j1939 protocol
short RP1210Core::SetMessageFilterForJ1939(unsigned char flag, unsigned char* PGN, unsigned char Priority, unsigned char SA, unsigned char TA)
{
unsigned char TX[32] = { 0 };
memset(TX, 0x00, sizeof(TX));
TX[0] = flag;
TX[1] = PGN[0];
TX[2] = PGN[1];
TX[3] = PGN[2];
TX[4] = Priority;
TX[5] = SA;
TX[6] = TA;
short ErrorCode = SendCommand(RP1210_Set_Message_Filtering_For_J1939, (char*)TX, 7);
return ErrorCode;
}
short RP1210Core::SetJ1919FilterType(unsigned char FilterType)
{
short ErrorCode = SendCommand(RP1210_Set_J1939_Filter_Type, (char*)(&FilterType), 1);
return ErrorCode;
}
short RP1210Core::SetAllFilterStatesToPass()
{
short ErrorCode = SendCommand(RP1210_Set_All_Filters_States_to_Pass, 0, 0);
return ErrorCode;
}
short RP1210Core::SetAllFilterStatesToDiscard()
{
short ErrorCode = SendCommand(RP1210_Set_All_Filters_States_to_Discard, 0, 0);
return ErrorCode;
}
RP1210Core* RP1210Core::theRp1210Instance = 0;
<file_sep>#pragma once
#include <QtWidgets/QDialog>
#include "ui_RP1210Window.h"
class RP1210Window : public QDialog
{
Q_OBJECT
public:
RP1210Window(QWidget *parent = Q_NULLPTR);
~RP1210Window();
private:
Ui::RP1210WindowClass ui;
class J1939FilterWindow* J1939FilterDialog;
QAction* selectAllAction;
QAction* clearAllAction;
QAction* copyAction;
QAction* deleteAction;
QAction* logtoFileAction;
QAction* separator01Action;
QAction* separator02Action;
private:
// 4/16/2017 : ZH : ini文件中获取到的数据
class RP1210IniData* IniData;
// 4/16/2017 : ZH : rp1210动态库
class RP1210Core* rp1210Core;
// 4/23/2017 : ZH : 消息读取线程
class RP1210ReadThread* rp1210ReadThread;
// 4/23/2017 : ZH : 消息解析
class RP1210MsgParser* msgParser;
//5/2/2017 ZH : ZH : 消息记录
class RP1210MsgLogger* msgLogger;
protected slots:
void OnAutoBaudRate(bool bAuto);
void OnConnect();
void OnDisConnect();
void OnClearLog();
void OnFilterWindow();
void OnSelectionChanged(QItemSelection selected,QItemSelection deSelected);
void OnScrollRangeChanged(int min, int max);
//4/27/2017 ZH :上下文菜单
void OnSelectAll();
void OnClearAll();
void OnDelete();
void OnCopy();
void OnLogtoFile();
public slots:
void OnLogMsg(QString Msg);
private:
// 4/18/2017 : ZH : 私有,辅助函数,根据客户选择拼接协议字符串,用来和硬件建立链接
QString GetProtocolString();
// 4/19/2017 : ZH : 私有,辅助函数,创建过滤器窗口并连接好各种信号槽
void SetUpFilterWindow();
//4/27/2017 ZH : 私有,辅助函数,设置好表格视图
void SetUpTableView();
};
<file_sep>
#include "MessageDef.h"
MessageBase::MessageBase(QByteArray rawMsg, bool useEcho /*= false*/)
:RawMsg(rawMsg)
,UseEcho(useEcho)
,TimeStamp(0)
{
// 4/23/2017 : ZH : 至少要4个字节
if (RawMsg.size() >= 4)
{
unsigned char c0, c1, c2, c3;
c0 = RawMsg.at(0);
c1 = RawMsg.at(1);
c2 = RawMsg.at(2);
c3 = RawMsg.at(3);
TimeStamp = (c0 << 24) | (c1 << 16) | (c2 << 8) | (c3); // 时间戳,大端存储
}
if (UseEcho)
{
if (RawMsg.size() >= 5)
{
Echo = RawMsg[4];
RawMsg.mid(5);
}
}
else
{
Echo = -1;
Data = RawMsg.mid(4);
}
GetRawMsgString();
}
MessageBase::~MessageBase()
{
Data.clear();
RawMsg.clear();
RawMsgStr.clear();
}
QString MessageBase::ByteArrayToQString(QByteArray arr) const
{
int len = arr.size() * 4;
char* temp = new char[len];
memset(temp, 0x00, len);
int index = 0;
for (int i = 0 ; i < arr.size(); ++i)
{
index += sprintf_s(&(temp[index]), 4, "%02X ", (unsigned char)arr.at(i));
}
QString str(temp);
delete [] temp;
return str;
}
QString MessageBase::GetRawMsgString()
{
if (RawMsgStr.isEmpty())
{
RawMsgStr = ByteArrayToQString(RawMsg);
}
return RawMsgStr;
}
QString MessageBase::GetRawMsgString() const
{
return RawMsgStr;
}
unsigned int MessageBase::GetTimeStamp() const
{
return TimeStamp;
}
char MessageBase::GetEchoByte() const
{
if (UseEcho)
return Echo; // 使用了Echo
else
return -1; // 未使用Echo
}
J1939Message::J1939Message(QByteArray rawMsg, bool useEcho /*= false*/)
:MessageBase(rawMsg,useEcho)
,PGN(0)
{
if (Data.size() >= 6)
{
unsigned char c2, c1, c0;
c2 = Data.at(2);
c1 = Data.at(1);
c0 = Data.at(0);
PGN = (c2 << 16) | (c1 << 8) | (c0); //PNG小端存储
Priority = Data[3];
SA = Data[4];
TA = Data[5];
J1939Data = Data.mid(6);
}
}
J1939Message::~J1939Message()
{
J1939Data.clear();
}
int J1939Message::GetPGN()const
{
return PGN;
}
unsigned char J1939Message::GetPriority()const
{
return Priority;
}
unsigned char J1939Message::GetSA()const
{
return SA;
}
unsigned char J1939Message::GetTA()const
{
return TA;
}
QByteArray J1939Message::GetJ1939Data()const
{
return J1939Data;
}
QString J1939Message::GetMsgDataString() const
{
//return GetRawMsgString();
return ByteArrayToQString(J1939Data);
}
<file_sep>#ifndef RP1210Core_h__
#define RP1210Core_h__
// 2017/04/16 : ZH : RP1210协议实体
#include <QObject>
#include "RP1210.h"
class RP1210Core : public QObject
{
Q_OBJECT
private:
RP1210Core(QObject *parent);
public:
static RP1210Core* GetInstance();
~RP1210Core();
DWORD LoadRp1210DLL(QString DLLPath);
void UnLoadRp1210DLL();
public:
// 4/19/2017 : ZH : RP1210 API 指针的再次简单封装调用,我不想直接使用裸函数指针来做操作.
short ClientConnect(short DeviceId, QString Protocol,long SendBufferLen = 0,long ReceiveBufferLen = 0,bool IsAppPacketizingIncomingMsgs = false);
short ClientDisconnect();
short SendCommand(short CommandNumber,char* ClentCommand,short MsgSize);
short ReadMessge(char* RxBuffer, short BufferSize, short BlockOnSend);
QString GetErrorMsg(short ErrorID);
public:
// 4/19/2017 : ZH : 简单封装后的RP1210_SendCommand函数的具体命令函数
short ClaimJ1939Address(unsigned char ToolAddress);
short SetMessageFilterForJ1939(unsigned char flag,unsigned char* PGN,unsigned char Priority,unsigned char SA,unsigned char TA);
short SetJ1919FilterType(unsigned char FilterType);
short SetAllFilterStatesToPass();
short SetAllFilterStatesToDiscard();
//Set_Message_Filtering_For_J1939
signals:
void LogMsg(QString Msg);
private:
// 4/16/2017 : ZH : 动态库导出函数指针定义
fxRP1210_ClientConnect pRP1210_ClientConnect;
fxRP1210_ClientDisconnect pRP1210_ClientDisconnect;
fxRP1210_ReadMessage pRP1210_ReadMessage;
fxRP1210_SendMessage pRP1210_SendMessage;
fxRP1210_SendCommand pRP1210_SendCommand;
fxRP1210_ReadVersion pRP1210_ReadVersion;
fxRP1210_ReadDetailedVersion pRP1210_ReadDetailedVersion;
fxRP1210_GetHardwareStatus pRP1210_GetHardwareStatus;
fxRP1210_GetErrorMsg pRP1210_GetErrorMsg;
fxRP1210_GetLastErrorMsg pRP1210_GetLastErrorMsg;
private:
HINSTANCE hRP1210DLL; // 4/16/2017 : ZH : 动态库句柄
static RP1210Core* theRp1210Instance;
private:
short ClientID; // RP1210_ClientConnect调用成功后返回的客户端id,后面动态库的调用都需要使用到此函数。
};
#endif // RP1210Core_h__
<file_sep>#include "RP1210MsgLogger.h"
#include "MessageDef.h"
#include <QFile>
#include <QDateTime>
#include <QMessageBox>
#include <QCoreApplication>
RP1210MsgLogger::RP1210MsgLogger(bool startLog /*= false*/, QObject *parent /*= 0*/)
: QObject(parent)
, logFile(0)
{
if (startLog)
StartLog();
}
RP1210MsgLogger::~RP1210MsgLogger()
{
StopLog();
}
bool RP1210MsgLogger::IsLog() const
{
return logFile ? true : false;
}
void RP1210MsgLogger::StartLog()
{
StopLog();
QDateTime currentTime = QDateTime::currentDateTime();
QString strTime = currentTime.toString("dd-MM-yyyy_hh-mm-ss-zzz");
QString path = QCoreApplication::applicationDirPath();
path = path + "/" + strTime + ".log";
logFile = new QFile(path,this);
if (!logFile->open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(0, tr("Failed to create file!"), tr("Failed to create file : %1").arg(path), QMessageBox::Default);
//logFile->deleteLater();
delete logFile;
logFile = 0;
return;
}
logFile->write(strTime.toUtf8());
}
void RP1210MsgLogger::StopLog()
{
if (logFile)
{
if (logFile->isWritable())
{
QDateTime currentTime = QDateTime::currentDateTime();
QString strTime = currentTime.toString("dd-MM-yyyy_hh-mm-ss-zzz");
logFile->write(strTime.toUtf8());
logFile->flush();
}
logFile->close();
//logFile->deleteLater();
delete logFile;
}
logFile = 0;
}
void RP1210MsgLogger::LogToFile(QString msg)
{
if (logFile && logFile->isWritable())
{
logFile->write(msg.toUtf8());
logFile->write("\n");
}
}
void RP1210MsgLogger::LogToFile(J1939Message const* msg)
{
logFile->write(msg->GetRawMsgString().toUtf8());
logFile->write("\n");
}
|
c3f3cce4c635d075b36ba024f1fd797705fc3b9f
|
[
"C",
"C++"
] | 21
|
C++
|
CrazyWolf2014/RP1210App
|
0304e2b6ef1458e6dc10e93ca43625d06fb5b71b
|
24c3e2d74219f357ac3f75b50c18591cbe24ce6a
|
refs/heads/master
|
<file_sep>//con esta función eliminamos las lasCookies
function comercookies(name, color) {
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() - 1);
document.cookie = "name="+name+"; expires=" + tiempo.toGMTString();
document.cookie = "color="+color+"; expires=" + tiempo.toGMTString();
window.location.reload();
}
function crearIndice(name, color){
let cuerpo = document.getElementById("cuerpo");
let form = document.getElementById("iniciar");
cuerpo.removeChild(form);
let nombrar = document.createElement("div");
nombrar.setAttribute("id", "nombrar");
cuerpo.appendChild(nombrar);
let indice = document.createElement("div");
indice.setAttribute("id", "indice");
cuerpo.appendChild(indice);
nombrar.innerHTML = "<h1 id='nombrar'>¡Hola "+name+"!</h1><h3>¿Qué quieres jugar?</h3>";
indice.innerHTML="<button class='botoncitosuwu' id='buttonbusca'>Buscaminas</button><button class='botoncitosuwu' id='buttonkarel'>Karel Dug</button><button class='botoncitosuwu' id='buttonspace'>Space Invaders</button> <button class='botoncitosuwu' id='cerrar'>Cerrar Sesión</button>";
let minas = document.getElementById("buttonbusca");
minas.addEventListener("click", ()=>{
window.location = "./templates/buscaminas.html";
});
let dog = document.getElementById("buttonkarel");
dog.addEventListener("click", ()=>{
window.location = "./templates/digdug.html";
});
let space = document.getElementById("buttonspace");
space.addEventListener("click", ()=>{
window.location = "./templates/Space.html";
});
let cerrar = document.getElementById("cerrar");
cerrar.addEventListener("click", ()=>{
comercookies(name, color);
});
}
function obtenerCookie(clave) { //Función para obener el valor de una cookie existente. En caso de no existir se devuelve "".
let name = clave + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
let boton = document.getElementById("botoncito");
boton.addEventListener("click", ()=>{
let name = document.getElementById("name").value;
let color = document.getElementById("color").value;
let tiempo = new Date();
if ((color!="M" && color!="O")||name=="") {
alert("¡¡¡Ese no es un valor aceptado!!!")
}
else{
window.location.reload();
document.cookie = "name="+name;
document.cookie = "color="+color;
}
});
let name=obtenerCookie("name");
if (name!="") {
crearIndice(name, color)
}<file_sep>//Tal vez si nos hubieran dado esta funcion antes no se me hbaría caído el pelo del estres
function obtenerCookie(clave) { //Función para obener el valor de una cookie existente. En caso de no existir se devuelve "".
var name = clave + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
//Con esta funcion se genera la pagina al perder
function lostgame(cuerpo, salir, info, tablero, contador){
cuerpo.removeChild(info);
cuerpo.removeChild(tablero);
let final = document.createElement("div");
final.setAttribute("id", "fin");
cuerpo.appendChild(final);
final.innerHTML = "<h1 id='end'>End Game</h1><h4 id='punct'>Puntuación: "+contador+"</h4>";
let regresar = document.createElement("div");
regresar.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() - 1);
document.cookie = "dificulty=easy; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=medium; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=hard; expires=" + tiempo.toGMTString();
document.cookie;
window.location = "../index.html";
});
regresar.setAttribute("id", "regreso");
regresar.innerHTML = "<button id='button'>Regresar</button>";
final.appendChild(regresar);
}
//Con esta funcion se forma la página al perder
function winedgame(cuerpo, salir, info, tablero, contador, casillas){
cuerpo.removeChild(info);
cuerpo.removeChild(tablero);
let final = document.createElement("div");
final.setAttribute("id", "fin");
cuerpo.appendChild(final);
final.innerHTML = "<h1 id='end'>¡Has ganado!</h1><h4 id='punct'>Puntuación: "+contador+"</h4>";
let regresar = document.createElement("div");
regresar.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() - 1);
document.cookie = "dificulty=easy; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=medium; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=hard; expires=" + tiempo.toGMTString();
document.cookie;
window.location = "../index.html";
});
regresar.setAttribute("id", "regreso");
regresar.innerHTML = "<button id='button'>Regresar</button>";
final.appendChild(regresar);
}
//Con esta funcion los espacios en blanco expanden la función descubrir a los demás
function expandir(abajo, atras, arriba, enfrente, centro, central, casillas, tamano, contador){
for (let d = abajo; d <= arriba; d++) {
for (let c = atras; c <= enfrente; c++) {
let cuadro = d + "" + c;
let cuadrado = document.getElementById(cuadro);
if (cuadrado.textContent == "") {
if (casillas[d][c] == 0) {
if (d == centro && c == central) {
cuadrado.textContent = "";
cuadrado.style.backgroundColor = "white";
cuadrado.style.backgroundImage = "url('../statics/media/img/pastoquemado.jpg')";
}
else if (cuadrado.style.backgroundColor != "white") {
contador+=1;
contador=descubrir(d, c, casillas, tamano, contador);
}
}
else if (casillas[d][c] != "bomba"){
document.getElementById(cuadro).innerHTML = "<p>" + casillas[d][c] + "</p>";
cuadrado.style.backgroundColor = "white";
cuadrado.style.backgroundImage = "url('../statics/media/img/pastoquemado.jpg')";
contador+=casillas[d][c]*10;
}
}
}
}
return contador;
};
//Con esta funcion se muestran los numeros de las casillas
function descubrir(va, wa, casillas, tamano, contador){
if (va == 0 && wa == 0) {
contador=expandir(va, wa, va + 1, wa + 1, va, wa, casillas, tamano, contador);
}
else if (va == 0 && (wa > 0 && wa < tamano-1)) {
contador=expandir(va, wa - 1, va + 1, wa + 1, va, wa, casillas, tamano, contador);
}
else if (va == 0 && wa == tamano-1) {
contador=expandir(va, wa - 1, va + 1, wa, va, wa, casillas, tamano, contador);
}
else if (( va > 0 && va < tamano-1) && wa == tamano-1) {
contador=expandir(va - 1, wa - 1, va + 1, wa, va, wa, casillas, tamano, contador);
}
else if (va==tamano-1 && wa == tamano-1) {
contador=expandir(va - 1, wa - 1, va, wa, va, wa, casillas, tamano, contador);
}
else if (va==tamano-1 && (wa > 0 && wa < tamano-1)) {
contador=expandir(va - 1, wa - 1, va, wa + 1, va, wa, casillas, tamano, contador);
}
else if (va==tamano-1 && wa == 0 ) {
contador=expandir(va - 1, wa, va, wa + 1, va, wa,casillas, tamano, contador);
}
else if ((va > 0 && va < tamano-1) && wa==0 ) {
contador=expandir(va - 1, wa, va + 1, wa + 1, va, wa, casillas, tamano, contador);
}
else {
contador=expandir(va - 1, wa - 1, va + 1, wa + 1, va, wa, casillas, tamano, contador);
}
return contador;
}
//Con esta se asignan los numeros de las bombas cercanas a cada casilla
function numeritos(abajo, atras, arriba, enfrente, casillas){
for (let q = abajo; q <= arriba; q++) {
for (let o = atras; o <= enfrente; o++) {
if (casillas[q][o] != "bomba") {
casillas[q][o] = (parseInt(casillas[q][o]+1))
}
}
}
}
//Con esta funcion ubicmaos a las casillas de los bordes del tablero
function adyacentes(casillas, tamano){
for (var v = 0; v < tamano; v++) {
for (var w = 0; w < tamano; w++) {
if (casillas[v][w] == "bomba") {
if ( v == 0 && w == 0) {
numeritos(v, w, v+1, w+1, casillas);
}
else if (v == 0 && (w > 0 && w < tamano-1)) {
numeritos(v, w - 1, v + 1, w + 1, casillas);
}
else if (v == 0 && w == tamano-1) {
numeritos(v, w - 1, v + 1, w, casillas);
}
else if (( v > 0 && v < tamano-1) && w == tamano-1 ) {
numeritos(v-1, w-1, v+1, w, casillas);
}
else if (v==tamano-1 && w == tamano-1) {
numeritos(v-1, w-1, v, w, casillas);
}
else if (v==tamano-1 && (w > 0 && w < tamano-1)) {
numeritos(v-1, w-1, v, w+1, casillas);
}
else if (v==tamano-1 && w == 0 ) {
numeritos(v-1, w, v, w+1, casillas);
}
else if ( w==0 && (v > 0 && v < tamano-1)) {
numeritos(v-1, w, v+1, w+1, casillas);
}
else {
numeritos(v-1, w -1, v+1, w+1, casillas);
}
}
}
}
}
//con esta función eliminamos las lasCookies
function comercookies() {
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() - 1);
document.cookie = "dificulty=easy; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=medium; expires=" + tiempo.toGMTString();
document.cookie;
document.cookie = "dificulty=hard; expires=" + tiempo.toGMTString();
document.cookie;
window.location.reload();
}
//Con esta funcion generamos el tablero del buscaminas y llamaos las demás funciones
function buscaminasuwu(tamano, long){
let cuerpo = document.getElementById("buscaminas");
let header = document.getElementById("titulo");
//Aqui se crea es asided para visualizar las instrucciones y la puntuación
let info = document.createElement("aside");
info.setAttribute("id", "info");
cuerpo.appendChild(info);
let contador=0;
info.innerHTML = "<section id='score'>Puntuación: "+contador+"</section>";
let inst = document.createElement("div");
inst.setAttribute("id", "inst");
inst.innerHTML = "<h3 id='tit'>Instrucciones:</h3> <div>El juego consiste en despejar todas las casillas de una pantalla que no oculten una mina. Al hacer click derecho algunas casillas revelarán un número que indica las minas que existen en todas las casillas circundantes. Si se descubre una casilla sin número indica que ninguna de las casillas vecinas tiene mina y estas se descubren automáticamente. Si se descubre una casilla con una mina se pierde la partida, para ganar, seleccione todas las minas con clik izquierdo</div>";
info.appendChild(inst);
//y finalmente se crea el tablero, dependiendo de la dificultas cambia el tamaño
let tablero = document.createElement("div");
tablero.setAttribute("id", "tablero");
cuerpo.appendChild(tablero);
let casillas=[];
let random;
let random2;
let bombitas;
var dificultad =obtenerCookie("dificulty");;
if (dificultad=="easy") {
bombitas=3;
}
else if (dificultad=="medium") {
bombitas=7;
}
else if (dificultad == "hard"){
bombitas = 13;
}
else {
console.log("kestapazandaaa");
}
//Aqui generamos las bombas aleatoriamente
for (var m = 0; m < tamano; m++) {
casillas[m]=[];
for (var n = 0; n < tamano; n++) {
casillas[m][n]=0;
}
}
for (let z = 0; z < bombitas; z++) {
do {
random = Math.floor(Math.random()*tamano);
random2 = Math.floor(Math.random()*tamano);
} while (casillas[random][random2]=="bomba");
casillas[random][random2] = "bomba";
}
adyacentes(casillas, tamano);
//Con este div creamos un boton que elimine las cookies y regrese al inicio
let salir = document.createElement("div");
salir.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() + 1000*60*60*24);
document.cookie = "casillas="+casillas+"; expires=" + tiempo.toGMTString();
document.cookie;
window.location = "../index.html";
});
salir.setAttribute("id", "salida");
salir.innerHTML = "<button id='button'>Salir</button>";
header.appendChild(salir);
//ahora creamos las casillas
for (let a = 0; a < tamano; a++) {
for (let b = 0; b < tamano; b++) {
let casilla = document.createElement("div");
casilla.classList.add("casilla");
casilla.style.backgroundImage = "url('../statics/media/img/pasto.jpg')";
casilla.style.width = long + "%";
casilla.style.height = long + "%";
casilla.setAttribute("id", a + "" + b);
let cinta=0;
//evento para click derecho que muestra la casilla
casilla.addEventListener("click", ()=>{
if (cinta==0) {
let ids = casilla.id.split("");
let id1 = parseInt(ids[0],10);
let id2 = parseInt(ids[1],10);
let cuadro = ids[0] + ids [1];
let cuadrado = document.getElementById(cuadro)
if (casillas[id1][id2] == 0) {
contador+=1;
casilla.style.backgroundImage = "url('../statics/media/img/pastoquemado.jpg')";
cuadrado.style.backgroundColor = "white";
contador=descubrir(id1, id2, casillas, tamano, contador, info);
info.innerHTML = "<section id='score'>Puntuación: "+contador+"</section>";
info.appendChild(inst);
}
else if (casillas[id1][id2] != "bomba") {
contador+=casillas[id1][id2]*10;
info.innerHTML = "<section id='score'>Puntuación: "+contador+"</section>";
info.appendChild(inst);
casilla.style.backgroundImage = "url('../statics/media/img/pastoquemado.jpg')";
cuadrado.innerHTML = "<p>" + casillas[id1][id2] + "</p>";
cuadrado.style.backgroundColor = "white";
}
else {
cuadrado.style.backgroundImage = "url(../statics/media/img/mina.png)";
lostgame(cuerpo, salir, info, tablero, contador);
}
}
});
let ids = casilla.id.split("");
let id1 = parseInt(ids[0],10);
let id2 = parseInt(ids[1],10);
let bombotas = 0;
if (casillas[id1][id2] == "bomba") {
bombotas=1;
}
//evento para el click izquierdo que cambia el fondo y detecta si la casilla tiene una bomba
casilla.oncontextmenu = function () {
let ids = casilla.id.split("");
let id1 = parseInt(ids[0],10);
let id2 = parseInt(ids[1],10);
let cuadro = ids[0] + ids [1];
if (cinta==0 && casillas[id1][id2] == "bomba"){
casilla.style.backgroundImage = "url('../statics/media/img/pasto_cinta.jpg')";
cinta=1;
if (bombotas==1) {
bombitas-=1;
bombotas=0;
if (bombitas==0){
winedgame(cuerpo, salir, info, tablero, contador, casillas);
}
}
}
else if (cinta==0 && casillas[id1][id2] != "bomba"){
casilla.style.backgroundImage = "url('../statics/media/img/pasto_cinta.jpg')";
cinta=1;
bombitas+=1;
if (bombitas==0){
winedgame(cuerpo, salir, info, tablero, contador, casillas);
}
}
else if (cinta==1 && casillas[id1][id2] != "bomba"){
casilla.style.backgroundImage = "url('../statics/media/img/pasto.jpg')";
cinta=0;
bombitas-=1;
if (bombitas==0){
winedgame(cuerpo, salir, info, tablero, contador, casillas);
}
}
else if (cinta==1 && casillas[id1][id2] == "bomba") {
casilla.style.backgroundImage = "url('../statics/media/img/pasto.jpg')";
cinta=0;
if (bombotas==0) {
bombitas+=1;
bombotas=1;
if (bombitas==0){
winedgame(cuerpo, salir, info, tablero, contador, casillas);
}
}
}
return false;
}
tablero.appendChild(casilla);
}
}
}
//Con esta funcion generamos la página con la seleccion de dificultad
function dificulty(){
let cuerpo = document.getElementById("buscaminas");
let header = document.getElementById("titulo");
let salir = document.createElement("div");
salir.addEventListener("click", ()=>{
comercookies();
window.location = "../index.html";
});
salir.setAttribute("id", "salida");
salir.innerHTML = "<button id='button'>Salir</button>";
header.appendChild(salir);
let form = document.createElement("div");
form.setAttribute("id", "dificulty");
cuerpo.appendChild(form);
//para guardar los datos necesitamos una cookie
let easy = document.createElement("div");
easy.classList.add("dif");
easy.setAttribute("id", "facil");
//para facil
easy.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() + 1000*60*60*24);
document.cookie = "dificulty=easy; expires=" + tiempo.toGMTString();
window.location.reload();
});
form.appendChild(easy);
let muestra1 = document.createElement("div");
muestra1.classList.add("muestra");
muestra1.style.backgroundImage = "url(../statics/media/img/easy.png)";
easy.appendChild(muestra1);
let desc1 = document.createElement("div");
desc1.classList.add("desc");
easy.appendChild(desc1);
desc1.innerHTML = "<h5>Fácil</h5>";
//para medio
let medium = document.createElement("div");
medium.classList.add("dif");
medium.setAttribute("id", "medium");
medium.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() + 1000*60*60*24);
document.cookie = "dificulty=medium; expires=" + tiempo.toGMTString();
window.location.reload();
});
form.appendChild(medium);
let muestra2 = document.createElement("div");
muestra2.classList.add("muestra");
muestra2.style.backgroundImage = "url(../statics/media/img/medium.png)";
medium.appendChild(muestra2);
let desc2 = document.createElement("div");
desc2.classList.add("desc");
medium.appendChild(desc2);
desc2.innerHTML = "<h5>Medio</h5>";
//para dificil
let hard = document.createElement("div");
hard.classList.add("dif");
hard.setAttribute("id", "hard");
hard.addEventListener("click", ()=>{
let tiempo = new Date();
tiempo.setTime(tiempo.getTime() + 1000*60*60*24);
document.cookie = "dificulty=hard; expires=" + tiempo.toGMTString();
window.location.reload();
});
form.appendChild(hard);
let muestra3 = document.createElement("div");
muestra3.classList.add("muestra");
muestra3.style.backgroundImage = "url(../statics/media/img/hard.png)";
hard.appendChild(muestra3);
let desc3 = document.createElement("div");
desc3.classList.add("desc");
hard.appendChild(desc3);
desc3.innerHTML = "<h5>Difícil</h5>";
}
//Inicio del programa
//Recibe el nombre y si hay una cookie de la dificultad genera el tablero, si no, te manda a la seleccion de dificultad
let name=obtenerCookie("name");
let usuario = document.getElementById("user");
let nombre = document.createElement("div");
nombre.setAttribute("id", "usaurio");
nombre.innerHTML = "<h3 id='nickname'>"+name+"</h3>";
usuario.appendChild(nombre);
let dificultad=obtenerCookie("dificulty");
if (dificultad=="easy") {
var tamano = 5;
var long = 19;
buscaminasuwu(tamano, long);
}
else if (dificultad=="medium") {
var tamano = 7;
var long = 13;
buscaminasuwu(tamano, long);
}
else if (dificultad=="hard") {
var tamano = 10;
var long = 9;
buscaminasuwu(tamano, long);
}
else {
dificulty();
}<file_sep># ARCADE_MARAVILLOSO
_El proyecto se enfoca en crear un centro de arcade con uso de JavaScript, CSS y Canvas, para pasar el rato y liberarse de estos
tiempos difíciles que se están viviendo_
## Recomendaciones
*Antes de comenzar la instalación, por favor asegúrese de tener espacio disponible en su dispositivo, una buena conexión Wi-Fi para evitar problemas durante el proceso y que su navegador por defecto sea Google Chrome.*
*También cerciórese de tener GIT en su ordenador. Puede descargarlo gratuitamente aquí [Descargar Git](https://git-scm.com/downloads).*
*Por último, sugerimos que su editor de texto sea Atom.*
### Instalación
*1.-Dirigirse al repositorio de GitHub para descargar los archivos necesarios para el funcionamiento de la página [https://github.com/Oviedo404/Arcade_Maravilloso]*
*2.-Intalarlos dentro de Xampp*
### EQUIPO MARAVILLA
* **<NAME>** - *Buscaminas, Diseño de la página y menú de inicio* - [NaimadGam](https://github.com/NaimadGam)
* **<NAME>** - *Space Invaders, Diseño de la página* - [Alexander-Chef](https://github.com/Alexander-Chef)
* **<NAME>** - *DigDug, diseño de la página* - [Oviedo404](https://github.com/Oviedo404)
* **<NAME>** - *Space Invaders* - [astridveiga](https://github.com/astridveiga)
<file_sep>var x = 100;
var y = 100;
var canvas;
var contexto;
var player;
var imagenEnemigo;
var teclaPulsada = null;
var tecla = [];
var colorBala = "red";
var balas_array = new Array();
var enemigos_array = new Array();
var balasEnemigas_array = new Array();
var de;
var puntos = 0;
var finJuego = false;
function obtenerCookie(clave) { //Función para obener el valor de una cookie existente. En caso de no existir se devuelve "".
var name = clave + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function Bala(x,y,w){
this.x = x;
this.y = y;
this.w = w;
this.dibuja = function(){
contexto.save();
contexto.fillStyle = colorBala;
contexto.fillRect(this.x, this.y, this.w, this.w);
this.y = this.y - 4;
contexto.restore();
};
this.dispara = function(){
contexto.save();
contexto.fillStyle = colorBala;
contexto.fillRect(this.x, this.y, this.w, this.w);
this.y = this.y + 6;
contexto.restore();
};
}
function Jugador(x){
this.x = x;
this.y = 400;
this.w = 30;
this.h = 15;
this.dibuja = function(x){
this.x = x;
contexto.drawImage(player, this.x, this.y, this.w, this.h);
};
}
function Enemigo(x,y){
this.x = x;
this.y = y;
this.w = 35;
this.veces = 0;
this.dx = 5;
this.ciclos = 0;
this.num = 14;
this.figura = true;
this.vive = true;
this.dibuja = function(){
if(this.ciclos > 30){
if(this.veces>this.num){
this.dx *= -1;
this.veces = 0;
this.num = 28;
this.y += 20;
this.dx = (this.dx>0)? this.dx++:this.dx--;
} else {
this.x += this.dx;
}
this.veces++;
this.ciclos = 0;
this.figura = !this.figura;
} else {
this.ciclos++;
}
if(this.vive){
if(this.figura){
contexto.drawImage(imagenEnemigo,0,0,40,30, this.x, this.y, 35,30);
} else {
contexto.drawImage(imagenEnemigo,50,0,35,30, this.x, this.y, 35, 30);
}
} else {
contexto.fillStyle = "black";
contexto.fillRect(this.x, this.y, 35, 30);
}
};
}
function anima(){
if(finJuego==false){
requestAnimationFrame(anima);
verifica();
pinta();
colisiones();
}
}
function score(){
contexto.save();
contexto.fillStyle = "#FFFFFF";
contexto.clearRect(0,0,canvas.width,40);
contexto.font = "25px Courier";
contexto.fillText("Puntuación: "+puntos,10,20);
contexto.restore();
}
function mensaje(cadena){
var lon = (canvas.width-(63*cadena.length))/2;
contexto.fillStyle = "White";
contexto.clearRect(0,0,canvas.width, canvas.height);
contexto.font = "bold 100px Rosewood Std";
contexto.fillText(cadena,lon,220);
}
function mensaje2(cadena){
var lon = (canvas.width-(70*cadena.length))/2;
contexto.fillStyle = "red";
contexto.clearRect(0,0,canvas.width, canvas.height);
contexto.font = "bold 100px Rosewood Std";
contexto.fillText(cadena,lon,220);
}
function colisiones(){
for(var i=0; i<enemigos_array.length; i++){
for(var j=0; j<balas_array.length; j++){
enemigo = enemigos_array[i];
bala = balas_array[j];
if(enemigo != null && bala != null){
if((bala.x > enemigo.x)&&
(bala.x < enemigo.x+enemigo.w)&&
(bala.y > enemigo.y)&&
(bala.y < enemigo.y+enemigo.w)){
enemigo.vive = false;
enemigos_array[i] = null;
balas_array[j] = null;
puntos += 10;
}
}
}
}
for(var j=0; j<balasEnemigas_array.length; j++){
bala = balasEnemigas_array[j];
if(bala != null){
if((bala.x > jugador.x)&&
(bala.x < jugador.x+jugador.w)&&
(bala.y > jugador.y)&&
(bala.y < jugador.y+jugador.h)){
gameOver();
}
}
}
}
function gameOver(){
contexto.clearRect(0,0,canvas.width,canvas.height);
balas_array = [];
enemigos_array = [];
balasEnemigas_array = [];
clearTimeout(de);
finJuego = true;
mensaje2("GAME OVER");
}
var KEY_LEFT = 37;
var KEY_RIGHT = 39;
var BARRA = 32;
function verifica(){
if(tecla[KEY_RIGHT]) x+=10;
if(tecla[KEY_LEFT]) x-=10;
if(x>canvas.width-10) x = canvas.width -10;
if(x<0) x = 0;
//Disparo
if(tecla[BARRA]){
balas_array.push(
new Bala(jugador.x+12,jugador.y-3,5));
tecla[BARRA]=false;
disparaEnemigo();
}
}
function pinta(){
contexto.clearRect(0,0,canvas.width, canvas.height);
score();
jugador.dibuja(x);
for(var i=0; i<balas_array.length; i++){
if(balas_array[i]!=null){
balas_array[i].dibuja();
if(balas_array[i].y<0) balas_array[i] = null;
}
}
for(var i=0; i<balasEnemigas_array.length; i++){
if(balasEnemigas_array[i]!=null){
balasEnemigas_array[i].dispara();
if(balasEnemigas_array[i].y>canvas.height) balasEnemigas_array[i] = null;
}
}
numEnemigos = 0;
for(var i=0; i<enemigos_array.length; i++){
if(enemigos_array[i] != null){
enemigos_array[i].dibuja();
numEnemigos++;
if(enemigos_array[i].y==jugador.y) gameOver();
}
}
if(numEnemigos==0) gameOver();
}
function disparaEnemigo(){
var ultimos = new Array();
for(var i=enemigos_array.length-1; i>0; i--){
if(enemigos_array[i]!=null){
ultimos.push(i);
}
if(ultimos.length==10) break;
}
d = ultimos[Math.floor(Math.random()*10)];
balasEnemigas_array.push(new Bala(enemigos_array[d].x+enemigos_array[d].w/2,
enemigos_array[d].y,5));
}
window.requestAnimationFrame=(function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){window.setTimeout(callback,17);}
})();
document.addEventListener("keydown",function(e){
teclaPulsada=e.keyCode;
tecla[e.keyCode]=true;
});
document.addEventListener("keyup",function(e){
tecla[e.keyCode]=false;
});
window.onload = function(){
canvas = document.getElementById("Tablero");
if(canvas && canvas.getContext){
contexto = canvas.getContext("2d");
if(contexto){
x = canvas.width/2;
player = new Image();
imagenEnemigo = new Image();
imagenEnemigo.src = "../statics/media/img/enemigo.png";
player.src = "../statics/media/img/jugador.png";
mensaje("INVADERS");
player.onload = function(){
jugador = new Jugador(0);
setTimeout(anima,3500);
}
imagenEnemigo.onload = function(){
for(var i=0; i<6; i++){
for(var j=0; j<10; j++){
enemigos_array.push(new Enemigo(100+40*j, 30+45*i));
}
}
de = setTimeout(disparaEnemigo,3500);
}
}
}
}
let header = document.getElementById("titulo");
let name=obtenerCookie("name");
let usuario = document.getElementById("user");
let nombre = document.createElement("div");
nombre.setAttribute("id", "usuario");
nombre.innerHTML = "<h3 id='nickname'>"+name+"</h3>";
usuario.appendChild(nombre);
let reiniciar = document.createElement("div");
reiniciar.addEventListener("click", ()=>{
window.location = "../index.html";
});
reiniciar.setAttribute("id", "salida");
reiniciar.innerHTML = "<button id='button'>Salir</button>";
header.appendChild(reiniciar);<file_sep>let tabla = document.getElementsByClassName('tierra')[0];
let contenedor = document.getElementById("contenedor");
let mundo = document.getElementsByTagName("body")[0];
let puntos = document.getElementsByClassName("puntaje")[0];
let vidas = document.getElementsByClassName("vidas")[0];
let rondas = document.getElementsByClassName("ronda")[0];
//Tamaño del mundo
let width=23;
let height=17;
let width_2=24;
let height_2=18;
class taizo{
constructor(y,x,est, ind, ori){
this.y=y;
this.x=x;
this.est=est; //1 vivo, 2 disparando, 3 muerto
this.ind=ind;
this.ori=ori;
}
}
class celda{
constructor(y,x,est,ind){
this.y=y;
this.x=x;
this.est=est;
this.ind=ind;
}
}
class p{
constructor(y,x,est,num,ind){
this.y=y;
this.x=x;
this.est=est;
this.num=num;
this.ind=ind;
}
}
class pooka{
constructor(est, vel, ind, estInd, num, x, y, des){
this.est=est; //1 Vivo, 2 congelado, 3 espera, 4 muerto
this.vel=vel;
this.ind=ind;
this.estInd=estInd;
this.num=num;
this.indAcutal = ind;
this.time=NaN;
this.x=x;
this.y=y;
this.des=des;
}
}
//Celdas: 0-Celda, 1-Taizo, 2-CeldaDes, 4-Bomba, 3-Piedras, 5-Enemigo
let x, x_length = 24;
let y, y_length= 18;
let celdas=[];
let estado=[];
///Posición de Taizo
let taizoX=12;
let taizoY=9;
let dirX=0;
let dirY=0;
//Definición del jugador
let ind=228;
let ori="der";
let taizoHori= new taizo (taizoY, taizoX, 1, ind, ori);
let c=0;
//Construir tablero
function tablero(){
console.log(taizoHori);
console.log(taizoX);
console.log(taizoY);
for (y = 0; y < y_length; y++) {
for (x = 0; x < x_length; x++) {
if(x==taizoX){
if(y<taizoY){
estado[c]= new celda(y,x,2,c);
}
if(y==taizoY){
estado[c]= new celda(y,x,1,c);
}
if(y>taizoY){
estado[c] = new celda(y,x,0,c);
}
}
else{
estado[c] = new celda(y,x,0,c);
}
c++;
}
}
}
//Crear tunel y celdas en el mundo
function creaTablero(){
for(indice in estado){
let celdaD = document.createElement("div");
if(estado[indice].est==2){
celdaD.classList.add("celdaDes");
}
if(estado[indice].est==1){
console.log("Taizo");
celdaD.classList.add("taizoder");
}
if(estado[indice].est==0){
celdaD.classList.add("celda");
}
tabla.appendChild(celdaD);
}
}
function nivelMod(niv ){
let ene=0;
if(niv==1){
ene=4;
tunelEnemigo(3 );
crearEnemigo(ene,niv);
}else if(niv==2 || niv==3){
ene=5;
crearEnemigo(ene,niv);
tunelEnemigo(4);
}else if(niv==4){
ene=5;
crearEnemigo(ene,niv);
tunelEnemigo(4);
}else if(niv==6){
ene=6;
crearEnemigo(ene,niv);
tunelEnemigo(4 );
}else if(niv==7){
ene=6;
crearEnemigo(ene,niv);
tunelEnemigo();
}else if(niv==8){
ene=6;
crearEnemigo(ene,niv);
tunelEnemigo(5);
}else if(niv==9){
ene=6;
crearEnemigo(ene,niv);
tunelEnemigo(5);
}else if(niv==10){
ene=6;
crearEnemigo(ene,niv);
tunelEnemigo(5);
}else if(niv>10){
ene=6;
crearEnemigo(ene,niv);
let nivel=Math.round(Math.random()*(10-6)+6);
tunelEnemigo(nivel);
}else if(niv==50){
tunelEnemigo(4);
}
}
let pookas=[];
function crearEnemigo(num, niv){
let nivel=parseInt(niv);
// let vel=100*nivel;
//let ind;
for(let i=0;i<num;i++){
let velo=(200*niv)+i;
let vel=velo;
let bool=true;
let ind=indice;
while(bool==true){
x=Math.round(Math.random()*(23-0)+0);
if(x!=12){
for(indice in estado){
if(estado[indice].est==2 && estado[indice].x!=12 && estado[indice].x==x){
ind=indice;
bool=false;
}
}
}
}
let celdaPook= tabla.getElementsByTagName("div")[ind];
estado[ind].est=5;
let xP=estado[ind].x;
let yP=estado[ind].y;
let estInd=2;
pookas[i]=new pooka(1, vel, ind, estInd, i, xP, yP, 0);
celdaPook.classList.add("pooka");
}
}
function movimientoPooka(pooka, ){
const direcciones=[+1,-1,+width_2,-width_2];
let direccion = direcciones[Math.floor(Math.random() * direcciones.length)];
//let aleatorio = 0;
pooka.time = setInterval(()=>{
// if(aleatorio<4){
let ind=parseInt(pooka.ind);
let indVerif=ind+direccion;
if(indVerif>=0 && indVerif<=431 && estado[indVerif].est!=0 && estado[indVerif].est!=5 && estado[indVerif].est!=3 && pooka.est==1 && pooka.estInd==2){
// console.log(estado[ind].ind);
let estVi=estado[indVerif].est
estado[ind].est=2;
let xMP=estado[indVerif].x;
let yMP=estado[indVerif].y;
estado[indVerif].est=5;
pooka.ind=indVerif;
pooka.estInd=estVi;
pooka.x=xMP;
pooka.y=yMP;
let celdaViPook=tabla.getElementsByTagName("div")[ind];
let celdaNovPook=tabla.getElementsByTagName("div")[indVerif];
celdaViPook.classList.add("celdaDes");
celdaNovPook.classList.add("pooka");
celdaViPook.classList.remove("pooka");;
celdaNovPook.classList.remove("celdaDes");
}else{
if(pooka.estInd==4){
pooka.est=2;
let celdaInPook=tabla.getElementsByTagName("div")[pooka.ind];
celdaInPook.classList.add("pookaInf");
celdaInPook.classList.remove("pooka");
if(taizoHori.est==1){
if(puntaje<1500){
celdaInPook.classList.add("pookaPar");
celdaInPook.classList.remove("pookaInf");
pooka.est=3;
setTimeout(()=>{
pooka.est=1;
pooka.estInd=2;
celdaInPook.classList.add("celdaDes");
celdaInPook.classList.remove("pookaPar");
celdaInPook.classList.remove("bomba");
},1000);
}else{
celdaInPook.classList.add("pookaPar");
celdaInPook.classList.remove("pookaInf");
pooka.est=4;
clearInterval(pooka.time);
celdaInPook.classList.add("pookaMor");
setTimeout(()=>{
celdaInPook.classList.remove("pookaPar");
celdaInPook.classList.remove("bomba");
estado[pooka.ind].est=2;
celdaInPook.classList.add("celdaDes");
celdaInPook.classList.remove("pookaMor");
pookas.splice(pooka.num, 1);
},800);
}
}
}
if(pooka.estInd==1){
golpeEnemigo();
}
direccion= direcciones[Math.round(Math.random() * direcciones.length)];
}
},pooka.vel);
}
function golpeEnemigo( ){ //Ayuda
pookas.forEach(pooka => clearInterval(pooka.time))
mundo.removeEventListener("keyup", controlHori);
mundo.removeEventListener("keydown",bomba);
mundo.removeEventListener("keyup",bomba);
let celdaM=tabla.getElementsByTagName("div")[taizoHori.ind];
console.log(celdaM);
celdaM.classList.add("taizoM");
celdaM.classList.remove("pooka");
celdaM.classList.remove("taizoder");
setTimeout(()=>{
vidasR--;
vidas.innerText="Vidas "+vidasR;
taizoHori.ind=228;
taizoHori.x=12;
taizoHori.y=9;
taizoHori.ind=228;
taizoHori.ori="der";
taizoX=12;
taizoY=9;
//$(".tierra").remove();
reinicioJ(puntaje,vidasR,nivel);
},10000);
}
function subenivel(){
nivel++;
nivel.innerText="Vidas "+nivel;
reinicioJ(puntaje,vidasR,nivel);
}
function tunelEnemigo(num){
//1 vertical, 0 horizontal
for(let i=0; i<=num;i++){
let pos=Math.round(Math.random());
let ind;
if(pos==0){
let bool=true;
do{
ind=Math.round(Math.random()*(429-2)+2);
let x=estado[ind].x;
let y=estado[ind].y;
if(x>=2 && x<=22 && x!=10 && x!=13 &&x!=14 &&x!=12 &&x!=11){
bool=false;
}
}while(bool==true)
if(estado[ind].est==0 && estado[ind-1].est==0 && estado[ind+1].est==0){
let celda=tabla.getElementsByTagName("div")[ind];
let celda2=tabla.getElementsByTagName("div")[ind-1];
let celda3=tabla.getElementsByTagName("div")[ind+1];
celda.classList.add("celdaDes");
celda2.classList.add("celdaDes");
celda3.classList.add("celdaDes");
celda.classList.remove("celda");
celda2.classList.remove("celda");
celda3.classList.remove("celda");
estado[ind].est=2;
estado[ind-1].est=2;
estado[ind+1].est=2;
}else{
i--;
}
}else if(pos==1){
let bool=true;
do{
ind=Math.round(Math.random()*(429-2)+2);
let y=estado[ind].y;
let x=estado[ind].x;
if(x!=10 && x!=13 &&x!=14 &&x!=12 &&x!=11 && y>=2 && y<=16){
bool=false;
}
}while(bool==true)
if(estado[ind].est==0 && estado[ind+24].est==0 && estado[ind-24].est==0){
let celda=tabla.getElementsByTagName("div")[ind];
let celda2=tabla.getElementsByTagName("div")[ind+24];
let celda3=tabla.getElementsByTagName("div")[ind-24];
celda.classList.add("celdaDes");
celda2.classList.add("celdaDes");
celda3.classList.add("celdaDes");
celda.classList.remove("celda");
celda2.classList.remove("celda");
celda3.classList.remove("celda");
estado[ind].est=2;
estado[ind+24].est=2;
estado[ind-24].est=2;
}else{
i--;
}
}
}
}
function alePiedraX(l){
let bool=true;
l=parseInt(l);
do{
if(l==0){
x=Math.round(Math.random()*(9-2)+2);
}else if(l==1){
x=Math.round(Math.random()*(21-14)+14 );
}else if(l==2){
x=Math.round(Math.random()*(9-2)+2);
}else if(l==3){
x=Math.round(Math.random()*(21-14)+14);
}
for(indice in estado){
if(estado[indice].est==0){
bool=false;
return x;
}
}
}while(bool==true)
}
function alePiedraY(l){
let bool=true;
do{
if(l==0){
y=Math.round(Math.random()*(8-2)+2);
}else if(l==1){
y=Math.round(Math.random()*(8-2)+2);
}else if(l==2){
y=Math.round(Math.random()*(14-9)+9);
}else if(l==3){
y=Math.round(Math.random()*(14-9)+9);
}
for(indice in estado){
if(estado[indice].est==0){
bool=false;
return y;
}
}
}while(bool==true)
}
let piedra=[];
//Construir piedras
function compPiedra(){
for (let j = 0; j < 4; j++) {
let x=alePiedraX(j);
let y=alePiedraY(j);
for(indice in estado){
if(estado[indice].x==x && estado[indice].y==y){
let celda =tabla.getElementsByTagName("div")[indice];
celda.classList.add("piedra");
celda.classList.remove("celda");
estado[indice].est=3;
piedra[j]= new p(y,x,1,j,indice);
}
}
}
}
//Función del disparo de la bomba
function bomba(event){
let tecla=event.keyCode;
let tipo=event.type;
let ind=taizoHori.ind;
let ori=taizoHori.ori;
if(tecla==13){
let bool=true;
if(tipo==="keydown"){
do{
if(ori=="arr"){
taizoHori.est=2;
let uno=ind-24;
if(uno>=0 && estado[uno].est==2){
let celUno=tabla.getElementsByTagName("div")[uno];
celUno.classList.add("bomba");
celUno.classList.remove("celdaDes");
estado[uno].est=4;
let dos=ind-48;
if(dos>=0 && estado[dos].est==2){
let celDos=tabla.getElementsByTagName("div")[dos];
celDos.classList.add("bomba");
celDos.classList.remove("celdaDes");
estado[dos].est=4;
let tres=ind-72;
if(tres>=0 && estado[tres].est==2){
let celTres=tabla.getElementsByTagName("div")[tres];
celTres.classList.add("bomba");
celTres.classList.remove("celdaDes");
estado[tres].est=4;
}else{
bool=false;
}
}else{
bool=false
}
}else{
bool=false;
}
}else if(ori=="aba"){
taizoHori.est=2;
let uno=ind+24;
if(uno<=431 && estado[uno].est==2){
let celUno=tabla.getElementsByTagName("div")[uno];
celUno.classList.add("bomba");
celUno.classList.remove("celdaDes");
estado[uno].est=4;
let dos=ind+48;
if(dos<=431 && estado[dos].est==2){
let celDos=tabla.getElementsByTagName("div")[dos];
celDos.classList.add("bomba");
celDos.classList.remove("celdaDes");
estado[dos].est=4;
let tres=ind+72;
if(tres<=431 && estado[tres].est==2){
let celTres=tabla.getElementsByTagName("div")[tres];
celTres.classList.add("bomba");
celTres.classList.remove("celdaDes");
estado[tres].est=4;
}else{
bool=false;
}
}else{
bool=false
}
}else{
bool=false;
}
}else if(ori=="der"){
taizoHori.est=2;
let uno=ind+1;
if(uno<=431 && estado[uno].est==2){
let celUno=tabla.getElementsByTagName("div")[uno];
celUno.classList.add("bomba");
celUno.classList.remove("celdaDes");
estado[uno].est=4;
let dos=ind+2;
if(dos<=431 && estado[dos].est==2){
let celDos=tabla.getElementsByTagName("div")[dos];
celDos.classList.add("bomba");
celDos.classList.remove("celdaDes");
estado[dos].est=4;
let tres=ind+3;
if(tres<=431 && estado[tres].est==2){
let celTres=tabla.getElementsByTagName("div")[tres];
celTres.classList.add("bomba");
celTres.classList.remove("celdaDes");
estado[tres].est=4;
}else{
bool=false;
}
}else{
bool=false
}
}else{
bool=false;
}
}else if(ori=="izq"){
taizoHori.est=2;
let uno=ind-1;
if(uno>=0 && estado[uno].est==2){
let celUno=tabla.getElementsByTagName("div")[uno];
celUno.classList.add("bomba");
celUno.classList.remove("celdaDes");
estado[uno].est=4;
let dos=ind-2;
if(dos>=0 && estado[dos].est==2){
let celDos=tabla.getElementsByTagName("div")[dos];
celDos.classList.add("bomba");
celDos.classList.remove("celdaDes");
estado[dos].est=4;
let tres=ind-3;
if(tres>=0 && estado[tres].est==2){
let celTres=tabla.getElementsByTagName("div")[tres];
celTres.classList.add("bomba");
celTres.classList.remove("celdaDes");
estado[tres].est=4;
}else{
bool=false;
}
}else{
bool=false
}
}else{
bool=false;
}
}
}while(bool==true)
}else if(tipo==="keyup"){
taizoHori.est=1;
for(indice in estado){
if(estado[indice].est==4){
estado[indice].est=2;
let celRem=tabla.getElementsByTagName("div")[indice];
celRem.classList.add("celdaDes");
celRem.classList.remove("bomba");
}
}
}
}
}
//Movimiento de Hori
function controlHori(evento){
let pos=taizoHori.ind;
let nov=tabla.getElementsByClassName("taizo"+taizoHori.ori)[0];
let viX=taizoHori.x;
let viY=taizoHori.y;
let novX;
let novY;
switch(event.keyCode){
case 65:
if(taizoHori.x!==0 && taizoHori.est==1){
if(estado[pos-1].est==2 || estado[pos-1].est==0 ){
estado[pos].est=2;
nov.classList.add("celdaDes");
nov.classList.remove("taizo"+taizoHori.ori);
novX=viX-1;
taizoHori.x=novX;
taizoHori.ori="izq";
for(indice in estado){
if(estado[indice].x==novX){
if(estado[indice].y==viY){
let novInd=indice;
novInd=parseInt(novInd,10);
taizoHori.ind=novInd;
estado[indice].est=1;
let cel=tabla.getElementsByTagName("div")[indice];
if(cel.classList=="celda"){
puntaje=puntaje+10;
puntos.innerText="Puntaje: "+puntaje;
cel.classList.remove("celda");
cel.classList.add("taizoizq");
}else{
cel.classList.remove("celdaDes");
cel.classList.add("taizoizq");
}
}
}
}
}
}
break;
case 87:
if(taizoHori.y!==0 && taizoHori.est==1){
if(estado[pos-24].est==2 || estado[pos-24].est==0){
estado[pos].est=2;
nov.classList.add("celdaDes");
nov.classList.remove("taizo"+taizoHori.ori);
novY=viY-1;
taizoHori.y=novY;
taizoHori.ori="arr";
for(indice in estado){
if(estado[indice].y==novY){
if(estado[indice].x==viX){
let novInd=indice;
novInd=parseInt(novInd,10);
taizoHori.ind=novInd;
estado[indice].est=1;
let cel=tabla.getElementsByTagName("div")[indice];
if(cel.classList=="celda"){
cel.classList.remove("celda");
puntaje=puntaje+10;
puntos.innerText="Puntaje: "+puntaje;
cel.classList.add("taizoarr");
}else{
cel.classList.remove("celdaDes");
cel.classList.add("taizoarr");
}
}
}
}
}
}
break;
case 83:
if(taizoHori.y!==height && taizoHori.est==1){
if(estado[pos+24].est==0 || estado[pos+24].est==2){
estado[pos].est=2;
nov.classList.add("celdaDes");
nov.classList.remove("taizo"+taizoHori.ori);
novY=viY+1;
taizoHori.y=novY;
taizoHori.ori="aba";
for(indice in estado){
if(estado[indice].y==novY){
if(estado[indice].x==viX){
let novInd=indice;
novInd=parseInt(novInd,10);
taizoHori.ind=novInd;
estado[indice].est=1;
let cel=tabla.getElementsByTagName("div")[indice];
if(cel.classList=="celda"){
puntaje=puntaje+10;
puntos.innerText="Puntaje: "+puntaje;
cel.classList.remove("celda");
cel.classList.add("taizoaba");
}else{
cel.classList.remove("celdaDes");
cel.classList.add("taizoaba");
}
}
}
}
}
}
break;
case 68:
if(taizoHori.x!==width && taizoHori.est==1){
if(estado[pos+1].est==0 || estado[pos+1].est==2){
estado[pos].est=2;
nov.classList.add("celdaDes");
nov.classList.remove("taizo"+taizoHori.ori);
novX=viX+1;
taizoHori.x=novX;
taizoHori.ori="der";
for(indice in estado){
if(estado[indice].x==novX){
if(estado[indice].y==viY){
let novInd=indice;
novInd=parseInt(novInd,10);
taizoHori.ind=novInd;
estado[indice].est=1;
let cel=tabla.getElementsByTagName("div")[indice];
if(cel.classList=="celda"){
puntaje=puntaje+10;
puntos.innerText="Puntaje: "+puntaje;
cel.classList.remove("celda");
cel.classList.add("taizoder");
}else{
cel.classList.remove("celdaDes");
cel.classList.add("taizoder");
}
}
}
}
}
}
break;
}
}
//Puntajes, nivel y vidas
let puntaje=0;
let vidasR=3;
let nivel=1;
if(vidasR==3 && nivel==1){
tablero();
creaTablero();
reinicioF(0, 3, 1);
}
function reinicioJ(puntos, taizoV, nivel){
tabla.innerHTML="";
console.log(estado);
console.log(taizoHori);
console.log(taizoX);
console.log(taizoY);
creaTablero();
mundo.addEventListener("keyup", controlHori);
mundo.addEventListener("keydown",bomba);
mundo.addEventListener("keyup",bomba);
puntos.innerText="Puntaje: "+puntos;
vidas.innerText="Vidas " +taizoV;
rondas.innerText="LEVEL"+nivel;
elem=setTimeout(()=>{
compPiedra();
nivelMod(nivel);
if(pookas.length>0){
pookas.forEach(pooka => movimientoPooka(pooka));
}else{
subenivel();
}
},2000);
}
function reinicioF(puntos, taizoV, nivel){
mundo.addEventListener("keyup", controlHori);
mundo.addEventListener("keydown",bomba);
mundo.addEventListener("keyup",bomba);
puntos.innerText="Puntaje: "+puntos;
vidas.innerText="Vidas " +taizoV;
rondas.innerText="LEVEL"+nivel;
elem=setTimeout(()=>{
compPiedra();
nivelMod(nivel);
if(pookas.length>0){
pookas.forEach(pooka => movimientoPooka(pooka));
}else{
subenivel();
}
},2000);
}
//bicho();
//bicho2();
//tocaPiedra();// puede ser en el movimiento
//subonivel();
//tunelEnemigo();
//ganar();
|
8e9b489d221a22c233d4452c92db6c322ef4dab4
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
Oviedo404/Arcade_Maravilloso
|
8c4f64d39301a9d3047909b60d3e2eb0074bf35e
|
c9f1df5a966494117f691d900dd86b7d58c267e0
|
refs/heads/master
|
<file_sep>const button = document.querySelector("#search")
const breedInput = document.querySelector("#dogFinder")
const imageDiv = document.querySelector("#searchResults")
const modal =document.querySelector("#modal")
const modalContent =document.querySelector("#modalContent")
const modalImg = document.querySelector("#modalImg")
const exit = document.querySelector("#exit")
const savedFavBtn = document.querySelector("#savedFavBtn")
const favoritesPage = window.location.pathname.includes("favs")
if (favoritesPage){
// savedFavBtn.addEventListener('click', async function (){
console.log(localStorage.getItem("saved"))
const savedDog = localStorage.getItem("saved")
imageDiv.innerHTML +=`<div> ${savedDog} </div>`
}
button.addEventListener('click', async function (){
// const apitest = await axios.get(`https://dog.ceo/api/breed/hound/images`)
// console.log (apitest)
searchResults.innerHTML = ""
const breed = breedInput.value
const response = await axios.get(`https://dog.ceo/api/breed/${breed}/images/random/300`)
console.log(response)
const imageURL = response.data.message
// imageDiv.innerHTML = `<img src=${imageURL}>`
imageURL.forEach(function (dog) {
imageDiv.innerHTML +=`<div id=${dog} class="doggyCrate"> <img class="doggyImg" src=${dog} /> </div>`
})
})
document.addEventListener("click", async function (e) {
const element = e.target.parentElement
if (element.className === "doggyCrate") {
const dogId = element.id
let button = `<div class="${dogId}" id="save"> <button id="saveMe">Save</button> </div>`
modal.style.display = "block"
modalContent.innerHTML = `<img src=${dogId} />`
modalClick.innerHTML = `${button}`
modalContent.addEventListener("click", function () {
modal.style.display = "none"
})
}
})
document.addEventListener("click", async function (i) {
const elementSave = i.target.parentElement
if (elementSave.id === "save") {
modalClick.innerHTML = `<p id="saveConfirmation"> You Saved Me! <3 </p>`
const dogIdSave = elementSave.className
localSaveImg = `<img src=${dogIdSave} />`
localStorage.setItem(`saved`,`${localSaveImg}`);
}
})
exit.addEventListener("click", function(){
modal.style.display = "none"
})
// Return To The TOP
let returnToTop = document.querySelector(`#return-to-top`)
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
returnToTop.style.display = "block";
} else {
returnToTop.style.display = "none";
}
}
returnToTop.addEventListener(`click`, function() {
document.body.scrollTo({top: 0, behavior: 'smooth'});
document.documentElement.scrollTo({top: 0, behavior: 'smooth'});
})
|
c71213ad980faac3a8dcc187d5841b7c2465b2db
|
[
"JavaScript"
] | 1
|
JavaScript
|
AnthonyHorta/FuzzyFriends
|
b49f5b34eeef1fc2ca2d23c00bf011ca740288ad
|
2f8e513d186cf080968f5c612699fba1dcdb8387
|
refs/heads/master
|
<repo_name>williamhuang03/Space-Invaders-TM4C123<file_sep>/PinMap.h
// Enumeration for GPIO Pin mapping
enum GPIO_PIN {
GPIO_PIN_0 = (1U << 0),
GPIO_PIN_1 = (1U << 1),
GPIO_PIN_2 = (1U << 2),
GPIO_PIN_3 = (1U << 3),
GPIO_PIN_4 = (1U << 4),
GPIO_PIN_5 = (1U << 5),
GPIO_PIN_6 = (1U << 6),
GPIO_PIN_7 = (1U << 7)
};
// Enumeration for GPIO Port mapping
enum PORT {
GPIO_PORT_A = (1U << 0),
GPIO_PORT_B = (1U << 1),
GPIO_PORT_C = (1U << 2),
GPIO_PORT_D = (1U << 3),
GPIO_PORT_E = (1U << 4),
GPIO_PORT_F = (1U << 5)
};
// Enumeration for ADC module mapping
enum ADC {
ADC_0 = (1U << 0)
};
// Enumeration for ADC Sampler Sequence Register
enum ADC_ACTSS {
ADC_SS3 = (1U << 3),
ADC_BUSY = (1U << 16)
};
<file_sep>/Nokia5110.c
#include "Nokia5110.h"
#include "tm4c123gh6pm.h"
// *****************************************************
// Launchpad to Nokia 5110 LCD Pin Setup
// Use SSI0 module (Port A)
// TI Pin (Type) Nokia 5110 Pin Pin #
// PA7 (GPIO) RST 1
// PA3 (SSI0Fss) CE 2
// PA6 (GPIO) DC 3
// PA5 (SSI0Tx) Din 4
// PA2 (SSI0Clk) CLK 5
// - () BL 7
// +3.3V () VCC 6
// GND () GND 8
// *****************************************************
// *************************************************
// Initializes LCD
// Uses 80 MHz as max system clock and setting SSI clock
// to 4 MHz. Max SSI clock is specifed by LCD as 4 MHz
// Formula for SSI clock is: SSIClk = System Clock / 20
// Inputs: None
// Outputs: None
// Assumes: System clock is no greater than 80 MHz
// *************************************************
void Nokia5110_Init(void) {
/* LCD Init */
volatile uint8_t delay;
/* SSI Initialization */
SYSCTL->RCGCSSI |= SSI_MODULE_0; /* Use SSI Module 0 (SSI0) */
while(!(SYSCTL->RCGCSSI & SSI_MODULE_0)); /* Wait for module to initialize */
SYSCTL->RCGCGPIO |= GPIO_A; /* Initialize Port A as SSI0 uses port A */
while(!(SYSCTL->RCGCGPIO & GPIO_A)); /* Wait for port A to initialize */
GPIOA->DIR |= PA6 | PA7; // PA6, PA7 output
GPIOA->AFSEL |= PA2 | PA3 | PA5; // Alternative function select for PA2, PA3, PA5
GPIOA->PCTL |= (2U << 8) | (2U << 12) | (2U << 20); // Select SSI alternate function for PA2, PA3, PA5
GPIOA->DEN |= PA2 | PA3 | PA5 | PA6 | PA7; // Configure pins as digital
/* SSI Configuration */
SSI0->CR1 &= ~(1U << 1); // Disable SSI port for configuration
SSI0->CR1 = 0x00000000; // Master mode
/* Configure SSI0Clk to 4 MHz = 80 MHz/(4*(1+4)) */
SSI0->CC = 0x00; // System clock as source
SSI0->CPSR = 4; // CPSR = 4
SSI0->CR0 &= 0x00; // Steady state low SSI0Clk when not used, data is captured on rising edge, Freescale frame format
SSI0->CR0 = (4U << 8); // SCR = 4
SSI0->CR0 |= (0x7 << 0); // 8 bit data size
SSI0->CR1 |= (1U << 1); // Enable SSI
/* LCD Initialization */
GPIOA->DATA |= RST; // Set reset pin to high
GPIOA->DATA &= ~RST; // Set reset pin to low
for(delay = 0; delay < 100; delay++); // Delay for reset pulse
GPIOA->DATA |= RST; // Reset pin back high
LCDWrite(COMMAND, 0x21); // Enable chip (PD=0), Horizontal addressing (V=0), Extended instructions (H=1)
LCDWrite(COMMAND, LCD_CONTRAST);
LCDWrite(COMMAND, 0x04); // set temp coefficient
LCDWrite(COMMAND, 0x14); // LCD bias mode 1:48: try 0x13 or 0x14
LCDWrite(COMMAND, 0x20); // Switch to basic instruction set
LCDWrite(COMMAND, DISPLAY_MODE); // set display control to normal mode: 0x0D for inverse
Nokia5110_Clear();
}
// *************************************************
// Sends instructions to LCD
// Inputs: type: either DATA or COMMAND instructions
// data: 8-bit instruction data to LCD driver
// Outputs: None
// *************************************************
static void LCDWrite(TYPE_OF_WRITE type, uint8_t data) {
while((SSI0->SR & BSY)); // Wait for SSI0 to be not busy
GPIOA->DATA &= ~(DC); // Force D/C to known low state
GPIOA->DATA |= type << 6;
SSI0->DR = data;
while((SSI0->SR & BSY));
}
// *************************************************
// Clears LCD screen and sets cursor bck to 0,0 position
// Inputs: none
// Outputs: none
// *************************************************
void Nokia5110_Clear(void) {
int16_t i;
for(i = 0; i < (MAX_X*MAX_Y/8); i++) {
LCDWrite(DATA, 0x00);
}
Nokia5110_SetCursor(0,0);
}
// *************************************************
// Sets cursor at x_pos and y_pos
// Max x_pos is is MAX_X - 1, max y_pos is MAX_Y - 1
// Inputs: x_pos: new x position on LCD
// y_pos: new y position on LCD
// Outputs:
// *************************************************
void Nokia5110_SetCursor(uint8_t x_pos, uint8_t y_pos){
if(x_pos > 83 || y_pos > 5) return; // bad inputs, do nothing and return
LCDWrite(COMMAND, 0x80|(x_pos)); // setting bit 7 updates X-position
LCDWrite(COMMAND, 0x40|y_pos); // setting bit 6 updates Y-position
}
// *************************************************
// Sends a single ASCII character to the LCD screen
// ASCII font based on uint8_t ASCII variable
// Inputs: c: ASCII character to output
// Outputs: none
// *************************************************
static void OutChar(uint8_t c) {
uint8_t i;
for(i = 0; i < 5; i++) {
LCDWrite(DATA, ASCII[c - 0x20][i]);
}
}
// *************************************************
// Write a string of ASCII characters to LCD screen
// Inputs: *s: pointer to string of message to send
// Outputs: none
// *************************************************
void Nokia5110_Printf(uint8_t *s) {
while(*s) {
OutChar(*s++);
}
}
// *************************************************
// Fills whole screen by drawing a 84x48 bitmap image
// Inputs: *p: pointer to bitmap image of size 504 byte
// Outputs: none
// *************************************************
void Nokia5110_DrawFullMap(uint8_t *p){
uint16_t i;
Nokia5110_SetCursor(0,0);
for(i=0; i < (MAX_X*MAX_Y/8); i++) {
LCDWrite(DATA, p[i]);
}
}
uint8_t Screen[SCREENW*SCREENH/8]; // buffer stores the next image to be printed on the screen
//********Nokia5110_PrintBMP*****************
// Bitmaps defined above were created for the LM3S1968 or
// LM3S8962's 4-bit grayscale OLED display. They also
// still contain their header data and may contain padding
// to preserve 4-byte alignment. This function takes a
// bitmap in the previously described format and puts its
// image data in the proper location in the buffer so the
// image will appear on the screen after the next call to
// Nokia5110_DisplayBuffer();
// The interface and operation of this process is modeled
// after RIT128x96x4_BMP(x, y, image);
// inputs: xpos horizontal position of bottom left corner of image, columns from the left edge
// must be less than 84
// 0 is on the left; 82 is near the right
// ypos vertical position of bottom left corner of image, rows from the top edge
// must be less than 48
// 2 is near the top; 47 is at the bottom
// ptr pointer to a 16 color BMP image
// threshold grayscale colors above this number make corresponding pixel 'on'
// 0 to 14
// 0 is fine for ships, explosions, projectiles, and bunkers
// outputs: none
void Nokia5110_PrintBMP(uint8_t xpos, uint8_t ypos, const uint8_t *ptr, uint8_t threshold){
long width = ptr[18], height = ptr[22], i, j;
unsigned short screenx, screeny;
unsigned char mask;
// check for clipping
if((height <= 0) || // bitmap is unexpectedly encoded in top-to-bottom pixel order
((width%2) != 0) || // must be even number of columns
((xpos + width) > SCREENW) || // right side cut off
(ypos < (height - 1)) || // top cut off
(ypos > SCREENH)) { // bottom cut off
return;
}
if(threshold > 14){
threshold = 14; // only full 'on' turns pixel on
}
// bitmaps are encoded backwards, so start at the bottom left corner of the image
screeny = ypos/8;
screenx = xpos + SCREENW*screeny;
mask = ypos%8; // row 0 to 7
mask = 0x01<<mask; // now stores a mask 0x01 to 0x80
j = ptr[10]; // byte 10 contains the offset where image data can be found
for(i=1; i<=(width*height/2); i=i+1){
// the left pixel is in the upper 4 bits
if(((ptr[j]>>4)&0xF) > threshold){
Screen[screenx] |= mask;
} else{
Screen[screenx] &= ~mask;
}
screenx = screenx + 1;
// the right pixel is in the lower 4 bits
if((ptr[j]&0xF) > threshold){
Screen[screenx] |= mask;
} else{
Screen[screenx] &= ~mask;
}
screenx = screenx + 1;
j = j + 1;
if((i%(width/2)) == 0){ // at the end of a row
if(mask > 0x01){
mask = mask>>1;
} else{
mask = 0x80;
screeny = screeny - 1;
}
screenx = xpos + SCREENW*screeny;
// bitmaps are 32-bit word aligned
switch((width/2)%4){ // skip any padding
case 0: j = j + 0; break;
case 1: j = j + 3; break;
case 2: j = j + 2; break;
case 3: j = j + 1; break;
}
}
}
}
// There is a buffer in RAM that holds one screen
// This routine clears this buffer
void Nokia5110_ClearBuffer(void){
int i;
for(i=0; i<SCREENW*SCREENH/8; i=i+1){
Screen[i] = 0; // clear buffer
}
}
//********Nokia5110_DisplayBuffer*****************
// Fill the whole screen by drawing a 48x84 screen image.
// inputs: none
// outputs: none
// assumes: LCD is in default horizontal addressing mode (V = 0)
void Nokia5110_DisplayBuffer(void){
Nokia5110_DrawFullMap(Screen);
}
//********Nokia5110_OutUDec*****************
// Output a 16-bit number in unsigned decimal format with a
// fixed size of five right-justified digits of output.
// Inputs: n 16-bit unsigned number
// Outputs: none
// assumes: LCD is in default horizontal addressing mode (V = 0)
void Nokia5110_OutUDec(uint32_t n){
if(n < 10){
Nokia5110_Printf(" ");
OutChar(n+'0'); /* n is between 0 and 9 */
} else if(n<100){
Nokia5110_Printf(" ");
OutChar(n/10+'0'); /* tens digit */
OutChar(n%10+'0'); /* ones digit */
} else if(n<1000){
Nokia5110_Printf(" ");
OutChar(n/100+'0'); /* hundreds digit */
n = n%100;
OutChar(n/10+'0'); /* tens digit */
OutChar(n%10+'0'); /* ones digit */
}
else if(n<10000){
OutChar(' ');
OutChar(n/1000+'0'); /* thousands digit */
n = n%1000;
OutChar(n/100+'0'); /* hundreds digit */
n = n%100;
OutChar(n/10+'0'); /* tens digit */
OutChar(n%10+'0'); /* ones digit */
}
else {
OutChar(n/10000+'0'); /* ten-thousands digit */
n = n%10000;
OutChar(n/1000+'0'); /* thousands digit */
n = n%1000;
OutChar(n/100+'0'); /* hundreds digit */
n = n%100;
OutChar(n/10+'0'); /* tens digit */
OutChar(n%10+'0'); /* ones digit */
}
}
<file_sep>/Nokia5110.h
#include <stdint.h>
#ifndef SPACEINVADERS_NOKIA_5110_H
#define SPACEINVADERS_NOKIA_5110_H
// *************************************************
// User Adjustable Parameters
// *************************************************
// *************************************************
// LCD Contrast
// Adjust LCD contrast. Choose from 0x80 to 0xFF
// *************************************************
#define LCD_CONTRAST 0xA4
// *************************************************
// Display Mode
// 0x0C for normal, 0x0D for inverse
// *************************************************
#define DISPLAY_MODE 0x0C
// *************************************************
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// DO NOT MAKE CHANGES FROM HERE ON
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// *************************************************
// Maximum dimensions
#define MAX_Y 48
#define MAX_X 84
// Screen dimensions
#define SCREENW 84
#define SCREENH 48
#define SSI_MODULE_0 (1U << 0)
#define GPIO_A (1U << 0)
// Adapted from http://playground.arduino.cc/Code/PCD8544
static const uint8_t ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ?
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f ?
};
// Test Full Image
static uint8_t full_img[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xE0, 0xE0, 0xF8, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC,
0xCC, 0xC6, 0xC2, 0xC2, 0x42, 0x21, 0x31, 0x19, 0xC9, 0xF8, 0x08, 0x07, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x3E, 0x3C, 0x0C, 0xF8, 0xF8, 0xBC, 0x3C,
0x3E, 0x3F, 0x80, 0xC0, 0xE0, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF8, 0xF0, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x1E, 0x0C, 0xF8, 0x10, 0x10, 0xE0, 0x60, 0x43, 0x5F,
0x5E, 0xDE, 0xDF, 0xDF, 0xCF, 0x67, 0xE7, 0xF7, 0xFF, 0xFF, 0xFD, 0xFC, 0xFC, 0xFC,
0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x04,
0x04, 0x04, 0x04, 0xFC, 0xFC, 0xFC, 0xFC, 0x7C, 0x3C, 0x1C, 0x1C, 0x0C, 0xFC, 0xF0,
0x30, 0x70, 0x70, 0xF0, 0xC0, 0xC0, 0xC0, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0xC0,
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, 0x00, 0x00,
0x00, 0x07, 0x01, 0x01, 0x01, 0x01, 0x81, 0x81, 0x7F, 0x3F, 0x0F, 0x07, 0x03, 0xC1,
0xE0, 0xF8, 0xFF, 0xFF, 0xFF, 0x3F, 0x1F, 0x1F, 0x0F, 0x07, 0x03, 0x03, 0xE0, 0xF0,
0xF0, 0xF8, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xFE, 0xFE, 0xFB, 0xFB,
0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xF8, 0xF8, 0xE8, 0xE4, 0xE3, 0xFB,
0xF8, 0xF8, 0xF8, 0x88, 0xF8, 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, 0x03, 0x02, 0x06, 0x07, 0x08, 0x08, 0x88, 0xC8, 0x44, 0x42, 0xC3,
0xC3, 0xC7, 0xCF, 0xCF, 0xCF, 0x8E, 0x1C, 0x38, 0x38, 0xF8, 0xF8, 0xF8, 0xF3, 0xF3,
0xD7, 0x97, 0x17, 0x17, 0x17, 0x37, 0x67, 0xCF, 0x9F, 0x3F, 0x3F, 0x7F, 0xFF, 0xF0,
0xF0, 0xF0, 0xF0, 0xF8, 0xEC, 0xEE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xC7, 0xC7, 0xC7, 0x27, 0x17, 0x3C, 0x78, 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, 0xFF, 0x00, 0xC0, 0xE0, 0x93, 0xFF,
0xFD, 0xFD, 0xFF, 0x7F, 0x0F, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x0F,
0x9F, 0xFF, 0xFD, 0xFE, 0xFC, 0xFC, 0xFC, 0xFF, 0xFF, 0xFF, 0xF8, 0x00, 0x00, 0x1F,
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x8F, 0x8F, 0x8F, 0x8F, 0x4F, 0x3F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE, 0x28, 0x18, 0x00, 0x00};
enum PORT_A_BIT {
PA7 = (1U << 7),
PA6 = (1U << 6),
PA5 = (1U << 5), /* AF: SSI0Tx */
PA3 = (1U << 3), /* AF: SSI0Fss */
PA2 = (1U << 2), /* AF: SSI0Clk */
};
enum LCD_PIN {
RST = PA7,
CE = PA3,
DC = PA6,
DIN = PA5,
CLK = PA2
};
typedef enum {
COMMAND = 0,
DATA = 1
} TYPE_OF_WRITE;
enum SSI_STATUS_RESGITER {
TFE = (1U << 0), // Tx FIFO Empty
TFF = (1U << 1), // Tx Fifo Not Full
BSY = (1U << 4) // SSI Module Busy
};
// *************************************************
// Initializes LCD
// Uses 24 MHz as max system clock and setting SSI clock
// to 2.67 MHz. Max SSI clock is specifed by LCD as 4 MHz
// Formula for SSI clock is: SSIClk = System Clock / 6
// Inputs: None
// Outputs: None
// Assumes: System clock is no greater than 24 MHz
// *************************************************
void Nokia5110_Init(void);
// *************************************************
// Sends instructions to LCD
// Inputs: type: either DATA or COMMAND instructions
// data: 8-bit instruction data to LCD driver
// Outputs: None
// *************************************************
static void LCDWrite(TYPE_OF_WRITE type, uint8_t data);
// *************************************************
// Clears LCD screen and sets cursor bck to 0,0 position
// Inputs: none
// Outputs: none
// *************************************************
void Nokia5110_Clear(void);
// *************************************************
// Sets cursor at x_pos and y_pos
// Max x_pos is is MAX_X - 1, max y_pos is MAX_Y - 1
// Inputs: x_pos: new x position on LCD
// y_pos: new y position on LCD
// Outputs: none
// *************************************************
void Nokia5110_SetCursor(uint8_t x_pos, uint8_t y_pos);
// *************************************************
// Sends a single ASCII character to the LCD screen
// ASCII font based on uint8_t ASCII variable
// Inputs: c: ASCII character to output
// Outputs: none
// *************************************************
static void OutChar(uint8_t c);
// *************************************************
// Write a string of ASCII characters to LCD screen
// Inputs: *s: pointer to string of message to send
// Outputs: none
// *************************************************
void Nokia5110_Printf(uint8_t *s);
// *************************************************
// Fills whole screen by drawing a 84x48 bitmap image
// Inputs: *p: pointer to bitmap image of size 504 byte
// Outputs: none
// *************************************************
void Nokia5110_DrawFullMap(uint8_t *p);
void Nokia5110_Test(void);
//********Nokia5110_PrintBMP*****************
// Bitmaps defined above were created for the LM3S1968 or
// LM3S8962's 4-bit grayscale OLED display. They also
// still contain their header data and may contain padding
// to preserve 4-byte alignment. This function takes a
// bitmap in the previously described format and puts its
// image data in the proper location in the buffer so the
// image will appear on the screen after the next call to
// Nokia5110_DisplayBuffer();
// The interface and operation of this process is modeled
// after RIT128x96x4_BMP(x, y, image);
// inputs: xpos horizontal position of bottom left corner of image, columns from the left edge
// must be less than 84
// 0 is on the left; 82 is near the right
// ypos vertical position of bottom left corner of image, rows from the top edge
// must be less than 48
// 2 is near the top; 47 is at the bottom
// ptr pointer to a 16 color BMP image
// threshold grayscale colors above this number make corresponding pixel 'on'
// 0 to 14
// 0 is fine for ships, explosions, projectiles, and bunkers
// outputs: none
void Nokia5110_PrintBMP(uint8_t xpos, uint8_t ypos, const uint8_t *ptr, uint8_t threshold);
// There is a buffer in RAM that holds one screen
// This routine clears this buffer
void Nokia5110_ClearBuffer(void);
//********Nokia5110_DisplayBuffer*****************
// Fill the whole screen by drawing a 48x84 screen image.
// inputs: none
// outputs: none
// assumes: LCD is in default horizontal addressing mode (V = 0)
void Nokia5110_DisplayBuffer(void);
//********Nokia5110_OutUDec*****************
// Output a 16-bit number in unsigned decimal format with a
// fixed size of five right-justified digits of output.
// Inputs: n 16-bit unsigned number
// Outputs: none
// assumes: LCD is in default horizontal addressing mode (V = 0)
void Nokia5110_OutUDec(uint32_t n);
#endif // SPACEINVADERS_NOKIA_5110_H
<file_sep>/SpaceInvaders.c
#include <stdbool.h>
#include "tm4c123gh6pm.h"
#include "SpaceInvaders.h"
#include "Nokia5110.h"
#include "Fire.h"
#include "Sprites.h"
#include "Position.h"
#include "PinMap.h"
#include "Sound.h"
uint32_t score;
static uint8_t new_game;
int main(void) {
score = 0;
new_game = 1;
game_over = 0;
StartScreen();
for(;;) {
while(!game_over) {
if(new_game) {
new_game = 0;
Sprites_Init(true, true, true, false, false);
g_draw = 1;
}
if(g_draw) {
// Draw screen
Sprites_DrawBuffer();
Nokia5110_DisplayBuffer();
g_draw = 0;
}
if(num_enemies == 0) {
Sprites_Init(false, false, true, true, true);
}
if(sprite_player.life == 0) { game_over = 1; }
}
if(game_over) { GameOver(); }
}
}
// *****************************************************************
// Shows start screen of game
// Displays BMP image Title
// *****************************************************************
void StartScreen(void) {
Nokia5110_ClearBuffer();
Nokia5110_PrintBMP(0, 48, bmp_Title, 0);
Nokia5110_DisplayBuffer();
NVIC_DisableIRQ(TIMER2A_IRQn);
while(!Fire_Status()); // wait until push button is pressed
NVIC_EnableIRQ(TIMER2A_IRQn);
}
void GameOver(void) {
Nokia5110_Clear();
Nokia5110_SetCursor(20,0);
Nokia5110_Printf("Game Over!");
Nokia5110_SetCursor(0, 2);
Nokia5110_Printf("Score: ");
Nokia5110_OutUDec(score);
Nokia5110_SetCursor(0,4);
Nokia5110_Printf("Fire to play!!");
NVIC_DisableIRQ(TIMER2A_IRQn);
while(!Fire_Status());
NVIC_EnableIRQ(TIMER2A_IRQn);
game_over = 0;
score = 0;
new_game = 1;
}
void SysTick_Handler(void) {
switch(Fire_Status()) {
case 0x01:
// Create player missile
if(CreateMissile_Player()) {
Sound_FireMissile();
sound_flag = 1;
}
break;
case 0x02:
// Create bunker missile
if(CreateMissile_Bunker()) {
Sound_FireMissile();
sound_flag = 1;
}
break;
default:
// do nothing
break;
}
// Create Enemy Missile
if(CreateMissile_Enemy()) {
Sound_FireMissile();
sound_flag = 1;
}
// Move Sprites
if(Sprites_Move(Position_Read())) {
Sound_FastInvader();
sound_flag = 1;
}
// Check Collisions
Sprites_CheckCollision();
Sprites_MissilesDelay();
g_draw = 1;
}
<file_sep>/Sound.c
#include "tm4c123gh6pm.h"
#define SOUND
#include "Sound.h"
#include "PinMap.h"
uint8_t sound_flag;
static uint32_t sound_count;
static uint32_t sound_index;
const static uint8_t *sound_wave;
static uint8_t sound_data;
// -------------------------------------------------
// Initializes Timer2A at 11 kHz and enables
// Port B3, B2, B1, B0 to be digital outputs
// -------------------------------------------------
void Sound_Init(void) {
/* Initialize GPIO Port B */
SYSCTL->RCGCGPIO |= (1U << 1);
while(!(SYSCTL->RCGCGPIO & (1U << 1)));
GPIOB->DIR |= GPIO_PIN_3 | GPIO_PIN_2 | GPIO_PIN_1 | GPIO_PIN_0;
GPIOB->DEN |= GPIO_PIN_3 | GPIO_PIN_2 | GPIO_PIN_1 | GPIO_PIN_0;
/* Initializing GPTM 2 */
SYSCTL->RCGCTIMER |= (1U << 2);
while(!(SYSCTL->RCGCTIMER & (1U << 2)));
/* Configure GPTM 2 to be periodic mode */
// Disable Timer A
TIMER2->CTL &= ~(1U << 0);
TIMER2->CFG = 0x00000000;
TIMER2->TAMR |= 0x02;
// Loading value of 11 kHz into Timer2A
TIMER2->TAILR = 7272 - 1;
TIMER2->IMR |= (1U << 0); // enable interrupt on timeout
TIMER2->ICR |= (1U << 0); // Clear interrupt flag
NVIC_EnableIRQ(TIMER2A_IRQn); // Enable timer interrupt in NVIC
NVIC_SetPriority(TIMER2A_IRQn, 4); // Set priority to 4
TIMER2->CTL |= (1U << 0); // Enable timer and start counting
}
// -------------------------------------------------
// Points sound_wave to the sound data and sets sound_count
// to be the number of data and sound index to be 0
// -------------------------------------------------
static void Sound_Play(const uint8_t *sound, uint32_t count) {
sound_wave = sound;
sound_count = count;
sound_index = 0;
}
void Sound_FireMissile(void) {
Sound_Play(sound_shoot, 4080);
}
void Sound_FastInvader(void) {
Sound_Play(sound_fastinvader1, 982);
}
// -------------------------------------------------
// Play sound if sound flag = 1 and sound_index is still
// not at sound_count.
// -------------------------------------------------
void TIMER2A_Handler(void) {
if(sound_count != sound_index && sound_flag == 1) {
sound_data = (sound_wave[sound_index] >> 4);
GPIOB->DATA = sound_data;
sound_index++;
} else {
sound_flag = 0;
}
TIMER2->ICR |= (1U << 0); // Acknowledge interrupt
}
<file_sep>/Fire.h
#include <stdint.h>
#ifndef SPACEINVADERS_FIRE_H
#define SPACEINVADERS_FIRE_H
static volatile uint8_t global_player_fire_flag = 0; // 0: not pushed, 1: pushed
static volatile uint8_t global_bunker_fire_flag = 0; // 0: not pushed, 2: pushed
// **********************************************************
// Initializes Port E Pin 1 and Pin 0 as GPIO digital inputs
// to control firing of missiles from ship and bunkers
// PE1: missile from player ship
// PE0: missile from bunkers
// Inputs: none
// Outputs: none
// **********************************************************
void Fire_Init(void);
// **************************************************************
// Returns the logical OR of global_bunker_fire_flag & global_player_fire_flag
// Inputs: none
// Outputs: global_bunker_fire_flag | global_player_fire_flag
// *************************************************************
uint8_t Fire_Status(void);
void Fire_Test(void);
#endif // SPACEINVADERS_FIRE_H
<file_sep>/SysTick.c
#include "tm4c123gh6pm.h"
#include "SysTick.h"
// ***************************************************************************
// Configures SysTick to be 30 Hz assuming that the system clock is 80 MHz
// Inputs: None
// Outputs: None
// assumes clock is 80 MHz
// // ***************************************************************************
void SysTick_Init(void) {
// 0. Disable Systick
SysTick->CTRL &= 0x00;
// 1. Program the value in the STRELOAD register.
SysTick->LOAD = 2666667-1; // 30 Hz assuming 80 MHz clock
// 2. Clear the STCURRENT register by writing to it with any value.
SysTick->VAL = 0;
// 3. Configure the STCTRL register for the required operation.
SysTick->CTRL |= (1U << 2); // Use System Clock
SysTick->CTRL |= (1U << 1); // Enable interrupts
SysTick->CTRL |= (1U << 0); // Enable Systick
}
<file_sep>/README.md
# README.md
Space Invaders game on a TM4C123 (Cortex-M4).
See SpaceInvaders.mp4 for video of gameplay
<file_sep>/SysTick.h
#ifndef SPACEINVADERS_SYSTICK_H
#define SPACEINVADERS_SYSTICK_H
// ***************************************************************************
// Configures SysTick to be 30 Hz assuming that the system clock is 80 MHz
// Inputs: None
// Outputs: None
// assumes clock is 80 MHz
// // ***************************************************************************
void SysTick_Init(void);
#endif // SPACEINVADERS_SYSTICK_H
<file_sep>/system_init.c
#include "Position.h"
#include "Fire.h"
#include "tm4c123gh6pm.h"
#include "PinMap.h"
#include "Nokia5110.h"
#include "PLL.h"
#include "SysTick.h"
#include "Sprites.h"
#include "Sound.h"
// System Initialization
void SystemInit(void) {
__set_PRIMASK(1);
PLL_Init(4);
SysTick_Init();
/* Port F Init for LED */
SYSCTL->RCGCGPIO |= GPIO_PORT_F;
while(!(SYSCTL->RCGCGPIO & GPIO_PORT_F));
GPIOF->DIR |= GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3;
GPIOF->DEN |= GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3;
Fire_Init();
Position_Init();
Nokia5110_Init();
Sound_Init();
__set_PRIMASK(0);
}
<file_sep>/Sprites.h
#include <stdint.h>
#include <stdbool.h>
#ifndef SPACEINVAERS_SPRITES_H
#define SPACEINVAERS_SPRITES_H
#ifdef SPRITES_STATIC
// Private members
// **********************************************************************
// BMP Sprites
// **********************************************************************
#define WIDTH_LOC 18
#define HEIGHT_LOC 22
// ----------------------------------------------------------------------
// Bunker BMP 18 x 5
const static uint8_t bmp_bunker[3][179] = {
{ // [2] Life = 1
0x42, 0x4D, 0xB2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x0A, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xAA, 0x00,
0x00, 0x00, 0xAA, 0x0A, 0xA0, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0x0A, 0x00, 0x00, 0x00, 0x0A, 0x0A, 0x0A, 0xA0, 0xAA, 0xA0, 0xA0, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x0A, 0x00, 0xA0, 0xA0,
0xA0, 0x00, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF},
{ // [1] Life = 2
0x42, 0x4D, 0xB2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0x00,
0x00, 0x00, 0xAA, 0xAA, 0xA0, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0x0A, 0x00, 0x00, 0x00, 0x0A, 0x0A, 0xAA, 0xAA, 0xAA, 0xAA, 0xA0, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0x0A, 0xA0, 0xA0, 0xAA,
0xAA, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xA0, 0x00, 0x0A, 0x0A, 0x0A, 0x00, 0x00, 0x00, 0x00, 0xFF},
{ // [0] Life = 3
0x42, 0x4D, 0xB2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0x00,
0x00, 0x00, 0xAA, 0xAA, 0xA0, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xA0, 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0xFF}
};
// ----------------------------------------------------------------------
// Small Enemy A 16 x 10 : 1 Life
const static uint8_t bmp_enemyA[2][199] = {
{ // Position 1
0x42, 0x4D, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x50, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0F, 0xF0, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0F,
0xF0, 0xFF, 0xFF, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF},
{ // Position 2
0x42, 0x4D, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x50, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F,
0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF,
0xF0, 0xFF, 0xFF, 0x0F, 0xFF, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0x0F, 0x00, 0x00, 0xF0, 0x0F, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}
};
const static uint8_t bmp_enemyB[2][199] = {
{ // Position 1
0x42, 0x4D, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x50, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0F, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF},
{ // Position 2
0x42, 0x4D, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x50, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F,
0x0F, 0x00, 0x00, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}
};
// ----------------------------------------------------------------------
// Player Ship 18 x 8
const static uint8_t bmp_player[] = {
0x42, 0x4D, 0xD6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00,
0x00, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xAA, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF};
// ----------------------------------------------------------------------
// Missile 4 x 9
const static uint8_t bmp_missile[2][155] = {
{ // Position 1
0x42, 0x4D, 0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0xF0, 0x00,
0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF},
{ // Position 2
0x42, 0x4D, 0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x0F,
0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}
};
// ------------------------------------------------------------------------
// Small explosion
const static uint8_t bmp_explosion[] = {
0x42, 0x4D, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x50, 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, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 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, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF
};
#define BUNKER_FIRE_DELAY 25
#define BUNKER_LIFE 3
#define PLAYER_LIFE 5
static uint8_t bunker_fire_delay;
static uint8_t ENEMY_FIRE_DELAY;
static uint8_t enemy_fire_delay;
static uint8_t enemy_spd;
static uint8_t ENEMY_SPD_COUNTER = 0;
static int8_t move_direction = 1; // 1: right, -1 left
#endif // Private members
extern uint32_t score;
typedef struct {
uint8_t life;
const uint8_t *p_img;
uint8_t img_num;
uint8_t x;
uint8_t y;
uint8_t width;
uint8_t height;
uint8_t fire_spd;
uint16_t fire_delay;
} Sprite;
#define MAX_ENEMY_ROW 2
#define MAX_ENEMY_COL 3
#define MAX_BUNKERS 3
extern Sprite sprite_player;
extern Sprite sprite_player_missile;
extern Sprite sprite_bunker[MAX_BUNKERS];
extern Sprite sprite_bunker_missile[MAX_BUNKERS];
extern Sprite sprite_enemy[MAX_ENEMY_ROW][MAX_ENEMY_COL];
extern Sprite sprite_enemy_missile[MAX_ENEMY_ROW][MAX_ENEMY_COL];
extern uint8_t num_enemies;
// -----------------------------------------------------------------------
// Initializes all sprites' attributes
// Inputs: none
// Outputs: none
// -----------------------------------------------------------------------
void Sprites_Init(bool player, bool bunkers, bool enemies, bool inc_enemy_spd, bool inc_enemy_fire_spd);
// -----------------------------------------------------------------------
// Checks for collision of missiles into sprites
// If collision occurs, take the contacted sprite's life and subtract it
// from the life of the missile.
// If life of sprite is 0, change the image to nothing.
// -----------------------------------------------------------------------
void Sprites_CheckCollision(void);
// ----------------------------------------------------------------------
// Draws all sprite's on screen if their life is > 0
// Inputs: none
// Outputs: true : enemy moved ; false - enemy did not move
// ----------------------------------------------------------------------
bool Sprites_Move(uint16_t player_adc_value);
// ----------------------------------------------------------------------
// Creates player's missile, Bunker Missiles, Enemy missiles
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
bool CreateMissile_Player(void);
bool CreateMissile_Bunker(void);
bool CreateMissile_Enemy(void);
// ----------------------------------------------------------------------
// Draws all sprite's on screen if their life is > 0
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
void Sprites_DrawBuffer(void);
// ----------------------------------------------------------------------
// Sets sprite's life, width, and height
// Inputs: *spr : the sprite we are setting
// life : the # of lives the sprite has
// width : sprite's img width (usually location 18 of bmp data)
// height : sprite's img height (usually location 22 of bmp data)
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetGeneral(Sprite *spr, uint8_t life, uint8_t width, uint8_t height);
// ----------------------------------------------------------------------
// Sets sprite's img info
// Inputs: *spr : the sprite we are setting
// *img : pointer to image the sprite will display
// img_num : the number of images(or "positions") that a bmp_image group has
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetImg(Sprite *spr, const uint8_t *img, uint8_t img_num);
// ----------------------------------------------------------------------
// Sets sprite's location on screen
// Inputs: *spr : the sprite we are setting
// fire_spd : the # of pixels per ?s the sprite's missile will travel through the screen
// fire_delay : the # of seconds before the next missile can be fired..
// if it can be fired that is.
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetFireStats(Sprite *spr, uint8_t fire_spd, uint16_t fire_delay);
// ----------------------------------------------------------------------
// Sets sprite's location on screen
// Inputs: *spr : the sprite we are setting
// x : x location
// y : y location
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetLocation(Sprite *spr, uint8_t x, uint8_t y);
// ----------------------------------------------------------------------
// Check's to see if a missie can be created.
// A missile can be created if the sprite trying to fire the missile has a life > 0
// AND if the sprite's missile has not been created yet (i.e sprite's missile's life = 0)
// Inputs: *spr : sprite that is trying to create missile
// *spr_missile : sprite to sprite's missile
// Outputs: none
// ----------------------------------------------------------------------
static bool Sprite_ValidMissile(Sprite *spr, Sprite *spr_missile);
// ----------------------------------------------------------------------
// Increases counter in order to delay next missile's fire
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
void Sprites_MissilesDelay(void);
// ----------------------------------------------------------------------
// Moves enemies accross the screen, changing directions when reaching
// one end of the screen
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
static void Sprites_MoveEnemy(void);
#endif // SPACEINVADERS_SPRITES_H
<file_sep>/Position.h
#include <stdint.h>
#ifndef SPACEINVADERS_POSITION_H
#define SPACEINVADERS_POSITION_H
// **********************************************************
// Initializes Port E Pin 2 as ADC to control movement of
// player ship with a slide potentiometer
// Inputs: none
// Outputs: none
// **********************************************************
void Position_Init(void);
// **********************************************************
// Readers ADC value of PE2 to determine position of player ship
// Inputs: none
// Outputs: none
// **********************************************************
uint16_t Position_Read(void);
// **********************************************************
// Test function for ADC0
// Inputs: none
// Outputs: none
// **********************************************************
void ADC0_Test(void);
#endif // SPACEINVADERS_POSITION_H
<file_sep>/Position.c
#include "tm4c123gh6pm.h"
#include "Position.h"
#include "PinMap.h"
volatile static uint8_t global_adc0_ss3_flag = 0;
volatile static uint16_t global_adc0_ss3_value;
// **********************************************************
// Initializes Port E Pin 2 as ADC to control movement of
// player ship with a slide potentiometer
// Inputs: none
// Outputs: none
// **********************************************************
void Position_Init(void) {
// Enable Port E clock if not aleady initialized
if (!(SYSCTL->RCGCGPIO & GPIO_PORT_E)) {
SYSCTL->RCGCGPIO |= GPIO_PORT_E;
while(!(SYSCTL->RCGCGPIO & GPIO_PORT_E));
}
// Enable ADC0 clock and configure PE2 as input
SYSCTL->RCGCADC |= ADC_0;
while(!(SYSCTL->RCGCADC & ADC_0));
GPIOE->DIR &= ~ GPIO_PIN_2;
// Select alternative function for PE2
GPIOE->AFSEL |= GPIO_PIN_2;
GPIOE->PCTL &= ~(15U << 8);
// Disable digital pin for PE2
GPIOE->DEN &= ~GPIO_PIN_2;
// Disable analog isolation circuit on PE2
GPIOE->AMSEL |= GPIO_PIN_2;
// **********************************************************
// Sample Sequencer Configuration
// **********************************************************
// Step 1. Disable sample sequencer 3
ADC0->ACTSS &= ~ADC_SS3;
// Step 2. Configure for software trigger
ADC0->EMUX &= ~(0xF000);
// Step 3. -> Skip, not using PWM
// Step 4.
ADC0->SSMUX3 = 0x1; // AIN1
// Step 5. Configure sample sequencer 3
ADC0->SSCTL3 &= 0x00;
ADC0->SSCTL3 |= (1U << 2) | (1U << 1); // Enable interrupt, set END0
// Step 6. Enable interrupt in sample sequencer 3
ADC0->IM |= (1U << 3);
// Step 7. Enable sample sequencer 3
ADC0->ACTSS |= (1U << 3);
ADC0->ISC |= (1U << 3); // Clear interrupt on sample sequencer 3
NVIC_EnableIRQ(ADC0SS3_IRQn); // Allow interrupt on ADC0 Sample Sequencer 3
}
// **********************************************************
// Readers ADC value of PE2 to determine position of player ship
// Inputs: none
// Outputs: returns global_adc_0_ss3_value
// **********************************************************
uint16_t Position_Read(void) {
ADC0->PSSI |= (ADC_SS3); // Get ADC reading on sampler sequence 3
//while(!global_adc0_ss3_flag);
global_adc0_ss3_flag = 0;
return global_adc0_ss3_value;
}
// **************************************************************
// ISR For ADC0 Sample Sequencer 3
// Read sample and set flag
// **************************************************************
void ADC0SS3_Handler(void) {
global_adc0_ss3_value = ADC0->SSFIFO3 & 0xFFF; // Read ADC result
while(ADC0->ACTSS & ADC_BUSY);
global_adc0_ss3_flag = 1; // Set flag indicating ADC result has been read
ADC0->ISC |= (1U << 3); // Acknowledge interrupt
}
void ADC0_Test(void) {
Position_Read();
if(global_adc0_ss3_value < 2000) {
GPIOF->DATA &= ~GPIO_PIN_3;
} else {
GPIOF->DATA |= GPIO_PIN_3;
}
}
<file_sep>/Sprites.c
#define SPRITES_STATIC
#include <stdbool.h>
#include "tm4c123gh6pm.h"
#include <stdint.h>
#include "Sprites.h"
#include "Random.h"
#include "Nokia5110.h"
Sprite sprite_player;
Sprite sprite_player_missile;
Sprite sprite_bunker[MAX_BUNKERS];
Sprite sprite_bunker_missile[MAX_BUNKERS];
Sprite sprite_enemy[MAX_ENEMY_ROW][MAX_ENEMY_COL];
Sprite sprite_enemy_missile[MAX_ENEMY_ROW][MAX_ENEMY_COL];
uint8_t num_enemies = 0;
// ----------------------------------------------------------------------
// Initiates all sprites
// 1. First set img
// 2. Set General info
// 3. Set location
// 4. Set Fire stations
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
void Sprites_Init(bool player, bool bunkers, bool enemies, bool inc_enemy_spd, bool inc_enemy_fire_spd) {
uint8_t i, j, k;
uint32_t enemy_life;
const uint8_t *enemy_img;
if(inc_enemy_spd == true) {
if(enemy_spd == 1) { enemy_spd = 2; }
enemy_spd--;
} else {
enemy_spd = 10;
}
if(inc_enemy_fire_spd) {
if(ENEMY_FIRE_DELAY == 1) { ENEMY_FIRE_DELAY = 2; }
ENEMY_FIRE_DELAY--;
} else {
ENEMY_FIRE_DELAY = 50;
}
// Initiate player sprite
if(player) {
Sprite_SetImg(&sprite_player, bmp_player, 1);
Sprite_SetGeneral(&sprite_player, PLAYER_LIFE, sprite_player.p_img[18], sprite_player.p_img[22]);
Sprite_SetLocation(&sprite_player, 0, 47);
Sprite_SetFireStats(&sprite_player, 2, 0);
}
// Initiate bunker sprite
if(bunkers) {
for(i = 0; i < MAX_BUNKERS; i++) {
Sprite_SetImg(&sprite_bunker[i], bmp_bunker[0], 3);
Sprite_SetGeneral(&sprite_bunker[i], BUNKER_LIFE, sprite_bunker[i].p_img[18], sprite_bunker[i].p_img[22]);
Sprite_SetLocation(&sprite_bunker[i], i * (sprite_bunker[i].width + 14), sprite_player.y - sprite_player.height);
Sprite_SetFireStats(&sprite_bunker[i], 2, BUNKER_FIRE_DELAY);
}
}
// Initiate Enemies A and B randomly
if(enemies) {
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
// Randomly choose enemy A or enemy B
k = (Random()>>24) % 2;
if (k) {
enemy_img = bmp_enemyA[0];
} else {
enemy_img = bmp_enemyB[0];
}
// Randomly give enemies life of 0, or 1
enemy_life = (Random()>>24) % 4;
Sprite_SetImg(&sprite_enemy[i][j], enemy_img, 2);
Sprite_SetGeneral(&sprite_enemy[i][j], enemy_life, sprite_enemy[i][j].p_img[18], sprite_enemy[i][j].p_img[22]);
Sprite_SetLocation(&sprite_enemy[i][j], j * (sprite_enemy[i][j].width + 14), i * sprite_enemy[i][j].height + sprite_enemy[i][j].height);
Sprite_SetFireStats(&sprite_enemy[i][j], 2, ENEMY_FIRE_DELAY);
}
}
}
Sprites_DrawBuffer();
move_direction = 1; // Force enemies to move right
}
// ----------------------------------------------------------------------
// Sets sprite's life, width, and height
// Inputs: *spr : the sprite we are setting
// life : the # of lives the sprite has
// width : sprite's img width (usually location 18 of bmp data)
// height : sprite's img height (usually location 22 of bmp data)
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetGeneral(Sprite *spr, uint8_t life, uint8_t width, uint8_t height) {
spr->life = life;
spr->width = width;
spr->height = height;
}
// ----------------------------------------------------------------------
// Sets sprite's img info
// Inputs: *spr : the sprite we are setting
// *img : pointer to image the sprite will display
// img_num : the number of images(or "positions") that a bmp_image group has
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetImg(Sprite *spr, const uint8_t *img, uint8_t img_num){
spr->p_img = img;
spr->img_num = img_num;
}
// ----------------------------------------------------------------------
// Sets sprite's location on screen
// Inputs: *spr : the sprite we are setting
// x : x location
// y : y location
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetLocation(Sprite *spr, uint8_t x, uint8_t y) {
spr->x = x;
spr->y = y;
}
// ----------------------------------------------------------------------
// Sets sprite's location on screen
// Inputs: *spr : the sprite we are setting
// fire_spd : the # of pixels per ?s the sprite's missile will travel through the screen
// fire_delay : the # of seconds before the next missile can be fired..
// if it can be fired that is.
// Outputs: none
// ----------------------------------------------------------------------
static void Sprite_SetFireStats(Sprite *spr, uint8_t fire_spd, uint16_t fire_delay) {
spr->fire_spd = fire_spd;
spr->fire_delay = fire_delay;
}
// ----------------------------------------------------------------------
// Draws all sprite's on screen if their life is > 0
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
void Sprites_DrawBuffer(void) {
uint8_t i, j;
Nokia5110_ClearBuffer();
// Player and player missile
if(sprite_player.life > 0) { Nokia5110_PrintBMP(sprite_player.x, sprite_player.y, sprite_player.p_img, 0); }
if(sprite_player_missile.life > 0) { Nokia5110_PrintBMP(sprite_player_missile.x, sprite_player_missile.y, sprite_player_missile.p_img, 0); }
// Bunkers and bunker missiles
for(i = 0; i < MAX_BUNKERS; i++) {
if(sprite_bunker[i].life > 0) {
Sprite_SetImg(&sprite_bunker[i], bmp_bunker[sprite_bunker[i].life - 1], 3);
Nokia5110_PrintBMP(sprite_bunker[i].x, sprite_bunker[i].y, sprite_bunker[i].p_img, 0);
}
if(sprite_bunker_missile[i].life > 0) { Nokia5110_PrintBMP(sprite_bunker_missile[i].x, sprite_bunker_missile[i].y, sprite_bunker_missile[i].p_img, 0); }
}
// Enemies
num_enemies = 0;
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
if( (sprite_enemy[i][j].life > 0) ) {
Nokia5110_PrintBMP(sprite_enemy[i][j].x, sprite_enemy[i][j].y, sprite_enemy[i][j].p_img, 0);
num_enemies++;
if(sprite_enemy_missile[i][j].life > 0) {
Nokia5110_PrintBMP(sprite_enemy_missile[i][j].x, sprite_enemy_missile[i][j].y, sprite_enemy_missile[i][j].p_img, 0);
}
}
}
}
}
// ----------------------------------------------------------------------
// Draws all sprite's on screen if their life is > 0, if missile is off screen
// then make it's life to 0
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
bool Sprites_Move(uint16_t player_adc_value){
uint8_t i, j;
static uint8_t enemy_move_speed;
bool enemy_moved = false;
// Move player and player missile
Sprite_SetLocation(&sprite_player, player_adc_value / 63, sprite_player.y);
Sprite_SetLocation(&sprite_player_missile, sprite_player_missile.x, sprite_player_missile.y - 1);
if((sprite_player_missile.y - sprite_player_missile.height) == 0) { sprite_player_missile.life = 0; }
// Move bunker missile
for(i = 0; i < MAX_BUNKERS; i++) {
Sprite_SetLocation(&sprite_bunker_missile[i], sprite_bunker_missile[i].x, sprite_bunker_missile[i].y - 1);
if((sprite_bunker_missile[i].y - sprite_bunker_missile[i].height) == 0) { sprite_bunker_missile[i].life = 0; }
}
// Move Enemies
if(enemy_move_speed >= enemy_spd) {
Sprites_MoveEnemy();
enemy_move_speed = 0;
enemy_moved = true;
}
enemy_move_speed++;
// Move Enemy missiles
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
Sprite_SetLocation(&sprite_enemy_missile[i][j], sprite_enemy_missile[i][j].x, sprite_enemy_missile[i][j].y + 1);
if(sprite_enemy_missile[i][j].y == 47) {
sprite_enemy_missile[i][j].life = 0;
}
}
}
return enemy_moved;
}
// ----------------------------------------------------------------------
// Creates player's missile
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
bool CreateMissile_Player(void) {
if(Sprite_ValidMissile(&sprite_player, &sprite_player_missile)) {
Sprite_SetImg(&sprite_player_missile, bmp_missile[0], 2);
Sprite_SetGeneral(&sprite_player_missile, 1, sprite_player_missile.p_img[18], sprite_player_missile.p_img[22]);
Sprite_SetLocation(&sprite_player_missile, sprite_player.x + sprite_player.width/2, sprite_player.y - sprite_player.height);
Sprite_SetFireStats(&sprite_player_missile, sprite_player.fire_spd, sprite_player.fire_delay);
return true;
}
return false;
}
// ----------------------------------------------------------------------
// Creates bunker's missiles
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
bool CreateMissile_Bunker(void){
uint32_t i;
i = (Random()>>24) % MAX_BUNKERS;
if( (Sprite_ValidMissile(&sprite_bunker[i], &sprite_bunker_missile[i])) && (bunker_fire_delay >= BUNKER_FIRE_DELAY) ) {
Sprite_SetImg(&sprite_bunker_missile[i], bmp_missile[0], 2);
Sprite_SetGeneral(&sprite_bunker_missile[i], 1, sprite_bunker_missile[i].p_img[18], sprite_bunker_missile[i].p_img[22]);
Sprite_SetLocation(&sprite_bunker_missile[i], sprite_bunker[i].x + sprite_bunker[i].width/2, sprite_bunker[i].y - sprite_bunker[i].height);
Sprite_SetFireStats(&sprite_bunker_missile[i], sprite_bunker[i].fire_spd, sprite_bunker[i].fire_delay);
bunker_fire_delay = 0;
return true;
}
return false;
}
// ----------------------------------------------------------------------
// Creates bunker's missiles
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
bool CreateMissile_Enemy(void){
uint32_t i, j;
i = (Random()>>24) % MAX_ENEMY_ROW;
j = (Random()>>24) % MAX_ENEMY_COL;
if( (Sprite_ValidMissile(&sprite_enemy[i][j], &sprite_enemy_missile[i][j])) && (enemy_fire_delay >= ENEMY_FIRE_DELAY) ) {
Sprite_SetImg(&sprite_enemy_missile[i][j], bmp_missile[0], 2);
Sprite_SetGeneral(&sprite_enemy_missile[i][j], 1, sprite_enemy_missile[i][j].p_img[18], sprite_enemy_missile[i][j].p_img[22]);
Sprite_SetLocation(&sprite_enemy_missile[i][j], sprite_enemy[i][j].x + sprite_enemy[i][j].width/2, sprite_enemy[i][j].y + sprite_enemy[i][j].height/2);
Sprite_SetFireStats(&sprite_enemy_missile[i][j], sprite_enemy[i][j].fire_spd, sprite_enemy[i][j].fire_delay);
enemy_fire_delay = 0;
return true;
}
return false;
}
// ----------------------------------------------------------------------
// Check's to see if a missie can be created.
// A missile can be created if the sprite trying to fire the missile has a life > 0
// AND if the sprite's missile has not been created yet (i.e sprite's missile's life = 0)
// Inputs: *spr : sprite that is trying to create missile
// *spr_missile : sprite to sprite's missile
// Outputs: none
// ----------------------------------------------------------------------
static bool Sprite_ValidMissile(Sprite *spr, Sprite *spr_missile) {
if(spr->life > 0 && spr_missile->life == 0) {
return true;
}
return false;
}
// ----------------------------------------------------------------------
// Increases counter in order to delay next missile's fire
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
void Sprites_MissilesDelay(void){
bunker_fire_delay++;
enemy_fire_delay++;
}
// ----------------------------------------------------------------------
// Moves enemies accross the screen, changing directions when reaching
// one end of the screen
// Inputs: none
// Outputs: none
// ----------------------------------------------------------------------
static void Sprites_MoveEnemy(void) {
uint8_t i, j;
// Move enemy
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
if(sprite_enemy[i][j].life > 0) {
Sprite_SetLocation(&sprite_enemy[i][j], sprite_enemy[i][j].x + move_direction, sprite_enemy[i][j].y);
}
}
}
// Determine next move direction by determining if sprites are at left most or right most of screen
// if left most, move direction is right (1); if right most, move direction is left (-1)
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
if(sprite_enemy[i][j].life > 0) {
if(move_direction == 1) {
if(sprite_enemy[i][j].x == 68) {
move_direction = -1;
return;
}
} else if (move_direction == -1) {
if(sprite_enemy[i][j].x == 0) {
move_direction = 1;
return;
}
}
}
}
}
}
// -----------------------------------------------------------------------
// Checks for collision of missiles into sprites
// If collision occurs, take the contacted sprite's life and subtract it
// from the life of the missile.
// If life of sprite is 0, change the image to nothing.
// -----------------------------------------------------------------------
void Sprites_CheckCollision(void) {
uint8_t i, j, k;
// Check player missile on enemy
for(i = 0; i < MAX_ENEMY_ROW; i++) {
for(j = 0; j < MAX_ENEMY_COL; j++) {
// player missile on enemy
if(
((sprite_player_missile.x >= sprite_enemy[i][j].x ) && (sprite_player_missile.x <= (sprite_enemy[i][j].x + sprite_enemy[i][j].width))) &&
((sprite_player_missile.y - sprite_player_missile.height) == sprite_enemy[i][j].y)) {
if(sprite_player_missile.life > 0 && sprite_enemy[i][j].life > 0) {
sprite_enemy[i][j].life -= 1;
sprite_player_missile.life = 0;
score += 10;
}
}
// enemy missile on player
if( (sprite_enemy_missile[i][j].x >= sprite_player.x) && (sprite_enemy_missile[i][j].x <= sprite_player.x + sprite_player.width) &&
(sprite_enemy_missile[i][j].y == sprite_player.y - sprite_player.height) ) {
if(sprite_player.life > 0 && sprite_enemy_missile[i][j].life > 0) {
sprite_player.life -= 1;
sprite_enemy_missile[i][j].life = 0;
}
}
for(k = 0; k < MAX_BUNKERS; k++) {
// bunker missile on enemy
if (
((sprite_bunker_missile[k].x >= sprite_enemy[i][j].x) && (sprite_bunker_missile[k].x <= sprite_enemy[i][j].x + sprite_enemy[i][j].width) &&
(sprite_bunker_missile[k].y == sprite_enemy[i][j].y))) {
if(sprite_bunker_missile[k].life > 0 && sprite_enemy[i][j].life > 0) {
sprite_enemy[i][j].life -= 1;
sprite_bunker_missile[k].life = 0;
score += 10;
}
} // bunker missile on enemy
// enemy missile on bunker
if ( (sprite_enemy_missile[i][j].x >= sprite_bunker[k].x) && (sprite_enemy_missile[i][j].x <= sprite_bunker[k].x + sprite_bunker[k].width) &&
(sprite_enemy_missile[i][j].y == (sprite_bunker[k].y - sprite_bunker[k].height))
) {
if(sprite_bunker[k].life > 0 && sprite_enemy_missile[i][j].life > 0) {
sprite_bunker[k].life -= 1;
sprite_enemy_missile[i][j].life = 0;
}
}
}
}
}
}
<file_sep>/Fire.c
#include "Fire.h"
#include "tm4c123gh6pm.h"
#include "PinMap.h"
// **********************************************************
// Initializes Port E Pin 1 and Pin 0 as GPIO digital inputs
// to control firing of missiles from ship and bunkers
// PE1: missile from player ship
// PE0: missile from bunkers
// Inputs: none
// Outputs: none
// **********************************************************
void Fire_Init(void) {
// Enable Port E clock if not aleady initialized
if (!(SYSCTL->RCGCGPIO & GPIO_PORT_E)) {
SYSCTL->RCGCGPIO |= GPIO_PORT_E;
while(!(SYSCTL->RCGCGPIO & GPIO_PORT_E));
}
GPIOE->DIR &= ~(GPIO_PIN_1|GPIO_PIN_0); // PE1 and PE0 as inputs
//GPIOE->AFSEL &= ~(GPIO_PIN_1|GPIO_PIN_0);
//GPIOE->AMSEL &= ~(GPIO_PIN_1|GPIO_PIN_0);
GPIOE->DEN |= (GPIO_PIN_1|GPIO_PIN_0); // PE1 and PE0 digital enable
// Interrupt configuration
GPIOE->IM &= ~(GPIO_PIN_1|GPIO_PIN_0); // Mask interrupt on PE1 and PE0 to configure interrupts
GPIOE->IS &= ~(GPIO_PIN_1|GPIO_PIN_0); // Edge-senstive interrupt on PE1 and PE0
GPIOE->IBE &= ~(GPIO_PIN_1|GPIO_PIN_0); // Do not interrupt on both edges
GPIOE->IEV &= ~(GPIO_PIN_1|GPIO_PIN_0); // Interrupt on falling edges
GPIOE->ICR |= GPIO_PIN_1|GPIO_PIN_0; // Clear raw interrupt status for PE1 and PE0
GPIOE->IM |= (GPIO_PIN_1|GPIO_PIN_0);
NVIC_EnableIRQ(GPIOE_IRQn); // Allow interrupt on GPIOE
}
// **********************************************************
// ISR for PE1 and PE0
// Inputs: none
// Outputs: none
// **********************************************************
void GPIOE_Handler(void) {
// Check RIS of PE1 (player ship fire)
if(GPIOE->RIS & GPIO_PIN_1) {
global_player_fire_flag = 0x01;
GPIOE->ICR |= GPIO_PIN_1;
}
// Check RIS of PE0 (bunker fire)
if (GPIOE->RIS & GPIO_PIN_0) {
global_bunker_fire_flag = 0x02;
GPIOE->ICR |= GPIO_PIN_0;
}
}
// **************************************************************
// Returns the logical OR of global_bunker_fire_flag & global_player_fire_flag
// Inputs: none
// Outputs: global_bunker_fire_flag | global_player_fire_flag
// *************************************************************
uint8_t Fire_Status(void) {
uint8_t fire_status = global_bunker_fire_flag | global_player_fire_flag;
global_bunker_fire_flag = 0;
global_player_fire_flag = 0;
return fire_status;
}
void Fire_Test(void) {
if(global_player_fire_flag == 1) {
GPIOF->DATA ^= GPIO_PIN_1;
global_player_fire_flag = 0;
}
if(global_bunker_fire_flag == 2) {
GPIOF->DATA ^= GPIO_PIN_2;
global_bunker_fire_flag = 0;
}
}
|
761f335fe5ea8a5cc392f210ee47df5ed6414225
|
[
"Markdown",
"C"
] | 15
|
C
|
williamhuang03/Space-Invaders-TM4C123
|
eb59e65640b0b2ff0ffc4f9ce5eaf0a81a8bc01e
|
e8b18bc5e01620125d9995310a1c41acb405b154
|
refs/heads/master
|
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import {HttpClientModule} from '@angular/common/http'
import {RouterModule} from '@angular/router'
import { AppComponent } from './app.component';
import {TestComponent} from './Test/test.component';
import { Test1Component } from './Test/test1.component';
import { ProductListComponent } from './products/product-list.component';
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component'
import { ProductService } from './products/product.service';
import { ProductDetailComponent } from './products/product-detail.component';
import { HomeComponent } from './home/home.component';
import {ProductDetailGuard} from './products/product-detail.guard';
import { CustomerComponent } from './customers/customer.component'
@NgModule({
declarations: [
AppComponent,
TestComponent,
Test1Component,
ProductListComponent,
ProductFilterPipe,
StarComponent,
ProductDetailComponent,
HomeComponent,
CustomerComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{path:'products',component:ProductListComponent},
{path:'product/:id',component:ProductDetailComponent,canActivate:[ProductDetailGuard]},
{path:'welcome',component:HomeComponent},
{path:'customerForm',component:CustomerComponent},
{path:'',redirectTo:'welcome',pathMatch:'full'},
{path:'**',redirectTo:'welcome',pathMatch:'full'},
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit, Input, OnChanges,Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-star',
templateUrl: './star.component.html',
styleUrls: ['./star.component.css']
})
export class StarComponent implements OnInit,OnChanges {
@Input() rating:number
starWidth:number
@Output() notify:EventEmitter<string> = new EventEmitter<string>()
constructor() { }
ngOnInit() {
}
ngOnChanges(){
this.starWidth =this.rating * 86/5
console.log(this.starWidth)
}
onClick():void{
//this.notify.emit('the rating :' + this.rating + ' was clicked')
this.notify.emit(`the rating ${this.rating} was clicked`)
}
}
<file_sep>
import {Component} from '@angular/core'
@Component({
selector:'app-test',
template:`<h1>Helo From Test Component</h1>
<p>Learning Component Without CLI</p>
`,
styles:[
`
p{
color:green;
}`
]
})
export class TestComponent{}<file_sep>import { Component, OnInit } from '@angular/core';
import {IProduct} from '../products/product'
import { ProductService } from './product.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
pageTitle:string='Product List'
showImage:boolean=false
listFilter:string
products :IProduct[]
errorMessage:string
constructor(private _productService:ProductService) {}
toggleImage():void{
this.showImage = !this.showImage
}
ngOnInit() {
// this.products= this._productService.getProducts();
// console.log('init method called')
//subscribing to the observable
this._productService.getProducts()
.subscribe((products)=>this.products=products,
error=>this.errorMessage=<any>error)
}
onRatingClicked(message:string):void{
this.pageTitle = 'Product List:' + message
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { IProduct } from './product';
import {ActivatedRoute,Router} from '@angular/router'
import {ProductService} from './product.service'
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
pageTitle:string='Product Detail'
product:IProduct
errorMessage:string
constructor(private _activatedRoute:ActivatedRoute,
private _productService:ProductService,
private _router:Router) { }
ngOnInit() {
const param = this._activatedRoute.snapshot.paramMap.get('id')
if(param){
const id = +param
this._productService.getProduct(id)
.subscribe(p=>this.product=p,
error=>this.errorMessage=<any>error
)
}
}
onBack():void{
this._router.navigate(['/products'])
}
}
<file_sep>import { Injectable } from '@angular/core';
import {IProduct} from './product'
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {tap,catchError,map} from 'rxjs/operators'
@Injectable({
providedIn: 'root'
})
export class ProductService {
private _productUrl='./assets/api/products.json'
products:IProduct[]
constructor(private _httpClient:HttpClient) { }
//Without observables
// getProducts():IProduct[]{
// return this. products
// }
//Using Observables
getProducts():Observable<IProduct[]>{
//console.log(this._httpClient.get<IProduct[]>(this._productUrl).toPromise())
return this._httpClient.get<IProduct[]>(this._productUrl)
.pipe(
tap((data)=> console.log('All Data :' + JSON.stringify(data))),
catchError(this.handleError)
)
}
getProduct(id:number):Observable<IProduct>{
return this.getProducts().pipe(
map((products:IProduct[])=>products.find((p)=>p.productId===id)),
catchError(this.handleError)
)
}
private handleError(err){
let errorMsg=''
if(err.error instanceof Error){
errorMsg = `An error occured : ${err.error.message}`
}else{
errorMsg=`Server returned code :${err.status}
error message is : ${err.message}`
}
console.log(errorMsg)
return throwError(errorMsg)
}
}
<file_sep>export class Customer {
constructor(public firstName='',
public lastName='',
public email='',
public zip?:string
){}
}
|
e039e78b95d036e448952c7dffb27d01104b1d88
|
[
"TypeScript"
] | 7
|
TypeScript
|
github-2018-zensar/Angular7Online
|
418a8fd7ef466dc7fc2f8efa0750d0cd2c5b98d2
|
508e1ec94e1e0a0ceac24f921611790a7f39a416
|
refs/heads/master
|
<repo_name>RaiaN/rokoko_houdini_plugin<file_sep>/OBJ_RokokoFrontend/RokokoSocketReader.cpp
// Copyright <NAME> 2020
#include "RokokoSocketReader.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <system_error>
#include <string>
#include <iostream>
#include <UT/UT_NetSocket.h>
#include <UT/UT_WorkBuffer.h>
#include <UT/UT_NetSocket.h>
#pragma comment( lib, "ws2_32.lib")
class WSASession
{
public:
WSASession()
{
bIsValid = (WSAStartup(MAKEWORD(2, 2), &data) == 0);
}
~WSASession()
{
WSACleanup();
}
bool IsValid() const
{
return bIsValid;
}
private:
WSAData data;
bool bIsValid;
};
class UDPSocket
{
public:
UDPSocket(unsigned short port)
{
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bIsValid = (sock != INVALID_SOCKET);
if (!bIsValid)
{
return;
}
Bind(port);
}
~UDPSocket()
{
closesocket(sock);
}
void Bind(unsigned short port)
{
sockaddr_in add;
add.sin_family = AF_INET;
add.sin_addr.s_addr = htonl(INADDR_ANY);
add.sin_port = htons(port);
const int ret = bind(sock, reinterpret_cast<SOCKADDR *>(&add), sizeof(add));
bIsValid = (ret >= 0);
}
void RecvFrom(char* buffer, int len, int flags = 0)
{
fd_set read_s;
timeval time_out;
FD_ZERO(&read_s);
FD_SET(sock, &read_s);
time_out.tv_sec = 0;
time_out.tv_usec = 0;
const int socketsNum = select(0, &read_s, NULL, NULL, &time_out);
if (socketsNum != SOCKET_ERROR && FD_ISSET(sock, &read_s))
{
sockaddr_in from;
int size = sizeof(from);
const int bytesReceived = recvfrom(sock, buffer, len, flags, reinterpret_cast<SOCKADDR*>(&from), &size);
if (bytesReceived >= 0)
{
buffer[bytesReceived] = 0;
}
}
else
{
buffer[0] = 0;
}
}
bool IsValid() const
{
return bIsValid;
}
private:
SOCKET sock;
bool bIsValid;
};
RokokoSocketReader::RokokoSocketReader(const std::string& inIp, int inPort) : ip(inIp), port(inPort)
{
createClientSocket();
}
RokokoSocketReader::~RokokoSocketReader()
{
destroyClientSocket();
}
bool RokokoSocketReader::read(std::string& outBuffer)
{
if (!udpSocket)
{
return false;
}
char buffer[1024 * 100];
udpSocket->RecvFrom(buffer, sizeof(buffer));
outBuffer = buffer;
return true;
}
void RokokoSocketReader::setIpAndPort(const std::string& inIp, int inPort)
{
ip = inIp;
port = inPort;
reset();
}
void RokokoSocketReader::reset()
{
destroyClientSocket();
createClientSocket();
}
void RokokoSocketReader::createClientSocket()
{
udpSocket = new UDPSocket(port);
session = new WSASession();
}
void RokokoSocketReader::destroyClientSocket()
{
if (udpSocket)
{
delete udpSocket;
udpSocket = nullptr;
}
if (session)
{
delete session;
session = nullptr;
}
}
<file_sep>/OBJ_RokokoFrontend/OBJ_RokokoFrontend.h
// Copyright <NAME> 2020
#ifndef _OBJ_ROKOKO_FRONTEND_H_
#define _OBJ_ROKOKO_FRONTEND_H_
#include <OBJ/OBJ_Geometry.h>
#include <OP/OP_Error.h>
#include <OP/OP_Context.h>
#include <OP/OP_OperatorPair.h>
class OP_Network;
class OP_Operator;
class OP_TemplatePair;
class PRM_Template;
class RokokoReceiver;
class OBJ_RokokoFrontend : public OBJ_Geometry
{
public:
OBJ_RokokoFrontend(OP_Network* net, const char* name, OP_Operator* op);
virtual ~OBJ_RokokoFrontend();
static OP_Node* myConstructor(
OP_Network* net,
const char* name,
OP_Operator* entry
);
static OP_TemplatePair* buildTemplatePair(OP_TemplatePair* prevstuff);
static int UI_OnUpdateRateChanged(void* data, int index, fpreal t, const PRM_Template* templateParam);
static int UI_OnIpOrPortChanged(void* data, int index, fpreal t, const PRM_Template* templateParam);
static int UI_OnReset(void* data, int index, fpreal t, const PRM_Template* templateParam);
void OnUpdateRateChanged();
void OnIpOrPortChanged();
void OnReset();
public:
int GET_PORT();
int GET_UPDATE_RATE();
std::string GET_IP();
protected:
OP_ERROR cookMyObj(OP_Context& context) override;
private:
RokokoReceiver* receiver;
};
#endif
<file_sep>/README.md
# rokoko_houdini_plugin
This plugin allows to use Rokoko Studio Live data to manipulate Houdini objects
<file_sep>/OBJ_RokokoFrontend/python_socket.py
#!/usr/bin/env python3
import socket
import json
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 11111 # Port to listen on (non-privileged ports are > 1023)
rokoko_frame_json = {}
with open("rokoko_input.txt", "r") as inp:
rokoko_frame_json = json.loads(inp.read())
def update_frame_data():
rokoko_frame_json['props'][0]['position']['x'] = rokoko_frame_json['props'][0]['position']['x'] + 0.0001
rokoko_frame_json['props'][0]['position']['y'] = rokoko_frame_json['props'][0]['position']['y'] + 0.0001
rokoko_frame_json['props'][0]['position']['z'] = rokoko_frame_json['props'][0]['position']['z'] + 0.0001
rokoko_frame_json['props'][0]['rotation']['x'] = rokoko_frame_json['props'][0]['rotation']['x'] + 0.0001
rokoko_frame_json['props'][0]['rotation']['y'] = rokoko_frame_json['props'][0]['rotation']['y'] + 0.0001
rokoko_frame_json['props'][0]['rotation']['z'] = rokoko_frame_json['props'][0]['rotation']['z'] + 0.0001
rokoko_frame_json['props'][0]['rotation']['w'] = rokoko_frame_json['props'][0]['rotation']['w'] + 0.0001
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print('BIND')
s.bind((HOST, PORT))
print('LISTEN')
s.listen()
print('ACCEPT')
conn, addr = s.accept()
print((conn, addr))
print('SEND DATA')
with conn:
print('Connected by', addr)
while True:
print('sendall')
update_frame_data()
serialized_data = json.dumps(rokoko_frame_json)
send_res = conn.sendall(serialized_data.encode())
if send_res is None:
print('succ')
<file_sep>/OBJ_RokokoFrontend/BoneInfo.h
// Copyright <NAME> 2020
#ifndef _BONE_INFO_H
#define _BONE_INFO_H
#include <string>
#include "TransformInfo.h"
struct BoneInfo
{
public:
std::string name;
TransformInfo transform;
};
#endif<file_sep>/OBJ_RokokoFrontend/RokokoReceiver.cpp
// Copyright <NAME> 2020
#include "RokokoReceiver.h"
#include <UT/UT_Array.h>
#include <UT/UT_XformOrder.h>
#include <UT/UT_Vector3.h>
#include <OP/OP_Director.h>
#include <OP/OP_Node.h>
#include <CH/CH_Manager.h>
#include "RokokoSocketReader.h"
#include "RokokoDataParser.h"
#include "PropTrackerInfo.h"
#include "ActorInfo.h"
RokokoReceiver::RokokoReceiver(const std::string& inIp, int inPort, int inRate) : rate(inRate)
{
socketReader = new RokokoSocketReader(inIp, inPort);
dataParser = new RokokoDataParser();
}
RokokoReceiver::~RokokoReceiver()
{
delete socketReader;
delete dataParser;
}
const char* RokokoReceiver::getClassName() const
{
return "RokokoReceiver";
}
int RokokoReceiver::getPollTime()
{
return rate;
}
int RokokoReceiver::processEvents()
{
if (!socketReader || !dataParser)
{
return 1;
}
std::string data;
if (!socketReader->read(data))
{
return 1;
}
dataParser->parse(data);
const UT_Array<PropTrackerInfo>& propTrackers = dataParser->getPropTrackers();
for (int objInd = 0; objInd < propTrackers.size(); ++objInd)
{
const PropTrackerInfo& objInfo = propTrackers[objInd];
const std::string objName("/obj/" + objInfo.name);
OP_Node* Node = OPgetDirector()->findNode(objName.c_str());
if (Node)
{
const fpreal evalTime = CHgetEvalTime();
// TODO: Rokoko coordinate system?
Node->setFloat("t", 0, evalTime, objInfo.transform.position.x());
Node->setFloat("t", 1, evalTime, objInfo.transform.position.y());
Node->setFloat("t", 2, evalTime, objInfo.transform.position.z());
UT_XformOrder order;
UT_Vector3 EulerRotations = objInfo.transform.rotation.computeRotations(order);
Node->setFloat("r", 0, evalTime, EulerRotations[0]);
Node->setFloat("r", 1, evalTime, EulerRotations[1]);
Node->setFloat("r", 2, evalTime, EulerRotations[2]);
}
}
const UT_Array<ActorInfo>& actors = dataParser->getActors();
for (int actorInd = 0; actorInd < actors.size(); ++actorInd)
{
const ActorInfo& actorInfo = actors[actorInd];
for (int boneInd = 0; boneInd < actorInfo.bones.size(); ++boneInd)
{
const BoneInfo& boneInfo = actorInfo.bones[boneInd];
const std::string boneName("/obj/Root/" + boneInfo.name + "_bone");
OP_Node* Node = OPgetDirector()->findNode(boneName.c_str());
if (Node)
{
const fpreal evalTime = CHgetEvalTime();
// TODO: Rokoko coordinate system?
Node->setFloat("t", 0, evalTime, boneInfo.transform.position.x() * 10);
Node->setFloat("t", 1, evalTime, boneInfo.transform.position.y() * 10);
Node->setFloat("t", 2, evalTime, boneInfo.transform.position.z() * 10);
UT_XformOrder order;
UT_Vector3 EulerRotations = boneInfo.transform.rotation.computeRotations(order);
Node->setFloat("r", 0, evalTime, EulerRotations[0]);
Node->setFloat("r", 1, evalTime, EulerRotations[1]);
Node->setFloat("r", 2, evalTime, EulerRotations[2]);
}
}
}
return 1;
}
void RokokoReceiver::start()
{
if (!bInstalled)
{
installGenerator();
bInstalled = true;
}
}
void RokokoReceiver::stop()
{
uninstallGenerator();
bInstalled = false;
}
void RokokoReceiver::setUpdateRate(int inRate)
{
rate = inRate;
}
void RokokoReceiver::setIpAndPort(const std::string& inIp, int inPort)
{
socketReader->setIpAndPort(inIp, inPort);
}
void RokokoReceiver::reset()
{
socketReader->reset();
}
<file_sep>/OBJ_RokokoFrontend/ActorInfo.h
// Copyright <NAME> 2020
#ifndef _ACTOR_INFO_H
#define _ACTOR_INFO_H
#include <string>
#include <UT/UT_StringHolder.h>
#include <UT/UT_Array.h>
#include "TransformInfo.h"
#include "BoneInfo.h"
struct ActorInfo
{
public:
std::string name;
// std::string timestamp;
UT_Array<BoneInfo> bones;
};
#endif<file_sep>/OBJ_RokokoFrontend/OBJ_RokokoFrontend.cpp
// Copyright <NAME> 2020
#include "OBJ_RokokoFrontend.h"
#include <SYS/SYS_Math.h>
#include <UT/UT_DSOVersion.h>
#include <PRM/PRM_Include.h>
#include <OP/OP_Operator.h>
#include <OP/OP_OperatorPair.h>
#include <OP/OP_OperatorTable.h>
#include <CH/CH_Manager.h>
#include "RokokoReceiver.h"
static PRM_Name Port_Param("port", "Port");
static PRM_Name IP_Param("ip", "IP");
static PRM_Name UpdateRate_Param("update_rate", "Update rate (FPS)");
static PRM_Name ResetBtnParam("reset_receiver", "Reset");
static PRM_Default PortDefault(11111);
static PRM_Default IPDefault(0, "127.0.0.1");
static PRM_Default UpdateRateDefault(60);
static PRM_Range PortRange(PRM_RANGE_UI, 1, PRM_RANGE_UI, 65535);
static PRM_Range UpdateRateRange(PRM_RANGE_UI, 1, PRM_RANGE_UI, 240);
static PRM_Template templatelist[] =
{
PRM_Template(PRM_INT_E, 1, &Port_Param, &PortDefault, 0, &PortRange, &OBJ_RokokoFrontend::UI_OnIpOrPortChanged),
PRM_Template(PRM_STRING, 1, &IP_Param, &IPDefault, 0, 0, &OBJ_RokokoFrontend::UI_OnIpOrPortChanged),
PRM_Template(PRM_INT_E, 1, &UpdateRate_Param, &UpdateRateDefault, 0, &UpdateRateRange, &OBJ_RokokoFrontend::UI_OnUpdateRateChanged),
PRM_Template(PRM_CALLBACK, 1, &ResetBtnParam, 0, 0, 0, &OBJ_RokokoFrontend::UI_OnReset),
// blank terminating Template.
PRM_Template()
};
// Constructor for new object class
OBJ_RokokoFrontend::OBJ_RokokoFrontend(OP_Network* net, const char* name, OP_Operator* op) : OBJ_Geometry(net, name, op)
{
const std::string ip = GET_IP();
const int port = GET_PORT();
const int updateRateMs = 1000 / GET_UPDATE_RATE();
receiver = new RokokoReceiver(ip, port, updateRateMs);
receiver->start();
}
// virtual destructor for new object class
OBJ_RokokoFrontend::~OBJ_RokokoFrontend()
{
if (receiver)
{
receiver->stop();
delete receiver;
receiver = nullptr;
}
}
static void copyParmWithInvisible(PRM_Template& src, PRM_Template& dest)
{
PRM_Name* new_name;
new_name = new PRM_Name(src.getToken(), src.getLabel(), src.getExpressionFlag());
new_name->harden();
dest.initialize(
(PRM_Type)(src.getType() | PRM_TYPE_INVISIBLE),
src.getTypeExtended(),
src.exportLevel(),
src.getVectorSize(),
new_name,
src.getFactoryDefaults(),
src.getChoiceListPtr(),
src.getRangePtr(),
src.getCallback(),
src.getSparePtr(),
src.getParmGroup(),
(const char *)src.getHelpText(),
src.getConditionalBasePtr()
);
}
// this function returns the OP_TemplatePair that combines the parameters
// of this object with those of its ancestors in the (object class hierarchy)
OP_TemplatePair* OBJ_RokokoFrontend::buildTemplatePair(OP_TemplatePair* prevstuff)
{
OP_TemplatePair* rokokoTemplates;
OP_TemplatePair* geo;
// The parm templates here are not created as a static list because
// if that static list was built before the OBJbaseTemplate static list
// (which it references) then that list would be corrupt. Thus we have
// to force our static list to be created after OBJbaseTemplate.
static PRM_Template* theTemplate = 0;
if (!theTemplate)
{
PRM_Template* obj_template = OBJ_Geometry::getTemplateList(OBJ_PARMS_PLAIN);
int size = PRM_Template::countTemplates(obj_template);
theTemplate = new PRM_Template[size + 1]; // add +1 for sentinel
for (int i = 0; i < size; i++)
{
theTemplate[i] = obj_template[i];
copyParmWithInvisible(obj_template[i], theTemplate[i]);
}
}
// Here, we have to "inherit" template pairs from geometry and beyond. To
// do this, we first need to instantiate our template list, then add the
// base class templates.
rokokoTemplates = new OP_TemplatePair(templatelist, prevstuff);
geo = new OP_TemplatePair(theTemplate, rokokoTemplates);
return geo;
}
int OBJ_RokokoFrontend::UI_OnUpdateRateChanged(void* data, int index, fpreal t, const PRM_Template* templateParam)
{
OBJ_RokokoFrontend* rokokoFrontend = static_cast<OBJ_RokokoFrontend*>(data);
rokokoFrontend->OnUpdateRateChanged();
return 1;
}
int OBJ_RokokoFrontend::UI_OnIpOrPortChanged(void* data, int index, fpreal t, const PRM_Template* templateParam)
{
OBJ_RokokoFrontend* rokokoFrontend = static_cast<OBJ_RokokoFrontend*>(data);
rokokoFrontend->OnIpOrPortChanged();
return 1;
}
int OBJ_RokokoFrontend::UI_OnReset(void* data, int index, fpreal t, const PRM_Template* templateParam)
{
OBJ_RokokoFrontend* rokokoFrontend = static_cast<OBJ_RokokoFrontend*>(data);
rokokoFrontend->OnReset();
return 1;
}
void OBJ_RokokoFrontend::OnUpdateRateChanged()
{
const int updateRateMs = 1000 / GET_UPDATE_RATE();
receiver->setUpdateRate(updateRateMs);
}
void OBJ_RokokoFrontend::OnIpOrPortChanged()
{
const std::string newIp = GET_IP();
const int newPort = GET_PORT();
receiver->setIpAndPort(newIp, newPort);
}
void OBJ_RokokoFrontend::OnReset()
{
receiver->reset();
}
int OBJ_RokokoFrontend::GET_PORT()
{
return evalInt("port", 0, CHgetEvalTime());
}
int OBJ_RokokoFrontend::GET_UPDATE_RATE()
{
return evalInt("update_rate", 0, CHgetEvalTime());
}
std::string OBJ_RokokoFrontend::GET_IP()
{
UT_String value;
evalString(value, "ip", 0, CHgetEvalTime());
return value.c_str();
}
OP_Node* OBJ_RokokoFrontend::myConstructor(OP_Network* net, const char* name, OP_Operator* op)
{
return new OBJ_RokokoFrontend(net, name, op);
}
OP_ERROR OBJ_RokokoFrontend::cookMyObj(OP_Context& context)
{
OP_ERROR errorstatus = OP_ERROR::UT_ERROR_NONE;
/*if (receiver)
{
receiver->start();
}*/
return errorstatus;
}
// this function installs the new object in houdini's object table.
void newObjectOperator(OP_OperatorTable* table)
{
table->addOperator(
new OP_Operator(
"obj_rokoko_frontend",
"Rokoko Frontend",
OBJ_RokokoFrontend::myConstructor,
OBJ_RokokoFrontend::buildTemplatePair(0),
OBJ_RokokoFrontend::theChildTableName,
0,
1,
nullptr
)
);
}<file_sep>/OBJ_RokokoFrontend/RokokoDataParser.h
// Copyright <NAME> 2020
#ifndef _ROKOKO_DATA_PARSER_H_
#define _ROKOKO_DATA_PARSER_H_
#include <string>
#include <UT/UT_Vector3.h>
#include <UT/UT_Quaternion.h>
#include <UT/UT_Array.h>
#include "PropTrackerInfo.h"
#include "ActorInfo.h"
class UT_JSONValue;
class UT_JSONValueMap;
class RokokoDataParser
{
public:
RokokoDataParser();
virtual ~RokokoDataParser();
public:
void parse(const std::string& data);
const UT_Array<PropTrackerInfo>& getPropTrackers();
const UT_Array<ActorInfo>& getActors();
protected:
void parseData(const UT_JSONValue* jsonValue);
PropTrackerInfo parsePropTracker(const UT_JSONValueMap* propTrackerAsMap) const;
void parsePropsOrTrackers(const UT_JSONValue* jsonValue);
ActorInfo parseActor(const UT_JSONValueMap* actorAsMap) const;
void parseActors(const UT_JSONValue* jsonValue);
UT_Vector3 parsePosition(const UT_JSONValue* jsonValue) const;
UT_Quaternion parseRotation(const UT_JSONValue* jsonValue) const;
private:
UT_Array<PropTrackerInfo> propTrackers;
UT_Array<ActorInfo> actors;
};
#endif<file_sep>/OBJ_RokokoFrontend/RokokoDataParser.cpp
// Copyright <NAME> 2020
#include "RokokoDataParser.h"
#include <UT/UT_StringHolder.h>
#include <UT/UT_JSONParser.h>
#include <UT/UT_JSONValue.h>
#include <UT/UT_JSONValueMap.h>
#include <UT/UT_JSONValueArray.h>
#include <UT/UT_Set.h>
RokokoDataParser::RokokoDataParser()
{
}
RokokoDataParser::~RokokoDataParser()
{
}
void RokokoDataParser::parse(const std::string& data)
{
propTrackers.clear();
UT_AutoJSONParser parser(data.c_str(), data.length());
UT_JSONValue value;
if (value.parseValue(parser))
{
parseData(&value);
}
}
const UT_Array<PropTrackerInfo>& RokokoDataParser::getPropTrackers()
{
return propTrackers;
}
const UT_Array<ActorInfo>& RokokoDataParser::getActors()
{
return actors;
}
void RokokoDataParser::parseData(const UT_JSONValue* jsonValue)
{
if (!jsonValue)
{
return;
}
static const UT_StringRef PROPS_KEY("props");
static const UT_StringRef TRACKERS_KEY("trackers");
static const UT_StringRef FACES_KEY("faces");
static const UT_StringRef ACTORS_KEY("actors");
UT_JSONValueMap* jsonMap = jsonValue->getMap();
if (!jsonMap)
{
// TODO: SET ERROR
return;
}
UT_JSONValue* props = jsonMap->get(PROPS_KEY);
if (props)
{
parsePropsOrTrackers(props);
}
UT_JSONValue* trackers = jsonMap->get(TRACKERS_KEY);
if (trackers)
{
parsePropsOrTrackers(trackers);
}
UT_JSONValue* actors = jsonMap->get(ACTORS_KEY);
if (actors)
{
parseActors(actors);
}
// TODO: faces
}
PropTrackerInfo RokokoDataParser::parsePropTracker(const UT_JSONValueMap* propTrackerAsMap) const
{
static const UT_StringRef NAME_KEY("name");
static const UT_StringRef POSITION_KEY("position");
static const UT_StringRef ROTATION_KEY("rotation");
PropTrackerInfo propTrackerInfo;
const UT_JSONValue* nameValue = propTrackerAsMap->get(NAME_KEY);
if (nameValue)
{
propTrackerInfo.name = nameValue->getS();
}
propTrackerInfo.transform.position = parsePosition(propTrackerAsMap->get(POSITION_KEY));
propTrackerInfo.transform.rotation = parseRotation(propTrackerAsMap->get(ROTATION_KEY));
return propTrackerInfo;
}
void RokokoDataParser::parsePropsOrTrackers(const UT_JSONValue* jsonValue)
{
if (!jsonValue)
{
return;
}
UT_JSONValueArray* objects = jsonValue->getArray();
if (!objects)
{
return;
}
for (int objInd = 0; objInd < objects->size(); ++objInd)
{
UT_JSONValue* obj = objects->get(objInd);
if (obj)
{
UT_JSONValueMap* objAsMap = obj->getMap();
if (objAsMap)
{
propTrackers.append(parsePropTracker(objAsMap));
}
}
}
}
ActorInfo RokokoDataParser::parseActor(const UT_JSONValueMap* actorAsMap) const
{
static const UT_StringRef NAME_KEY("name");
static const UT_StringRef TIMESTAMP_KEY("timestamp");
static const UT_StringRef POSITION_KEY("position");
static const UT_StringRef ROTATION_KEY("rotation");
static const UT_Set<UT_StringRef> BONES_KEYS =
{
UT_StringRef("hip"), UT_StringRef("spine"), UT_StringRef("neck"), UT_StringRef("head"),
UT_StringRef("leftShoulder"), UT_StringRef("leftUpperArm"), UT_StringRef("leftLowerArm"), UT_StringRef("leftHand"),
UT_StringRef("rightShoulder"), UT_StringRef("rightUpperArm"), UT_StringRef("rightLowerArm"), UT_StringRef("rightHand"),
UT_StringRef("leftUpLeg"), UT_StringRef("leftLeg"), UT_StringRef("leftToe"), UT_StringRef("leftToeEnd"),
UT_StringRef("rightUpLeg"), UT_StringRef("rightLeg"), UT_StringRef("rightToe"), UT_StringRef("rightToeEnd"),
UT_StringRef("leftThumbProximal"), UT_StringRef("leftThumbMedial"), UT_StringRef("leftThumbDistal"), UT_StringRef("leftThumbTip"),
UT_StringRef("leftIndexProximal"), UT_StringRef("leftIndexMedial"), UT_StringRef("leftIndexDistal"), UT_StringRef("leftIndexTip"),
UT_StringRef("leftMiddleProximal"), UT_StringRef("leftMiddleMedial"), UT_StringRef("leftMiddleDistal"), UT_StringRef("leftMiddleTip"),
UT_StringRef("leftRingProximal"), UT_StringRef("leftRingMedial"), UT_StringRef("leftRingDistal"), UT_StringRef("leftRingTip"),
UT_StringRef("leftLittleProximal"), UT_StringRef("leftLittleMedial"), UT_StringRef("leftLittleDistal"), UT_StringRef("leftLittleTip"),
UT_StringRef("rightThumbProximal"), UT_StringRef("rightThumbMedial"), UT_StringRef("rightThumbDistal"), UT_StringRef("rightThumbTip"),
UT_StringRef("rightIndexProximal"), UT_StringRef("rightIndexMedial"), UT_StringRef("rightIndexDistal"), UT_StringRef("rightIndexTip"),
UT_StringRef("rightMiddleProximal"), UT_StringRef("rightMiddleMedial"), UT_StringRef("rightMiddleDistal"), UT_StringRef("rightMiddleTip"),
UT_StringRef("rightRingProximal"), UT_StringRef("rightRingMedial"), UT_StringRef("rightRingDistal"), UT_StringRef("rightRingTip"),
UT_StringRef("rightLittleProximal"), UT_StringRef("rightLittleMedial"), UT_StringRef("rightLittleDistal"), UT_StringRef("rightLittleTip"),
};
ActorInfo actorInfo;
const UT_JSONValue* nameValue = actorAsMap->get(NAME_KEY);
if (nameValue)
{
actorInfo.name = nameValue->getS();
}
for (UT_StringRef boneName : BONES_KEYS)
{
const UT_JSONValue* boneValue = actorAsMap->get(boneName);
if (boneValue)
{
UT_JSONValueMap* boneAsMap = boneValue->getMap();
if (boneAsMap)
{
BoneInfo bone;
bone.name = boneName.c_str();
bone.transform.position = parsePosition(boneAsMap->get(POSITION_KEY));
bone.transform.rotation = parseRotation(boneAsMap->get(ROTATION_KEY));
actorInfo.bones.append(bone);
}
}
}
return actorInfo;
}
void RokokoDataParser::parseActors(const UT_JSONValue* jsonValue)
{
if (!jsonValue)
{
return;
}
UT_JSONValueArray* actorsArray = jsonValue->getArray();
for (int actorInd = 0; actorInd < actorsArray->size(); ++actorInd)
{
UT_JSONValue* actor = actorsArray->get(actorInd);
if (actor)
{
UT_JSONValueMap* actorAsMap = actor->getMap();
if (actorAsMap)
{
actors.append(parseActor(actorAsMap));
}
}
}
}
UT_Vector3 RokokoDataParser::parsePosition(const UT_JSONValue* jsonValue) const
{
UT_Vector3 position(0.0, 0.0, 0.0);
UT_JSONValueMap* positionValueMap = jsonValue->getMap();
if (positionValueMap)
{
const UT_JSONValue* xValue = positionValueMap->get("x");
const UT_JSONValue* yValue = positionValueMap->get("y");
const UT_JSONValue* zValue = positionValueMap->get("z");
if (xValue)
{
position.x() = xValue->getF();
}
if (yValue)
{
position.y() = yValue->getF();
}
if (zValue)
{
position.z() = zValue->getF();
}
}
return position;
}
UT_Quaternion RokokoDataParser::parseRotation(const UT_JSONValue* jsonValue) const
{
UT_Quaternion rotation;
UT_JSONValueMap* rotationValueMap = jsonValue->getMap();
if (rotationValueMap)
{
const UT_JSONValue* xValue = rotationValueMap->get("x");
const UT_JSONValue* yValue = rotationValueMap->get("y");
const UT_JSONValue* zValue = rotationValueMap->get("z");
const UT_JSONValue* wValue = rotationValueMap->get("w");
if (xValue)
{
rotation.x() = xValue->getF();
}
if (yValue)
{
rotation.y() = yValue->getF();
}
if (zValue)
{
rotation.z() = zValue->getF();
}
if (wValue)
{
rotation.w() = wValue->getF();
}
}
return rotation;
}
<file_sep>/OBJ_RokokoFrontend/PropTrackerInfo.h
// Copyright <NAME> 2020
#ifndef _PROP_TRACKER_INFO_H
#define _PROP_TRACKER_INFO_H
#include <string>
#include <UT/UT_Vector3.h>
#include <UT/UT_Quaternion.h>
#include "TransformInfo.h"
struct PropTrackerInfo
{
public:
std::string name;
TransformInfo transform;
};
#endif<file_sep>/OBJ_RokokoFrontend/RokokoReceiver.h
// Copyright <NAME> 2020
#ifndef _ROKOKO_RECEIVER_H_
#define _ROKOKO_RECEIVER_H_
#include <string>
#include <FS/FS_EventGenerator.h>
class RokokoSocketReader;
class RokokoDataParser;
class RokokoReceiver : public FS_EventGenerator
{
public:
RokokoReceiver(const std::string& inIp, int inPort, int inRate);
virtual ~RokokoReceiver();
virtual const char* getClassName() const override;
virtual int getPollTime() override;
virtual int processEvents() override;
public:
void start();
void stop();
void setUpdateRate(int inRate);
void setIpAndPort(const std::string& inIp, int inPort);
void reset();
private:
bool bInstalled = false;
RokokoSocketReader* socketReader;
RokokoDataParser* dataParser;
int rate;
};
#endif<file_sep>/OBJ_RokokoFrontend/CMakeLists.txt
cmake_minimum_required( VERSION 3.6 )
project( HDK_Project )
# CMAKE_PREFIX_PATH must contain the path to the toolkit/cmake subdirectory of
# the Houdini installation. See the "Compiling with CMake" section of the HDK
# documentation for more details, which describes several options for
# specifying this path.
# list( APPEND CMAKE_PREFIX_PATH "$ENV{HFS}/toolkit/cmake" )
# Please set HDK_PATH environment variable
list( APPEND CMAKE_PREFIX_PATH "$ENV{HDK_PATH}/toolkit/cmake" )
# Locate Houdini's libraries and header files.
# Registers an imported library target named 'Houdini'.
find_package( Houdini REQUIRED )
set( library_name OBJ_RokokoFrontend )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
# No optimization.
# Turn on debugging information instead.
# Add a library and its source files.
add_library( ${library_name} SHARED
OBJ_RokokoFrontend.cpp
OBJ_RokokoFrontend.h
RokokoDataParser.cpp
RokokoDataParser.h
RokokoSocketReader.cpp
RokokoSocketReader.h
RokokoReceiver.cpp
RokokoReceiver.h
TransformInfo.h
PropTrackerInfo.h
BoneInfo.h
ActorInfo.h
)
# Link against the Houdini libraries, and add required include directories and
# compile definitions.
target_link_libraries( ${library_name} Houdini )
# Include ${CMAKE_CURRENT_BINARY_DIR} for the generated header.
target_include_directories( ${library_name} PRIVATE
${CMAKE_CURRENT_BINARY_DIR}
)
target_include_directories( ${library_name} PRIVATE
"$ENV{HDK_PATH}/toolkit/include"
)
# Sets several common target properties, such as the library's output directory.
houdini_configure_target( ${library_name} )
<file_sep>/OBJ_RokokoFrontend/RokokoSocketReader.h
// Copyright <NAME> 2020
#ifndef _ROKOKO_SOCKET_READER_H_
#define _ROKOKO_SOCKET_READER_H_
#include <string>
class UDPSocket;
class WSASession;
class RokokoSocketReader
{
public:
RokokoSocketReader(const std::string& inIp, int inPort);
virtual ~RokokoSocketReader();
public:
bool read(std::string& outBuffer);
void setIpAndPort(const std::string& inIp, int inPort);
void reset();
private:
void createClientSocket();
void destroyClientSocket();
private:
UDPSocket* udpSocket;
WSASession* session;
std::string ip;
int port;
};
#endif
|
c6a2caafdeb4cf5b064996bae5f51ce8aedac288
|
[
"Markdown",
"Python",
"CMake",
"C++"
] | 14
|
C++
|
RaiaN/rokoko_houdini_plugin
|
617b7213fefe62632f06218a72adc74ac69a085a
|
965ff46c3ffd68a33e98f8fa591fb805b316caa6
|
refs/heads/master
|
<repo_name>sunilshrestha123/backend-ilamfashion<file_sep>/src/utils/crypt.js
// import bcrypt from 'bcrypt';
// export const hashing = async string => {
// console.log('tein', string);
// try {
// return await bcrypt.hash(string, 11);
// } catch (e) {
// console.log('tet');
// console.log(e);
// }
// };
<file_sep>/src/controller/userController.js
const express = require('express');
import * as userService from '../service/userService';
const router = express();
router.get('/', (req, res, next) => {
userService
.getAllUser()
.then(data => {
console.log(data);
res.status(201).send({ data: data });
})
.catch(err => next(err));
});
router.get('/:id', (req, res, next) => {
userService
.getUserById(req.params.id)
.then(data => {
console.log(data);
res.status(201).send({ data: data });
})
.catch(err => next(err));
});
// router.post('/', (req, res, next) => {
// console.log('body', req.body);
// userService
// .getUserUpdate(req.body)
// .then(data => {
// console.log(data);
// res.status(200).send({ data });
// })
// .catch(err => next(err));
// });
//post
router.post('/', (req, res, next) => {
console.log('body', req.body);
userService
.getUserAdd(req.body)
.then(data => {
console.log(data);
res.status(200).send({ data });
})
.catch(err => next(err));
});
export default router;
<file_sep>/src/seeds/primarymenu.js
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('primarymenu').del()
.then(function () {
// Inserts seed entries
return knex('primarymenu').insert([
{id: 1, name:'Home' },
{id: 2, name:'Contact-Us' }
]);
});
};
<file_sep>/src/migrations/20200307080937_primarymenu.js
exports.up = function (knex, Promise) {
return knex.schema.createTable('primarymenu', (table) => {
table.increments('id').primary().unsigned();
table.text('name').notNullable();
table.timestamps(true, true);
});
};
exports.down = function (knex, Promise) {
return knex.dropTable();
};
<file_sep>/src/model/contactus.js
import knex from 'knex';
import knexConfig from '../knexConfig';
const knexfile = knex(knexConfig);
class Contactus {
static async getAllContactus() {
let result = await knexfile('contactus');
return result;
}
static async addContactus(data) {
return await knexfile('contactus').insert(data);
}
static async getContactusById(id) {
let result = await knexfile('contactus').where('id', id);
return result;
}
}
export default Contactus;
<file_sep>/src/controller/mainslideController.js
const express = require('express');
import * as mainslideService from '../service/mainslideService';
const router = express();
router.get('/', (req, res, next) => {
mainslideService
.getAllMainSlide()
.then((mainslide) => {
res.status(201).send({ data: mainslide });
})
.catch((err) => next(err));
});
export default router;
<file_sep>/src/service/mainslideService.js
import MainSlide from '../model/mainslide';
export async function getAllMainSlide() {
return await MainSlide.getAllMainSlide();
}
<file_sep>/src/seeds/contactus.js
exports.seed = function (knex, Promise) {
// Deletes ALL existing entries
return knex('contactus')
.del()
.then(function ()
{ // Inserts seed entries
return knex('contactus').insert([ {
id: 1, f_name: 'sunil', l_name: 'shrestha', email: '<EMAIL>', mobile: '9860689684', address: 'ilam', message: 'hello nepal i wnat something' },
{ id: 2, f_name: 'suraj', m_name: 'bhadur', l_name: 'shrestha', email: '<EMAIL>', mobile: '9818245144', address: 'ilam', message: 'hello nepal i wnat something' },
{ id: 3, f_name: 'kabita', l_name: 'shrestha', email: '<EMAIL>', mobile: '9818245145', address: 'ilam', message: 'hello nepal i wnat something' }
]);
});
};<file_sep>/src/model/user.js
import knex from 'knex';
import knexConfig from '../knexConfig';
const knexfile = knex(knexConfig);
// const GET_DEPARTMENT = "SELECT * FROM department";
// const nameValidator=[
// validate({
// validator:'isLength',
// argument:[]
// })
class User {
static async getAllUser() {
// let result = await knexConfig("department");
var result = await knexfile('users');
// let results = await knexConfig.raw(GET_DEPARTMENT);
return result;
}
static async getUserById(id) {
let result = await knexfile('users').where('id', id);
return result;
}
static async getUserAdd(data) {
return await knexfile('users').insert(data);
}
// static sync getUserDelete(id){
// return await k
// }
}
export default User;
<file_sep>/src/controller/contactusController.js
const express = require('express');
import * as contactusService from '../service/contactusService';
import Contactus from '../model/contactus';
const router = express();
router.get('/', (req, res, next) => {
contactusService
.getAllContactus()
.then((data) => {
console.log(data);
res.status(201).send({ data: data });
})
.catch((err) => next(err));
});
router.post('/', (req, res, next) => {
console.log('body value', req.body);
contactusService
.addContactus(req.body)
.then((data) => {
console.log(data);
res.status(200).send({ data });
})
.catch((err) => next(err));
});
router.get('/:id', (req, res, next) => {
contactusService
.getContactusById(req.params.id)
.then((data) => {
console.log(data);
res.status(200).send({ data });
})
.catch((err) => next(err));
});
router.patch('/:id', (req, res, next) => {
if (req.params.id * 1 > contactus.length) {
return res.status(404);
// console.log('data is pudated');
}
});
export default router;
<file_sep>/src/model/Subcategory.js
import knex from 'knex';
import knexConfig from '../knexConfig';
const knexfile = knex(knexConfig);
class Subcategory {
static async addsubCategory(subcategory) {
return await knexfile('subcategory').insert(subcategory);
}
static async getAllSubcategory() {
return await knexfile('subcategory');
}
}
export default Subcategory;
<file_sep>/src/controller/patnerController.js
const express = require('express');
const router=express();
router.post('/',(req,res,next)=>{
console.log('patner',req.body);
patnerService.addPartner(req.body)
.then(Partner=>{
console.log(partner)
req.status(200).send({partner});
})
})
<file_sep>/src/controller/categoryController.js
const express = require('express');
import * as categoryService from '../service/category';
const router = express();
router.get('/', (req, res, next) => {
categoryService
.getAllCategory()
.then((category) => {
console.log(category);
res.status(201).send({ category: category });
})
.catch((err) => next(err));
});
router.post('/', (req, res, next) => {
console.log('contact us', req.body);
contactusService
.addContactus(res.body)
.then((data) => {
console.log(category);
res.status(200).send({ category });
})
.catch((err) => next(err));
});
router.patch('/:id');
// console.log('body', req.body);
// userService
// .getUserAdd(req.body)
// .then(data => {
// console.log(data);
// res.status(200).send({ data });
// })
// .catch(err => next(err));
// });
export default router;
<file_sep>/src/service/contactusService.js
import Contactus from '../model/contactus';
export async function getAllContactus() {
return await Contactus.getAllContactus();
}
export async function addContactus(data) {
return await Contactus.addContactus(data);
}
export async function getContactusById(id) {
return await Contactus.getContactusById(id);
}
<file_sep>/src/migrations/20200408025553_regsiter.js
exports.up = function (knex) {
return knex.schema.createTable('register', (t) => {
t.increments('id').primary().unsigned();
t.text('f_name').notNullable();
t.text('m_name');
t.text('l_name');
t.text('email').unique().notNullable();
t.text('mobile').unique().notNullable();
t.text('password');
t.timestamps(true, true);
});
};
exports.down = function (knex) {
return knex.schema.dropTable('register');
};
<file_sep>/src/index.js
import './knexConfig';
import cors from 'cors';
import parse from 'body-parser';
import express from 'express';
const morgan = require('morgan');
import router from './route';
import logger from './logger';
import { hashing } from './utils/crypt';
const app = express();
const port = 3002;
app.use(morgan('combined'));
app.use(cors());
app.use(parse.json());
// app.use(app.router);
app.use('/api', router);
// app.get('/test', async (req, res) => {
// console.log('tete');
// console.log(await hashing('teting'));
// res.status(200).send({ data: hashing('sunil') });
// });
app.listen(port, () => logger.info('message'));
<file_sep>/src/seeds/mainslide.js
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('mainslide')
.del()
.then(function () {
// Inserts seed entries
return knex('mainslide').insert([
{
id: 1,
heading: 'Laptop',
des: 'lenovo,dell,hp,mac,accer laptop are availabe here',
url: 'rowValue1',
},
{
id: 2,
heading: 'Printer',
des: 'we are the authorized company for canon printer in nepal',
url: 'rowValue2',
},
{
id: 3,
heading: 'Mobile',
des: 'samsung,oppo,huwai mobile availabe here to us',
url: 'rowValue3',
},
]);
});
};
<file_sep>/src/migrations/20200307082942_category.js
exports.up = function (knex, Promise) {
return knex.schema.createTable('category', (table) => {
table.integer('id').primary();
table.text('ct_name').notNullable().unique();
table.text('ct_des').notNullable();
table.boolean('ct_status').notNullable().default(true);
table.timestamps(true, true);
});
};
exports.down = function (knex, Promise) {
return knex.schema.dropTable('category');
};
<file_sep>/src/service/subcategoryService.js
import Subcategory from '../model/Subcategory';
export async function addsubCategory(subcategory) {
return await Subcategory.addsubCategory(subcategory);
}
export async function getAllSubcategory() {
return await Subcategory.getAllSubcategory();
}
export async function subcategoryById(id) {
return await Subcategory.subcategoryById(id);
}
export async function updateById(id) {
return await Subcategory.updateById(id);
}
export async function deleteById(id) {
return await Subcategory.deleteById(id);
}
|
3bafc8d6517711b0de0cb8bf77f4fe6f93aa2b46
|
[
"JavaScript"
] | 19
|
JavaScript
|
sunilshrestha123/backend-ilamfashion
|
e4364613394dca2d607dad41041fe4387c082fa9
|
9e2cb36ad4d361a358e0cef48a414211dd58c7e7
|
refs/heads/master
|
<repo_name>sabrina0904/Java7<file_sep>/src/soalan68.java
/*Bina satu program ringkas yang memaparkan nama, jantina
*warna kegemaran dan memberi ulasan mengenai warna kegemaran yang dipilih.
* Warna merah=membawa makna kekuaatan, kemarahan dan semangat
*Warna Biru=membawa maksud ketenangan, keikhlasan dan harapan.
* Warna Kuning=melambangkan kegembiraan, penuh semangat dan riang
*Warna Hijau=menggambarkan kehidupan, kestabilan dan ketulenan
*Warna Hitam=dikaitkan dengan kejahatan dan penuh kerahsiaan.
*Warna putih=adalah berani tetapi tidak suka tunjukkan keberanian.
*/
/**
*
* @author user
*/
import java.util.*;
public class soalan68 {
public static void main(String[] args){
String ulasan = null;
Scanner input = new Scanner(System.in);
System.out.print("Masukkan nama anda");
String nama=input.next();
System.out.print("Taipkan warna kegemaran anda\n merah/biru/kuning/hijau/putih: ");
String warna=input.next();
switch(warna){
case "merah" :{
ulasan="membawa makna kekuaatan, kemarahan dan semangat";
break;
}case "biru" :{
ulasan=("membawa maksud ketenangan, keikhlasan dan harapan. ");
break;
}case "kuning" :{
ulasan=("melambangkan kegembiraan, penuh semangat dan riang");
break;
}case"hijau" :{
ulasan=("menggambarkan kehidupan, kestabilan dan ketulenan");
break;
}case "hitam" :{
ulasan=("dikaitkan dengan kejahatan dan penuh kerahsiaan.");
break;
}case "putih" :{
ulasan=("adalah berani tetapi tidak suka tunjukkan keberanian.");
break;
}default :{
System.out.println("Maaf pilihan salah ");
System.out.println("Maaf pilihan salah ");
}
}
System.out.println(nama+",warna anda "+ulasan);
}
}
|
668d4dfc3472fdd092719283e2c4d38690fdab7c
|
[
"Java"
] | 1
|
Java
|
sabrina0904/Java7
|
acfbe1834d1023b42915e1556be4eb3941c89a47
|
3c95a91dc46f466967bd104e4811588084c42ce8
|
refs/heads/master
|
<file_sep>// Weekly schedule
var scheduleDay;
// shows all the values in textboxes when the slider changes
function showValue() {
var hours0 = Math.floor(document.getElementById("sliderTime0").value);
var mins0 = (document.getElementById("sliderTime0").value * 60) % 60;
hours0 = ("0" + hours0).slice(-2);
mins0 = ("0" + mins0).slice(-2);
document.getElementById("textTime0").value = hours0 + ":" + mins0;
// ----------
var hours1 = Math.floor(document.getElementById("sliderTime1").value);
var mins1 = (document.getElementById("sliderTime1").value * 60) % 60;
hours1 = ("0" + hours1).slice(-2);
mins1 = ("0" + mins1).slice(-2);
document.getElementById("textTime1").value = hours1 + ":" + mins1;
// ----------
var hours2 = Math.floor(document.getElementById("sliderTime2").value);
var mins2 = (document.getElementById("sliderTime2").value * 60) % 60;
hours2 = ("0" + hours2).slice(-2);
mins2 = ("0" + mins2).slice(-2);
document.getElementById("textTime2").value = hours2 + ":" + mins2;
// ----------
var hours3 = Math.floor(document.getElementById("sliderTime3").value);
var mins3 = (document.getElementById("sliderTime3").value * 60) % 60;
hours3 = ("0" + hours3).slice(-2);
mins3 = ("0" + mins3).slice(-2);
document.getElementById("textTime3").value = hours3 + ":" + mins3;
// ----------
var hours4 = Math.floor(document.getElementById("sliderTime4").value);
var mins4 = (document.getElementById("sliderTime4").value * 60) % 60;
hours4 = ("0" + hours4).slice(-2);
mins4 = ("0" + mins4).slice(-2);
document.getElementById("textTime4").value = hours4 + ":" + mins4;
// ----------
var hours5 = Math.floor(document.getElementById("sliderTime5").value);
var mins5 = (document.getElementById("sliderTime5").value * 60) % 60;
hours5 = ("0" + hours5).slice(-2);
mins5 = ("0" + mins5).slice(-2);
document.getElementById("textTime5").value = hours5 + ":" + mins5;
// ----------
var hours6 = Math.floor(document.getElementById("sliderTime6").value);
var mins6 = (document.getElementById("sliderTime6").value * 60) % 60;
hours6 = ("0" + hours6).slice(-2);
mins6 = ("0" + mins6).slice(-2);
document.getElementById("textTime6").value = hours6 + ":" + mins6;
// ----------
var hours7 = Math.floor(document.getElementById("sliderTime7").value);
var mins7 = (document.getElementById("sliderTime7").value * 60) % 60;
hours7 = ("0" + hours7).slice(-2);
mins7 = ("0" + mins7).slice(-2);
document.getElementById("textTime7").value = hours7 + ":" + mins7;
// ----------
var hours8 = Math.floor(document.getElementById("sliderTime8").value);
var mins8 = (document.getElementById("sliderTime8").value * 60) % 60;
hours8 = ("0" + hours8).slice(-2);
mins8 = ("0" + mins8).slice(-2);
document.getElementById("textTime8").value = hours8 + ":" + mins8;
// ----------
var hours9 = Math.floor(document.getElementById("sliderTime9").value);
var mins9 = (document.getElementById("sliderTime9").value * 60) % 60;
hours9 = ("0" + hours9).slice(-2);
mins9 = ("0" + mins9).slice(-2);
document.getElementById("textTime9").value = hours9 + ":" + mins9;
}
// change sliders accordingly to the textbox values
function setSliders(){
var time0 = (document.getElementById("textTime0").value).replace(":", "").replace(".", "");
if (time0.length == 4) {
var hours = parseInt(time0.substring(0, 2));
var mins = parseInt(time0.substring(2, 4))/60;
document.getElementById("sliderTime0").value = hours + mins;
} else if (time0.length == 3) {
var hours = parseInt(time0.substring(0, 1));
var mins = parseInt(time0.substring(1, 3))/60;
document.getElementById("sliderTime0").value = hours + mins;
} else if (time0.length < 3 && time0.length > 0) {
var hours = time0;
document.getElementById("sliderTime0").value = hours;
}
// ----------
var time1 = (document.getElementById("textTime1").value).replace(":", "").replace(".", "");
if (time1.length == 4) {
var hours = parseInt(time1.substring(0, 2));
var mins = parseInt(time1.substring(2, 4))/60;
document.getElementById("sliderTime1").value = hours + mins;
} else if (time1.length == 3) {
var hours = parseInt(time1.substring(0, 1));
var mins = parseInt(time1.substring(1, 3))/60;
document.getElementById("sliderTime1").value = hours + mins;
} else if (time1.length < 3 && time1.length > 0) {
var hours = time1;
document.getElementById("sliderTime1").value = hours;
}
// ----------
var time2 = (document.getElementById("textTime2").value).replace(":", "").replace(".", "");
if (time2.length == 4) {
var hours = parseInt(time2.substring(0, 2));
var mins = parseInt(time2.substring(2, 4))/60;
document.getElementById("sliderTime2").value = hours + mins;
} else if (time2.length == 3) {
var hours = parseInt(time2.substring(0, 1));
var mins = parseInt(time2.substring(1, 3))/60;
document.getElementById("sliderTime2").value = hours + mins;
} else if (time2.length < 3 && time2.length > 0) {
var hours = time2;
document.getElementById("sliderTime2").value = hours;
}
// ----------
var time3 = (document.getElementById("textTime3").value).replace(":", "").replace(".", "");
if (time3.length == 4) {
var hours = parseInt(time3.substring(0, 2));
var mins = parseInt(time3.substring(2, 4))/60;
document.getElementById("sliderTime3").value = hours + mins;
} else if (time3.length == 3) {
var hours = parseInt(time3.substring(0, 1));
var mins = parseInt(time3.substring(1, 3))/60;
document.getElementById("sliderTime3").value = hours + mins;
} else if (time3.length < 3 && time3.length > 0) {
var hours = time3;
document.getElementById("sliderTime3").value = hours;
}
// ----------
var time4 = (document.getElementById("textTime4").value).replace(":", "").replace(".", "");
if (time4.length == 4) {
var hours = parseInt(time4.substring(0, 2));
var mins = parseInt(time4.substring(2, 4))/60;
document.getElementById("sliderTime4").value = hours + mins;
} else if (time4.length == 3) {
var hours = parseInt(time4.substring(0, 1));
var mins = parseInt(time4.substring(1, 3))/60;
document.getElementById("sliderTime4").value = hours + mins;
} else if (time4.length < 3 && time4.length > 0) {
var hours = time4;
document.getElementById("sliderTime4").value = hours;
}
// ----------
var time5 = (document.getElementById("textTime5").value).replace(":", "").replace(".", "");
if (time5.length == 4) {
var hours = parseInt(time5.substring(0, 2));
var mins = parseInt(time5.substring(2, 4))/60;
document.getElementById("sliderTime5").value = hours + mins;
} else if (time5.length == 3) {
var hours = parseInt(time5.substring(0, 1));
var mins = parseInt(time5.substring(1, 3))/60;
document.getElementById("sliderTime5").value = hours + mins;
} else if (time5.length < 3 && time5.length > 0) {
var hours = time5;
document.getElementById("sliderTime5").value = hours;
}
// ----------
var time6 = (document.getElementById("textTime6").value).replace(":", "").replace(".", "");
if (time6.length == 4) {
var hours = parseInt(time6.substring(0, 2));
var mins = parseInt(time6.substring(2, 4))/60;
document.getElementById("sliderTime6").value = hours + mins;
} else if (time6.length == 3) {
var hours = parseInt(time6.substring(0, 1));
var mins = parseInt(time6.substring(1, 3))/60;
document.getElementById("sliderTime6").value = hours + mins;
} else if (time6.length < 3 && time6.length > 0) {
var hours = time6;
document.getElementById("sliderTime6").value = hours;
}
// ----------
var time7 = (document.getElementById("textTime7").value).replace(":", "").replace(".", "");
if (time7.length == 4) {
var hours = parseInt(time7.substring(0, 2));
var mins = parseInt(time7.substring(2, 4))/60;
document.getElementById("sliderTime7").value = hours + mins;
} else if (time7.length == 3) {
var hours = parseInt(time7.substring(0, 1));
var mins = parseInt(time7.substring(1, 3))/60;
document.getElementById("sliderTime7").value = hours + mins;
} else if (time7.length < 3 && time7.length > 0) {
var hours = time7;
document.getElementById("sliderTime7").value = hours;
}
// ----------
var time8 = (document.getElementById("textTime8").value).replace(":", "").replace(".", "");
if (time8.length == 4) {
var hours = parseInt(time8.substring(0, 2));
var mins = parseInt(time8.substring(2, 4))/60;
document.getElementById("sliderTime8").value = hours + mins;
} else if (time8.length == 3) {
var hours = parseInt(time8.substring(0, 1));
var mins = parseInt(time8.substring(1, 3))/60;
document.getElementById("sliderTime8").value = hours + mins;
} else if (time8.length < 3 && time8.length > 0) {
var hours = time8;
document.getElementById("sliderTime8").value = hours;
}
// ----------
var time9 = (document.getElementById("textTime9").value).replace(":", "").replace(".", "");
if (time9.length == 4) {
var hours = parseInt(time9.substring(0, 2));
var mins = parseInt(time9.substring(2, 4))/60;
document.getElementById("sliderTime9").value = hours + mins;
} else if (time9.length == 3) {
var hours = parseInt(time9.substring(0, 1));
var mins = parseInt(time9.substring(1, 3))/60;
document.getElementById("sliderTime9").value = hours + mins;
} else if (time9.length < 3 && time9.length > 0) {
var hours = time9;
document.getElementById("sliderTime9").value = hours;
}
showValue();
}
// --------
function weekLoopPrev(){
scheduleDay = Days[Days.indexOf(scheduleDay) - 1];
scheduleStart.innerHTML = dayThis;
}
function weekLoopNext(){
scheduleStart.innerHTML = "monday";
}
var switch0 = document.getElementById("switch0");
var sliderTime0 = document.getElementById("sliderTime0");
var textTime0 = document.getElementById("textTime0");
var switch1 = document.getElementById("switch1");
var sliderTime1 = document.getElementById("sliderTime1");
var textTime1 = document.getElementById("textTime1");
var switch2 = document.getElementById("switch2");
var sliderTime2 = document.getElementById("sliderTime2");
var textTime2 = document.getElementById("textTime2");
var switch3 = document.getElementById("switch3");
var sliderTime3 = document.getElementById("sliderTime3");
var textTime3 = document.getElementById("textTime3");
var switch4 = document.getElementById("switch4");
var sliderTime4 = document.getElementById("sliderTime4");
var textTime4 = document.getElementById("textTime4");
var switch5 = document.getElementById("switch5");
var sliderTime5 = document.getElementById("sliderTime5");
var textTime5 = document.getElementById("textTime5");
var switch6 = document.getElementById("switch6");
var sliderTime6 = document.getElementById("sliderTime6");
var textTime6 = document.getElementById("textTime6");
var switch7 = document.getElementById("switch7");
var sliderTime7 = document.getElementById("sliderTime7");
var textTime7 = document.getElementById("textTime7");
var switch8 = document.getElementById("switch8");
var sliderTime8 = document.getElementById("sliderTime8");
var textTime8 = document.getElementById("textTime8");
var switch9 = document.getElementById("switch9");
var sliderTime9 = document.getElementById("sliderTime9");
var textTime9 = document.getElementById("textTime9");
//Code for getting all data from the server
var ServerUrl = 'http://wwwis.win.tue.nl/2id40-ws/04';
//Backup server
//var ServerUrl = 'http://pcwin889.win.tue.nl/2id40-ws/04';
Type = {
Day : 'day',
Night : 'night'
};
Days = {
Monday : 'Monday',
Tuesday : 'Tuesday',
Wednesday : 'Wednesday',
Thursday : 'Thursday',
Friday : 'Friday',
Saturday : 'Saturday',
Sunday : 'Sunday'
};
var MinTemperature = parseFloat(5.0);
var MaxTemperature = parseFloat(30.0);
var MaxSwitches = 5;
var Time;
var CurrentDay;
var DayTemperature;
var NightTemperature;
var CurrentTemperature;
var TargetTemperature;
var ProgramState;
var Program = {};
Program[Days.Monday] = [];
Program[Days.Tuesday] = [];
Program[Days.Wednesday] = [];
Program[Days.Thursday] = [];
Program[Days.Friday] = [];
Program[Days.Saturday] = [];
Program[Days.Sunday] = [];
/* Retreive day program
*/
function getProgram(day) {
return Program[day];
}
/* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
*/
function sortMergeProgram(day) {
var program = getProgram(day);
program.sort(function(a, b){return parseTime(a[0])-parseTime(b[0])});
for (var i = 0; i < program.length - 1; i++) {
if (parseTime(program[i][1]) >= parseTime(program[i+1][0])) {
var start = (program[i][0]);
var end = (parseTime(program[i][1]) > parseTime(program[i+1][1])) ? program[i][1] : program[i+1][1];
program.splice(i, 2);
program.push([start, end]);
sortMergeProgram(day);
break;
}
}
}
/* Retrieves all data from the server except for weekProgram
*/
function get(attribute_name, xml_tag) {
return requestData(
"/"+attribute_name,
function(data) {
return $(data).find(xml_tag).text();
}
);
}
/* Retrieves the week program
*/
function getWeekProgram() {
return requestData(
'/weekProgram',
function(data) {
$(data).find('day').each(function() {
var day = $(this).attr('name');
Program[day] = [];
$(this).find('switch').each(function() {
if ($(this).attr('state') == 'on') {
if ($(this).attr('type') == Type.Day) {
getProgram(day).push([$(this).text(), '00:00']);
} else {
getProgram(day)[getProgram(day).length - 1][1] = $(this).text();
}
}
})
});
return Program;
}
);
}
/* Uploads all data to the server except for currentTemperature and weekProgram
*/
function put(attribute_name, xml_tag, value){
uploadData("/"+attribute_name, "<" + xml_tag + ">"+ value + "</" + xml_tag + ">");
}
function requestData(address, func) {
var result;
$.ajax({
type: "get",
url: ServerUrl + address,
dataType: "xml",
async: false,
success: function(data) {
result = func(data);
}
});
return result;
}
/* Uploads the week program
*/
function setWeekProgram() {
var doc = document.implementation.createDocument(null, null, null);
var program = doc.createElement('week_program');
program.setAttribute('state', ProgramState ? 'on' : 'off');
for (var key in Program) {
var day = doc.createElement('day');
day.setAttribute('name', key);
var daySwitches = [];
var nightSwitches = [];
var i, text, sw;
var periods = getProgram(key);
for (i = 0; i < periods.length; i++ ) {
daySwitches.push(periods[i][0]);
nightSwitches.push(periods[i][1]);
}
for (i = 0; i < MaxSwitches; i++) {
sw = doc.createElement('switch');
sw.setAttribute('type', Type.Day);
if (i < daySwitches.length) {
sw.setAttribute('state', 'on');
text = doc.createTextNode(daySwitches[i]);
} else {
sw.setAttribute('state', 'off');
text = doc.createTextNode('00:00');
}
sw.appendChild(text);
day.appendChild(sw);
}
for (i = 0; i < MaxSwitches; i++ ) {
sw = doc.createElement('switch');
sw.setAttribute('type', Type.Night);
if (i < nightSwitches.length) {
sw.setAttribute('state', 'on');
text = doc.createTextNode(nightSwitches[i]);
} else {
sw.setAttribute('state', 'off');
text = doc.createTextNode('00:00');
}
sw.appendChild(text);
day.appendChild(sw);
}
program.appendChild(day);
}
doc.appendChild(program);
uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
}
/* Creates the default week program
*/
function setDefault() {
var doc = document.implementation.createDocument(null, null, null);
var program = doc.createElement('week_program');
program.setAttribute('state', ProgramState ? 'on' : 'off');
for (var key in Program) {
var day = doc.createElement('day');
day.setAttribute('name', key);
var daySwitches = [];
var nightSwitches = [];
var i, text, sw;
for (i = 0; i < MaxSwitches; i++) {
sw = doc.createElement('switch');
sw.setAttribute('type', Type.Night);
sw.setAttribute('state', 'off');
text = doc.createTextNode('00:00');
sw.appendChild(text);
day.appendChild(sw);
}
for (i = 0; i < MaxSwitches; i++) {
sw = doc.createElement('switch');
sw.setAttribute('type', Type.Day);
sw.setAttribute('state', 'off');
text = doc.createTextNode('00:00');
sw.appendChild(text);
day.appendChild(sw);
}
program.appendChild(day);
}
doc.appendChild(program);
uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
}
function uploadData(address, xml) {
$.ajax({
type: "put",
url: ServerUrl + address,
contentType: 'application/xml',
data: xml,
async: false
});
}
function parseTime(t) {
return parseFloat(t.substr(0,2)) + parseFloat(t.substr(3,2))/60;
}
/* Adds a heating period for a specific day
*/
function addPeriod(day, start, end) {
var program = getWeekProgram()[day];
program.push([start, end]);
sortMergeProgram(day);
setWeekProgram();
}
/* Removes a heating period from a specific day.
idx is the idex of the period with values from 0 to 4
*/
function removePeriod(day, idx) {
var program = getWeekProgram()[day];
var start = program[idx][0];
var end = program[idx][1];
program.splice(idx,1);
setWeekProgram();
}
/* Checks whether the temperature is within the range [5.0,30.0]
*/
function inTemperatureBoundaries(temp) {
temp = parseFloat(temp);
return ( temp >= MinTemperature && temp <= MaxTemperature);
}
function getAll() {
CurrentDay = get("day", "current_day");
scheduleDay = CurrentDay;
var todayDay = document.getElementById("dayNow");
if (todayDay != null) {
todayDay.innerHTML = CurrentDay;
}
var scheduleStart = document.getElementById("scheduleDay");
if (scheduleStart != null) {
scheduleStart.innerHTML = CurrentDay;
}
Time = get("time", "time");
document.getElementById("timeNow").innerHTML = Time;
}
$(document).ready(getAll);
<file_sep>Schedule page:
- let the user be able to loop through the days ( buttons are already there, with onClick function attached )
- wire the checkboxes to enable/disable switches
- make the schedule put the values onto the server
- make the schedule get the values from the server onload
|
6187b3ba292049d652efcc5c3f83bb3db6304942
|
[
"JavaScript",
"Text"
] | 2
|
JavaScript
|
General01L/2ID40
|
0236c032e7e30c593085eb91558ccd4e6f713085
|
6946638d86b864e0dd63f946ba363beb1d73aec5
|
refs/heads/master
|
<repo_name>kgodey/react-tags<file_sep>/dist-modules/components/DragAndDropHelper.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.dropCollect = exports.dragSource = exports.tagTarget = exports.tagSource = undefined;
var _reactDom = require('react-dom');
var _utils = require('./utils');
var tagSource = {
beginDrag: function beginDrag(props) {
return { id: props.tag.index, index: props.index };
},
canDrag: function canDrag(props) {
return (0, _utils.canDrag)(props);
}
};
var tagTarget = {
hover: function hover(props, monitor, component) {
var dragIndex = monitor.getItem().index;
var hoverIndex = props.index;
if (dragIndex === hoverIndex) {
return;
}
var hoverBoundingRect = (0, _reactDom.findDOMNode)(component).getBoundingClientRect();
var hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
var clientOffset = monitor.getClientOffset();
var hoverClientX = clientOffset.x - hoverBoundingRect.left;
// Only perform the move when the mouse has crossed half of the items width
if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
return;
}
if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
return;
}
props.moveTag(dragIndex, hoverIndex);
monitor.getItem().index = hoverIndex;
},
canDrop: function canDrop(props) {
return (0, _utils.canDrop)(props);
}
};
var dragSource = function dragSource(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
};
var dropCollect = function dropCollect(connect) {
return {
connectDropTarget: connect.dropTarget()
};
};
exports.tagSource = tagSource;
exports.tagTarget = tagTarget;
exports.dragSource = dragSource;
exports.dropCollect = dropCollect;<file_sep>/dist-modules/components/utils.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildRegExpFromDelimiters = buildRegExpFromDelimiters;
exports.canDrag = canDrag;
exports.canDrop = canDrop;
var _escapeRegExp = require('lodash/escapeRegExp');
var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Convert an array of delimiter characters into a regular expression
* that can be used to split content by those delimiters.
* @param {Array<char>} delimiters Array of characters to turn into a regex
* @returns {RegExp} Regular expression
*/
function buildRegExpFromDelimiters(delimiters) {
var delimiterChars = delimiters.map(function (delimiter) {
// See: http://stackoverflow.com/a/34711175/1463681
var chrCode = delimiter - 48 * Math.floor(delimiter / 48);
return String.fromCharCode(96 <= delimiter ? chrCode : delimiter);
}).join('');
var escapedDelimiterChars = (0, _escapeRegExp2.default)(delimiterChars);
return new RegExp('[' + escapedDelimiterChars + ']+');
}
/**
* Returns true when the tag is drag enabled
* @param {object} params props of the tag element
* @returns {boolean} true/false
* The three different properties which controls this function are moveTag, readOnly and allowDragDrop.
*/
function canDrag(params) {
var moveTag = params.moveTag,
readOnly = params.readOnly,
allowDragDrop = params.allowDragDrop;
return moveTag !== undefined && !readOnly && allowDragDrop;
}
/**
* Returns true when the tag is drop enabled
* @param {object} params props of the tag element
* @returns {boolean} true/false
* The two different properties which controls this function are readOnly and allowDragDrop.
*/
function canDrop(params) {
var readOnly = params.readOnly,
allowDragDrop = params.allowDragDrop;
return !readOnly && allowDragDrop;
}
|
1881e1673cabf957bec53d24fd052b42f2a1b0c5
|
[
"JavaScript"
] | 2
|
JavaScript
|
kgodey/react-tags
|
1643ac0585e2f54812a6089f4c7adb6aaac422a3
|
b415893a7b1e85a6bfb03bfee63aa274fe6e089f
|
refs/heads/master
|
<file_sep>#pragma once
class Floaters {
public:
static inline constexpr u32 maxFloaters = 32;
struct Floater : public Point2D {
Point2D* target;
} positions[maxFloaters];
enum Type : u8 {
None,
Credits,
} types[maxFloaters];
void addFloater(Point2D position, Point2D *target, Type type) {
Point2D ref = Graphics::camera + Point2D{f32(screenWidth/2), f32(screenHeight/2)};
u32 longest = 0;
u32 id = 0;
for (u32 i = 0; i < maxFloaters; ++i) {
u32 distance = (positions[i] - ref).lengthSquared();
if (distance >= longest) {
longest = distance;
id = i;
}
}
positions[id] = Floater{
position,
target
};
types[id] = type;
}
void draw(){
for (u32 id = 0; id < maxFloaters; ++id) {
switch(types[id]) {
case None:
break;
case Credits: {
auto delta = positions[id] - *positions[id].target;
f32 magnitude = std::max(abs(delta.x), abs(delta.y));
if (magnitude < 8) {
types[id] = None;
break;
}
positions[id] -= (delta * 4) / magnitude;
// Graphics::draw(BitmapFrame<8>(credits, (frame >> 1) & 3), positions[id]);
break;
}
}
}
}
void clear() {
for (u32 i = 0; i < maxFloaters; ++i) {
types[i] = None;
}
}
} floaters;
<file_sep>#pragma once
#include <Femto>
#include <cstdio>
inline bool renderCutScene(u32 scene, u32 page) {
constexpr const u32 pageSize = 220 * 176 * 2;
File logo;
char buff[100];
snprintf(buff, sizeof(buff), "data/mission_%d.i16", scene);
if (!logo.openRO(buff)){
LOG("Could not open ", buff, "\n");
return false;
}
u32 size = logo.size();
if (page * pageSize >= size) {
LOG("End of CutScene\n");
return false;
}
LOG("Rendered scene ", scene, "-", page, "\n");
logo.seek(page * pageSize);
streamI16(logo, 220, 176, 0xFFFF);
return true;
}
inline u32 currentScenePage = 0, deadkey = 0;
inline void nextScenePage() {
if (!renderCutScene(0, currentScenePage++)) {
currentScenePage = 0;
targetBacklight = 0;
}
deadkey = getTime();
}
inline void updateEnterCutScene() {
if (updateEnter(GameState::CutScene)) {
gameRenderer->detach();
nextScenePage();
}
}
inline void updateCutScene() {
delay(0);
if (targetBacklight != 0) {
if ((getTime() - deadkey) > 250 && isPressed(Button::A)) {
nextScenePage();
}
} else {
if (backlight == 0) {
targetBacklight = 255;
gameState = GameState::Space;
gameRenderer->attach();
}
}
}
<file_sep>bool loadGhost(u32 trackId, void* data, u32 size);
bool saveGhost(u32 trackId, void* data, u32 size);
<file_sep>#pragma once
#include <Femto>
#include <cstdint>
using RenderTexture = Bitmap<8, 2+64*64>;
inline RenderTexture buffers[] = {
{64, 64},
{64, 64}
};
constexpr inline u32 bufferCount = sizeof(buffers) / sizeof(buffers[0]);
inline u32 usedBufferCount = 0;
inline u32 bufferHash[bufferCount];
RenderTexture* drawMesh(const u8* node, f32 scale = 1, f32 yRotation = 0, f32 zRotation = 0, u32 recolor = 0, f32 fskew = 0, bool isInShade = false) {
PROFILER;
if (usedBufferCount >= bufferCount){
usedBufferCount++;
LOG("Ran out of textures ", usedBufferCount, "\n");
return nullptr;
}
s32 syRotation = f32ToS24q8(yRotation) >> 4;
s32 szRotation = f32ToS24q8(zRotation) >> 4;
u32 hash = reinterpret_cast<uintptr_t>(node) +
syRotation * 991 +
szRotation * 463 +
recolor * 253 +
f32ToS24q8(scale) * 1001 +
f32ToS24q8(fskew) * 971;
if (bufferHash[usedBufferCount] == hash) {
return &buffers[usedBufferCount++];
}
bufferHash[usedBufferCount] = hash;
auto& bitmap = buffers[usedBufferCount++];
bitmap.fill(0);
u32 width = bitmap.width();
u32 height = bitmap.height();
s32 centerX = width / 2;
s32 centerY = height / 2;
s32 iscale = std::min(width, height) * scale;
// for (s32 y = 0; y < iscale; ++y) {
// for (s32 x = 0; x < iscale; ++x) {
// bitmap.ptr()[2 + (centerX - iscale/2) + x + ((y + (centerY - iscale/2)) * width)] = 1;
// }
// }
// return &bitmap;
u32 faceCount = (node[0] << 8) | node[1];
u32 vertexCount = node[2];
s8 vtxCache[node[2] * 2];
s32 crY = f32ToS24q8(cos(yRotation));
s32 srY = f32ToS24q8(sin(yRotation));
s32 crZ = f32ToS24q8(cos(zRotation));
s32 srZ = f32ToS24q8(sin(zRotation));
auto vtx = reinterpret_cast<const s8*>(node + 3 + faceCount * 4);
f32 fiskew = f32(1.0f) - fskew;
s32 skew = f32ToS24q8(fskew);
s32 iskew = f32ToS24q8(f32(1.0f) - fskew);
for (u32 vtxId = 0; vtxId < vertexCount; ++vtxId) {
auto ptr = vtx + vtxId * 3;
s32 Ax = *ptr++ * iscale;
s32 Ay = *ptr++ * iscale;
s32 Az = *ptr * iscale;
s32 T = (crZ * Ax - srZ * Ay) >> 8;
Ay = (crZ * Ay + srZ * Ax) >> 8;
Ax = T;
T = (crY * Ax - srY * Az) >> 8;
Az = crY * Az + srY * Ax;
Ax = T;
vtxCache[vtxId * 2] = -(Ay*iskew - Ax*skew) >> 16;
vtxCache[vtxId * 2 + 1] = Az >> 16;
}
for (u32 face = 0; face < faceCount; ++face) {
u32 index = 3 + face * 4;
u32 color = u8(node[index++]) + (recolor << 3);
auto indexA = vtxCache + node[index++] * 2;
auto indexB = vtxCache + node[index++] * 2;
auto indexC = vtxCache + node[index ] * 2;
s32 Ax = indexA[0];
s32 Ay = indexA[1];
// s32 Az = indexA[2];
s32 Bx = indexB[0];
s32 By = indexB[1];
// s32 Bz = indexB[2];
s32 Cx = indexC[0];
s32 Cy = indexC[1];
// s32 Cz = indexC[2];
// s32 Nx = (Ay - Cy) * (Bz - Cz) - (Az - Cz) * (By - Cy);
// s32 Ny = (Az - Cz) * (Bx - Cx) - (Ax - Cx) * (Bz - Cz);
// s32 Nz = (Ax - Cx) * (By - Cy) - (Ay - Cy) * (Bx - Cx);
// Ay = Ay/2 - Az;
// By = By/2 - Bz;
// Cy = Cy/2 - Cz;
s32 Nx = (Ax - Bx)*(Ay - Cy) - (Ay - By)*(Ax - Cx);
if (Nx > 0)
continue;
Nx = -Nx;
if (isInShade)
Nx >>= 1;
u32 hue = (color >> 3) << 3;
s32 lum = (color & 7) + (Nx >> 3) - 2;
if (lum < 0) lum = 0;
else if (lum > 7) lum = 7;
/* s32 lum = 5; */
color = hue + lum;
bitmap.fillTriangle(
centerX + Ax, centerY - Ay,
centerX + Bx, centerY - By,
centerX + Cx, centerY - Cy,
color
);
}
return &bitmap;
}
<file_sep>#pragma once
#include <Femto>
class Camera3D {
public:
Point3D position = {15, 50, -10};
Point3D speed;
f32 rotation = f32(1.0f);
u16 zBuffer[screenWidth];
void follow(Point3D target, f32 targetRotation);
s32 distanceTo(const Point3D& target);
f32 angleTo(const Point3D& target);
} inline camera3D;
<file_sep>#include <Femto>
#include "Camera3D.h"
#include "Terrain.h"
#include "Renderer.h"
f32 Camera3D::angleTo(const Point3D& target) {
PROFILER;
auto delta = target - Ground::relative(camera3D.position, target);
return -atan2(delta.x, delta.z);
}
s32 Camera3D::distanceTo(const Point3D& target) {
PROFILER;
return (Ground::relative(camera3D.position, target) - target).xz().lengthSquared();
}
void Camera3D::follow(Point3D target, f32 targetRotation) {
PROFILER;
Point3D forwardOffset {f32(50.0f), 0, 0};
forwardOffset.rotateXZ(targetRotation);
auto& terrain = gameRenderer->get<Ground>();
s32 groundHeight = (terrain.getHeightAtPoint({position.x, position.z}) + 5);
if (target.y < groundHeight)
target.y = groundHeight;
auto delta = (target + forwardOffset) - position;
f32 lookAtRotation = -atan2(delta.x, delta.z);
rotation += angleDelta(rotation, lookAtRotation) * f32(0.3f);
// rotation = lookAtRotation;
// Point3D offset {0, f32(3.0f), f32(-4.0f) + sin(frame++ * f32(0.1f)) * 2};
Point3D offset {0, f32(3.0f), f32(4.5f)};
offset.rotateXZ(targetRotation + PI/2);
position.tweenTo(target + offset, 2);
// position = target + offset;
// delta = (target + offset) - position;
// delta *= f32(0.3f);
// speed.tweenTo(delta, 5);
// position += speed * f32(0.5f);
}
<file_sep>#pragma once
#include "item.h"
class Shop {
public:
enum class Mode {
topLevel,
buy,
owned
} mode;
u32 selection;
bool dirty;
u32 redrawTime;
void init() {
mode = Mode::topLevel;
selection = 0;
dirty = true;
redrawTime = getTime();
}
void tick() {
u32 now = getTime();
if (dirty || now - redrawTime < 200)
return;
int move = isPressed(Button::Down) - isPressed(Button::Up);
selection += move;
dirty |= move != 0;
dirty |= isPressed(Button::A) || isPressed(Button::B) || isPressed(Button::C);
}
void redraw() {
if (isPressed(Button::C)) {
if (mode == Mode::topLevel) {
targetBacklight = 0;
return;
} else {
setMode(Mode::topLevel);
}
}
redrawTime = getTime();
dirty = false;
Graphics::clearText();
Graphics::setCursor(20, 8);
switch (mode) {
case Mode::topLevel: redrawTopLevel(); break;
case Mode::buy: redrawBuy(); break;
case Mode::owned: redrawOwned(); break;
}
}
void setMode(Mode mode) {
if (this->mode == mode) {
return;
}
this->mode = mode;
dirty = true;
selection = 0;
}
void redrawTopLevel() {
using namespace Graphics;
print("Menu");
setCursor(5, (0 + 3) * 8);
print(selection == 0 ? '>' : ' ', "Buy items");
setCursor(5, (1 + 3) * 8);
print(selection == 1 ? '>' : ' ', "View owned items");
if (selection >= 2) {
if (s32(selection) < 0) selection = 1;
else selection = 0;
dirty = true;
}
if (isPressed(Button::A)) {
switch (selection) {
case 0: setMode(Mode::buy); break;
case 1: setMode(Mode::owned); break;
}
}
}
void redrawBuy() {
constexpr const u32 maxShopItems = 5;
using namespace Graphics;
print("Item Shop");
u32 line = 0;
u32 key = 0;
key += getTime() / 0x5460000;
key += world * 1664525;
key += 1013904223;
u32 itemIds[maxShopItems];
for (u32 i = 0; i < maxShopItems; ++i) {
key ^= key << 17;
key ^= key >> 13;
key ^= key << 5;
line = key % itemCount;
for (u32 j = 0; j < i; ++j) {
if (itemIds[j] == line) {
line = (line + 1) % itemCount;
j = 0;
}
}
itemIds[i] = line;
}
line = 0;
for (u32 i = 0; i < maxShopItems; ++i) {
u32 item = itemIds[i];
char pref = selection == line ? '>' : ' ';
setCursor(5, (line + 3) * 8);
print(pref, items[item].name);
setCursor(38 * 5, (line + 3) * 8);
print(sellPrice(items[item].price), "c\n");
++line;
}
if (selection >= line) {
if (s32(selection) < 0) selection = line;
else selection = 0;
dirty = true;
}
}
s32 buyPrice(s32 basePrice) {
auto i = f32(universe.worldKillCount[world]) / f32(255);
return basePrice - (1 - i) * (basePrice * f32(0.5));
}
s32 sellPrice(s32 basePrice) {
auto i = f32(universe.worldKillCount[world]) / f32(255);
return basePrice + (1 - i) * (basePrice * f32(0.5));
}
void redrawOwned() {
using namespace Graphics;
print("Inventory");
u32 line = 0;
for (u32 item = 0; item < itemCount; ++item) {
u32 count = universe.ownedItems[item];
if (!count) continue;
bool equipped = Ship::player->isEquipped(item);
char pref = selection == line ? '>' : ' ';
setCursor(5, (line + 3) * 8);
print(pref, items[item].name);
if (equipped)
print(" [e]");
setCursor(30 * 5, (line + 3) * 8);
print(" x", count);
setCursor(38 * 5, (line + 3) * 8);
print(items[item].price, "c\n");
++line;
}
if (selection >= line) {
if (s32(selection) < 0) selection = line;
else selection = 0;
dirty = true;
}
}
} shop;
void updateEnterShop() {
if (updateEnter(GameState::Shop)) {
shopRenderer = &renderer.emplace<ShopRenderer>();
shop.init();
}
}
void updateShop() {
using namespace Graphics;
clear();
if (targetBacklight == 255) {
shop.tick();
if (shop.dirty)
shop.redraw();
} else {
if (backlight == 0) {
gameState = GameState::Space;
gameRenderer = &renderer.emplace<GameRenderer>();
targetBacklight = 255;
}
}
}
<file_sep>#include <Femto>
#include <File>
#include "Renderer.h"
#include "Ghost.h"
class PNGWriter {
public:
File file;
u32 width, height, positionX = 0, positionY = 0;
u32 remaining, lineSize;
u16 deflateFilled = 0;
u32 crc = 0;
u32 adler = 1;
static constexpr inline u32 DEFLATE_MAX_BLOCK_SIZE = 65535;
void crc32(const u8* data, u32 len) {
crc = ~crc;
for (u32 i = 0; i < len; i++) {
for (u32 j = 0; j < 8; j++) { // Inefficient bitwise implementation, instead of table-based
u32 bit = (crc ^ (data[i] >> j)) & 1;
crc = (crc >> 1) ^ ((-bit) & UINT32_C(0xEDB88320));
}
}
crc = ~crc;
}
void adler32(const u8* data, u32 len) {
u32 s1 = adler & 0xFFFF;
u32 s2 = adler >> 16;
for (u32 i = 0; i < len; i++) {
s1 = (s1 + data[i]) % 65521;
s2 = (s2 + s1) % 65521;
}
adler = s2 << 16 | s1;
}
void writeInt32BE(u32 val, u8* array) {
array[0] = val >> 24;
array[1] = val >> 16;
array[2] = val >> 8;
array[3] = val;
}
#define BIGEND(V) u8(V >> 24), u8(V >> 16), u8(V >> 8), u8(V)
PNGWriter(const char* name, u32 w, u32 h) : width(w), height(h) {
file.openRW(name, true, false);
lineSize = w * 3 + 1;
remaining = lineSize * h;
u32 numBlocks = remaining / DEFLATE_MAX_BLOCK_SIZE;
if (remaining % DEFLATE_MAX_BLOCK_SIZE != 0)
numBlocks++; // Round up
// 5 bytes per DEFLATE uncompressed block header, 2 bytes for zlib header, 4 bytes for zlib Adler-32 footer
u32 idatSize = numBlocks * 5 + 6 + remaining;
// Write header (not a pure header, but a couple of things concatenated together)
u8 header[] = { // 43 bytes long
// PNG header
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,
// IHDR chunk
0x00, 0x00, 0x00, 0x0D,
0x49, 0x48, 0x44, 0x52,
BIGEND(w),
BIGEND(h),
0x08, // bit depth
0x02, // color type. 2 = color used
0x00, 0x00, 0x00, // compression, filter, interlace
0, 0, 0, 0, // IHDR CRC-32 placeholder
};
// // eXif chunk
// 0x00, 0x00, 0x00, 0x5a, // size
// 0x65, 0x58, 0x49, 0x66, // eXIf
// 0x4d, 0x4d, 0x00, 0x2a,
// 0x00, 0x00, 0x00, 0x08,
// 0x00, 0x05, 0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00, 0x01, 0x1a,
// 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x4a, 0x01, 0x1b, 0x00, 0x05, 0x00, 0x00,
// 0x00, 0x01, 0x00, 0x00, 0x00, 0x52, 0x01, 0x28, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
// 0x00, 0x00, 0x02, 0x13, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00,
// 0x00, 0x01,
// 0x74, 0x6c, 0xe5, 0x6f,
u8 idat[] = {
// IDAT chunk
BIGEND(idatSize), // 'idatSize' placeholder
0x49, 0x44, 0x41, 0x54,
// DEFLATE data
0x08, 0x1D,
};
crc = 0;
crc32(&header[12], 17);
writeInt32BE(crc, &header[29]);
file.write(header);
file.write(idat);
crc = 0;
crc32(&idat[4], 6); // 0xD7245B6B
}
void write(const u8* pixels, u32 count) {
count *= 3; // Convert pixel count to byte count
while (count > 0) {
if (deflateFilled == 0) { // Start DEFLATE block
auto size = DEFLATE_MAX_BLOCK_SIZE;
if (remaining < size)
size = remaining;
const u8 header[] = { // 5 bytes long
static_cast<u8>(remaining <= DEFLATE_MAX_BLOCK_SIZE),
static_cast<u8>(size >> 0),
static_cast<u8>(size >> 8),
static_cast<u8>((size >> 0) ^ 0xFF),
static_cast<u8>((size >> 8) ^ 0xFF),
};
file.write(header);
crc32(header, sizeof(header) / sizeof(header[0]));
}
if (positionX == 0) { // Beginning of line - write filter method byte
u8 b[] = {0};
file.write(b);
crc32(b, 1);
adler32(b, 1);
positionX++;
remaining--;
deflateFilled++;
} else { // Write some pixel bytes for current line
u32 n = DEFLATE_MAX_BLOCK_SIZE - deflateFilled;
n = std::min(lineSize - positionX, n);
n = std::min(n, count);
file.write(pixels, n);
// Update checksums
crc32(pixels, n);
adler32(pixels, n);
// Increment positions
count -= n;
pixels += n;
positionX += n;
remaining -= n;
deflateFilled += n;
}
if (deflateFilled >= DEFLATE_MAX_BLOCK_SIZE)
deflateFilled = 0; // End current block
if (positionX == lineSize) { // Increment line
positionX = 0;
positionY++;
if (positionY == height) { // Reached end of pixels
u8 footer[] = { // 20 bytes long
0, 0, 0, 0, // DEFLATE Adler-32 placeholder
0, 0, 0, 0, // IDAT CRC-32 placeholder
// IEND chunk
0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x4E, 0x44,
0xAE, 0x42, 0x60, 0x82,
};
writeInt32BE(adler, &footer[0]);
crc32(&footer[0], 4);
writeInt32BE(crc, &footer[4]);
file.write(footer);
}
}
}
}
};
bool loadGhost(u32 trackId, void* data, u32 size) {
auto bdata = reinterpret_cast<u8*>(data);
char fileName[32];
snprintf(fileName, sizeof(fileName), "data/%d.png", trackId);
File ghost;
if (!ghost.openRO(fileName)) {
LOG("No ghost for track ", fileName, "\n");
return false;
}
ghost.seek(0x30);
for (u32 y = 0; y < 176; ++y) {
u8 b;
ghost >> b;
for (u32 x = 0; x < 220; ++x) {
ghost >> b;
u8 o = b & 7;
ghost >> b;
o |= (b & 3) << 3;
ghost >> b;
o |= (b & 7) << 5;
*bdata++ = o;
size--;
if (!size) return true;
}
}
return true;
}
bool saveGhost(u32 trackId, void* data, u32 size) {
char fileName[32];
snprintf(fileName, sizeof(fileName), "data/%d.png", trackId);
PNGWriter png(fileName, 220, 176);
if (!png.file)
return false;
auto& ground = gameRenderer->get<Ground>();
auto fillers = static_cast<Graphics::DynamicRenderer*>(gameRenderer)->fillers;
auto fillerCount = static_cast<Graphics::DynamicRenderer*>(gameRenderer)->fillerCount;
auto bdata = reinterpret_cast<u8*>(data);
auto &text = gameRenderer->get<TextLayer>();
File ooo;
ooo.openRO("data/1on1.i16");
u8 w = 0, h = 0;
ooo >> w >> h;
for (int y = 0; y < 176; ++y) {
Schedule::runUpdateHooks(false, getTimeMicro());
u8 pixels[220*3];
u16 line[220 + 16];
for (u32 x = 0; x < 220; ++x)
line[x + 8] = ground.palette[ground.heightmap[(Ground::mapWidth/2 - screenWidth/2) + x + Ground::mapWidth * (y + (Ground::mapHeight/2 - screenHeight/2))]];
if (y < h) {
for (u32 x = 0; x < w; ++x){
if (u16 c = ooo.read<u16>()) {
line[x + 8 + (screenWidth/2 - w/2)] = c;
}
}
}
if (y > screenHeight - 45) {
for (u32 x = 8; x < 228; ++x) {
line[x] = (line[x] >> 2) & 0x39e7;
}
}
text(line + 8, y);
// for (u32 i = 0; i < fillerCount; ++i) {
// fillers[i](line + 8, y);
// }
for (u32 x = 0; x < 220; ++x) {
u8 db;
if (size) {
db = *bdata;
bdata++;
size--;
} else {
db = 0;
}
u32 R = (line[x + 8] >> 11 << 3);
u32 G = (((line[x + 8] >> 5) & 0x3F) << 2);
u32 B = ((line[x + 8] & 0x1F) << 3);
R |= (db & 7); db >>= 3;
G |= (db & 3); db >>= 2;
B |= (db & 7);
pixels[x * 3 ] = R;
pixels[x * 3 + 1] = G;
pixels[x * 3 + 2] = B;
}
// flushLine16(line + 8);
png.write(pixels, 220);
}
// File ghost(fileName, true);
// if (ghost) {
// ghost.write(data, size);
// return true;
// }
// return false;
return true;
}
<file_sep>#pragma once
#include <File>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <string>
#endif
using SerializeProperty = void (*)(const StringInfo&, void*, std::size_t);
class Serialize {
using Proxy = void (*)(void* obj, SerializeProperty cb);
u32 hash, size;
File file;
inline static Serialize* instance;
inline static bool wasInit = false;
Serialize() {
init();
}
public:
static void init(){
if (wasInit)
return;
wasInit = true;
#ifdef __EMSCRIPTEN__
EM_ASM(
FS.mkdir("/persistent");
FS.mount(IDBFS, {}, "/persistent");
FS.syncfs(true, function (err) {
try{ FS.mkdir("/persistent/data"); } catch(ex) {}
});
);
#endif
}
bool toFile(void* value, Proxy proxy, const char* fileName) {
#ifdef __EMSCRIPTEN__
std::string path = "/persistent/";
path += fileName;
fileName = path.c_str();
#endif
if (!file.openRW(fileName, true, false)) {
LOGD("Could not open ", fileName, "\n");
return false;
}
proxy(value, +[](const StringInfo& info, void* ptr, std::size_t size){
instance->file << (u32) info << (u32) size;
instance->file.write(ptr, size);
// LOG("Saved ", (std::string_view)info, "\n");
});
#ifdef __EMSCRIPTEN__
EM_ASM(
FS.syncfs(function (err){
// console.log("Sync'ed");
});
);
#endif
return true;
}
template <typename Type>
static bool toFile(Type& value, const char* fileName) {
Serialize s;
instance = &s;
auto proxy = +[](void* obj, SerializeProperty cb){
reinterpret_cast<Type*>(obj)->_serialize_(cb);
};
return s.toFile(reinterpret_cast<void*>(&value), proxy, fileName);
}
bool fromFile(void* value, Proxy proxy, const char* fileName) {
#ifdef __EMSCRIPTEN__
std::string path = "/persistent/";
path += fileName;
fileName = path.c_str();
#endif
if (!file.openRO(fileName))
return false;
while (true) {
size = 0;
file >> hash >> size;
if (!size) return true;
proxy(value, +[](const StringInfo& info, void* ptr, std::size_t size){
if (info == instance->hash) {
instance->file.read(ptr, std::min<u32>(instance->size, size));
// LOG("Loaded ", (std::string_view)info, " ", instance->file.tell(), " ", instance->size, "\n");
instance->file >> instance->hash >> instance->size;
}
});
}
}
template <typename Type>
static bool fromFile(Type& value, const char* fileName) {
Serialize s;
instance = &s;
auto proxy = +[](void* obj, SerializeProperty cb){
reinterpret_cast<Type*>(obj)->_serialize_(cb);
};
return s.fromFile(reinterpret_cast<void*>(&value), proxy, fileName);
}
};
#define SERIALIZE(FILENAME) \
bool save(const char* name = FILENAME) { return Serialize::toFile(*this, name); } \
bool load(const char* name = FILENAME) { return Serialize::fromFile(*this, name); } \
void _serialize_(SerializeProperty cb_)
#define PROPERTY(NAME) cb_( #NAME, reinterpret_cast<void*>(&NAME), sizeof(NAME) )
<file_sep>#include "Settings.hpp"
#include <cstring>
static void save() {
File file;
file.openRW("data/1on1Settings.ini", true, false);
file << "autoAccelerate " << (Settings::autoAccelerate ? "true" : "false") << "\n";
file << "name ";
file.write(Settings::name, strlen(Settings::name));
file << "\n";
char buff[32];
snprintf(buff, sizeof(buff), "%d", Settings::pod);
file << "pod ";
file.write(buff, strlen(buff));
file << "\n";
snprintf(buff, sizeof(buff), "%d", Settings::color);
file << "color ";
file.write(buff, strlen(buff));
file << "\n";
}
static u32 readKey(File& file) {
u32 v1 = 5381, v2 = 2166136261;
u8 c;
do {
file >> c;
} while (c && c <= ' ');
while(c > ' '){
if (c >= 'A' && c <= 'Z')
c = c - 'A' + 'a';
v1 = (v1 * 251) ^ c;
v2 = (v2 ^ c) * 16777619;
file >> c;
}
return v1 * 13 + v2;
}
static u32 readString(File& file, char* out, u32 maxSize) {
u32 pos = 0;
u8 c;
do {
file >> c;
} while (c && c <= ' ');
while(c && c != '\n' && pos < (maxSize - 1)){
out[pos++] = c;
file >> c;
}
out[pos] = 0;
return pos;
}
static bool readBool(File& file) {
u8 c;
do {
file >> c;
} while (c && c <= ' ');
while(file.read<u8>() > ' ');
return c == 't' || c == 'T' || c == 'y' || c == 'Y';
}
static u32 readNumber(File& file) {
u8 c;
do {
file >> c;
} while (c && c <= ' ');
u32 n = 0;
while (c >= '0' && c <= '9') {
n = n * 10 + (c - '0');
file >> c;
}
return n;
}
bool read() {
File file;
if (!file.openRO("data/1on1Settings.ini")) {
return false;
}
auto size = file.size();
while (file.tell() < size) {
switch (readKey(file)) {
case "autoaccelerate"_hash:
Settings::autoAccelerate = readBool(file);
LOG("autoAccelerate ", Settings::autoAccelerate, "\n");
break;
case "name"_hash:
readString(file, Settings::name, sizeof(Settings::name));
LOG("name ", Settings::name, "\n");
break;
case "pod"_hash:
Settings::pod = readNumber(file);
LOG("pod ", Settings::pod, "\n");
break;
case "color"_hash:
case "colour"_hash:
Settings::color = readNumber(file);
LOG("color ", Settings::color, "\n");
break;
default:
LOG("Unknown key\n");
break;
}
}
return true;
}
bool Settings::load() {
if (!read()){
save();
return false;
}
return true;
}
<file_sep>#pragma once
inline constexpr u16 miloslav[] = {
colorFromRGB(0, 0, 0),
colorFromRGB(32, 36, 32),
colorFromRGB(72, 72, 72),
colorFromRGB(104, 108, 104),
colorFromRGB(144, 144, 144),
colorFromRGB(176, 180, 176),
colorFromRGB(216, 216, 216),
colorFromRGB(248, 252, 248),
colorFromRGB(32, 20, 16),
colorFromRGB(64, 40, 40),
colorFromRGB(96, 64, 64),
colorFromRGB(128, 84, 80),
colorFromRGB(160, 104, 104),
colorFromRGB(192, 128, 128),
colorFromRGB(224, 148, 144),
colorFromRGB(248, 168, 168),
colorFromRGB(32, 24, 16),
colorFromRGB(64, 52, 40),
colorFromRGB(96, 80, 64),
colorFromRGB(128, 108, 80),
colorFromRGB(160, 136, 104),
colorFromRGB(192, 164, 128),
colorFromRGB(224, 192, 144),
colorFromRGB(248, 220, 168),
colorFromRGB(24, 32, 16),
colorFromRGB(56, 64, 40),
colorFromRGB(88, 96, 64),
colorFromRGB(112, 128, 80),
colorFromRGB(144, 160, 104),
colorFromRGB(176, 192, 128),
colorFromRGB(208, 224, 144),
colorFromRGB(232, 252, 168),
colorFromRGB(16, 32, 16),
colorFromRGB(40, 64, 40),
colorFromRGB(64, 96, 64),
colorFromRGB(88, 128, 80),
colorFromRGB(112, 160, 104),
colorFromRGB(136, 192, 128),
colorFromRGB(160, 224, 144),
colorFromRGB(184, 252, 168),
colorFromRGB(16, 32, 24),
colorFromRGB(40, 64, 48),
colorFromRGB(64, 96, 72),
colorFromRGB(80, 128, 96),
colorFromRGB(104, 160, 128),
colorFromRGB(128, 192, 152),
colorFromRGB(144, 224, 176),
colorFromRGB(168, 252, 200),
colorFromRGB(16, 28, 24),
colorFromRGB(40, 64, 56),
colorFromRGB(64, 96, 88),
colorFromRGB(80, 128, 120),
colorFromRGB(104, 160, 152),
colorFromRGB(128, 192, 184),
colorFromRGB(144, 224, 216),
colorFromRGB(168, 252, 248),
colorFromRGB(16, 24, 32),
colorFromRGB(40, 48, 64),
colorFromRGB(64, 76, 96),
colorFromRGB(80, 100, 128),
colorFromRGB(104, 128, 160),
colorFromRGB(128, 152, 192),
colorFromRGB(144, 176, 224),
colorFromRGB(168, 204, 248),
colorFromRGB(16, 20, 32),
colorFromRGB(40, 40, 64),
colorFromRGB(64, 64, 96),
colorFromRGB(88, 84, 128),
colorFromRGB(112, 104, 160),
colorFromRGB(136, 128, 192),
colorFromRGB(160, 148, 224),
colorFromRGB(184, 168, 248),
colorFromRGB(24, 20, 32),
colorFromRGB(56, 40, 64),
colorFromRGB(88, 64, 96),
colorFromRGB(112, 84, 128),
colorFromRGB(144, 104, 160),
colorFromRGB(176, 128, 192),
colorFromRGB(208, 148, 224),
colorFromRGB(232, 168, 248),
colorFromRGB(32, 20, 24),
colorFromRGB(64, 40, 48),
colorFromRGB(96, 64, 80),
colorFromRGB(128, 84, 104),
colorFromRGB(160, 104, 136),
colorFromRGB(192, 128, 160),
colorFromRGB(224, 148, 192),
colorFromRGB(248, 168, 216),
colorFromRGB(32, 8, 8),
colorFromRGB(64, 20, 16),
colorFromRGB(96, 32, 32),
colorFromRGB(128, 40, 40),
colorFromRGB(160, 52, 48),
colorFromRGB(192, 64, 64),
colorFromRGB(224, 72, 72),
colorFromRGB(248, 84, 80),
colorFromRGB(32, 20, 8),
colorFromRGB(64, 44, 16),
colorFromRGB(96, 68, 32),
colorFromRGB(128, 92, 40),
colorFromRGB(160, 116, 48),
colorFromRGB(192, 136, 64),
colorFromRGB(224, 160, 72),
colorFromRGB(248, 184, 80),
colorFromRGB(24, 32, 8),
colorFromRGB(48, 64, 16),
colorFromRGB(80, 96, 32),
colorFromRGB(104, 128, 40),
colorFromRGB(136, 160, 48),
colorFromRGB(160, 192, 64),
colorFromRGB(192, 224, 72),
colorFromRGB(216, 252, 80),
colorFromRGB(8, 32, 8),
colorFromRGB(24, 64, 16),
colorFromRGB(40, 96, 32),
colorFromRGB(56, 128, 40),
colorFromRGB(72, 160, 48),
colorFromRGB(88, 192, 64),
colorFromRGB(104, 224, 72),
colorFromRGB(120, 252, 80),
colorFromRGB(8, 32, 16),
colorFromRGB(16, 64, 32),
colorFromRGB(32, 96, 56),
colorFromRGB(40, 128, 72),
colorFromRGB(48, 160, 96),
colorFromRGB(64, 192, 112),
colorFromRGB(72, 224, 128),
colorFromRGB(80, 252, 152),
colorFromRGB(8, 32, 24),
colorFromRGB(16, 64, 56),
colorFromRGB(32, 96, 88),
colorFromRGB(40, 128, 120),
colorFromRGB(48, 160, 152),
colorFromRGB(64, 192, 184),
colorFromRGB(72, 224, 216),
colorFromRGB(80, 252, 248),
colorFromRGB(8, 16, 32),
colorFromRGB(16, 36, 64),
colorFromRGB(32, 56, 96),
colorFromRGB(40, 76, 128),
colorFromRGB(48, 96, 160),
colorFromRGB(64, 112, 192),
colorFromRGB(72, 132, 224),
colorFromRGB(80, 152, 248),
colorFromRGB(8, 8, 32),
colorFromRGB(24, 20, 64),
colorFromRGB(40, 32, 96),
colorFromRGB(56, 40, 128),
colorFromRGB(72, 52, 160),
colorFromRGB(88, 64, 192),
colorFromRGB(96, 72, 224),
colorFromRGB(112, 84, 248),
colorFromRGB(24, 8, 32),
colorFromRGB(48, 20, 64),
colorFromRGB(80, 32, 96),
colorFromRGB(104, 40, 128),
colorFromRGB(136, 52, 160),
colorFromRGB(160, 64, 192),
colorFromRGB(192, 72, 224),
colorFromRGB(216, 84, 248),
colorFromRGB(32, 8, 16),
colorFromRGB(64, 20, 40),
colorFromRGB(96, 32, 64),
colorFromRGB(128, 40, 88),
colorFromRGB(160, 52, 112),
colorFromRGB(192, 64, 136),
colorFromRGB(224, 72, 160),
colorFromRGB(248, 84, 184),
colorFromRGB(32, 0, 0),
colorFromRGB(64, 0, 0),
colorFromRGB(96, 0, 0),
colorFromRGB(128, 0, 0),
colorFromRGB(160, 0, 0),
colorFromRGB(192, 0, 0),
colorFromRGB(224, 0, 0),
colorFromRGB(248, 0, 0),
colorFromRGB(32, 16, 0),
colorFromRGB(64, 32, 0),
colorFromRGB(96, 48, 0),
colorFromRGB(128, 68, 0),
colorFromRGB(160, 84, 0),
colorFromRGB(192, 100, 0),
colorFromRGB(224, 120, 0),
colorFromRGB(248, 136, 0),
colorFromRGB(24, 32, 0),
colorFromRGB(56, 64, 0),
colorFromRGB(88, 96, 0),
colorFromRGB(112, 128, 0),
colorFromRGB(144, 160, 0),
colorFromRGB(176, 192, 0),
colorFromRGB(200, 224, 0),
colorFromRGB(232, 252, 0),
colorFromRGB(8, 32, 0),
colorFromRGB(24, 64, 0),
colorFromRGB(32, 96, 0),
colorFromRGB(48, 128, 0),
colorFromRGB(56, 160, 0),
colorFromRGB(72, 192, 0),
colorFromRGB(80, 224, 0),
colorFromRGB(96, 252, 0),
colorFromRGB(0, 32, 0),
colorFromRGB(0, 64, 8),
colorFromRGB(0, 96, 8),
colorFromRGB(0, 128, 16),
colorFromRGB(0, 160, 24),
colorFromRGB(0, 192, 24),
colorFromRGB(0, 224, 32),
colorFromRGB(0, 252, 40),
colorFromRGB(0, 32, 16),
colorFromRGB(0, 64, 40),
colorFromRGB(0, 96, 64),
colorFromRGB(0, 128, 88),
colorFromRGB(0, 160, 112),
colorFromRGB(0, 192, 128),
colorFromRGB(0, 224, 152),
colorFromRGB(0, 252, 176),
colorFromRGB(0, 20, 32),
colorFromRGB(0, 44, 64),
colorFromRGB(0, 68, 96),
colorFromRGB(0, 92, 128),
colorFromRGB(0, 116, 160),
colorFromRGB(0, 140, 192),
colorFromRGB(0, 160, 224),
colorFromRGB(0, 184, 248),
colorFromRGB(0, 4, 32),
colorFromRGB(0, 12, 64),
colorFromRGB(0, 16, 96),
colorFromRGB(0, 24, 128),
colorFromRGB(0, 28, 160),
colorFromRGB(0, 36, 192),
colorFromRGB(0, 40, 224),
colorFromRGB(0, 48, 248),
colorFromRGB(8, 0, 32),
colorFromRGB(16, 0, 64),
colorFromRGB(32, 0, 96),
colorFromRGB(40, 0, 128),
colorFromRGB(56, 0, 160),
colorFromRGB(64, 0, 192),
colorFromRGB(72, 0, 224),
colorFromRGB(88, 0, 248),
colorFromRGB(24, 0, 32),
colorFromRGB(56, 0, 64),
colorFromRGB(80, 0, 96),
colorFromRGB(112, 0, 128),
colorFromRGB(136, 0, 160),
colorFromRGB(168, 0, 192),
colorFromRGB(200, 0, 224),
colorFromRGB(224, 0, 248),
colorFromRGB(32, 0, 16),
colorFromRGB(64, 0, 32),
colorFromRGB(96, 0, 48),
colorFromRGB(128, 0, 72),
colorFromRGB(160, 0, 88),
colorFromRGB(192, 0, 104),
colorFromRGB(224, 0, 120),
colorFromRGB(248, 0, 136),
};
<file_sep>#pragma once
struct Item {
const char* name;
s32 price = 1000;
s32 addHP = 0;
f32 mulHP = 1;
f32 regHP = 0;
f32 addDmg = 0;
f32 mulDmg = 1;
f32 mulFireError = 1;
f32 addShield = 0;
f32 mulShield = 1;
s32 addPod = 0;
s32 addFireRate = 0;
};
inline constexpr Item items[] = {
{
.name = "Health Booster",
.price = 500,
.addHP = 50
},
{
.name = "Health Booster+",
.price = 750,
.addHP = 70
},
{
.name = "Health Regen",
.price = 1000,
.regHP = f32(1.0f/30.0f)
},
{
.name = "Cannon Scope",
.price = 800,
.mulFireError = f32(0.8)
},
{
.name = "Cannon Scope+",
.price = 1200,
.mulFireError = f32(0.7)
},
{
.name = "Rapid Fire",
.price = 400,
.addFireRate = -20
},
{
.name = "Rapid Fire+",
.price = 800,
.addFireRate = -50
},
{
.name = "Shield Booster",
.price = 250,
.addShield = 50
},
{
.name = "Shield Booster+",
.price = 450,
.addShield = 100
},
{
.name = "Shield Ex",
.price = 1000,
.mulShield = 2
},
{
.name = "Pod slot",
.price = 2000,
.addPod = 1
},
{
.name = "Pod slot 2",
.price = 3000,
.addPod = 2
},
{
.name = "Pod slot 4",
.price = 4000,
.addPod = 4
}
};
inline constexpr u32 itemCount = ARRAY_LENGTH(items);
<file_sep>#pragma once
#include <Femto>
#include <layers/Tiles.hpp>
#include "../img-src/bg.h"
/*
class Background : public Graphics::layer::Tiles<64, 64> {
public:
Background() :
Graphics::layer::Tiles<64, 64>(Graphics::layer::TileSource{this})
{}
using Tiles<64, 64>::operator();
s32 X, Y, oldY, oldX;
Graphics::layer::TileCopy operator () (s32 x, s32 y) {
if (y != Y) {
X = oldX = x;
Y = oldY = (y & 0x3F) * 64;
}
return {this};
}
void operator () (u16* line, s32 x, s32 y, u32 width) {
auto bmp = reinterpret_cast<const u16*>(bg + 2);
if (y != oldY) {
oldY = y;
X = oldX;
}
auto overlay = (bmp[Y + (X++ & 0x3F)] & 0xF7DF) >> 1; // ~0x8410;
bmp += y * width + x + (width - x);
line += width - x;
for( s32 i = -width + x; i < 0; ++i ){
line[i] = ((bmp[i] & 0xF7DF) >> 1) + overlay;
}
}
};
*/
class Background {
public:
s32 gy, gx;
const u16* tile = reinterpret_cast<const u16*>(bg + 2);
void init(const u8* tile){
gy = round(-Graphics::camera.y);
gx = round(Graphics::camera.x);
this->tile = reinterpret_cast<const u16*>(tile + 2);
}
void operator () (u16* line, s32 y) {
y -= gy;
auto overlay = &tile[y & (63 << 6)];
auto bmp = &tile[(y & 63) * 64];
line += screenWidth;
s32 x = gx;
for (s32 i = -screenWidth; i < 0;) {
line[i++] = bmp[x&63] + overlay[(x >> 6)&63]; ++x;
line[i++] = bmp[x&63] + overlay[(x >> 6)&63]; ++x;
line[i++] = bmp[x&63] + overlay[(x >> 6)&63]; ++x;
line[i++] = bmp[x&63] + overlay[(x >> 6)&63]; ++x;
}
}
};
<file_sep>#pragma once
#include <Femto>
#include "../meshes/BasePod.h"
#include "../meshes/Pod2.h"
#include "../meshes/Pod3.h"
#include "../meshes/Pod4.h"
#include "../meshes/Pod5.h"
#include "../meshes/Pod6.h"
struct Stats {
const u8* mesh;
const char* name;
u32 boostMax;
f32 thrust;
f32 boostThrust;
u32 maxHP;
f32 turnRate;
f32 grip;
};
constexpr const Stats shipStats[] = {
{
.mesh=BasePod,
.name="Seneus",
.boostMax=60,
.thrust=f32(170.0f),
.boostThrust=f32(250.0f),
.maxHP=100,
.turnRate=f32(16.0f),
.grip=f32(1.0f)
}, {
.mesh=Pod2,
.name="Mazion",
.boostMax=80,
.thrust=f32(190.0f),
.boostThrust=f32(270.0f),
.maxHP=100,
.turnRate=f32(15.0f),
.grip=f32(1.0f)
}, {
.mesh=Pod3,
.name="Atus",
.boostMax=60,
.thrust=f32(170.0f),
.boostThrust=f32(250.0f),
.maxHP=100,
.turnRate=f32(16.0f),
.grip=f32(1.0f)
}, {
.mesh=Pod4,
.name="Baanella",
.boostMax=60,
.thrust=f32(170.0f),
.boostThrust=f32(250.0f),
.maxHP=100,
.turnRate=f32(16.0f),
.grip=f32(1.0f)
}, {
.mesh=Pod5,
.name="Tashtronia",
.boostMax=60,
.thrust=f32(170.0f),
.boostThrust=f32(250.0f),
.maxHP=100,
.turnRate=f32(16.0f),
.grip=f32(1.0f)
}, {
.mesh=Pod6,
.name="Diaronia",
.boostMax=60,
.thrust=f32(170.0f),
.boostThrust=f32(250.0f),
.maxHP=100,
.turnRate=f32(16.0f),
.grip=f32(1.0f)
},
};
constexpr const u32 shipStatsCount = sizeof(shipStats) / sizeof(shipStats[0]);
<file_sep>#pragma once
#include <Femto>
inline u32 frame;
class Particles {
public:
static inline constexpr u32 maxParticles = 50;
static inline constexpr u32 indexWidth = screenWidth / 32 + 1;
static inline constexpr u16 color = 0XECA6; // colorFromRGB(0x774611);
enum class Shape : uint8_t {
Smoke,
BigSmoke,
Dot,
BigCircle,
Circle,
Line,
Bomb,
Shield
} shape;
struct Particle : public Point2D {
s16 vx, vy;
u8 mask, ttl, data;
Shape shape;
} buffer[maxParticles];
static inline u32 index[screenHeight][indexWidth];
u32 ringHead = 0, ringTail = 0;
u32 inc(u32& i){
u32 old = i++;
if (i == maxParticles) i = 0;
return old;
}
void purge() {
ringHead = ringTail = 0;
}
void insert(const Particle& p, s32 offset = 0) {
auto& b = buffer[inc(ringHead)];
b = p;
b.x += s24q8ToF32(p.vx) * offset;
b.y += s24q8ToF32(p.vy) * offset;
if (ringHead == ringTail) {
inc(ringTail);
}
}
static void clear() {
for (u32 y = 0; y < screenHeight; ++y) {
for(u32 x = 0; x < indexWidth; ++x) {
index[y][x] = 0;
}
}
}
Particle* find(const Point2D& p, u32 mask, f32 radius) {
u32 age = 0;
for( u32 current = ringTail; current != ringHead; inc(current)) {
auto &c = buffer[current];
age++;
if (!(c.mask & mask))
continue;
auto sum = radius;
switch(c.shape){
case Shape::Dot: sum += 1; break;
case Shape::Circle: sum += 3; break;
case Shape::BigCircle: sum += 6; break;
case Shape::Shield: sum += 20; break;
case Shape::Bomb:
if (c.ttl < 60) {
sum += c.ttl;
}
break;
case Shape::Smoke: sum += (age >> 4) + 1; break;
case Shape::BigSmoke: sum += (age >> 3) + 1; break;
case Shape::Line: sum += 1; break;
}
if (sum != radius && (c - p).distanceCheck(sum))
return &c;
}
return nullptr;
}
void draw(Particle&& p, u32 age) {
s32 prevY = round(p.y - Graphics::camera.y);
s32 prevX = round(p.x - Graphics::camera.x);
p.x += s24q8ToF32(p.vx);
p.y += s24q8ToF32(p.vy);
s32 y = round(p.y - Graphics::camera.y);
s32 x = round(p.x - Graphics::camera.x);
if (u32(x) >= screenWidth || u32(y) >= screenHeight)
return;
auto shape = p.shape;
u32 radius = 0;
u32 stride = 1;
switch(shape){
case Shape::Dot: break;
case Shape::Circle: radius = 3; break;
case Shape::BigCircle: radius = 6; shape = Shape::Circle; break;
case Shape::Shield: stride = 2; radius = 20; shape = Shape::Circle; break;
case Shape::Bomb:
if (p.ttl < 60) {
radius = p.ttl += 7;
shape = Shape::Circle;
}
break;
case Shape::Smoke: radius = (age >> 4) + 1; shape = Shape::Circle; break;
case Shape::BigSmoke: radius = (age >> 3) + 1; shape = Shape::Circle; break;
case Shape::Line: radius = 1; break;
}
s32 sy = std::max<s32>(y - radius, 0);
s32 ey = std::min<s32>(screenHeight, sy + radius*2 + 1);
s32 sx = std::max<s32>(x - radius, 0);
s32 ex = std::min<s32>(screenWidth, sx + radius*2 + 1);
if (shape == Shape::Dot && !p.ttl) {
} else if (shape == Shape::Circle) {
radius = radius * radius;
for (s32 i = sy; i < ey; i += stride) {
for (s32 j = sx; j < ex; j += stride) {
u32 d = (y - i) * (y - i) + (x - j) * (x - j);
if (d <= radius) {
s32 w = j >> 5, b = j & 0x1F;
index[i][w] |= 1 << b;
}
}
}
} else if (shape == Shape::Line || shape == Shape::Dot) {
if (shape == Shape::Dot) {
p.ttl--;
} else {
for (s32 i = sy; i < ey; ++i) {
for (s32 j = sx; j < ex; ++j) {
if (u32(j) < screenWidth && u32(i) < screenHeight) {
s32 w = j >> 5, b = j & 0x1F;
index[i][w] |= 1 << b;
}
}
}
}
if (y > prevY) {
s32 t = prevY;
prevY = y;
y = t;
t = prevX;
prevX = x;
x = t;
}
s32 dy = prevY - y;
s32 dx = prevX - x;
s32 step = x < prevX ? 1 : -1;
if (dy > abs(dx)) {
s32 error = std::abs(dx << 15) / dy;
for (s32 i = y; i < prevY; ++i) {
if (u32(x) < screenWidth && u32(i) < screenHeight) {
s32 w = x >> 5, b = x & 0x1F;
index[i][w] |= 1 << b;
}
if ((((i - 1 - prevY) * u32(error) + (1<<14)) >> 15) != (((i - prevY) * u32(error) + (1<<14)) >> 15)) {
x += step;
}
}
} else if (dx) {
s32 error = (dy << 15) / std::abs(dx);
s32 total = std::abs(dx);
for (s32 i = y; i <= prevY; ++i) {
s32 acc = error * total;
s32 end = (acc + (1<<14)) >> 15;
for (; total && ((acc + (1<<14)) >> 15) == end; acc -= error){
total--;
s32 cx = x;
x += step;
if (u32(cx) < screenWidth && u32(i) < screenHeight) {
s32 w = cx >> 5, b = cx & 0x1F;
index[i][w] |= 1 << b;
};
}
}
}
}
}
void update(){
u32 age = 0;
for( u32 current = ringTail; current != ringHead; inc(current)) {
draw(std::move(buffer[current]), ++age);
}
}
void operator () (u16* line, u32 y) {
if (y == 0) update();
for (u32 w = 0; w < indexWidth; ++w) {
u32 c = index[y][w];
if (!c) continue;
u32 x = w << 5;
for (u32 b = 0; b <= 0x1F; ++b, ++x) {
if (c & (1 << b))
line[x] += color;
}
}
}
};
<file_sep>#pragma once
#include <Femto>
#include <File>
class Settings {
public:
static inline bool autoAccelerate = true;
static inline char name[32] = {'P', 'l', 'a', 'y', 'e', 'r', 0};
static inline u32 pod = 0;
static inline u32 color = 0;
static bool load();
};
<file_sep>
#pragma once
#include "Femto"
namespace Graphics {
inline constexpr u16 generalPalette[] = {
colorFromRGB(0, 0, 0),
colorFromRGB(1, 1, 1),
colorFromRGB(2, 2, 2),
colorFromRGB(3, 3, 3),
colorFromRGB(4, 4, 4),
colorFromRGB(5, 5, 5),
colorFromRGB(6, 6, 6),
colorFromRGB(7, 7, 7),
colorFromRGB(8, 8, 8),
colorFromRGB(9, 9, 9),
colorFromRGB(10, 10, 10),
colorFromRGB(11, 11, 11),
colorFromRGB(12, 12, 12),
colorFromRGB(13, 13, 13),
colorFromRGB(14, 14, 14),
colorFromRGB(15, 15, 15),
colorFromRGB(16, 16, 16),
colorFromRGB(17, 17, 17),
colorFromRGB(18, 18, 18),
colorFromRGB(19, 19, 19),
colorFromRGB(20, 20, 20),
colorFromRGB(21, 21, 21),
colorFromRGB(22, 22, 22),
colorFromRGB(23, 23, 23),
colorFromRGB(24, 24, 24),
colorFromRGB(25, 25, 25),
colorFromRGB(26, 26, 26),
colorFromRGB(27, 27, 27),
colorFromRGB(28, 28, 28),
colorFromRGB(29, 29, 29),
colorFromRGB(30, 30, 30),
colorFromRGB(31, 31, 31),
colorFromRGB(32, 32, 32),
colorFromRGB(33, 33, 33),
colorFromRGB(34, 34, 34),
colorFromRGB(35, 35, 35),
colorFromRGB(36, 36, 36),
colorFromRGB(37, 37, 37),
colorFromRGB(38, 38, 38),
colorFromRGB(39, 39, 39),
colorFromRGB(40, 40, 40),
colorFromRGB(41, 41, 41),
colorFromRGB(42, 42, 42),
colorFromRGB(43, 43, 43),
colorFromRGB(44, 44, 44),
colorFromRGB(45, 45, 45),
colorFromRGB(46, 46, 46),
colorFromRGB(47, 47, 47),
colorFromRGB(48, 48, 48),
colorFromRGB(49, 49, 49),
colorFromRGB(50, 50, 50),
colorFromRGB(51, 51, 51),
colorFromRGB(52, 52, 52),
colorFromRGB(53, 53, 53),
colorFromRGB(54, 54, 54),
colorFromRGB(55, 55, 55),
colorFromRGB(56, 56, 56),
colorFromRGB(57, 57, 57),
colorFromRGB(58, 58, 58),
colorFromRGB(59, 59, 59),
colorFromRGB(60, 60, 60),
colorFromRGB(61, 61, 61),
colorFromRGB(62, 62, 62),
colorFromRGB(63, 63, 63),
colorFromRGB(64, 64, 64),
colorFromRGB(65, 65, 65),
colorFromRGB(66, 66, 66),
colorFromRGB(67, 67, 67),
colorFromRGB(68, 68, 68),
colorFromRGB(69, 69, 69),
colorFromRGB(70, 70, 70),
colorFromRGB(71, 71, 71),
colorFromRGB(72, 72, 72),
colorFromRGB(73, 73, 73),
colorFromRGB(74, 74, 74),
colorFromRGB(75, 75, 75),
colorFromRGB(76, 76, 76),
colorFromRGB(77, 77, 77),
colorFromRGB(78, 78, 78),
colorFromRGB(79, 79, 79),
colorFromRGB(80, 80, 80),
colorFromRGB(81, 81, 81),
colorFromRGB(82, 82, 82),
colorFromRGB(83, 83, 83),
colorFromRGB(84, 84, 84),
colorFromRGB(85, 85, 85),
colorFromRGB(86, 86, 86),
colorFromRGB(87, 87, 87),
colorFromRGB(88, 88, 88),
colorFromRGB(89, 89, 89),
colorFromRGB(90, 90, 90),
colorFromRGB(91, 91, 91),
colorFromRGB(92, 92, 92),
colorFromRGB(93, 93, 93),
colorFromRGB(94, 94, 94),
colorFromRGB(95, 95, 95),
colorFromRGB(96, 96, 96),
colorFromRGB(97, 97, 97),
colorFromRGB(98, 98, 98),
colorFromRGB(99, 99, 99),
colorFromRGB(100, 100, 100),
colorFromRGB(101, 101, 101),
colorFromRGB(102, 102, 102),
colorFromRGB(103, 103, 103),
colorFromRGB(104, 104, 104),
colorFromRGB(105, 105, 105),
colorFromRGB(106, 106, 106),
colorFromRGB(107, 107, 107),
colorFromRGB(108, 108, 108),
colorFromRGB(109, 109, 109),
colorFromRGB(110, 110, 110),
colorFromRGB(111, 111, 111),
colorFromRGB(112, 112, 112),
colorFromRGB(113, 113, 113),
colorFromRGB(114, 114, 114),
colorFromRGB(115, 115, 115),
colorFromRGB(116, 116, 116),
colorFromRGB(117, 117, 117),
colorFromRGB(118, 118, 118),
colorFromRGB(119, 119, 119),
colorFromRGB(120, 120, 120),
colorFromRGB(121, 121, 121),
colorFromRGB(122, 122, 122),
colorFromRGB(123, 123, 123),
colorFromRGB(124, 124, 124),
colorFromRGB(125, 125, 125),
colorFromRGB(126, 126, 126),
colorFromRGB(127, 127, 127),
colorFromRGB(128, 128, 128),
colorFromRGB(129, 129, 129),
colorFromRGB(130, 130, 130),
colorFromRGB(131, 131, 131),
colorFromRGB(132, 132, 132),
colorFromRGB(133, 133, 133),
colorFromRGB(134, 134, 134),
colorFromRGB(135, 135, 135),
colorFromRGB(136, 136, 136),
colorFromRGB(137, 137, 137),
colorFromRGB(138, 138, 138),
colorFromRGB(139, 139, 139),
colorFromRGB(140, 140, 140),
colorFromRGB(141, 141, 141),
colorFromRGB(142, 142, 142),
colorFromRGB(143, 143, 143),
colorFromRGB(144, 144, 144),
colorFromRGB(145, 145, 145),
colorFromRGB(146, 146, 146),
colorFromRGB(147, 147, 147),
colorFromRGB(148, 148, 148),
colorFromRGB(149, 149, 149),
colorFromRGB(150, 150, 150),
colorFromRGB(151, 151, 151),
colorFromRGB(152, 152, 152),
colorFromRGB(153, 153, 153),
colorFromRGB(154, 154, 154),
colorFromRGB(155, 155, 155),
colorFromRGB(156, 156, 156),
colorFromRGB(157, 157, 157),
colorFromRGB(158, 158, 158),
colorFromRGB(159, 159, 159),
colorFromRGB(160, 160, 160),
colorFromRGB(161, 161, 161),
colorFromRGB(162, 162, 162),
colorFromRGB(163, 163, 163),
colorFromRGB(164, 164, 164),
colorFromRGB(165, 165, 165),
colorFromRGB(166, 166, 166),
colorFromRGB(167, 167, 167),
colorFromRGB(168, 168, 168),
colorFromRGB(169, 169, 169),
colorFromRGB(170, 170, 170),
colorFromRGB(171, 171, 171),
colorFromRGB(172, 172, 172),
colorFromRGB(173, 173, 173),
colorFromRGB(174, 174, 174),
colorFromRGB(175, 175, 175),
colorFromRGB(176, 176, 176),
colorFromRGB(177, 177, 177),
colorFromRGB(178, 178, 178),
colorFromRGB(179, 179, 179),
colorFromRGB(180, 180, 180),
colorFromRGB(181, 181, 181),
colorFromRGB(182, 182, 182),
colorFromRGB(183, 183, 183),
colorFromRGB(184, 184, 184),
colorFromRGB(185, 185, 185),
colorFromRGB(186, 186, 186),
colorFromRGB(187, 187, 187),
colorFromRGB(188, 188, 188),
colorFromRGB(189, 189, 189),
colorFromRGB(190, 190, 190),
colorFromRGB(191, 191, 191),
colorFromRGB(192, 192, 192),
colorFromRGB(193, 193, 193),
colorFromRGB(194, 194, 194),
colorFromRGB(195, 195, 195),
colorFromRGB(196, 196, 196),
colorFromRGB(197, 197, 197),
colorFromRGB(198, 198, 198),
colorFromRGB(199, 199, 199),
colorFromRGB(200, 200, 200),
colorFromRGB(201, 201, 201),
colorFromRGB(202, 202, 202),
colorFromRGB(203, 203, 203),
colorFromRGB(204, 204, 204),
colorFromRGB(205, 205, 205),
colorFromRGB(206, 206, 206),
colorFromRGB(207, 207, 207),
colorFromRGB(208, 208, 208),
colorFromRGB(209, 209, 209),
colorFromRGB(210, 210, 210),
colorFromRGB(211, 211, 211),
colorFromRGB(212, 212, 212),
colorFromRGB(213, 213, 213),
colorFromRGB(214, 214, 214),
colorFromRGB(215, 215, 215),
colorFromRGB(216, 216, 216),
colorFromRGB(217, 217, 217),
colorFromRGB(218, 218, 218),
colorFromRGB(219, 219, 219),
colorFromRGB(220, 220, 220),
colorFromRGB(221, 221, 221),
colorFromRGB(222, 222, 222),
colorFromRGB(223, 223, 223),
colorFromRGB(224, 224, 224),
colorFromRGB(225, 225, 225),
colorFromRGB(226, 226, 226),
colorFromRGB(227, 227, 227),
colorFromRGB(228, 228, 228),
colorFromRGB(229, 229, 229),
colorFromRGB(230, 230, 230),
colorFromRGB(231, 231, 231),
colorFromRGB(232, 232, 232),
colorFromRGB(233, 233, 233),
colorFromRGB(234, 234, 234),
colorFromRGB(235, 235, 235),
colorFromRGB(236, 236, 236),
colorFromRGB(237, 237, 237),
colorFromRGB(238, 238, 238),
colorFromRGB(239, 239, 239),
colorFromRGB(240, 240, 240),
colorFromRGB(241, 241, 241),
colorFromRGB(242, 242, 242),
colorFromRGB(243, 243, 243),
colorFromRGB(244, 244, 244),
colorFromRGB(245, 245, 245),
colorFromRGB(246, 246, 246),
colorFromRGB(247, 247, 247),
colorFromRGB(248, 248, 248),
colorFromRGB(249, 249, 249),
colorFromRGB(250, 250, 250),
colorFromRGB(251, 251, 251),
colorFromRGB(252, 252, 252),
colorFromRGB(253, 253, 253),
colorFromRGB(254, 254, 254),
colorFromRGB(255, 255, 255)
};
}
<file_sep>#pragma once
#include <Femto>
#include "../img-src/Gauge.h"
class BoostLayer {
public:
static inline u32 level = 0x7C;
void operator () (u16* line, s32 y) {
y -= screenHeight - Gauge[1];
if (y < 0)
return;
auto bmp = Gauge + 2 + y * Gauge[0];
line += screenWidth - Gauge[0];
s32 i = 0;
for (; i < Gauge[0]; ++i) {
if (bmp[i])
break;
}
for (; i < Gauge[0]; ++i) {
u8 c = bmp[i];
if (c && c <= level)
line[i] = c >> 3;
}
}
};
<file_sep>#pragma once
#include <Femto>
#include <LibProfiler>
#include <layers/Tiles.hpp>
#include "../img-src/map1.h"
#include "../img-src/map1h.h"
#include "miloslav.h"
#include "ztables.h"
template<u32 _mapWidth, u32 _mapHeight, u32 _maxDrawDist = 80>
class Terrain {
public:
static inline constexpr const u32 mapWidth = _mapWidth;
static inline constexpr const u32 mapHeight = _mapHeight;
static inline constexpr const u32 widthMask = mapWidth - 1;
static inline constexpr const u32 heightMask = mapHeight - 1;
static inline constexpr const s32 horizon = 50 << 8;
static inline constexpr const u32 maxDrawDist = _maxDrawDist;
u32 shadowMap[(mapWidth/32)*mapHeight];
const u8* heightmap = map1h + 2;
const u16* palette = map1;
template<s32 d>
static f32 relative(f32 c, f32 r) {
bool cn = c < 0;
bool rn = r < 0;
if (cn) c = -c;
if (rn) r = -r;
c = s24q8ToF32((f32ToS24q8(c) % (d << 8)));
r = s24q8ToF32((f32ToS24q8(r) % (d << 8)));
if (cn) c = -c;
if (rn) r = -r;
f32 m = c - r;
if (m >= d/2) c -= d;
else if(m < -d/2) c += d;
return c;
}
static Point2D relative(Point2D c, const Point2D& r) {
c.x = relative<mapWidth>(c.x, r.x);
c.y = relative<mapHeight>(c.y, r.y);
return c;
}
static Point3D relative(Point3D c, const Point3D& r) {
c.x = relative<mapWidth>(c.x, r.x);
c.z = relative<mapHeight>(c.z, r.z);
return c;
}
void clearShadows() {
PROFILER;
for (u32 i = 0; i < (mapWidth/32)*mapHeight; ++i)
shadowMap[i] = 0;
}
void plotShadow(s32 x, s32 y, s32 size){
PROFILER;
x = -x;
y = -y;
s32 rad = size / 2 - (size & 1);
s32 sy = y - rad;
s32 sx = x - rad;
rad *= rad;
for(s32 iy = sy; iy < sy+size; ++iy){
for(s32 ix = sx; ix < sx+size; ++ix){
if ((ix - x)*(ix - x) + (iy - y)*(iy - y) <= rad) {
shadowMap[((ix & widthMask) >> 5) + (iy & heightMask) * (mapWidth >> 5)] |= 1 << (ix & 0x1F);
}
}
}
}
s32 getHeightAtPoint(const Point2D& point) {
PROFILER;
s32 sgx = (f32ToS24q8(-point.x) + (1<<7));
s32 sgy = (f32ToS24q8(-point.y) + (1<<7));
return heightmap[((sgx >> 8) & widthMask) + ((sgy >> 8) & heightMask) * mapWidth];
}
Point3D getNormalAtPoint(const Point2D point) {
s32 Ax = (f32ToS24q8(-point.x) + (1<<7)) >> 8;
s32 Az = ((f32ToS24q8(-point.y) + (1<<7)) >> 8) + 2;
s32 Ay = heightmap[(Ax & widthMask) + (Az & heightMask) * mapWidth];
s32 Bx = Ax - 3;
s32 Bz = Az - 4;
s32 By = heightmap[(Bx & widthMask) + (Bz & heightMask) * mapWidth];
s32 Cx = Ax + 3;
s32 Cz = Az - 4;
s32 Cy = heightmap[(Cx & widthMask) + (Cz & heightMask) * mapWidth];
return {
(Ay - Cy) * (Bz - Cz) - (Az - Cz) * (By - Cy),
(Az - Cz) * (Bx - Cx) - (Ax - Cx) * (Bz - Cz),
(Ax - Cx) * (By - Cy) - (Ay - Cy) * (Bx - Cx)
};
}
bool isObstructed(Point3D target) {
// if (target.x - camera3D.position.x >= 128) target.x = (mapWidth - (target.x - camera3D.position.x));
// if (target.x - camera3D.position.x < -128) target.x = (mapWidth + (target.x - camera3D.position.x));
// if (target.z - camera3D.position.z >= 128) target.z = (mapHeight - (target.z - camera3D.position.z));
// if (target.z - camera3D.position.z < -128) target.z = (mapHeight + (target.z - camera3D.position.z));
// target = relative(target, camera3D.position);
s32 sgx = (f32ToS24q8(-camera3D.position.x) + (1<<7)) << 8;
s32 sgy = (f32ToS24q8(-camera3D.position.z) + (1<<7)) << 8;
s32 height = camera3D.position.y;
s32 prevSampleY = screenWidth;
f32 angle = camera3D.angleTo(target);
Point2D forward{0.0f, -1.0f};
forward.rotateXY(angle);
s32 fx = f32ToS24q8(forward.x);
s32 fy = f32ToS24q8(forward.y);
s32 targetDist = camera3D.distanceTo(target);
for (u32 step = 5; step < maxDrawDist; step++) {
s32 z = ztable[step];
s32 iz = iztable[step];
if ((z >> 8) * (z >> 8) > targetDist)
return false;
s32 px = (fx * z + sgx) >> 16;
s32 py = (fy * z + sgy) >> 16;
// shadowMap[((px & widthMask) >> 5) + (py & heightMask) * (mapWidth >> 5)] |= 1 << (px & 0x1F);
s32 sampleIndex = (px & widthMask) + (py & heightMask) * mapWidth;
s32 sample = heightmap[sampleIndex];
s32 sampleY = ((height - sample) * iz + (horizon + (1 << 7))) >> 8;
if (sampleY < target.y)
return true;
}
return false;
}
void operator () (u16* line, s32 column) {
PROFILER;
s32 sgx = (f32ToS24q8(-camera3D.position.x) + (1<<7)) << 8;
s32 sgy = (f32ToS24q8(-camera3D.position.z) + (1<<7)) << 8;
s32 height = camera3D.position.y;
s32 prevSampleY = screenWidth;
const f32 angle = camera3D.rotation - ((column - s32(screenHeight/2))*(f32(1.0f/(screenHeight*PI/4.0f))));
Point2D forward{0.0f, -1.0f};
forward.rotateXY(angle);
s32 fx = f32ToS24q8(forward.x);
s32 fy = f32ToS24q8(forward.y);
// s32 z = 2560 - 128;
for (u32 step = 0; step < maxDrawDist; step++) {
// z += 128 + step;
s32 z = ztable[step];
s32 iz = iztable[step];
s32 px = (fx * z + sgx) >> 16;
s32 py = (fy * z + sgy) >> 16;
s32 sampleIndex = (px & widthMask) + (py & heightMask) * mapWidth;
s32 sample = heightmap[sampleIndex];
s32 sampleY = ((height - sample) * iz + (horizon + (1 << 7))) >> 8;
if (sampleY >= prevSampleY)
continue;
if (sampleY < 0)
sampleY = 0;
sample |= (shadowMap[((px & widthMask) >> 5) + (py & heightMask) * (mapWidth >> 5)] >> (px & 0x1F)) & 1;
s32 diff = sampleY - prevSampleY;
auto point = line + prevSampleY;
prevSampleY = sampleY;
sample = palette[sample];
#ifdef TARGET_CORTEX_M
diff <<= 1;
__asm__ volatile (
".syntax unified" "\n"
"1:strh %2, [%1, %0] \n"
"adds %0, 2 \n"
"bne 1b \n"
: "+l" (diff)
: "l" (point), "l" (sample)
: "cc"
);
#else
while (diff) {
point[++diff] = sample;
}
#endif
if (sampleY == 0)
return;
}
#ifdef TARGET_CORTEX_M
if (prevSampleY) {
u32 sample = palette[255];
auto point = line + prevSampleY - 1;
prevSampleY = -prevSampleY << 1;
__asm__ volatile (
".syntax unified" "\n"
"1: adds %0, 2 \n"
"strh %2, [%1, %0] \n"
"bne 1b \n"
: "+l" (prevSampleY), "+l" (point)
: "l" (sample)
: "cc"
);
}
#else
for (s32 i = prevSampleY; i;) {
line[--i] = palette[255];
}
#endif
}
};
<file_sep>#pragma once
#include <variant>
#include <donut7x10.hpp>
#include <MonoText.hpp>
#include "Camera3D.h"
#include "Terrain.h"
#include "BoostLayer.h"
/* inline Particles shots; */
using SpriteLayer = Graphics::layer::FastDrawList<10, 5>;
using HUDLayer = Graphics::layer::DrawList<80, fontDonut>;
using Ground = Terrain<256, 256, 70>;
using TextLayer = Graphics::layer::MonoText<fontDonut>;
using GameRenderer = Graphics::Renderer<
Ground,
SpriteLayer,
BoostLayer,
TextLayer
>;
inline GameRenderer* gameRenderer;
inline std::variant<GameRenderer> renderer;
using cAction_t = void (*)(uptr);
inline u32 frame;
inline f32 shake;
inline const c8* streamedEffect = nullptr;
inline u32 effectPriority = 0;
inline char missionText[100];
inline bool ignoreAction = false;
inline void cActionNOP(uptr) {}
inline cAction_t cAction = cActionNOP;
inline uptr cActionArg;
inline const c8* featureCaption;
enum class GameState {
Start,
Logo,
Space,
EnterCutScene,
CutScene
} inline gameState = GameState::Start;
inline s32 backlight = 0, targetBacklight = 255;
void fadeOut();
bool updateEnter(GameState state);
<file_sep>#pragma once
#include <Femto>
#include <cstdint>
#include <cstring>
#include <string_view>
#include "Camera3D.h"
#include "Renderer.h"
#include "meshes.h"
#include "Ghost.h"
#include "Settings.hpp"
constexpr u32 shipCount = 2;
constexpr u32 currentVersion = 3;
struct Recording {
u32 version;
char name[32];
u32 pod;
u32 color;
u32 trackId;
u32 time;
u32 sampleCount;
u8 data[];
};
Recording* const recordingBanks[] = {
#ifdef TARGET_LPC11U68
reinterpret_cast<Recording*>(0x20000000),
reinterpret_cast<Recording*>(0x20004000)
#else
reinterpret_cast<Recording*>(new u8[0x800]),
reinterpret_cast<Recording*>(new u8[0x800])
#endif
};
inline constexpr const u32 maxBankSize = 0x800;
class Ship {
public:
static inline Ship* player = nullptr;
static inline u32 nextUID = 0;
const u32 uid;
Recording* recording;
const Stats* stats;
f32 thrust;
Point3D speed;
Point3D position;
f32 rotation;
f32 rotationSpeed;
u32 HP;
s32 boostMeter;
bool isBoosting;
u32 nextCheckpoint;
static inline u32 lapStart;
static inline u32 lapTime;
static inline u32 startFrame;
u32 bestLap = ~u32{};
Point3D relativePosition;
f32 cameraZ;
f32 skew;
static inline Point2D checkPoints[4];
void init(u32 trackId) {
bestLap = ~u32{};
startFrame = frame;
lapStart = getTimeMicro() / 1000;
nextCheckpoint = 1;
position = Point3D{0,0,0};
speed = Point3D{0,0,0};
thrust = 0;
rotation = PI;
rotationSpeed = 0;
recording->trackId = trackId;
if (isPlayer()) {
recording->sampleCount = 0;
strcpy(recording->name, Settings::name);
recording->pod = Settings::pod % shipStatsCount;
recording->color = Settings::color;
recording->version = currentVersion;
} else if (!loadGhost(trackId, recording, maxBankSize) || recording->version != currentVersion) {
LOG("Invalid recording version: ", recording->version, "\n");
MemOps::set(recording, 0, maxBankSize);
// } else {
// save(5);
}
}
Ship() : uid{nextUID++} {
recording = recordingBanks[uid];
if (!player){
player = this;
}
}
bool isPlayer() {
return this == player;
}
s32 radius() {
return 16;
}
void spawn() {
}
bool isDead() {
return HP <= 0;
}
bool dead() {
if (HP > 0)
return false;
return true;
}
void aiPlayer() {
PROFILER;
u32 prevTS = lapTime >> 8;
f32 w = s24q8ToF32(lapTime - (prevTS << 8));
f32 iw = 1 - w;
Point2D lerp;
Point2D prev, next;
if (recording->sampleCount > 0) {
prevTS %= recording->sampleCount;
prev.x = recording->data[prevTS * 2];
prev.y = recording->data[prevTS * 2 + 1];
u32 nextTS = prevTS + 1;
if (nextTS >= recording->sampleCount)
nextTS -= recording->sampleCount;
next.x = recording->data[nextTS * 2];
next.y = recording->data[nextTS * 2 + 1];
next = Ground::relative(next, prev);
lerp = prev * iw + next * w;
// LOG(prevTS, " x:", s32(lerp.x), " y:", s32(lerp.y), "\n");
} else {
lerp = prev = next = Point2D{0, 0};
}
// Graphics::print("\n\n\nxy:", s32(lerp.x), " x ", s32(lerp.y));
auto oldPosition = position;
position.x = lerp.x;
position.z = lerp.y;
auto newPosition = Ground::relative(position, oldPosition);
auto& terrain = gameRenderer->get<Ground>();
s32 groundHeight = terrain.getHeightAtPoint({position.x, position.z});
isInShade = groundHeight & 1;
position.y = tweenTo(position.y, groundHeight + 20, 2);
if ((oldPosition - newPosition).lengthSquared()) {
f32 newRotation = atan2(next.y - prev.y, next.x - prev.x);
rotation += angleDelta(rotation, newRotation) * f32(0.25f);
}
}
void writeRecordSample() {
PROFILER;
s32 x = position.x;
s32 z = position.z;
if (x == 0 && z == 0 && recording->sampleCount <= 0) {
lapStart = getTimeMicro() / 1000;
startFrame = (frame << 3);
lapTime = 0;
return;
}
if (recording->sampleCount == 0) {
lapStart = getTimeMicro() / 1000;
startFrame = (frame << 3);
lapTime = 0;
}
lapTime = (frame << 3) - startFrame; // getTimeMicro() / 1000 - lapStart;
u32 prevTS = lapTime >> 8;
if (prevTS == recording->sampleCount - 1)
return;
if (reinterpret_cast<uintptr_t>(&recording->data[prevTS * 2 + 1]) >= reinterpret_cast<uintptr_t>(recording) + maxBankSize) {
return;
}
if (x < 0) x = Ground::mapWidth + x;
else if (x >= Ground::mapWidth) x -= Ground::mapWidth;
if (z < 0) z = Ground::mapHeight + z;
else if (z >= Ground::mapHeight) z -= Ground::mapHeight;
if (x < 0) x = 0;
else if (x > 255) x = 255;
if (z < 0) z = 0;
else if (z > 255) z = 255;
// LOG(recording->sampleCount, " x:", x, " y:", z, "\n");
recording->sampleCount++;
recording->data[prevTS * 2] = x;
recording->data[prevTS * 2 + 1] = z;
}
void save(u32 trackId) {
PROFILER;
auto &text = gameRenderer->get<TextLayer>();
u32 lapTime = getTimeMicro()/1000 - lapStart;
u32 s = lapTime / 1000;
u32 ms = lapTime - s * 1000;
text.bindText();
Graphics::clearText();
Graphics::setCursor(0, screenHeight - 80);
Graphics::print(" v.", recording->version, " ");
#if defined(TARGET_LPC11U6X)
Graphics::print(((volatile uint32_t *) 0xE000ED00)[0] != 1947 ? "HW" : "EMU");
#endif
Graphics::print("\n Pod: ", stats->name);
Graphics::setCursor(5, screenHeight - 30);
Graphics::print(recording->name);
Graphics::print("\n Time: ", s, " s ", ms, " ms ");
saveGhost(trackId, recordingBanks[1], maxBankSize);
Graphics::clearText();
delay(1000);
}
void localPlayer() {
PROFILER;
static bool prevRight = false;
static bool prevDown = false;
static bool prevLeft = false;
static bool prevUp = false;
static bool prevB = false;
static u32 timeRight = 0;
static u32 timeDown = 0;
static u32 timeLeft = 0;
static u32 timeUp = 0;
static bool boost = false;
writeRecordSample();
u32 deltaRight = 500;
u32 deltaDown = 500;
u32 deltaLeft = 500;
u32 deltaUp = 500;
f32 targetThrust = stats->thrust;
Graphics::print(nextCheckpoint);
if (isBoosting) {
boostMeter -= frame & 1;
if (boostMeter < 0) boostMeter = 0;
if (boostMeter == 0 && isPressed(Button::Left)) {
} else if (!boostMeter || isPressed(Button::Right)) {
isBoosting = false;
boostMeter = 0;
LOG("Boost end\n");
} else {
targetThrust = stats->boostThrust;
}
} else {
if (isPressed(Button::Left)) {
boostMeter += 2;
if (boostMeter >= stats->boostMax) {
isBoosting = true;
boostMeter = stats->boostMax;
LOG("Boost start\n");
}
} else if (boostMeter > 0) {
boostMeter--;
}
}
BoostLayer::level = boostMeter * 128 / stats->boostMax;
rotationSpeed = tweenTo(rotationSpeed, (isPressed(Button::Up) - isPressed(Button::Down)) * stats->turnRate * (isBoosting ? f32(1.0f) : f32(1.3f)), f32(0.25f));
if (Settings::autoAccelerate) {
if (isPressed(Button::Right)) {
thrust = tweenTo(thrust, f32(-80.0f), 4);
} else {
thrust = tweenTo(thrust, targetThrust, 4 - isBoosting);
}
} else {
if (isPressed(Button::A)) {
thrust = tweenTo(thrust, targetThrust, 4 - isBoosting);
} else if (isPressed(Button::B)) {
thrust = tweenTo(thrust, f32(-80.0f), 4);
}
}
auto& terrain = gameRenderer->get<Ground>();
s32 groundHeight = terrain.getHeightAtPoint({position.x, position.z});
isInShade = groundHeight & 1;
if (groundHeight > position.y)
position.y = groundHeight;
groundHeight += 20;
f32 delta = (groundHeight - position.y) * f32(3.0f);
speed.y += delta;
if (delta > 15) {
auto groundNormal = terrain.getNormalAtPoint({position.x, position.z}).normalize();
f32 w = f32(100.0f) - std::abs(groundNormal.y) * f32(100.0f);
speed += groundNormal * w;
}
if (!(frame&3)) {
Point3D forward{thrust, 0, 0};
forward.rotateXZ(rotation);
speed += forward;
thrust *= f32(0.9f);
}
speed *= f32(0.8f);
position += speed * f32(0.01f);
rotation += rotationSpeed * f32(0.004f);
if (std::abs(f32ToS24q8(rotationSpeed)) < 50) rotationSpeed = 0;
auto rpos = -position.xz();
auto checkpointDelta = Ground::relative(checkPoints[nextCheckpoint], rpos) - rpos;
// if (!checkpointDelta.distanceCheck(128)) {
// checkpointDelta = (checkPoints[nextCheckpoint] - Point2D{
// ((s32(rpos.x) & Ground::widthMask) - Ground::mapWidth),
// ((s32(rpos.y) & Ground::heightMask) - Ground::mapHeight)
// });
// }
if (checkpointDelta.distanceCheck(15)) {
if (nextCheckpoint == 0) {
u32 now = getTimeMicro() / 1000;
if (lapStart) {
recording->time = now - lapStart;
auto other = reinterpret_cast<Recording*>(recordingBanks[1]);
if (!other->sampleCount || recording->time < other->time) {
MemOps::copy(recordingBanks[1], recording, maxBankSize);
recording->sampleCount = 0;
save(recording->trackId);
}
}
lapStart = now;
startFrame = frame << 3;
lapTime = 0;
}
nextCheckpoint = (nextCheckpoint + 1) & 3;
// LOG(uid, "] Next checkpoint: ", nextCheckpoint, "\n");
}
// if (isPlayer() && !(frame & 0xF))
// LOG(nextCheckpoint, " distance: ", s32(checkpointDelta.length()), " @{", s32(rpos.x), ",", s32(rpos.y), "}\n");
}
bool isInShade;
void update(u32 frame){
PROFILER;
stats = &shipStats[recording->pod];
if (isPlayer()) localPlayer();
else aiPlayer();
if (this->position.x > Ground::mapWidth) {
this->position.x -= Ground::mapWidth;
if (isPlayer())
camera3D.position.x -= Ground::mapWidth;
} else if (this->position.x < 0) {
this->position.x += Ground::mapWidth;
if (isPlayer())
camera3D.position.x += Ground::mapWidth;
}
if (this->position.z > Ground::mapHeight) {
this->position.z -= Ground::mapHeight;
if (isPlayer())
camera3D.position.z -= Ground::mapWidth;
} else if (this->position.z < 0) {
this->position.z += Ground::mapHeight;
if (isPlayer())
camera3D.position.z += Ground::mapWidth;
}
// Graphics::setCursor(0, s32(30 + uid * 10));
// Graphics::print(uid, ": ", s32(this->position.x), ", ", s32(this->position.z), " d:", s32(sqrt(f32(camera3D.distanceTo(this->position)))));
auto position = this->position;
auto camPosition = camera3D.position;
relativePosition = Ground::relative(position - camPosition, Point3D{0, 0, 0});
relativePosition.rotateXZ(-camera3D.rotation);
if (relativePosition.z >= 3 && relativePosition.z < Ground::maxDrawDist) {
cameraZ = relativePosition.length();
skew = sin(atan2(-relativePosition.y, relativePosition.z));
s32 fz = (1 << 24) / f32ToS24q8(cameraZ);
relativePosition.x *= s24q8ToF32(fz); // s24q8ToF32(f32ToS24q8(relativePosition.x) * fz);
relativePosition.y *= s24q8ToF32(fz >> 2); // s24q8ToF32(f32ToS24q8(relativePosition.y) * fz);
relativePosition.z = s24q8ToF32(fz);
} else {
cameraZ = 512;
}
}
void postUpdate() {
draw();
}
void draw(){
PROFILER;
if (cameraZ > Ground::maxDrawDist) {
return;
}
if (gameRenderer->get<Ground>().isObstructed({
position.x,
(Ground::horizon >> 8) - relativePosition.y,
position.z
}))
return;
gameRenderer->get<Ground>().plotShadow(position.x + f32(0.5f), position.z + f32(0.5f), 5);
f32 fz = relativePosition.z;// * f32(1.5f);
f32 scale = s24q8ToF32(f32ToS24q8(fz) >> 3);
constexpr const f32 maxScale = f32(1.75f);
bool tooBig = scale > maxScale;
if (tooBig) {
scale = s24q8ToF32(f32ToS24q8(fz) >> 4);
if (scale > maxScale){
// return;
// scale = f32(1.75f);
}
}
constexpr const s32 r = 64;
auto position2D = Point2D{
50 - relativePosition.y,
screenHeight/2 + relativePosition.x
} - (tooBig ? r : r/2);
if (auto bitmap = drawMesh(stats->mesh,
scale,
camera3D.rotation - rotation,
rotationSpeed * f32(0.03f),
recording->color,
skew,
isInShade)) {
if (tooBig) Graphics::draw<true, true>(*bitmap, position2D);
else Graphics::draw<true, false>(*bitmap, position2D);
}
}
static void broadcast(void (Ship::*method)(u32), u32);
} ships[shipCount];
inline void Ship::broadcast(void (Ship::*method)(u32), u32 data) {
PROFILER;
for (u32 i = 0; i < shipCount; ++i) {
(ships[i].*method)(data);
}
}
<file_sep>
#pragma once
inline u16 map1[] = {
colorFromRGB(0x5b7686),
colorFromRGB(0x515e66),
colorFromRGB(0x8091a0),
colorFromRGB(0x707d8b),
colorFromRGB(0xbccde8),
colorFromRGB(0x808d9f),
colorFromRGB(0x94a5b8),
colorFromRGB(0x536068),
colorFromRGB(0x907868),
colorFromRGB(0x624f45),
colorFromRGB(0x5b453b),
colorFromRGB(0x36432a),
colorFromRGB(0x33402c),
colorFromRGB(0x805853),
colorFromRGB(0xa77965),
colorFromRGB(0x8b5957),
colorFromRGB(0xa87868),
colorFromRGB(0x866059),
colorFromRGB(0xab7f73),
colorFromRGB(0x86665c),
colorFromRGB(0x405038),
colorFromRGB(0x43372f),
colorFromRGB(0x533f36),
colorFromRGB(0x48362b),
colorFromRGB(0x533c34),
colorFromRGB(0x4a3730),
colorFromRGB(0x513c39),
colorFromRGB(0x45372d),
colorFromRGB(0x574438),
colorFromRGB(0x46352d),
colorFromRGB(0x514138),
colorFromRGB(0x44322e),
colorFromRGB(0x593d38),
colorFromRGB(0x493532),
colorFromRGB(0x5b4438),
colorFromRGB(0x483932),
colorFromRGB(0x563d37),
colorFromRGB(0x453a2f),
colorFromRGB(0x523f37),
colorFromRGB(0x4a3a33),
colorFromRGB(0x554135),
colorFromRGB(0x48372e),
colorFromRGB(0x564135),
colorFromRGB(0x483a2f),
colorFromRGB(0x534235),
colorFromRGB(0x51392e),
colorFromRGB(0x524435),
colorFromRGB(0x4a3834),
colorFromRGB(0x584035),
colorFromRGB(0x503e31),
colorFromRGB(0x534239),
colorFromRGB(0x4f3c30),
colorFromRGB(0x524038),
colorFromRGB(0x4a3d33),
colorFromRGB(0x5a3f34),
colorFromRGB(0x4d3d31),
colorFromRGB(0x563e3c),
colorFromRGB(0x4e3d34),
colorFromRGB(0x53443b),
colorFromRGB(0x4e3f34),
colorFromRGB(0x5a463b),
colorFromRGB(0x513c36),
colorFromRGB(0x5c3e36),
colorFromRGB(0x553b37),
colorFromRGB(0x594236),
colorFromRGB(0x563b34),
colorFromRGB(0x554337),
colorFromRGB(0x4e3f37),
colorFromRGB(0x594538),
colorFromRGB(0x584234),
colorFromRGB(0x574238),
colorFromRGB(0x594435),
colorFromRGB(0x5a4336),
colorFromRGB(0x573e38),
colorFromRGB(0x594637),
colorFromRGB(0x504336),
colorFromRGB(0x564238),
colorFromRGB(0x524039),
colorFromRGB(0x55403c),
colorFromRGB(0x56443b),
colorFromRGB(0x5d4236),
colorFromRGB(0x5c423b),
colorFromRGB(0x5e483b),
colorFromRGB(0x5c453d),
colorFromRGB(0x533f37),
colorFromRGB(0x5d443a),
colorFromRGB(0x5e3f3c),
colorFromRGB(0x574039),
colorFromRGB(0x54463b),
colorFromRGB(0x5b4336),
colorFromRGB(0x594638),
colorFromRGB(0x5e4638),
colorFromRGB(0x594438),
colorFromRGB(0x5c463d),
colorFromRGB(0x5a443c),
colorFromRGB(0x57413c),
colorFromRGB(0x5b3f3d),
colorFromRGB(0x57483d),
colorFromRGB(0x584339),
colorFromRGB(0x544338),
colorFromRGB(0x604538),
colorFromRGB(0x544537),
colorFromRGB(0x55463c),
colorFromRGB(0x5f483b),
colorFromRGB(0x5c463b),
colorFromRGB(0x5e463c),
colorFromRGB(0x5d4138),
colorFromRGB(0x56493e),
colorFromRGB(0x584738),
colorFromRGB(0x60423a),
colorFromRGB(0x59493d),
colorFromRGB(0x614938),
colorFromRGB(0x58413a),
colorFromRGB(0x5c4439),
colorFromRGB(0x59463f),
colorFromRGB(0x5a493a),
colorFromRGB(0x59443a),
colorFromRGB(0x5f453a),
colorFromRGB(0x5d443d),
colorFromRGB(0x5c483c),
colorFromRGB(0x56463c),
colorFromRGB(0x604139),
colorFromRGB(0x62443a),
colorFromRGB(0x58493f),
colorFromRGB(0x574839),
colorFromRGB(0x5d443d),
colorFromRGB(0x5a483d),
colorFromRGB(0x60413a),
colorFromRGB(0x614538),
colorFromRGB(0x62483b),
colorFromRGB(0x5a4a3e),
colorFromRGB(0x61433d),
colorFromRGB(0x5d463d),
colorFromRGB(0x5b4338),
colorFromRGB(0x5a4238),
colorFromRGB(0x5c4539),
colorFromRGB(0x5a4939),
colorFromRGB(0x62483a),
colorFromRGB(0x604739),
colorFromRGB(0x594240),
colorFromRGB(0x574940),
colorFromRGB(0x5b433c),
colorFromRGB(0x56443e),
colorFromRGB(0x60483d),
colorFromRGB(0x62473d),
colorFromRGB(0x58453a),
colorFromRGB(0x63463f),
colorFromRGB(0x62473a),
colorFromRGB(0x5c4a3d),
colorFromRGB(0x5f453f),
colorFromRGB(0x58433f),
colorFromRGB(0x5d4b3a),
colorFromRGB(0x604b3a),
colorFromRGB(0x584441),
colorFromRGB(0x5d473e),
colorFromRGB(0x60473b),
colorFromRGB(0x63463d),
colorFromRGB(0x64473c),
colorFromRGB(0x5c483b),
colorFromRGB(0x5b4a3b),
colorFromRGB(0x634a3f),
colorFromRGB(0x61433c),
colorFromRGB(0x5d4541),
colorFromRGB(0x60493f),
colorFromRGB(0x5b453b),
colorFromRGB(0x64443c),
colorFromRGB(0x604841),
colorFromRGB(0x60473e),
colorFromRGB(0x5c493c),
colorFromRGB(0x594b3e),
colorFromRGB(0x624841),
colorFromRGB(0x634a42),
colorFromRGB(0x5b4a3a),
colorFromRGB(0x5a493e),
colorFromRGB(0x63473f),
colorFromRGB(0x5e4d3f),
colorFromRGB(0x64453b),
colorFromRGB(0x5d443c),
colorFromRGB(0x634b40),
colorFromRGB(0x614840),
colorFromRGB(0x5f443c),
colorFromRGB(0x594b3b),
colorFromRGB(0x5a4c3a),
colorFromRGB(0x604a3c),
colorFromRGB(0x65453c),
colorFromRGB(0x5a4c3c),
colorFromRGB(0x614441),
colorFromRGB(0x5a483d),
colorFromRGB(0x5c4c3e),
colorFromRGB(0x654c3e),
colorFromRGB(0x604b3e),
colorFromRGB(0x66443b),
colorFromRGB(0x664c42),
colorFromRGB(0x664a3c),
colorFromRGB(0x5a4c3c),
colorFromRGB(0x664641),
colorFromRGB(0x5f4e3c),
colorFromRGB(0x5c453d),
colorFromRGB(0x5e4a3c),
colorFromRGB(0x654640),
colorFromRGB(0x624b3c),
colorFromRGB(0x5d4b3c),
colorFromRGB(0x63473f),
colorFromRGB(0x634841),
colorFromRGB(0x65473c),
colorFromRGB(0x5f4c3f),
colorFromRGB(0x5b493d),
colorFromRGB(0x634841),
colorFromRGB(0x634a44),
colorFromRGB(0x664d3f),
colorFromRGB(0x684544),
colorFromRGB(0x604d3f),
colorFromRGB(0x654642),
colorFromRGB(0x5b453f),
colorFromRGB(0x5c4e43),
colorFromRGB(0x5b4540),
colorFromRGB(0x5e483c),
colorFromRGB(0x5e4643),
colorFromRGB(0x664642),
colorFromRGB(0x5c493e),
colorFromRGB(0x664741),
colorFromRGB(0x5f4c44),
colorFromRGB(0x624e3d),
colorFromRGB(0x604e44),
colorFromRGB(0x634e3f),
colorFromRGB(0x685041),
colorFromRGB(0x674d3c),
colorFromRGB(0x5c4b41),
colorFromRGB(0x5e4d3f),
colorFromRGB(0x614e41),
colorFromRGB(0x664d45),
colorFromRGB(0x614a42),
colorFromRGB(0x674940),
colorFromRGB(0x694e40),
colorFromRGB(0x624741),
colorFromRGB(0x69463d),
colorFromRGB(0x674a42),
colorFromRGB(0x644844),
colorFromRGB(0x694d41),
colorFromRGB(0x5e4643),
colorFromRGB(0x604842),
colorFromRGB(0x684e43),
colorFromRGB(0x644843),
colorFromRGB(0x6a5046),
colorFromRGB(0x6a4a3f),
colorFromRGB(0x684e42),
colorFromRGB(0x694945),
colorFromRGB(0x625040),
colorFromRGB(0x6a4b43),
colorFromRGB(0x654745),
colorFromRGB(0x604e45),
colorFromRGB(0x69473e),
colorFromRGB(0x674c3f),
colorFromRGB(0x5f4941),
colorFromRGB(0x5f4943),
colorFromRGB(0xffdead)
};
<file_sep>let palette;
let textures = {};
APP.getPalette(pal=>{
palette = pal;
let meshes = dir("meshes")
.filter( name=>/\.obj$/i.test(name) )
//.filter( f=>f=="Jet.obj")
.map( name => {
try {
return parseObj(read(`meshes/${name}`), name);
} catch(ex){
APP.error("Error parsing " + name + ex);
}
});
loadTextures(_=>{
meshes.forEach( mesh => {
if (mesh) {
exportMesh(mesh);
}
});
});
});
function loadTextures(cb) {
let count = 0;
for (let fileName in textures) {
let image = textures[fileName];
if (image) continue;
count++;
readImage("meshes/" + fileName)
.then(registerTexture.bind(null, fileName));
log("Loading ", fileName);
}
if (!count)
cb();
function registerTexture(name, data) {
count--;
textures[name] = data;
if (!count)
cb();
}
}
function kv( str ){
return str
.split("\n")
.map(line=>line.trim().split(/\s+/))
.reduce((obj, line)=>{
let cmd = line.shift();
if( cmd.length && cmd != "#"){
(obj[cmd] = obj[cmd] || []).push(line);
obj[cmd.toLowerCase()] = obj[cmd.toLowerCase()] || obj[cmd];
}
return obj;
}, {});
}
function parseObj(str, name){
let mtllib = {};
let cmtl = null;
let mesh = str
.split("\n")
.map(line=>line.trim().split(/\s+/))
.reduce((obj, line)=>{
let cmd = line.shift();
if( cmd == "mtllib" ){
read(`meshes/${line[0]}`)
.split(/\n(?=newmtl )/)
.forEach(str=>{
const mtl = kv(str);
if( mtl.newmtl )
mtllib[mtl.newmtl[0]] = mtl;
if( mtl.map_kd )
textures[mtl.map_kd] = null;
});
} else if( cmd == "usemtl" ) {
cmtl = mtllib[line[0]];
} else if( cmd == "f" ) {
let c = 0;
if( cmtl ){
if( !("c" in cmtl) ){
cmtl.c = RGB(... (cmtl.kd[0].map(x=>255*x)) )|0;
}
c = cmtl.c;
}
line = line.map(p => p.split("/").map(i=>i|0) );
line.c = c;
line.map_kd = cmtl.map_kd;
}
(obj[cmd] = obj[cmd] || []).push(line);
return obj;
}, {});
if(mesh.vn)
mesh.vn = mesh.vn.map(v=>v.map(f=>parseFloat(f)));
mesh.v = mesh.v.map(v=>v.map(f=>parseFloat(f)));
mesh.name = name;
return mesh;
}
function triangulate(faces) {
for (let i = 0; i < faces.length; ++i) {
let face = faces[i];
if (face.length > 3) {
let n = face.splice(0, 3, face[1], face[2]);
n.c = face.c;
n.map_kd = face.map_kd;
faces.push(n);
i--;
}
}
return faces;
}
function exportMesh(mesh){
let minX=0xFFFFFF, maxX = -0xFFFFFF;
let minY=0xFFFFFF, maxY = -0xFFFFFF;
let minZ=0xFFFFFF, maxZ = -0xFFFFFF;
let remap = [];
let cullCount = 0;
mesh.v.forEach(([x, y, z], i)=>{
if( x < minX ) minX = x;
if( x > maxX ) maxX = x;
if( y < minY ) minY = y;
if( y > maxY ) maxY = y;
if( z < minZ ) minZ = z;
if( z > maxZ ) maxZ = z;
});
let scaleX = 127 / (maxX - minX);
let scaleY = 127 / (maxY - minY);
let scaleZ = 127 / (maxZ - minZ);
scaleX = scaleY = scaleZ = Math.min(scaleX, scaleY, scaleZ);
mesh.v.forEach((a, i)=>{
let [x, y, z] = a;
x = ((x - minX) - (maxX - minX)/2) * scaleX;
y = ((y - minY) - (maxY - minY)/2) * scaleY;
z = ((z - minZ) - (maxZ - minZ)/2) * scaleZ;
if( x < -128 || x > 127 ) log("Invalid X: " + x);
if( y < -128 || y > 127 ) log("Invalid Y: " + y);
if( z < -128 || z > 127 ) log("Invalid Z: " + z);
a[0] = x;
a[1] = y;
a[2] = z;
});
mesh.f = triangulate(mesh.f);
mesh.f = mesh.f.filter((p, fi)=>{
const bad = p.findIndex(([i])=>mesh.v[i-1] === undefined);
if( bad != -1 ){
throw `${name} bad index: ${JSON.stringify(p)}[${bad}] on face ${fi}`;
}
let minX=0xFFFFFF, maxX = -0xFFFFFF;
let minY=0xFFFFFF, maxY = -0xFFFFFF;
let minZ=0xFFFFFF, maxZ = -0xFFFFFF;
let any = 0, nyc = 0;
p.y = 0;
p.forEach(([i, vti, vni])=>{
let [x, y, z] = mesh.v[i-1];
if (mesh.vn) {
let [nx, ny, nz] = mesh.vn[vni-1];
any += ny;
nyc++;
}
if( x < minX ) minX = x;
if( x > maxX ) maxX = x;
if( y < minY ) minY = y;
if( y > maxY ) maxY = y;
if( z < minZ ) minZ = z;
if( z > maxZ ) maxZ = z;
p.y += y;
});
if (!mesh.vn) {
let A = mesh.v[p[0][0] - 1];
let B = mesh.v[p[1][0] - 1];
let C = mesh.v[p[2][0] - 1];
any = (A[2] - C[2]) * (B[0] - C[0]) - (A[0] - C[0]) * (B[2] - C[2]);
}
any = 1;
if (any < 0) {
cullCount++;
return false;
}
// if ((maxX - minX) + (maxY - minY) + (maxZ - minZ) < 12){
if (Math.min((maxX - minX), (maxY - minY), (maxZ - minZ)) < 0) {
cullCount++;
return false;
}
p.forEach(([i])=>{
mesh.v[i-1].push(true);
});
return true;
});
let newI = 0;
mesh.v = mesh.v.filter( ([x, y, z, u], i)=>{
remap[i] = newI;
if( !u ) return false;
newI++;
return true;
});
const name = mesh.name.replace(/\.obj/g, '');
if(mesh.f.length > 0xFFFF){
log(`Too many faces in ${name}: ${mesh.f.length}`);
mesh.f.length = 0xFFFF;
return;
}
const vtxSize = 3;
const totalSize = 3 + mesh.f.length * 4 + mesh.v.length * vtxSize;
const bytes = new Uint8ClampedArray(totalSize);
const sbytes = new Int8Array(bytes.buffer);
let p = 0;
bytes[p++] = mesh.f.length >> 8;
bytes[p++] = mesh.f.length & 0xFF;
bytes[p++] = mesh.v.length;
mesh.f = mesh.f.sort((a, b) => a.y - b.y);
let error = false;
mesh.f.forEach(f=>{
let color = f.c|0;
if (textures[f.map_kd]) {
let tex = textures[f.map_kd];
//let u = Math.round(parseFloat(mesh.vt[f[0][1]-1][0]) * tex.width);
//let v = Math.round((1.0 - parseFloat(mesh.vt[f[0][1]-1][1])) * tex.height);
let u = 0, v = 0, sum = 0;
f.forEach(([i, uvi, ni], index)=>{
u += parseFloat(mesh.vt[uvi - 1][0]);
v += 1 - parseFloat(mesh.vt[uvi - 1][1]);
sum++;
});
if (sum > 1) {
u /= sum;
v /= sum;
}
u *= tex.width;
v *= tex.height;
let i = Math.round(u) + Math.round(v) * tex.width;
i *= 4;
let r = tex.data[i++]|0;
let g = tex.data[i++]|0;
let b = tex.data[i++]|0;
color = RGB(r, g, b);
}
bytes[p++] = color|0;
f.forEach(([i, uvi, ni], index)=>{
if( i-1 > 255 && !error ){
error = true;
APP.error(`I overflow in ${name}: ${i} with ${cullCount} culled.`);
}
if( index >= 3 ){
throw new Error(`${name} not triangulated: ${f.length}`);
}
bytes[p++] = remap[i - 1];
});
});
if (error)
return;
let v0 = p;
mesh.v.forEach(([x, y, z], i)=>{
sbytes[p++] = Math.round(x);
sbytes[p++] = Math.round(y);
sbytes[p++] = Math.round(z);
});
if( p != bytes.length )
log(name + " size mismatch:", p, bytes.length);
log("Exporting ", name, " culled ", cullCount, " faces:", mesh.f.length);
write(`meshes/${name[0].toUpperCase() + name.substr(1)}.h`, `constexpr inline u8 ${name}[] = {\n${Array.from(bytes).join(", ")}\n};\n`);
// log(`Wrote: meshes/${name[0].toUpperCase() + name.substr(1)}.bin`)
}
function RGB(r, g, b){
let closestI = 0;
let closestD = 0x7FFFFFFF;
for(let i=1; i<palette.length; i++ ){
let [cr, cg, cb] = palette[i];
cr -= r; cg -= g; cb -= b;
let d = cr*cr + cg*cg + cb*cb;
if( d < closestD ){
closestD = d;
closestI = i;
}
}
return closestI;
}
<file_sep>#pragma once
#include <Femto>
extern const char specialHUDSym[];
inline constexpr s32 HUDSize = 75;
inline constexpr s32 MaxHUD = (HUDSize/2)*(HUDSize/2);
inline void drawHUD(f32 bar1, u32 bar1Color, f32 bar2, u32 bar2Color, u32 life) {
using namespace Graphics;
using namespace _drawListInternal;
static f32 pbar1, pbar2;
if (bar1 > 1)
bar1 = 1;
else if (bar1 < 0)
bar1 = 0;
if (bar2 > 1)
bar2 = 1;
else if (bar2 < 0)
bar2 = 0;
pbar1 -= (pbar1 - bar1) * f32(0.2);
pbar2 -= (pbar2 - bar2) * f32(0.2);
draw_t f = [](u16 *line, Cmd &s, u32 y){
y++;
u32 Y = (y-HUDSize/2) * (y-HUDSize/2);
line += HUDSize + s.x;
s32 i = -HUDSize;
u16 c;
for(; i < 0; ++i){
s32 d = (i+HUDSize/2)*(i+HUDSize/2)+Y;
if (d < MaxHUD)
break;
}
c = ((HUDSize - y) < s.b1) ? reinterpret_cast<uptr>(s.data) : 0;
line[i - 2] = c;
line[i - 1] = c;
u16 bgc = ((y - 1) & 7) == 0 ? colorFromRGB(0x001F00) : colorFromRGB(0x001100);
for(; i < 0; ++i){
s32 d = (i+HUDSize/2)*(i+HUDSize/2)+Y;
if (d >= MaxHUD) break;
line[i] = ((line[i] & 0xF7DF) >> 1) | bgc;
if (((i + 2) & 7) == 0) {
line[i] |= colorFromRGB(0x001F00);
}
}
c = ((HUDSize - y) < s.b2) ? s.s : 0;
line[i++] = c;
line[i] = c;
};
gameRenderer->bind<HUDLayer>();
Cmd cmd = {
.data = reinterpret_cast<void*>((uptr)bar1Color),
.draw = f,
.x = 3,
.y = 3,
.maxY = HUDSize - 2,
.b1 = decl_cast(Cmd::b1, round(pbar1 * HUDSize)),
.b2 = decl_cast(Cmd::b2, round(pbar2 * HUDSize))
};
cmd.s = decl_cast(Cmd::s, bar2Color);
add(cmd);
setCursor(0, 0);
primaryColor = 0xFFFF;
print(getFPS());
}
template<typename Type>
inline void addToHUD(Point2D p, u32 color, Type type) {
gameRenderer->bind<HUDLayer>();
p *= f32(1.0f / 16.0f);
p += HUDSize/2;
if ((p - Point2D{HUDSize/2, HUDSize/2}).lengthSquared() >= MaxHUD)
return;
p += Graphics::camera;
Graphics::setCursor(p);
Graphics::primaryColor = color;
auto sym = specialHUDSym[(int)type];
if (!sym) {
f32 size = type == Type::Boss ? 2 : 1;
p += f32(3);
Graphics::fillRect(p - size, p + size, color);
} else {
Graphics::print(sym);
}
}
<file_sep>#include <Femto>
#include <LibProfiler>
#include <SFXVolumeSource.hpp>
#include "miloslav.h"
// #include "Particles.h"
#include "Serialize.hpp"
#include "drawMesh.h"
#include "Renderer.h"
#include "meshes.h"
#include "ship.h"
#include "cutscene.h"
Audio::Sink<7, 10000> audio;
Point2D refCamera;
void fadeOut() {
for (s32 i = backlight; i >= 0; i -= 11) {
setBacklight(s24q8ToF32(i));
delay(3);
}
backlight = 0;
setBacklight(backlight);
}
bool updateEnter(GameState state) {
targetBacklight = 0;
if (backlight != 0)
return false;
targetBacklight = 255;
gameState = state;
return true;
}
void updateCamera(f32 speed) {
// auto target = Ship::player->position - Point2D{s32(screenWidth/2), s32(screenHeight/2)};
// refCamera -= (refCamera - target) * speed;
// Graphics::camera = refCamera + (Point2D{shake, 0}).rotateXY(frame++ * f32(2.5f));
}
void init(){
Audio::init();
Audio::setVolume(0);
Graphics::textMode = Graphics::TextMode::Clip;
// Graphics::palette = Graphics::generalPalette;
Graphics::palette = miloslav;
setMaxFPS(30);
Graphics::primaryColor = colorFromRGB(0xFFFFFF);
Serialize::init();
gameRenderer = &std::get<GameRenderer>(renderer);
LOG("Free RAM: ", getFreeRAM(), "\n");
if (!Settings::load()) {
LOG("Could not load settings\n");
} else {
LOG("Loaded settings\n");
}
Ship::checkPoints[0] = Point2D{0, 0};
Ship::checkPoints[1] = Point2D{130, 54};
Ship::checkPoints[2] = Point2D{133, 184};
Ship::checkPoints[3] = Point2D{37, 155};
}
u32 paletteAnimFrame = 0;
void updatePalette() {
PROFILER;
if (paletteAnimFrame++ < 5)
return;
paletteAnimFrame = 0;
u32 cycleStart = 2, cycleEnd = 8;
auto of1 = map1[cycleStart];
/* * /
u32 i;
for(i = cycleStart; i < cycleEnd - 1; ++i)
map1[i] = map1[i+1];
map1[i++] = of1;
/*/
auto of2 = map1[cycleStart + 1];
u32 i;
for(i = cycleStart; i < cycleEnd - 2; ++i)
map1[i] = map1[i+2];
map1[i++] = of1;
map1[i++] = of2;
/**/
}
void playMusic() {
std::array musicList{
"music/JeffII-Jetfire.raw",
"music/ScottHolmesMusic-Hotshot.raw"
};
static u32 chosen = musicList.size();
chosen++;
if (chosen >= musicList.size())
chosen = random(0, musicList.size());
if (auto music = Audio::play(musicList[chosen])) {
music->setLoop(true);
LOG("Music started\n");
} else LOG("Music '", chosen, "' not found\n");
}
bool raceStarted = false;
void stats() {
PROFILER;
using namespace Graphics;
setCursor(0, 10);
// print(getFPS(), " ", profiler::getBottleneck());
}
void drawShips() {
PROFILER;
Ship* drawList[shipCount];
for (u32 i = 0; i < shipCount; ++i) {
Ship* current = &ships[i];
for (u32 j = 0; j < i; ++j) {
if (current->cameraZ > drawList[j]->cameraZ) {
auto tmp = drawList[j];
drawList[j] = current;
current = tmp;
}
}
drawList[i] = current;
}
for (u32 i = 0; i < shipCount; ++i)
drawList[i]->postUpdate();
}
void initFrame() {
PROFILER;
Graphics::clear();
usedBufferCount = 0;
}
void updateSpace() {
PROFILER;
if (!raceStarted) {
Ship::broadcast(&Ship::init, 0);
raceStarted = true;
playMusic();
}
initFrame();
updatePalette();
auto& terrain = gameRenderer->get<Ground>();
terrain.clearShadows();
camera3D.follow(Ship::player->position, Ship::player->rotation);
Ship::broadcast(&Ship::update, frame);
drawShips();
stats();
}
void updateStart(){
gameState = GameState::Space;
backlight = 0;
targetBacklight = 255;
// universe.load();
}
void updateLogo(){
// using namespace Graphics;
// gameRenderer->bind<HUDLayer>();
// BitmapFrame<4> bmp{logo};
// draw(bmp, screenWidth / 2 - bmp.width() / 2, screenHeight / 2 - bmp.height() / 2, (frame - 30) * f32(0.01f));
// camera.y = -f32(frame);
// gameRenderer->get<Background>().init(bg);
// if (targetBacklight == 255) {
// if (isPressed(Button::A) || isPressed(Button::B) || isPressed(Button::C))
// targetBacklight = 0;
// } else {
// if (backlight == 0) {
// gameState = GameState::Space;
// targetBacklight = 255;
// }
// }
}
void update(){
INIT_PROFILER;
PROFILER;
using namespace Graphics;
frame++;
clearText();
// Particles::clear();
// gameRenderer->bind<HUDLayer>();
// clear();
if (backlight != targetBacklight) {
if (backlight > targetBacklight) {
backlight -= 11;
if (backlight < targetBacklight)
backlight = targetBacklight;
} else {
backlight += 11;
if (backlight > targetBacklight)
backlight = targetBacklight;
}
if (backlight > 255) backlight = 255;
setBacklight(s24q8ToF32(backlight));
}
if (streamedEffect) {
static Audio::RAWFileSource* source = nullptr;
static u32 lastSoundTime = 0;
auto now = getTime();
if ((!source || source->ended()) && (now - lastSoundTime > effectPriority)) {
source = Audio::play<6>(streamedEffect);
if (source) source->setLoop(false);
lastSoundTime = now;
effectPriority = ~u32{};
}
streamedEffect = nullptr;
}
switch (gameState) {
case GameState::Start: updateStart(); break;
case GameState::Logo: updateLogo(); break;
case GameState::Space: updateSpace(); break;
case GameState::EnterCutScene: updateEnterCutScene(); break;
case GameState::CutScene: updateCutScene(); break;
}
// Graphics::setCursor(0, 20);
// Graphics::print(profiler::getBottleneck());
}
|
d33886db88b9ed5889a936ca4184b97645168bd2
|
[
"JavaScript",
"C",
"C++"
] | 25
|
C++
|
felipemanga/1on1
|
37e092f66c751576b1f9ce7efcfdfe236f78e93c
|
51c990ef0b9616713a61b7cc7e3ed87182ad7ace
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
import sys
import os
import paramiko
from subprocess import run
import shutil
import re
import io
import plistlib
from pygit2 import Repository, RemoteCallbacks, Keypair
from pygit2 import GIT_SORT_TIME, GIT_SORT_REVERSE
from pathlib import Path
from config import *
def init_ssh():
print("Setting up SSH connection...")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ip = DEVICE_IP
if ip == "":
ip = os.environ["THEOS_DEVICE_IP"]
ssh.connect(ip, username=DEVICE_USER, key_filename=os.path.expanduser("~/.ssh/id_rsa"))
except:
print("Client seems to be offline! Exiting...")
sys.exit()
return ssh
def run_clutch(ssh):
print("Decrypting app...")
_, stdout_, _ = ssh.exec_command("Clutch -b " + bundle_identifier, get_pty=True)
stdout_.channel.recv_exit_status()
lines = stdout_.readlines()
for line in lines:
if "/var/tmp/clutch" in line:
out_dir = "/" + line.split("/", 1)[1].rstrip() + "/"
# Remove shitty escape char
ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
return ansi_escape.sub("", out_dir)
return None
def copy_file(sftp):
print("Copying decrypted file...")
# Create local tmp directory if not already existing
if not os.path.exists(TEMP_DIR):
os.mkdir(TEMP_DIR)
folder = out_dir + bundle_identifier
file_name = sftp.listdir(folder)[0]
sftp.get(folder + "/" + file_name, TEMP_DIR + "/" + file_name)
return file_name
def extract_info(sftp):
all_bundle_dir = "/var/containers/Bundle/Application/"
bundles = sftp.listdir(all_bundle_dir)
for bundle in bundles:
sub_items = sftp.listdir(all_bundle_dir + bundle)
app = [item for item in sub_items if item.endswith(".app")][0]
with io.BytesIO() as fl:
sftp.getfo(all_bundle_dir + bundle + "/" + app + "/" + "Info.plist", fl)
fl.seek(0)
contents = plistlib.load(fl)
if contents["CFBundleIdentifier"] == bundle_identifier:
return contents["CFBundleName"], contents["CFBundleShortVersionString"], contents["CFBundleVersion"]
return None
def push(repo, ref="refs/heads/master", remote_name="origin"):
print("Pushing...")
ssh_rsa_dir = str(Path.home()) + "/.ssh/"
for remote in repo.remotes:
if remote.name == remote_name:
remote.credentials = Keypair("git", ssh_rsa_dir + "id_rsa.pub", ssh_rsa_dir + "id_rsa", "")
callbacks = RemoteCallbacks(credentials=remote.credentials)
remote.push([ref], callbacks=callbacks)
def try_commit_and_push(name, version, bundle_version):
repo = Repository("headers/.git")
new_commit_message = name + " " + version + " (" + bundle_version + ")"
# Already commited this version?
for commit in repo.walk(repo.head.target, GIT_SORT_TIME | GIT_SORT_REVERSE):
if commit.message == new_commit_message:
return False
index = repo.index
index.add_all()
index.write()
# print(index.diff_to_workdir().stats.files_changed)
# if index.diff_to_workdir().stats.files_changed == 0:
# return False
print("Commiting...")
user = repo.default_signature
tree = index.write_tree()
ref = "refs/heads/master"
repo.create_commit(ref, user, user, new_commit_message, tree, [repo.head.get_object().hex])
push(repo, ref)
return True
# Main
ssh = init_ssh()
if len(sys.argv) < 2:
print("No specified bundle identifier, fetching a list of installed applications...")
_, stdout_, _ = ssh.exec_command("Clutch -i", get_pty=True)
stdout_.channel.recv_exit_status()
lines = stdout_.readlines()
print("")
for line in lines:
print(line.strip())
number = int(input("Please choose a number: "))
if number < 1 or number > len(lines) - 1:
print("Number outside of range, exiting...")
sys.exit()
bundle_identifier = lines[number].strip().rsplit("<")[1][:-1]
else:
bundle_identifier = sys.argv[1]
out_dir = run_clutch(ssh)
if out_dir != None:
sftp = ssh.open_sftp()
file_name = copy_file(sftp)
name, short_version, bundle_version = extract_info(sftp)
ssh.close()
print("Closed SSH session.")
header_dir = "headers/" + bundle_identifier
# Remove any previous header files to avoid old files
if os.path.exists(header_dir):
shutil.rmtree(header_dir)
print("Starting class-dump...")
run(["./class-dump", TEMP_DIR + "/" + file_name, "-H", "-o", header_dir])
try_commit_and_push(name, short_version, bundle_version)
print("Cleaning up and exiting...")
shutil.rmtree(TEMP_DIR)
<file_sep>DEVICE_IP = ""
DEVICE_USER = "root"
TEMP_DIR = "tmp"
<file_sep># ios-app-headers-fetcher
Headers from iOS are easily browsed at [limneos site](http://developer.limneos.net/?ios=11.1.2) and [other GitHub repos](https://github.com/nst/iOS-Runtime-Headers/). However, headers from 3rd party apps are not publicity available. When building tweaks that depend on such apps, it's always a cat and mouse game to support their latest versions. Being able to compare classes and methods between versions makes this a lot easier.
ios-app-headers-fetcher is a Python script that first decrypts the app over SSH on an iOS device. The decrypted app is then transferred back where the headers are dumped and committed to a repo.
In my tweaks I often target Spotify and Deezer. These two, and possibly others can be found [at the headers repo](https://github.com/Nosskirneh/ios-app-headers).
## Requirements
[Clutch](https://github.com/KJCracks/Clutch) is used to decrypt apps. It exists several other solutions (CrackerXI, bfdecrypt, uncrypt11) that work on iOS 11, but as far as I know these do not support CLI or require the app to be opened.
[class-dump](http://stevenygard.com/download/class-dump-3.5.dmg) is used for retrieving the headers. I recommend compiling it from scratch to avoid the `Cannot find offset for address 0xa000000001003538 in stringAtAddress:` error with some (Swift?) apps.
## Installation
Firstly, make sure your ssh id_rsa file contains the SSH key from the device you're trying to connect. I recommend using `ssh-copy-id` if this is not the case.
`brew install libgit2` or [similar for other systems](https://github.com/libgit2/pygit2/blob/master/docs/install.rst)
`sudo -H pip3 install paramiko pygit2`
`git clone https://github.com/Nosskirneh/ios-app-headers-fetcher`
`cd ios-app-headers-fetcher; git clone <EMAIL>:Nosskirneh/ios-app-headers.git headers` or other repo of yours
Configure the IP in `config.py` or leave blank for use of `$THEOS_DEVICE_IP`.
|
c0b89d5696d73766c96024ba20bf4ee13f1b4c76
|
[
"Markdown",
"Python"
] | 3
|
Python
|
Nosskirneh/ios-app-headers-fetcher
|
77984940ab9e553db61dfdd786a85d53a307264e
|
561ec774df11f1d03eb972de8dd04a4b2358b6c6
|
refs/heads/master
|
<repo_name>StevenChoo/frontend-academy-nasa<file_sep>/projects/nasa-lib/src/lib/nasa-service/nasa-lib.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { NasaLibService } from './nasa-lib.service';
describe('NasaLibService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: NasaLibService = TestBed.get(NasaLibService);
expect(service).toBeTruthy();
});
});
<file_sep>/projects/nasa-lib/src/lib/nasa-service/nasa-lib.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from '@angular/common';
import { HttpParams } from '@angular/common/http';
export interface Coordinates {
latitude: number,
longitude: number
}
@Injectable({
providedIn: 'root'
})
export class NasaLibService {
private BASEURL: string = "https://api.nasa.gov/planetary/apod";
private PARAM_API_KEY: string = "api_key";
private QUERY_PARAM_DATE: string = "date";
private PARAM_HD: string = "hd";
private apiKey: string = "NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo";
private coordinates: Coordinates;
constructor(private http: HttpClient, private datePipe: DatePipe) {
}
public updateCoordinates(coordinates: Coordinates){
this.coordinates = coordinates;
}
public getCoordinates(){
return this.coordinates;
}
public getLatitude(){
return this.coordinates.latitude;
}
public getLongitude(){
return this.coordinates.longitude;
}
getPictureOfTheDay(date: Date = new Date()) {
return this.http.get(this.BASEURL, {params: this.getParams(date,true)})
.toPromise()
.then(response => {
debugger;
return Promise.resolve(response);
});
}
private getParams(date: Date, hdPicture: boolean = false): HttpParams {
return new HttpParams()
.set(this.PARAM_API_KEY, this.apiKey)
.set(this.QUERY_PARAM_DATE, this.datePipe.transform(date, "yyyy-MM-dd"))
.set(this.PARAM_HD, hdPicture ? "True" : "False");
}
}
<file_sep>/projects/nasa-lib/src/lib/nasa-lib.module.ts
import { NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NasaCoordinateCustomizerComponent } from './nasa-coordinate-customizer/nasa-coordinate-customizer.component';
import { NasaMapsComponent } from './nasa-maps/nasa-maps.component';
import { NasaPhotoViewer } from './nasa-photo-viewer/nasa-photo-viewer.component';
import { NasaLibService } from './nasa-service/nasa-lib.service';
@NgModule({
declarations: [
NasaCoordinateCustomizerComponent,
NasaMapsComponent,
NasaPhotoViewer
],
imports: [
BrowserModule,
ReactiveFormsModule,
FormsModule
],
exports: [
NasaCoordinateCustomizerComponent,
NasaMapsComponent,
NasaPhotoViewer
],
providers: [
NasaLibService
]
})
export class NasaLibModule { }
<file_sep>/projects/nasa-lib/src/lib/nasa-coordinate-customizer/nasa-coordinate-customizer.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { NasaLibService } from '../nasa-service/nasa-lib.service';
@Component({
selector: 'nasa-coordinate-customizer',
templateUrl: './nasa-coordinate-customizer.component.html',
styles: []
})
export class NasaCoordinateCustomizerComponent implements OnInit {
formGroup: FormGroup;
@Input() latitude: number;
@Input() longitude: number;
constructor(private nasaService: NasaLibService) { }
ngOnInit() {
this.formGroup = new FormGroup({
latitude: new FormControl(this.latitude),
longitude: new FormControl(this.longitude)
});
}
locate(): void {
this.nasaService.updateCoordinates(this.formGroup.value);
}
}
<file_sep>/projects/nasa-lib/src/public-api.ts
/*
* Public API Surface of nasa-lib
*/
export * from './lib/nasa-service/nasa-lib.service';
export * from './lib/nasa-coordinate-customizer/nasa-coordinate-customizer.component';
export * from './lib/nasa-maps/nasa-maps.component';
export * from './lib/nasa-photo-viewer/nasa-photo-viewer.component';
export * from './lib/nasa-lib.module';
<file_sep>/projects/nasa-lib/src/lib/nasa-maps/nasa-maps.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'nasa-maps',
templateUrl: './nasa-maps.component.html',
styles: []
})
export class NasaMapsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
234aa008acef7bbebb805e893c2f4ab34e1def60
|
[
"TypeScript"
] | 6
|
TypeScript
|
StevenChoo/frontend-academy-nasa
|
77df34bb27defc7bce8880103cedbe26896bd449
|
d4af25e36131573a34079dc0456fdba94a46920c
|
refs/heads/main
|
<repo_name>Michaelwahyu/Pemrograman-Berorientasi-Objek-Pertemuan-4<file_sep>/README.md
# Pemrograman-Berorientasi-Objek-Pertemuan-4<file_sep>/latihanmethod.java
Skip to content
Search or jump to…
Pull requests
Issues
Marketplace
Explore
@Michaelwahyu
Piluthfi
/
Pemrograman-Berorientasi-Objek-Pertemuan-4
Public
1
00
Code
Issues
Pull requests
Actions
Projects
Wiki
Security
Insights
Pemrograman-Berorientasi-Objek-Pertemuan-4/latihanMethod.java /
@Piluthfi
Piluthfi Add files via upload
Latest commit 7e56393 10 minutes ago
History
1 contributor
43 lines (34 sloc) 1.29 KB
import java.util.*;
public class latihanMethod {
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.print("panjang = ");
int inputPanjang = userInput.nextInt();
System.out.print("lebar = ");
int inputLebar = userInput.nextInt();
gambar(inputPanjang,inputLebar);
System.out.println("luas = " + luas(inputPanjang,inputLebar));
System.out.println("keliling = " + keliling(inputPanjang,inputLebar));
tampilkanKelilingDanLuas(inputPanjang,inputLebar);
}
private static void tampilkanKelilingDanLuas(int panjang,int lebar){
System.out.println("luas = " + luas(panjang,lebar));
System.out.println("keliling = " + keliling(panjang,lebar));
}
private static int keliling(int panjang, int lebar){
int hasil = (panjang + lebar) * 2;
return hasil;
}
private static int luas(int panjang, int lebar){
int hasil = panjang*lebar;
return hasil;
}
private static void gambar(int panjang, int lebar){
for(int i = 0; i < lebar; i++){
for(int j = 0; j < panjang; j++){
System.out.print("* ");
}
System.out.print("\n");
}
}
}
© 2021 GitHub, Inc.
Terms
Privacy
Security
Status
Docs
Contact GitHub
Pricing
API
Training
Blog
About
Loading complete
|
f37bfa70215a101ed10fded6289993ee55726865
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
Michaelwahyu/Pemrograman-Berorientasi-Objek-Pertemuan-4
|
c9bacb5ea2a4792ff01ff5046bf7ff29cea446f6
|
49db57a40d5889fcb43410e4932be4b600a3241c
|
refs/heads/master
|
<repo_name>iroperto/hyjservices<file_sep>/empresa.php
<?php require_once 'header.php'; ?>
<div>
<img src="img/aboutus.jpg" alt="equipo" class="d-block w-100" style="min-width: 100%;">
</div>
<div class="container" style="margin-top: 32px;">
<div class="row">
<div class="col-md-8 empresatxt">
<h1>Quienes somos</h1>
<p>H & J Service S.R.L. es una empresa de suministros de oficina establecida en 2013. Dedicada a suplir las necesidades de la industria y los proveedores de equipos de oficina. Al elegirnos obtiene el beneficio de contar con un servicio de calidad y productos clase A, justo cuando los necesita. Garantizamos el mejor servicio al cliente, por parte de nuestro equipo de expertos y nos aseguraremos de ofrecer los mejores productos a precios inmejorables. Póngase en contacto con nosotros hoy mismo para saber más sobre lo que podemos hacer por usted.</p>
<p>Somos una empresa especializada en las ventas y comercialización de materiales de oficinas, limpieza, sillas, sillones, escritorios, archivos, armarios, lockers, muebles, toners, computadoras, suministros de limpieza.</p>
<p>Contamos con un personal experto con muchos años de experiencia en el mercado. Somos una Empresa constituida bajo todas las normas y leyes de contrataciones del Estado Dominicano. Nuestro personal está altamente capacitado para brindarle un excelente servicio y hacer la diferencia en cada contacto con ustedes. Garantizamos la calidad de nuestros productos y servicios, asegurando así la lealtad de nuestros clientes.</p>
</div>
<div class="col-md-4 sidebar">
<div class="row">
<div class="col-md-12 mvv">
<h3>Misión</h3>
<p>Ofrecer equipos, productos y servicios de oficina e institucionales de calidad, apegados a los requerimientos y necesidades de nuestros clientes, sirviendo de apoyo a su productividad.</p>
</div>
<div class="col-md-12 mvv">
<h3>Visión</h3>
<p>Posicionarnos como opción en productos y servicios institucionales y de oficina, basados en el buen servicio y en la eficiencia.</p>
</div>
<div class="col-md-12 mvv">
<h3>Valores</h3>
<ul>
<li><i class="fas fa-angle-double-right"></i> Servicio al Cliente</li>
<li><i class="fas fa-angle-double-right"></i> Integridad</li>
<li><i class="fas fa-angle-double-right"></i> Honestidad</li>
<li><i class="fas fa-angle-double-right"></i> Puntualidad</li>
<li><i class="fas fa-angle-double-right"></i> Respeto</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/cotiza.php
<?php require_once 'header.php'; ?>
<div>
<img src="img/cotizar.jpg" alt="equipo" class="d-block w-100" style="min-width: 100%;">
</div>
<div class="container" style="margin-top: 32px;">
<h1>Solicitud de Cotización</h1>
<div class="card">
<h5 class="card-header info-color white-text text-center py-4">
<strong>Cotización</strong>
</h5>
<div class="card-body px-lg-5 pt-0">
<form class="text-center" id="formulario" style="color: #757575;" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="input-group">
<input name="nombre" type="text" class="form-control" id="nombre">
<label for="nombre">Nombre</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="input-group">
<input name="empresa" type="text" class="form-control" id="empresa">
<label for="empresa">Empresa</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="input-group">
<input name="email" type="email" class="form-control" id="email">
<label for="email">Email</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="input-group">
<input name="telefono" type="text" class="form-control" id="telefono">
<label for="telefono">Teléfono</label>
</div>
</div>
</div>
<div class="input-group">
<textarea name="direccion" id="direccion" class="form-control"></textarea>
<label for="direccion">Dirección</label>
</div>
<div class="input-group">
<textarea name="cotizacion" id="cotizacion" class="form-control"></textarea>
<label for="cotizacion">Articulos a cotizar</label>
</div>
<button id="btnEnviar">Enviar</button>
<input type="hidden" id="tipoform" value="cotizador">
</form>
<div id="respuesta">texto de respuesta</div>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/contacto.php
<?php require_once 'header.php'; ?>
<!--CUSTOM PAGE HEADER STARTS-->
<!--Header for PAGE & POST-->
<div class="">
<div class="shorthead">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d15135.111368812386!2d-69.8422571!3d18.4937195!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x5fd981388cd4b15c!2sH%26J+Services%2C+SRL!5e0!3m2!1ses-419!2sdo!4v1551882180628" width="100%" height="350" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
<div class="container" id="contacto">
<div class="row">
<div class="col-md-8">
<h1>Contacto</h1>
<p id="parrafo_contacto">Para asistirle con mayor rapidez, por favor revise las secciones disponibles a continuación para aclarar cualquier duda que tenga.</p>
<div id="formularioContacto">
<form id="formulario">
<div class="row">
<div class="col-md-6">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Nombre" name="nombre" id="nombre">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Asunto" name="asunto" id="asunto">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Teléfono" name="telefono" id="telefono">
</div>
<div class="col-md-12">
<textarea class="form-control" rows="9" placeholder="Mensaje" name="mensaje" id="mensaje"></textarea>
</div>
<div class="col-md-12">
<button class="btn btn-primary" id="btnEnviar">Enviar</button>
<input type="hidden" id="tipoform" value="contacto">
</div>
</div>
</form>
<div id="respuesta">texto de respuesta</div>
</div>
</div>
<div class="col-md-4" id="direccion">
<h3>Información de Contacto</h3>
<p>Club de Leones No. 330, Almarosa II, Sto Dgo Este</p>
<p>809 620.0233</p>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
<p><a href="http://www.hyjservice.com/" target="_blank">http://www.hyjservice.com</a></p>
<p><a href="http://www.hyjservices.com.do/" target="_blank">http://www.hyjservices.com.do</a></p>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/footer.php
<!--Footer Start-->
<div class="footer_wrap">
<div id="footer" class="container">
<div class="row">
<div class="col-md-4 col-sm-12 col-xs-12">
<h5>sobre nosotros</h5>
<p>H & J Service S.R.L. es una empresa de suministros de oficina establecida en 2013. Dedicada a suplir las necesidades de la industria.</p>
<p>Garantizamos el mejor servicio al cliente, por parte de nuestro equipo de expertos y nos aseguraremos de ofrecer los mejores productos a precios inmejorables.</p>
<div class="spacecode" style="height:20px;"></div>
<div class="social-icons">
<a href="http://www.facebook.com/hyjservices" target="_blank" title="facebook"><i class="fab fa-facebook fa-1x"></i></a>
<a href="http://www.twitter.com/hyjservices" target="_blank" title="twitter"><i class="fab fa-twitter fa-1x"></i></a>
<a href="https://wa.me/18497541713" target="_blank" title="whatsapp"><i class="fab fa-whatsapp fa-1x"></i></a>
<a href="https://www.linkedin.com/in/hyjservices/" target="_blank" title="linkedin"><i class="fab fa-linkedin fa-1x"></i></a>
<a href="https://www.instagram.com/hyjservices/" target="_blank" title="instagram"><i class="fab fa-instagram fa-1x"></i></a>
</div>
</div>
<div class="col-md-4 col-sm-12 col-xs-12">
<h5>enlaces</h5>
<div class="menu-footer-menu-container">
<ul id="menu-footer-menu" class="footmenu">
<li><a href="index.php"><i class="fas fa-angle-right"></i> Inicio</a>
</li>
<li>
<a href="empresa.php"><i class="fas fa-angle-right"></i> Empresa</a>
</li>
<li>
<a href="productos.php"><i class="fas fa-angle-right"></i> Productos</a>
</li>
<li>
<a href="servicios.php"><i class="fas fa-angle-right"></i> Servicios</a>
</li>
<li>
<a href="contacto.php"><i class="fas fa-angle-right"></i> Contacto</a>
</li>
<li>
<a href="cotiza.php"><i class="fas fa-angle-right"></i> Solicitar Cotización</a>
</li>
</ul>
</div>
</div>
<div class="col-md-4 col-sm-12 col-xs-12">
<h5>contactanos</h5>
<p> Póngase en contacto con nosotros hoy mismo para saber más sobre lo que podemos hacer por usted.</p>
<p><i class="fas fa-map-marker-alt"></i> Club de Leones No. 330, Almarosa II, Sto Dgo Este</p>
<p><i class="fas fa-phone"></i> 809.620.0233 LUN-VIE , 08.AM - 5.PM</p>
<p><i class="fas fa-envelope"></i> <a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
</div>
</div>
<div id="copyright">
<div class="container">
<div class="copytext">
<div class="float-left">© <?php echo date("Y"); ?> H y J Services, S.R.L. Todos los derechos reservados</div>
<div class="float-right"> Powered by <a href="http://www.ivanroperto.com/" target="_blank" rel="nofollow"><NAME></a></div>recent-posts-style4/
<div class="float-none"> </div>
</div>
</div>
</div>
<!--Footer END-->
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
<script src="bootstrap/js/bootstrap.bundle.js"></script>
<?php
$estado = strpos($_SERVER['REQUEST_URI'], 'cotiza.php');
if ($estado !== false) { ?>
<script type="text/javascript" src="js/formularios.js"></script>
<?php } ?>
<script type="text/javascript" src="js/site.js">
</script>
</body>
</html>
<file_sep>/servicios.php
<?php require_once 'header.php'; ?>
<div>
<img src="img/servicios.jpg" alt="equipo" class="d-block w-100" style="min-width: 100%;">
</div>
<div class="container" style="margin-top: 32px;">
<h1>Servicios</h1>
<div class="row products justify-content-center">
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/servicio1.jpg" alt="Entrega a Domicilio" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Entrega a Domicilio</h3>
<p>Ofrecemos entregas puerta a puerta a las principales ciudades del país en un plazo de 24 a 72 horas.</p>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/servicio2.jpg" alt="Reparación de Mobiliario de Oficina" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Reparación de Mobiliario de Oficina</h3>
<p>Reparación, Servicio y Mantenimiento de todo tipo de Muebles para Oficinas en general.</p>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/servicio3.jpg" alt="Reparación de Impresoras" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Reparación de Impresoras</h3>
<p>Reparamos todo tipo de Impresoras y fotocopiadoras, con un personal tecnico altamente calificado. </p>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/servicio4.jpg" alt="Colocación de Impresoras" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Colocación de Impresoras</h3>
<p>Colocamos Impresoras en tu oficina sin costo de compra o mantenimiento, con el compromiso de comprar los suministros del impresor.</p>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/productos.php
<?php require_once 'header.php'; ?>
<div>
<img src="img/productos.jpg" alt="equipo" class="d-block w-100" style="min-width: 100%;">
</div>
<div class="container" style="margin-top: 32px;">
<h1>Productos</h1>
<div class="row products justify-content-center">
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/dispensadores.jpg" alt="Dispensadores de Papel y Jabón Liquido" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Dispensadores de Papel y Jabón Liquido</h3>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/eqlimpieza.jpg" alt="Equipos y Materiales de Limpieza" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Equipos y Materiales de Limpieza</h3>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/eqofficina.jpg" alt="Equipos de Oficina" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Equipos de Oficina</h3>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/materialoficina.jpg" alt="Material Gastable de Oficina" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Material Gastable de Oficina</h3>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/toners.jpg" alt="Toners y Cartuchos" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Toners y Cartuchos</h3>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<img src="img/productos/prdlimpieza.jpg" alt="Productos de Limpieza" class="rounded-circle mx-auto d-block shadow p-2 img-fluid img-thumbnails">
<h3>Productos de Limpieza</h3>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/header.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es-ES">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="fontawesome/css/all.css">
<link rel="stylesheet" href="css/style.css">
<!-- Roboto Font-->
<link href="https://fonts.googleapis.com/css?family=Montserrat|Roboto" rel="stylesheet">
<?php
$estado = strpos($_SERVER['REQUEST_URI'], 'cotiza.php');
if ($estado !== false) { ?>
<link rel="stylesheet" href="css/formularios.css">
<?php } ?>
<title>:: H&J SERVICES, S.R.L. ::</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body>
<!--HEADER-->
<div class="header_wrap layer_wrapper">
<!--HEADER STARTS-->
<div class="container brand-bar">
<div class="row">
<div class="col-md-4">
<!--LOGO START-->
<div class="logo">
<a class="logoimga" title="Banking Sector" href="index.php"><img src="img/logo.png" /></a>
</div>
<!--LOGO END-->
</div>
<div class="col-md-8">
<div class="row left contact-header">
<div class="col-md-4 dotted-right">
<i class="fas fa-map-marker-alt"></i> Club de Leones No. 330<br />Almarosa II, <br />Sto Dgo Este</div>
<div class="col-md-4 dotted-right">
<i class="fas fa-phone"></i> 809-620-0233 <br /> LUN-VIE , 08.AM - 5.PM</div>
<div class="col-md-4">
<i class="fas fa-comments"></i><EMAIL></div>
</div>
</div>
</div>
</div>
<div class="container menu-bar">
<nav class="navbar navbar-expand-lg top-menu">
<button class="navbar-toggler ml-auto hidden-sm-up float-xs-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav menu">
<li class="nav-item">
<a class="nav-link" href="index.php">Inicio</a><span class="brd-right"> </span>
</li>
<li class="nav-item">
<a class="nav-link" href="empresa.php">Empresa</a><span class="brd-right"> </span>
</li>
<li class="nav-item">
<a class="nav-link" href="productos.php">Productos</a><span class="brd-right"> </span>
</li>
<li class="nav-item">
<a class="nav-link" href="servicios.php">Servicios</a><span class="brd-right"> </span>
</li>
<li class="nav-item">
<a class="nav-link" href="contacto.php">Contacto</a>
</li>
</ul>
<ul class="navbar-nav last-item">
<li class="nav-item">
<a class="nav-link" href="cotiza.php">Solicitar Cotización</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
</div>
<!--HEADER ENDS--></div><!--layer_wrapper class END-->
<file_sep>/index.php
<?php require_once 'header.php'; ?>
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="4"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="img/carrousel/slide01.jpg" alt="Equipos de Oficina" class="d-block w-100">
<div class="carousel-caption">
<h3>Muebles de Oficina</h3>
<p>Nuestros muebles contribuyen a una mejor organización de tus espacios.</p>
</div>
</div>
<div class="carousel-item">
<img src="img/carrousel/slide02.jpg" alt="Material Gastable" class="d-block w-100">
<div class="carousel-caption">
<h3 style="color: white;">Material Gastable</h3>
<p>Materiales de calidad y alta duración.</p>
</div>
</div>
<div class="carousel-item">
<img src="img/carrousel/slide03.jpg" alt="Productos de Limpieza" class="d-block w-100">
<div class="carousel-caption">
<h3 style="color: white;">Toners y Cartuchos</h3>
<p>Más impresiones de alta calidad en tus documentos.</p>
</div>
</div>
<div class="carousel-item">
<img src="img/carrousel/slide04.jpg" alt="Dispensadores" class="d-block w-100">
<div class="carousel-caption">
<h3>Dispensadores</h3>
<p>Dispensadores ajustados para todo tipo de espacios y necesidad.</p>
</div>
</div>
<div class="carousel-item">
<img src="img/carrousel/slide05.jpg" alt="Equipos y Materiales de Limpieza" class="d-block w-100">
<div class="carousel-caption">
<h3 style="color: white;">Equipos y Materiales de Limpieza</h3>
<p>Equipos de alto volumen y multifuncionales.</p>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev" onclick="$('#carouselExampleSlidesOnly').carousel('prev')">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next" onclick="$('#carouselExampleSlidesOnly').carousel('next')">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="container-fluid clientes" style="display: none;">
<div>
<h1 class="text-center">clientes satisfechos</h1>
<p class="text-center">Nuestros clientes son la parte mas importante y mejor cuidada de nuestra actividad comercial, ellos mismos lo confirman</p>
</div>
</div>
<div class="clientes" style="display:none;">
<div class="row justify-content-center">
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 text-center">
<p><i class="fas fa-quote-left fa-lg"></i></p>
<p style="font-style: italic;">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,</p>
<img src="img/clientes/01.jpg" alt="Cliente 1" class="rounded-circle mx-auto d-block shadow img-fluid img-thumbnails">
<p>Cliente 1</p>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 text-center cliente-centro">
<p><i class="fas fa-quote-left fa-lg"></i></p>
<p style="font-style: italic;"> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. </p>
<img src="img/clientes/02.jpg" alt="Cliente 2" class="rounded-circle mx-auto d-block shadow img-fluid img-thumbnails">
<p>Cliente 2</p>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 text-center">
<p><i class="fas fa-quote-left fa-lg"></i></p>
<p style="font-style: italic;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum </p>
<img src="img/clientes/03.jpg" alt="Cliente 3" class="rounded-circle mx-auto d-block shadow img-fluid img-thumbnails">
<p>Cliente 3</p>
</div>
</div>
</div>
<?php require_once 'footer.php'; ?>
<file_sep>/correo.php
<?php
mail("<EMAIL>","Asunto","Cuerpo del email");
?>
|
69bb68d4af6c89f6f9e49c91b9c972d837601272
|
[
"PHP"
] | 9
|
PHP
|
iroperto/hyjservices
|
b7122b5f4075a7035c77572787cda9d7f091b819
|
36b5d58d267ee01363d88b7f7ecc09f3fc0f6d91
|
refs/heads/master
|
<file_sep>//<NAME> TIA: 32055161
#ifndef __STATIC_STACK_H__
#define __STATIC_STACK_H__
const int STATIC_QUEUE_CAPACITY = 8;
struct StaticQueue
{
int current;
char values[STATIC_QUEUE_CAPACITY];
};
StaticQueue Create();
bool Push(StaticQueue& stack, char elem);
char Pop(StaticQueue& stack);
char Top(const StaticQueue& stack);
int Size(const StaticQueue& stack);
int Count(const StaticQueue& stack);
bool IsEmpty(const StaticQueue& stack);
bool Clear(StaticQueue& stack);
#endif <file_sep>//<NAME> TIA: 32055161
#include "PILHA.h"
StaticQueue Create()
{
StaticQueue queue = { 0, {0} };
return queue;
}
bool Push(StaticQueue& stack, char elem)
{
if (stack.current == STATIC_QUEUE_CAPACITY) {
return false;
}
stack.values[stack.current] = elem;
++stack.current;
return true;
}
char Pop(StaticQueue& stack)
{
if (IsEmpty(stack))
{
return '\0';
}
char elem = stack.values[stack.current - 1];
stack.values[stack.current - 1] = '\0';
--stack.current;
return elem;
}
char Top(const StaticQueue& stack)
{
if (IsEmpty(stack))
{
return '\0';
}
return stack.values[stack.current - 1];
}
int Size(const StaticQueue& stack)
{
return sizeof(stack.values) / sizeof(stack.values[0]);
}
int Count(const StaticQueue& stack)
{
return stack.current;
}
bool IsEmpty(const StaticQueue& stack)
{
return stack.current == 0;
}
bool Clear(StaticQueue& stack)
{
while (!IsEmpty(stack))
{
Pop(stack);
}
return IsEmpty(stack);
}<file_sep>//<NAME> TIA: 32055161
#include "PILHA.h"
#ifndef __STATIC_QUEUE_H__
#define __STATIC_QUEUE_H__
bool EnqueueQueue(StaticQueue& queue, char elem);
char DequeueQueue(StaticQueue& queue);
char FrontQueue(const StaticQueue& queue);
int SizeQueue(const StaticQueue& queue);
int CountQueue(const StaticQueue& queue);
bool IsEmptyQueue(const StaticQueue& queue);
bool ClearQueue(StaticQueue& queue);
#endif<file_sep>//<NAME> TIA: 32055161
#include "FILA.h"
#include "PILHA.h"
bool EnqueueQueue(StaticQueue& queue, char elem)
{
return Push(queue, elem);
}
char DequeueQueue(StaticQueue& queue)
{
return Pop(queue);
}
char FrontQueue(const StaticQueue& queue)
{
return Top(queue);
}
int SizeQueue(const StaticQueue& queue)
{
return Size(queue);
}
int CountQueue(const StaticQueue& queue)
{
return Count(queue);
}
bool IsEmptyQueue(const StaticQueue& queue)
{
return IsEmpty(queue);
}
bool ClearQueue(StaticQueue& queue)
{
return Clear(queue);
}
<file_sep>//<NAME> TIA: 32055161
#include <iostream>
#include <locale.h>
#include "FILA.h"
using namespace std;
int main()
{
setlocale(LC_ALL, "");
StaticQueue pilha1 = Create(); // Criação da pilha
StaticQueue fila = Create(); // Criação da pilha invertida para ser fila
int i;
int auxilio = 0;
char elemento;
char auxiliar;
for (i = 0; i < 5; i++) { // Laço para definir os elementos da pilha
cout << "Digite o " << i + 1 << "° elemento: ";
cin >> elemento;
EnqueueQueue(pilha1, elemento);
cout << "Quantidade de elementos na fila: " << CountQueue(pilha1) << "\n";
}
for (i = 0; i < 5; i++) { // Laço para definir os elementos da segunda pilha, só que invertido
auxiliar = FrontQueue(pilha1);
DequeueQueue(pilha1);
EnqueueQueue(fila, auxiliar);
}
cout << "Elementos da fila: " << "\n";
for (i = 4; i > -1; i--) { // laço para mostrar os elementos da segunda pilha, que no caso é a fila
cout << fila.values[i] << "\n";
auxilio = auxilio + 1;
}
cout << "Operação Dequeue será realizada agora " << "\n"; // Operação de Dequeue na fila.
DequeueQueue(fila);
cout << "Elementos da fila: " << "\n";
for (i = 4; i > -1; i--) { // laço para mostrar os elementos da fila depois do Dequeue
cout << fila.values[i] << "\n";
auxilio = auxilio + 1;
}
cout << "Primeiro elemento da fila: " << FrontQueue(fila) << "\n"; // Operação para mostrar o primeiro elemento da fila depois do dequeue
cout << "Quantidade de elementos na fila: " << CountQueue(fila); // Operação para mostrar quantos elementos tem na fila
return 0;
}
|
6bf85b58f4364a55602768efa3ae4f2e84626d9c
|
[
"C",
"C++"
] | 5
|
C
|
Adriianooo/Pilha_fila
|
e08aaaa713a326c4df65451881a58dde145c8d41
|
3afd9be843264941a2c709bd75d294ed007a8604
|
refs/heads/main
|
<file_sep># portfolio-Abderrazzak-Elkhayari_Frontend
|
84e138ec1c2be06023d4009fc175959982edf667
|
[
"Markdown"
] | 1
|
Markdown
|
elkhayari/portfolio-Abderrazzak-Elkhayari_Frontend
|
889ced83bb1e0c0e97b53903df772e09028db8f4
|
af75718c16cee1c76bf640a8856999f115e6b169
|
refs/heads/master
|
<file_sep><?php
echo "saluttttt".$titre;
?>
<file_sep># JyTravaille
Site internet J'y travaille
|
e94a62a4b4bde5c803d55c7678a460fd29746d72
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
ginius4ginius/JyTravaille
|
91e9989625105842774dd25a639cd323f21ebf29
|
517361ca05f4d358a99babc2a306a7732636cf3c
|
refs/heads/master
|
<repo_name>noah-wisch/ReduxSimpleStarterPractice2<file_sep>/src/reducers/ReducerBooks.js
export default function() {
return (
[
{ title: 'The Dog Stars', pages: 321 },
{ title: 'The Buried Giant', pages: 304 },
{ title: 'Harry Potter & The Deathly Hallows', pages: 759 },
{ title: 'The Hunger Games: Catching Fire', pages: 257 },
]
);
}
|
2a3ecebe2e94c0451e0cd8994723536b737667bc
|
[
"JavaScript"
] | 1
|
JavaScript
|
noah-wisch/ReduxSimpleStarterPractice2
|
0562c93290b614ff65741212a758be4242b0a8c8
|
f2f8277d977aaf12ef87efaaa44aa63d6a8da59c
|
refs/heads/master
|
<repo_name>LeewoodChan/LeewoodChan.github.io<file_sep>/README.md
# LeewoodChan.github.io<file_sep>/_posts/2019-04-03-Genki_Workbook_Audio.md
---
layout: post
title: Genki Workbook Audio
comments: true
# other options
permalink: "/genki_WK_audio/"
---
<style>
.list-group{
max-height: 300px;
overflow:scroll;
-webkit-overflow-scrolling: touch;
}
</style>
<!--script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script-->
<script type="text/javascript">//<![CDATA[
$(function(){
document.getElementById("nextAudio").onclick = function() {
forward();
}
document.getElementById("backAudio").onclick = function() {
backward();
}
$(document).ready(function(){
$(".song").first(0).addClass("active");
var startUrl = $(".song").first(0).attr('source');
console.log(startUrl);
$("#mp3_src").attr("src", startUrl);
var audio = $("audio-player");
$('audio').get(0).load();
updateCurrentPlay();
$('[source]').on('click', function(){
change( $(this).attr('source') );
$(this).addClass("active");
updateCurrentPlay();
//var currentPlay = $("#currentPlay");
//currentPlay.text($(this).text());
//console.log(currentPlay.text());
//console.log($(this).text());
});
$('#audio-player').on('ended', function() {
//alert("done");
forward();
// enable button/link
});
});
function change(sourceUrl) {
var audio = $("audio-player");
$("#mp3_src").attr("src", sourceUrl);
$(".song").removeClass("active");
/****************/
$('audio').get(0).pause();
$('audio').get(0).load();//suspends and restores all audio element
$('audio').get(0).play();
}
var updateCurrentPlay = function(){
var currentPlay = $("#currentPlay");
var current = $(".active").text();
console.log("current:" + current);
currentPlay.text(current);
}
var forward = function(){
//alert("forward");
var current = $(".active").next();
var currentText = current.text();
var currentUrl;
if(currentText === ""){
//current = $(".song").first(0).text();
currentUrl = $(".song").first(0).attr('source');
current =$(".song").first(0);
}else{
currentUrl = $(".active").next().attr('source');
}
//var sourceUrl = current.text();
console.log(currentUrl);
change(currentUrl);
current.addClass('active');
updateCurrentPlay();
}
var backward = function(){
var current = $(".active").prev();
var currentText = current.text();
var currentUrl;
//var sourceUrl = current.text();
if(currentText ===""){
//current = $(".song").last(0).text();
currentUrl = $(".song").last(0).attr('source');
current =$(".song").last(0);
}else{
currentUrl = $(".active").prev().attr('source');
}
console.log(currentUrl);
change(currentUrl);
current.addClass('active');
updateCurrentPlay();
}
});//]]>
</script>
<div class="container border px-0 border-warning bg-dark" id="audiowrap">
<div class="row mx-0" id="audio0">
<audio class="m-0 col-sm-12 border p-0" preload id="audio-player" controls="controls">
<source id="mp3_src" type="audio/mp3">
Your browser does not support HTML5 Audio!
</audio>
</div>
<div class="row border border-warning mx-0">
<button type="button" name="button" class="btn btn-dark col" id="backAudio">
<i class="fas fa-fast-backward" style="color:white"></i>
</button>
<a class="col-8 text-center text-white" id="currentPlay">Now playing.......</a>
<button type="button" name="button" class="btn btn-dark col" id="nextAudio">
<i class="fas fa-fast-forward" style="color:white"></i>
</button>
</div>
<div class="panel panel-primary" id="result_panel">
<div class="panel-body">
<div class="list-group">
{% for item in site.data.audio %}
<a href="#" source="{{ item.link }}" class="song list-group-item list-group-item-action py-1">{{ item.name }}</a>
<!--button type="button" source="{{ item.link }}" class="song list-group-item list-group-item-action">{{ item.name }}</button-->
{% endfor %}
</div>
</div>
</div>
</div>
<file_sep>/_site/genki_WK_audio/js/jquery.js
var imageTracker = 'playImage';
//set events handlers for on click
document.getElementById("nextAudio").onclick = function() {
forward();
}
document.getElementById("backAudio").onclick = function() {
backward();
}
//playing flag
var musicTracker = 'noMusic';
//playlist audios
var audios = [];
$(".song").each(function(){
var load = new Audio($(this).attr("source"));
load.load();
load.addEventListener('ended',function(){
forward();
});
audios.push(load);
});
//active track
var activeTrack = 0;
var playPause = function() {
if (musicTracker == 'noMusic') {
audios[activeTrack].play();
musicTracker = 'playMusic';
} else {
audios[activeTrack].pause();
musicTracker = 'noMusic';
}
showPlaying();
};
var stop = function() {
if (musicTracker == 'playMusic') {
audios[activeTrack].pause();
audios[activeTrack].currentTime = 0;
audios[activeTrack].play();
} else {
audios[activeTrack].currentTime = 0;
}
};
var forward = function(){
function increment(){
if (activeTrack < audios.length - 1)
activeTrack++;
else activeTrack = 0;
}
if (musicTracker == 'playMusic') {
audios[activeTrack].pause();
//audios[activeTrack].currentTime = 0;
increment();
audios[activeTrack].play();
} else {
increment();
}
showPlaying();
};
var backward = function(){
function decrement(){
if (activeTrack > 0)
activeTrack--;
else activeTrack = audios.length -1;
}
if (musicTracker == 'playMusic') {
audios[activeTrack].pause();
//audios[activeTrack].currentTime = 0;
decrement();
audios[activeTrack].play();
} else {
decrement();
}
showPlaying();
};
var showPlaying = function()
{
var src = audios[activeTrack].src;
$(".song").removeClass("active");
$("div[url='" + src + "']").addClass("active");
console.log( $("div[url='" + src + "']"));
};
|
6b3fa3a1e426453527c933b11f9bf42fe40d31c5
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
LeewoodChan/LeewoodChan.github.io
|
a55e22350a741e9bfbe49392576aca31089b3aca
|
afc3478aa497acc5c194675029a5ffb6a60da352
|
refs/heads/master
|
<file_sep>package service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import mapper.EasybuyOrderDetailMapper;
import mapper.EasybuyOrderDoMapper;
import mapper.EasybuyProductMapper;
import model.EasybuyOrderDetail;
import model.EasybuyOrderDetailExample;
import model.EasybuyOrderDoExample;
import model.EasybuyProduct;
import model.EasybuyProductExample;
import service.IndexService;
import vo.EasybuyAll;
@Service
@Transactional
public class IndexServiceImpl implements IndexService {
@Resource
private EasybuyProductMapper easybuyProductMapper;
@Resource
private EasybuyOrderDoMapper easybuyOrderDoMapper;
@Resource
private EasybuyOrderDetailMapper easybuyOrderDetailMapper;
public List<EasybuyProduct> list(int page , String name ,String orderby) {
EasybuyProductExample easybuyProductExample = new EasybuyProductExample();
if (name != null && !name.trim().equals("")) {
easybuyProductExample.createCriteria().andNameLike("%"+name+"%");
}
if(orderby!=null&&!orderby.equals("")){
easybuyProductExample.setOrderByClause("price "+orderby);
}
easybuyProductExample.setLimit(8);
easybuyProductExample.setOffset((page - 1) * 8);
return easybuyProductMapper.selectByExample(easybuyProductExample);
}
public long count(String name) {
EasybuyProductExample easybuyProductExample = new EasybuyProductExample();
if (name != null && !name.trim().equals("")) {
easybuyProductExample.createCriteria().andNameLike("%"+name+"%");
}
return easybuyProductMapper.countByExample(easybuyProductExample);
}
public EasybuyProduct findProById(Integer id) {
return easybuyProductMapper.selectByPrimaryKey(id);
}
public List<EasybuyAll> list2() {
EasybuyOrderDoExample easybuyOrderDoExample = new EasybuyOrderDoExample();
return easybuyOrderDoMapper.selectAllByExample(easybuyOrderDoExample);
}
public List<EasybuyOrderDetail> list3() {
EasybuyOrderDetailExample easybuyOrderDetailExample = new EasybuyOrderDetailExample();
return easybuyOrderDetailMapper.selectByExample(easybuyOrderDetailExample);
}
}
<file_sep>package service;
import java.util.List;
import model.EasybuyOrderDetail;
import model.EasybuyProduct;
import model.EasybuyProductCategory;
import model.EasybuyProductPhoto;
public interface EasybuyProductService {
public List<EasybuyProduct> list(int page , String name);
public long count(String name);
public EasybuyProduct select(Integer id);
public boolean insert(EasybuyProduct easybuyProduct);
public boolean update(EasybuyProduct easybuyProduct);
public boolean deleteNewsDatail(Integer id);
public List<EasybuyProductCategory> list2(Integer i);
public List<EasybuyProductCategory> list3(Integer i, String name);
public EasybuyProductCategory selectCategory(Integer id1);
public List<EasybuyProduct>list(int page,String name,Integer id,Integer categorylevel2id);
public int count(String name,Integer id,Integer categorylevel2id );
public List<EasybuyProduct>list2();
}
<file_sep>driverClass=com.mysql.jdbc.Driver
url=jdbc\:mysql\://172.16.58.3\:3306/db?useUnicode\=true&characterEncoding\=utf8
usr=admin
psw=admin
<file_sep>package action;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import model.EasybuyProduct;
import model.EasybuyProductCategory;
import service.DeatailsService;
import service.EasybuyProductService;
@Controller
public class DeatailsAction {
@Resource
private DeatailsService deatailsService;
@RequestMapping("/dratails.do")
public String dratails(Model model) {
int id = 739;
EasybuyProduct easybuyProduct = deatailsService.select(id);
model.addAttribute("easybuyProduct", easybuyProduct);
return "Details/Product";
}
}
<file_sep>package service.impl;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import mapper.EasybuyOrderMapper;
import model.EasybuyOrder;
import model.EasybuyOrderExample;
import service.EasybuyorderService;
@Service
@Transactional
public class EasybuyorderServiceImpl implements EasybuyorderService {
@Resource
private EasybuyOrderMapper easybuyOrderMapper;
@Override
public List<EasybuyOrder> list(String name,Integer page) {
EasybuyOrderExample easybuyOrderExample=new EasybuyOrderExample();
if(name !=null&&!name.trim().equals("")){
easybuyOrderExample.createCriteria().andSerialnumberLike("%"+name+"%");
}
easybuyOrderExample.setOrderByClause("createtime desc");
easybuyOrderExample.setLimit(6);
easybuyOrderExample.setOffset((page-1)*6);
return easybuyOrderMapper.selectByExample(easybuyOrderExample);
}
@Override
public boolean dele(Integer id) {
easybuyOrderMapper.deleteByPrimaryKey(id);
return true;
}
@Override
public int count(String name) {
EasybuyOrderExample easybuyOrderExample=new EasybuyOrderExample();
if(name !=null&&!name.trim().equals("")){
easybuyOrderExample.createCriteria().andSerialnumberLike("%"+name+"%");
}
return (int) easybuyOrderMapper.countByExample(easybuyOrderExample);
}
}
<file_sep>package mapper;
import java.util.List;
import model.EasybuyProduct;
import model.EasybuyProductExample;
import org.apache.ibatis.annotations.Param;
public interface EasybuyProductMapper {
long countByExample(EasybuyProductExample example);
int deleteByExample(EasybuyProductExample example);
int deleteByPrimaryKey(Integer id);
int insert(EasybuyProduct record);
int insertSelective(EasybuyProduct record);
List<EasybuyProduct> selectByExample(EasybuyProductExample example);
EasybuyProduct selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") EasybuyProduct record, @Param("example") EasybuyProductExample example);
int updateByExample(@Param("record") EasybuyProduct record, @Param("example") EasybuyProductExample example);
int updateByPrimaryKeySelective(EasybuyProduct record);
int updateByPrimaryKey(EasybuyProduct record);
}<file_sep>package mapper;
import java.util.List;
import model.EasybuyProductCategory;
import model.EasybuyProductCategoryExample;
import org.apache.ibatis.annotations.Param;
public interface EasybuyProductCategoryMapper {
long countByExample(EasybuyProductCategoryExample example);
int deleteByExample(EasybuyProductCategoryExample example);
int deleteByPrimaryKey(Integer id);
int insert(EasybuyProductCategory record);
int insertSelective(EasybuyProductCategory record);
List<EasybuyProductCategory> selectByExample(EasybuyProductCategoryExample example);
EasybuyProductCategory selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") EasybuyProductCategory record, @Param("example") EasybuyProductCategoryExample example);
int updateByExample(@Param("record") EasybuyProductCategory record, @Param("example") EasybuyProductCategoryExample example);
int updateByPrimaryKeySelective(EasybuyProductCategory record);
int updateByPrimaryKey(EasybuyProductCategory record);
}<file_sep>package service.impl;
import java.util.List;
import javax.annotation.Resource;
import mapper.EasybuyUserMapper;
import model.EasybuyUser;
import model.EasybuyUserExample;
import org.springframework.stereotype.Service;
import service.EasybuyUserService;
@Service
public class EasybuyUserServiceImpl implements EasybuyUserService {
@Resource
private EasybuyUserMapper easybuyUserMapper;
@Override
public boolean login(String loginName , String password) {
EasybuyUserExample easybuyUserExample = new EasybuyUserExample();
easybuyUserExample.createCriteria().andLoginnameEqualTo(loginName);
List<EasybuyUser> users = easybuyUserMapper.selectByExample(easybuyUserExample);
if (users != null && users.size() > 0) {
for(EasybuyUser u : users){
if (u.getPassword().equals(password)) {
return true;
}
}
}
return false;
}
@Override
public boolean register(EasybuyUser user) {
int result = easybuyUserMapper.insert(user);
if(result>0){
return true;
}
return false;
}
@Override
public List<EasybuyUser> allMessage() {
// TODO Auto-generated method stub
EasybuyUserExample example = new EasybuyUserExample();
return easybuyUserMapper.selectByExample(example);
}
@Override
public EasybuyUser getAdminByLoginname(String loginName) {
// TODO Auto-generated method stub
EasybuyUserExample example = new EasybuyUserExample();
example.createCriteria().andLoginnameEqualTo(loginName);
return easybuyUserMapper.selectByExample(example).get(0);
}
}
<file_sep>package service;
import model.EasybuyProduct;
public interface DeatailsService {
public EasybuyProduct select(Integer id);
}
<file_sep>package service;
import java.util.List;
import model.EasybuyOrder;
import model.EasybuyOrderDetail;
import model.EasybuyProduct;
import model.EasybuyUser;
import vo.Cart;
import vo.Cart1;
public interface Easybuy_Car1Service {
public boolean del(Integer id);
public List<Cart> list(Cart cart) ;
public List<EasybuyOrderDetail> selectDetail(EasybuyOrderDetail easybuyOrderDetail) ;
public List<EasybuyOrderDetail> list2();
//
public int selectOrderId(int userI);
public EasybuyOrderDetail update(EasybuyOrderDetail easybuyOrderDetail);
public EasybuyOrderDetail UpdateQ(EasybuyOrderDetail easybuyOrderDetail);
public EasybuyOrderDetail UpdateOrdreId(EasybuyOrderDetail easybuyOrderDetail);
public EasybuyOrderDetail stateUpdate(EasybuyOrderDetail easybuyOrderDetail);
public EasybuyOrderDetail add(EasybuyOrderDetail easybuyOrderDetail) ;
public EasybuyProduct select(Integer id) ;
// public EasybuyOrder selectOrder(Integer id);
public EasybuyUser selectUser(String loginName);
}
<file_sep>package service;
import java.util.List;
import vo.EasybuyAll;
import model.EasybuyOrderDetail;
import model.EasybuyProduct;
public interface IndexService {
public List<EasybuyProduct> list(int page , String name ,String orderby) ;
public long count(String name);
public EasybuyProduct findProById(Integer id);
public List<EasybuyAll> list2();
// public List<EasybuyOrderDetail> list3();
}
<file_sep>package mapper;
import java.util.List;
import model.EasybuyOrder;
import model.EasybuyOrderExample;
import org.apache.ibatis.annotations.Param;
public interface EasybuyOrderMapper {
long countByExample(EasybuyOrderExample example);
int deleteByExample(EasybuyOrderExample example);
int deleteByPrimaryKey(Integer id);
int insert(EasybuyOrder record);
int insertSelective(EasybuyOrder record);
List<EasybuyOrder> selectByExample(EasybuyOrderExample example);
EasybuyOrder selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") EasybuyOrder record, @Param("example") EasybuyOrderExample example);
int updateByExample(@Param("record") EasybuyOrder record, @Param("example") EasybuyOrderExample example);
int updateByPrimaryKeySelective(EasybuyOrder record);
int updateByPrimaryKey(EasybuyOrder record);
// EasybuyOrder selectOrder(Integer id );
}<file_sep>
package service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.EasybuyCar23Service;
import mapper.EasybuyOrderDetailMapper;
import mapper.EasybuyOrderMapper;
import model.EasybuyOrder;
import model.EasybuyOrderDetail;
import model.EasybuyOrderDetailExample;
import model.EasybuyOrderExample;
@Service
@Transactional
public class EasybuyCar23ServiceImpl implements EasybuyCar23Service {
@Resource
private EasybuyOrderDetailMapper easybuyOrderDetailMapper;
@Resource
private EasybuyOrderMapper easybuyOrderMapper;
public List<EasybuyOrderDetail> list(int page,Integer orderid) {
EasybuyOrderDetailExample easybuyOrderDetailExample = new EasybuyOrderDetailExample();
easybuyOrderDetailExample.createCriteria().andOrderidEqualTo(orderid);
return easybuyOrderDetailMapper.selectByExample(easybuyOrderDetailExample);
}
public long count() {
EasybuyOrderDetailExample easybuyOrderDetailExample = new EasybuyOrderDetailExample();
EasybuyOrder easybuyOrder=new EasybuyOrder();
easybuyOrder.setId(2);
easybuyOrderDetailExample.createCriteria().andOrderidEqualTo(easybuyOrder.getId());
return easybuyOrderDetailMapper.countByExample(easybuyOrderDetailExample);
}
@Override
public boolean add(EasybuyOrder easybuyOrder) {
easybuyOrderMapper.insert(easybuyOrder);
return true;
}
@Override
public List<EasybuyOrder> list() {
EasybuyOrderExample easybuyOrderExample = new EasybuyOrderExample();
return easybuyOrderMapper.selectByExample(easybuyOrderExample);
}
@Override
public List<EasybuyOrderDetail> detailtype(Integer orderid) {
EasybuyOrderDetailExample easybuyOrderDetailExample = new EasybuyOrderDetailExample();
easybuyOrderDetailExample.createCriteria().andOrderidEqualTo(orderid).andTypeEqualTo(0);
return easybuyOrderDetailMapper.selectByExample(easybuyOrderDetailExample);
}
@Override
public void state(EasybuyOrderDetail easybuyOrderDetail) {
easybuyOrderDetailMapper.modtype(easybuyOrderDetail);
}
}
<file_sep>package action;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import model.EasybuyOrder;
import model.EasybuyOrderDetail;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import service.EasybuyCar23Service;
@Controller
public class EasybuyCar23Action {
@Resource
private EasybuyCar23Service easybuyCar2Service;
@RequestMapping("/car2.do")
public String list(Integer page , Integer orderid,Integer type ,Model model) {
if (page == null || page < 1) {
page = 1;
}
long total = easybuyCar2Service.count();
long totalPage = total % 4 == 0 ? total / 4 : (total / 4) + 1;
if (page > totalPage) {
page = (int)totalPage;
}
orderid=1;
double totalcost=0;
if(orderid!=null){
List<EasybuyOrderDetail> list = easybuyCar2Service.list(page,orderid);
for(EasybuyOrderDetail e:list){
if(e.getType().equals(1)){
type=e.getType();
model.addAttribute("type" , type);
model.addAttribute("orderid", orderid);
break;
}else{
totalcost= e.getCost()+totalcost;
type=e.getType();
model.addAttribute("type" , type);
model.addAttribute("list" , list);
model.addAttribute("page", page);
model.addAttribute("totalPage", totalPage);
model.addAttribute("totalcost", totalcost);
model.addAttribute("orderid", orderid);
}
}
}
return "car/car2";
}
@RequestMapping("/car3add.do")
public String add( String userid,String loginname,String useraddress,Date createtime,String cost, Integer orderid,Model model){
// if(userid!=null&&cost!=null&&useraddress!=null&&!userid.trim().equals("")&&!cost.trim().equals("")){
// int uid = Integer.parseInt(userid);
// float cs = Integer.parseInt(cost);
long number=(long)((Math.random()*9+1)*1000000000);
List<EasybuyOrder> list = easybuyCar2Service.list();
for (EasybuyOrder i:list) {
if(i.getSerialnumber()==number){
number=(int)((Math.random()*9+1)*1000000000);
}
System.out.println("大家啊哦"+number);
EasybuyOrder easybuyOrder = new EasybuyOrder();
int uid=2;
float cs=33f;
// String serialnumber="944646444";
String useraddressa= "喊打喊杀";
String ln="dd";
easybuyOrder.setUserid(uid);
easybuyOrder.setLoginname(ln);
easybuyOrder.setUseraddress(useraddressa);
easybuyOrder.setCreatetime(new Date());
easybuyOrder.setCost(cs);
easybuyOrder.setSerialnumber(number);
if(easybuyCar2Service.add(easybuyOrder)){
System.out.println("成功 ");
List<EasybuyOrderDetail> typelist = easybuyCar2Service.detailtype(orderid);
for (EasybuyOrderDetail easybuyOrderDetail:typelist) {
easybuyOrderDetail.setType(1);
easybuyCar2Service.state(easybuyOrderDetail);
}
model.addAttribute("sn",number);
model.addAttribute("cs",cs);
System.out.println(easybuyOrder.getId()+"你好啊");
return "redirect:car3.do";
}
}
return "car/car3";
}
@RequestMapping(value="/car3.do")
public String car3(){
return "car/car3";
}
@RequestMapping(value="/order.do")
public String order(Double cost,Integer orderid){
return "car/car2";
}
}
<file_sep>package mapper;
import java.util.List;
import model.EasybuyOrderDetail;
import model.EasybuyOrderDetailExample;
import model.EasybuyOrderDoExample;
import org.apache.ibatis.annotations.Param;
import vo.EasybuyAll;
public interface EasybuyOrderDoMapper {
long countByExample(EasybuyOrderDetailExample example);
int deleteByExample(EasybuyOrderDetailExample example);
int deleteByPrimaryKey(Integer id);
int insert(EasybuyOrderDetail record);
int insertSelective(EasybuyOrderDetail record);
List<EasybuyOrderDetail> selectByExample(EasybuyOrderDetailExample example);
EasybuyOrderDetail selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") EasybuyOrderDetail record, @Param("example") EasybuyOrderDetailExample example);
int updateByExample(@Param("record") EasybuyOrderDetail record, @Param("example") EasybuyOrderDetailExample example);
int updateByPrimaryKeySelective(EasybuyOrderDetail record);
int updateByPrimaryKey(EasybuyOrderDetail record);
List<EasybuyAll> selectAllByExample(EasybuyOrderDoExample easybuyOrderDoExample);
}
|
c4b42cdea705725e2870d9ebb9f7d4df2ae6e751
|
[
"Java",
"INI"
] | 15
|
Java
|
QQxian/easybuy
|
798ec9a0ad4cde6eb065709073affecf5c84b6b2
|
f19568ebdd7347c0343aabfb6d49cd5ec12e59de
|
refs/heads/master
|
<file_sep><html>
<head>
<title>Mengenal Manajemen Variabel</title>
</head>
<body>
<?php
$kampusku="STEKOM";
$alamat1="Jl. Majapahit 304 Semarang";
$alamat2="Jl. Majapahit 605 Semarang";
echo"<a href=\"Link2b.php?kampusku=$kampusku&alamat1=$alamat1&alamat2=$alamat2\">Kampusku</a>";
?>
</body>
</html>
|
c17104e002f83c94253825ab37af671c8ed5d61d
|
[
"PHP"
] | 1
|
PHP
|
Afririko/Jobsheet7
|
83bf9554aaed5b34aa79ff1681941d60e450ddc7
|
f6a251b46f926525661a7d7f14dd2d982ed0f782
|
refs/heads/master
|
<repo_name>cuchifrito/ritmodelavida<file_sep>/memnat_intro_es.html
<!DOCTYPE HTML>
<html> <head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MEMORIA DE LA NATURALEZA: EL RITMO DE LA VIDA - por <NAME></title>
<link rel="stylesheet" type="text/css" href="css/memnat.css">
<link rel="stylesheet" href="css/gridism.css">
</head>
<body>
<h1></h1>
<div class="grid">
<div class="unit whole center">
<b>MEMORIA DE LA NATURALEZA: EL RITMO DE LA VIDA</b>
</div>
<div class="unit whole center">
por <NAME>
</div>
<div class="unit whole center">
<nav>
<b>Introducción</b>
<a href="memnat_stmt_es.html">Declaratoria</a>
<a href="memnat_manif_es.html">Manifiesto</a>
<a href="memnat_clock1_es.html">Reloj 1</a>
<a href="memnat_clock2_es.html">Reloj 2</a>
<a href="memnat_clock3_es.html">Reloj 3</a>
<a href="memnat_art_es.html">Vistas de la Instalación</a>
</nav>
</div>
<div class="unit whole left">
<p class="p8">
Deseo expresar mi agradecimiento al Museo de Arte de Ponce, a su junta de síndicos de la fundación <NAME>; a su directora ejecutiva <NAME>; a su curador asociado de arte europeo <NAME> d'Ors; a la coordinadora de exposiciones y asistente curatorial <NAME>, por invitarme a presentar mi obra en el Museo de Arte de Ponce para esta temporada de otoño de 2016.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
También quiero expresar mi agradecimiento a Soraya Serra, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, y demás empleados del museo quienes han estado trabajando arduamente para la realización de esta instalación. También al grupo de guías docentes del museo.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Dedico esta instalación a mi querida madre <NAME>, a mi querida esposa <NAME>, a mi hija, a mis tres nietas, a mi nieto, a mi dos hermanos y demás familia y amigos, al poblado de la Playa de Ponce, al pueblo de Ponce y a nuestro país Puerto Rico. También dedico esta exposición a todos los artista ponceños, de la región sur y de todo Puerto Rico, que a diario manifiestan su sentir más profundo de identidad, de pertenencia histórica y de espiritualidad.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
También quiero agradecer enormemente a <NAME>, programador de informática radicado en la Ciudad de Nueva York, y a <NAME>, especialista de retoque de imágenes digitales quienes colaboraron conmigo en la programación de la página web que creé especialmente para esta instalación.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Me siento honrado como artista Playero, Ponceño y Puertorriqueño en compartir mi perspectiva como un artista que hace referencia a la arteología. En esta instalación titulada <i>Memoria de la naturaleza: el ritmo de la vida</i>, me he concentrado en tres aspectos de mi trabajo como arteologista. En primer lugar, me referiré brevemente a mi filosofía como arteologista y a mi concepción artística relacionada con esta instalación. En segundo lugar, señalaré el aspecto místico de esta instalación con la visión mística del museo. Y, en tercer lugar, para concluir, quiero presentar mi posición acerca de la nueva era como parte de esta instalación.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Como he expresado en mi manifiesto, el arteologista es como el ave fénix recién nacida, que guarda los restos de sus antepasados en un lugar sagrado antes de iniciar el viaje hacia una nueva era. El arteologista medita sobre la realidad, observando y escuchando la verdad arraigada en el pasado, el presente y el futuro. Como un egregor o un griot, el arteologista ayuda a fermentar y madurar las conexiones que en el arte contemporáneo están vinculadas a la identidad cultural, el sentido histórico y la transformación espiritual.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Así como el arteologista escarba en esos hoyos donde se ha enterrado la verdad para encontrarse con el terreno fértil, la raíz, y la esencia que se deriva de esa búsqueda de la verdad y la transformación, así ha sido la exploración del proceso estético para el desarrollo de esta instalación por los pasados seis años.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
<i>Memoria de la naturaleza: el ritmo de la vida</i> es, precisamente, la búsqueda de la conexión que existe con el equilibrio de la vida, que proviene de las energías primordiales de la naturaleza como lo son el éter, el aire, el fuego, la tierra y el agua. También proviene de culturas ancestrales como la taína, la africana o la védica, que han influido grandemente en nuestra civilización mostrándonos el camino hacia la armonía con la naturaleza, expresado por medio de símbolos o códigos que marcan el ritmo de la vida. Además de establecer un lenguaje a partir de su sentir más profundo como seres humanos.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
En esta instalación, respondo a la luz del sol del Caribe que entra al Museo de Arte de Ponce por la sexta claraboya diseñada por el arquitecto <NAME>. La influencia vibratoria de la luz energética de sol nos afecta cada 24 minutos. Esta vibración energética es la misma energía en todas las partes del mundo. Además, esta energía no se puede crear ni destruir. Esta es la energía de la luz del sol que se proyecta sobre el ensamblaje multimedia en el centro de la instalación. El libro en este ensamblaje muestra dos tabletas conectadas al internet y a la página web <a href="http://ritmodelavida.github.io">http://ritmodelavida.github.io</a>, que he diseñado exclusivamente para esta instalación. El libro está sostenido por una estructura de metal anclada a una pintura circular de piso. Esta página web nos permite interactuar con los símbolos de los <i>tattwas</i> que están representados por medio de relojes de frecuencia programados a partir del alba en Ponce, Puerto Rico.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Esta proyección energética se dirige del centro de la instalación hacia los cuatro puntos cardinales, donde se encuentra mi interpretación de los <i>tattwas</i> en las pinturas realizadas con el medio de la encáustica en cada una de las paredes. También, justo sobre estas pinturas y debajo del libro, se encuentran desplegadas unas pinturas pequeñas que representan los símbolos geométricos de los <i>tattwas</i> para facilitar la interacción entre los relojes de frecuencia en las tabletas y las pinturas.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Al escanear el sello QR que se encuentra en la primera cédula con sus celulares, o tabletas digitales, el visitante puede conectarse con la página web y usarla libremente mientras camina por el museo, aprecia las obras y continúa dialogando con la instalación. Además el público puede interactuar desde cualquier parte del mundo con la instalación a la hora de Ponce mientras la exposición esté abierta en el museo. Cuando la exposición termine, el reloj de frecuencia se abrirá universalmente.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
<i>Memoria de la naturaleza: el ritmo de la vida</i> hace referencia a la visión mística del Museo de Arte de Ponce. Nuestro museo fue construido en dirección a la salida del sol, en la región sur de Puerto Rico y frente al Mar Caribe. Podemos apreciar la luz del alba, que entra al museo por la pared de cristal del jardín Granada que mira hacia el este. Esta luz continúa entrando por las ventanas y las siete claraboyas colocadas en el techo del museo, y es dirigida por las paredes diagonales que contribuyen a la iluminación natural y a la acústica. Al atardecer, por la pared oeste podemos apreciar la puesta de sol.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Este concepto de las claraboyas por donde entra la luz del sol es común en los museos. Tomemos el caso de la claraboya piramidal del Museo del Louvre de París, diseñada por el arquitecto <NAME>, que recibe la luz del sol de la ciudad de París, o la claraboya y paredes del Museo Metropolitano diseñadas por el mismo arquitecto, que reciben la luz del sol de la ciudad enigmática de Nueva York, o tantos otros museos del mundo. El sol es tan importante para el Museo de Arte de Ponce como para la mayoría de los museos del mundo que tienen alguna forma de iluminación por claraboyas, ventanas y puertas de cristal.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Para concluir, a modo de reflexión quiero decir que somos seres agraciados porque estamos presenciando y articulando el principio de esta nueva era y del siglo XXI. En los pasados 16 años, nos ha tocado confrontar y transformar los parámetros existentes a todos los niveles de la vida para beneficio de futuras generaciones. Como sabemos, el principio de la nueva era se caracteriza por el derrumbe de imperios y levantamiento de otros. Particularmente, esta era se ha caracterizado como un periodo de crisis a nivel global. Por lo tanto, tenemos la responsabilidad colectivamente de dirigir nuestro planeta en una dirección positiva para el beneficio de la humanidad y su medio ambiente.
</p>
<p class="p8"><b></b><br></p>
<p class="p8">
Dentro de este contexto histórico, expreso mi sentir como un arteologista. Espero que mi instalación <i>Memoria de la naturaleza: el ritmo de la vida</i>, que hace referencia a la energía como la misma en todas las partes del mundo y subraya que esta energía no se puede crear ni destruir (pero si influye en cada instante de nuestras vidas), se experimente como un arte de reflexión acerca del proceso creativo, de equilibrio y vibración energética. Y que el acto de la voluntad individual y colectiva sea como mirar y escuchar la luz del interior y el sentir profundo de las vibraciones cósmicas de esta nueva era.
</p>
</div>
<div class="unit whole center">
<nav>
<b>Introducción</b>
<a href="memnat_stmt_es.html">Declaratoria</a>
<a href="memnat_manif_es.html">Manifiesto</a>
<a href="memnat_clock1_es.html">Reloj 1</a>
<a href="memnat_clock2_es.html">Reloj 2</a>
<a href="memnat_clock3_es.html">Reloj 3</a>
<a href="memnat_art_es.html">Vistas de la Instalación</a>
</nav>
</div>
<div class="unit whole center">
<nav>
<a href="memnat_intro_en.html">English</a>
</nav>
</div>
</div>
</body> </html>
<file_sep>/README.md
# ritmodelavida
Copyright 2016 <NAME>
https://ritmodelavida.github.io
<file_sep>/PonceSunrise/PonceSunrise.go
package main
import (
"flag"
"fmt"
"github.com/nathan-osman/go-sunrise"
"time"
)
func main() {
var year = flag.Int("year", 2019, "year for sunrise calendar generation")
flag.Parse()
monthLastDay := map[time.Month]int{
time.January: 31,
time.February: 28,
time.March: 31,
time.April: 30,
time.May: 31,
time.June: 30,
time.July: 31,
time.August: 31,
time.September: 30,
time.October: 31,
time.November: 30,
time.December: 31,
}
loc := time.FixedZone("UTC-4", -4*60*60) // PR timezone
for month := time.January; month <= time.December; month++ {
for day := 1; day <= monthLastDay[month]; day++ {
rise, _ := sunrise.SunriseSunset(
18.001667, -66.606667, // Ponce, PR
*year, month, day,
)
fmt.Println(rise.In(loc).Format("20060102: {'hour': 3, 'minute': 4},"))
}
}
}
|
00ab83de4c3ed6a19967afb0d565046950359e1b
|
[
"Markdown",
"Go",
"HTML"
] | 3
|
HTML
|
cuchifrito/ritmodelavida
|
5614e7bdfcfd8f1e636a6f5811f6d4eb1fdb04b1
|
af30a19ce8f19f2fb58e2dc7bf6a36c497daeb2d
|
refs/heads/master
|
<file_sep>#include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 0.5;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.5;
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
// weights_computed is set to false
weights_computed = false;
/**
TODO:
Complete the initialization. See ukf.h for other member properties.
Hint: one or more values initialized above might be wildly off...
*/
}
UKF::~UKF() {}
void UKF::AugmentedSigmaPoints(MatrixXd* Xsig_aug){
n_x_ = x_.size();
n_aug_ = n_x_ + 2;
lambda_ = 3 - n_aug_;
//create augmented mean state
VectorXd x_aug = VectorXd(n_aug_);
x_aug.head(5) = x_;
x_aug(5) = 0;
x_aug(6) = 0;
//create augmented covariance matrix
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
P_aug.fill(0);
P_aug.topLeftCorner(n_x_, n_x_) = P_;
P_aug(n_x_, n_x_) = std_a_ * std_a_;
P_aug(n_x_+1, n_x_+1) = std_yawdd_ * std_yawdd_;
//create square root matrix
MatrixXd L = P_aug.llt().matrixL();
//create augmented sigma points
//MatrixXd Xsig_aug_ = MatrixXd(n_aug_, 2 * n_aug_ + 1);
Xsig_aug->col(0) = x_aug;
for (int i = 0; i < n_aug_; i++){
Xsig_aug->col(i + 1) = x_aug + sqrt(lambda_ + n_aug_) * L.col(i);
Xsig_aug->col(n_aug_ + i + 1) = x_aug - sqrt(lambda_ + n_aug_) * L.col(i);
}
}
double CircularPhi(double Phi){
while(Phi < -M_PI) Phi += 2 * M_PI;
while(Phi > M_PI) Phi -= 2 * M_PI;
return Phi;
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/**
TODO:
Complete this function! Estimate the object's location. Modify the state
vector, x_. Predict sigma points, the state, and the state covariance matrix.
*/
n_x_ = x_.size();
n_aug_ = n_x_ + 2;
MatrixXd Xsig_aug_ = MatrixXd(n_aug_, 2 * n_aug_ + 1);
AugmentedSigmaPoints(&Xsig_aug_);
Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1);
for (int i = 0; i < 2 * n_aug_ + 1; i++){
VectorXd xaug = Xsig_aug_.col(i);
double p_x = xaug(0);
double p_y = xaug(1);
double v = xaug(2);
double yaw = xaug(3);
double yawd = xaug(4);
double nu_a = xaug(5);
double nu_yawdd = xaug(6);
double px_p;
double py_p;
//avoid division by zero
if (fabs(yawd) > 0.001) {
px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw));
py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) );
}
else {
px_p = p_x + v*delta_t*cos(yaw);
py_p = p_y + v*delta_t*sin(yaw);
}
double v_p = v;
double yaw_p = yaw + yawd*delta_t;
double yawd_p = yawd;
//adding noise
px_p += 0.5 * delta_t * delta_t * cos(yaw) * nu_a;
py_p += 0.5 * delta_t * delta_t * sin(yaw) * nu_a;
v_p += delta_t * nu_a;
yaw_p += 0.5 * delta_t * delta_t * nu_yawdd;
yawd_p += delta_t * nu_yawdd;
//write predicted sigma point into right column
Xsig_pred_(0,i) = px_p;
Xsig_pred_(1,i) = py_p;
Xsig_pred_(2,i) = v_p;
Xsig_pred_(3,i) = yaw_p;
Xsig_pred_(4,i) = yawd_p;
}
}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Make sure you switch between lidar and radar
measurements.
*/
if (!is_initialized_){
is_initialized_ = true;
if (meas_package.sensor_type_ == MeasurementPackage::RADAR){
float ro = meas_package.raw_measurements_(0);
float theta = meas_package.raw_measurements_(1);
float ro_dot = meas_package.raw_measurements_(2);
float Px = ro * cos(theta);
float Py = ro * sin(theta);
float V = ro_dot;
x_ << Px, Py, V, 0, 0;
P_ = MatrixXd::Identity(x_.size(), x_.size());
P_ *= 0.5;
time_us_ = meas_package.timestamp_;
}
else if (meas_package.sensor_type_ == MeasurementPackage::LASER){
float Px = meas_package.raw_measurements_(0);
float Py = meas_package.raw_measurements_(1);
x_ << Px, Py, 0, 0, 0;
P_ = MatrixXd::Identity(x_.size(), x_.size());
P_ *= 0.5;
time_us_ = meas_package.timestamp_;
}
return;
}
else{
float delta_t = (meas_package.timestamp_ - time_us_) / 1000000.0;
time_us_ = meas_package.timestamp_;
Prediction(delta_t);
if (meas_package.sensor_type_ == MeasurementPackage::LASER){
UpdateLidar(meas_package);
}
else if (meas_package.sensor_type_ == MeasurementPackage::RADAR){
UpdateRadar(meas_package);
}
}
}
void UKF::ComputeWeights(){
weights_ = VectorXd(2 * n_aug_ + 1);
weights_(0) = lambda_ / (lambda_ + n_aug_);
float weight = 1 / (2 * (lambda_ + n_aug_));
for (int i = 1; i < 2 * n_aug_ + 1; i++){
weights_(i) = weight;
}
}
void UKF::PredictMeanAndCovariance(VectorXd* x_pred, MatrixXd* P_pred, MatrixXd Xsig, int AngleInd){
if (!weights_computed){
ComputeWeights();
weights_computed = true;
}
int n = x_pred->size();
VectorXd x = VectorXd(n);
MatrixXd P = MatrixXd(n, n);
x.fill(0);
P.fill(0);
//compute mean
for (int i = 0; i < 2 * n_aug_ + 1; i++){
x = x + Xsig.col(i) * weights_(i);
}
//compute covariance
for (int i = 1; i < 2 * n_aug_ + 1; i++){
VectorXd x_diff = Xsig.col(i) - x;
x_diff(AngleInd) = CircularPhi(x_diff(AngleInd));
P = P + weights_(i) * (Xsig.col(i) - x) * (Xsig.col(i) - x).transpose();
}
*x_pred = x;
*P_pred = P;
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use lidar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the lidar NIS.
*/
MatrixXd P_pred = MatrixXd(n_x_, n_x_);
VectorXd x_pred = VectorXd(n_x_);
PredictMeanAndCovariance(&x_pred, &P_pred, Xsig_pred_, 3);
x_ = x_pred;
P_ = P_pred;
int nl = meas_package.raw_measurements_.size();
VectorXd z = meas_package.raw_measurements_;
MatrixXd H_(nl, n_x_);
H_ << 1, 0, 0, 0, 0,
0, 1, 0, 0, 0;
MatrixXd R_(nl, nl);
R_ << std_laspx_*std_laspx_, 0,
0, std_laspy_*std_laspy_;
VectorXd z_pred = H_ * x_;
VectorXd y = z - z_pred;
MatrixXd Ht = H_.transpose();
MatrixXd S = H_ * P_ * Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd PHt = P_ * Ht;
MatrixXd K = PHt * Si;
//new estimate
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
x_(3) = CircularPhi(x_(3));
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
TODO:
prediction
Complete this function! Use radar data to update the belief about the object's
position. Modify the state vector, x_, and cov3ariance, P_.
You'll also need to calculate the radar NIS.
*/
VectorXd z = meas_package.raw_measurements_;
int nr = z.size();
MatrixXd R = MatrixXd(nr, nr);
R << std_radr_ * std_radr_, 0, 0,
0, std_radphi_ * std_radphi_, 0,
0, 0, std_radrd_ * std_radrd_;
MatrixXd Zsig(nr, 2 * n_aug_ + 1);
for (int i = 0; i < 2 * n_aug_ + 1; i++){
// extract values for better readibility
double p_x = Xsig_pred_(0,i);
double p_y = Xsig_pred_(1,i);
double v = Xsig_pred_(2,i);
double yaw = Xsig_pred_(3,i);
//yaw = CircularPhi(yaw);
double v1 = cos(yaw)*v;
double v2 = sin(yaw)*v;
// measurement model
Zsig(0,i) = sqrt(p_x*p_x + p_y*p_y); //r
Zsig(1,i) = atan2(p_y,p_x); //phi
//Zsig(1,i) = CircularPhi(Zsig(1,i));
Zsig(2,i) = (p_x*v1 + p_y*v2 ) / Zsig(0,i); //rd
}
//Calculate Mean of predicted sigma points in polar domain
MatrixXd P_pred = MatrixXd(nr, nr);
VectorXd z_pred = VectorXd(nr);
PredictMeanAndCovariance(&z_pred, &P_pred, Zsig, 1);
//Calculate Mean of predicted sigma points in cartesian domain
MatrixXd P = MatrixXd(n_x_, n_x_);
VectorXd x_pred = VectorXd(n_x_);
PredictMeanAndCovariance(&x_pred, &P, Xsig_pred_, 3);
x_ = x_pred;
P_ = P;
//Calculating S
MatrixXd S = P_pred + R;
//Calculating Tc
MatrixXd Tc = MatrixXd(n_x_, nr);
Tc.fill(0);
for (int i = 0; i < 2 * n_aug_ + 1; i++){
VectorXd z_diff = Zsig.col(i) - z_pred;
z_diff(1) = CircularPhi(z_diff(1));
VectorXd x_diff = Xsig_pred_.col(i) - x_;
x_diff(3) = CircularPhi(x_diff(3));
if (!weights_computed){
ComputeWeights();
weights_computed = true;
}
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//Kalman gain K
MatrixXd K = Tc * S.inverse();
//residual
VectorXd z_diff = z - z_pred;
z_diff(1) = CircularPhi(z_diff(1));
//Update State mean and Covariance Matrix
x_ = x_ + K * z_diff;
P_ = P_ - K * S * K.transpose();
x_(3) = CircularPhi(x_(3));
}
|
28947785af00c6ef83b7cecd54b8b3fecd8934c3
|
[
"C++"
] | 1
|
C++
|
Jasmamu1992/UnscentedKalmanFilter
|
fa432ec1f347a546598bd63a9e05e004e866d88f
|
c6c87c903f329a6e1d871049acea4fb07f09c7d0
|
refs/heads/master
|
<file_sep>package com.hit.view;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class PageFaultReplacementAmountPanel extends JPanel
{
protected static JTextField PageFault;
protected static JTextField PageReplacement;
public PageFaultReplacementAmountPanel()
{
PageFault = new JTextField("0",2);
PageReplacement = new JTextField("0",2);
PageFault.setFont(new Font("Arial",Font.ITALIC,12));
PageReplacement.setFont(new Font("Arial",Font.ITALIC,12));
JLabel PageFaultLabel = new JLabel("Page Fault Amount");
PageFaultLabel.setFont(new Font("Arial",Font.BOLD,14));
JLabel PageReplacementLabel = new JLabel("Page Replacement Amount");
PageReplacementLabel.setFont(new Font("Arial",Font.BOLD,14));
this.add(PageFaultLabel);
this.add(PageFault);
this.add(PageReplacementLabel);
this.add(PageReplacement);
}
public static int getPageReplacementCount()
{
return Integer.parseInt(PageReplacement.getText());
}
public static int getPageFaultCount()
{
return Integer.parseInt(PageFault.getText());
}
public static void setPageFaultCount(int count)
{
PageFault.setText(String.valueOf(count));
}
public static void setPageReplacementCount(int count)
{
PageReplacement.setText(String.valueOf(count));
}
}<file_sep>package com.hit.driver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Observable;
import java.util.Scanner;
import java.util.logging.Level;
import com.hit.util.MMULogger;
import com.hit.view.View;
public class CLI extends Observable implements Runnable,View
{
private static final String LRU = "LRU";
private static final String MRU = "MRU";
private static final String RANDOM = "RANDOM";
private static final String START = "start";
private static final String STOP = "stop";
private Scanner cin;
private PrintWriter cout;
public CLI(InputStream in, OutputStream out)
{
this.cin = new Scanner(in);
this.cout = new PrintWriter(out);
}
@Override
public void run()
{
start();
}
@Override
public void start()
{
String[] algoAndCapacity = null;
String buffer = " ";
while (!buffer.toLowerCase().equals(STOP))
{
write("please press 'start' to start");
buffer = this.cin.nextLine();
if(buffer.equals(STOP))
break;
while(!buffer.toLowerCase().equals(START))
{
write("not a valid command \nplease enter 'start' to start");
buffer = cin.nextLine();
}
do
{
write("please enter required algorithm and RAM capacity");
buffer = cin.nextLine();
algoAndCapacity = buffer.split(" ");
}
while(!(algoAndCapacity.length == 2));
while ((!is_valid_algo(algoAndCapacity[0])) || (!is_integer(algoAndCapacity[1])))
{
MMULogger.getInstance().write("CLI: not a valid command entered", Level.SEVERE);
write("not a valid command \nplease enter valid algorithm and capacity");
buffer = cin.nextLine();
algoAndCapacity = buffer.split(" ");
}
write("Thank you");
//MMULogger.getInstance().write("RC:"+algoAndCapacity[1], Level.INFO);
}
System.out.println("stopped");
cin.close();
cout.close();
setChanged();
notifyObservers(algoAndCapacity);
return;
}
public void write(String s)
{
cout.println(s);
cout.flush();
}
public boolean is_valid_algo(String s)
{
if(s.toUpperCase().equals(LRU)|| s.toUpperCase().equals(MRU) || s.toUpperCase().equals(RANDOM))
{
return true;
}
return false;
}
public boolean is_integer(String s)
{
try
{
Integer.parseInt(s);
return true;
}
catch (Exception e){}
return false;
}
}<file_sep>package com.hit.view;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import javax.swing.JFrame;
public class MMUView extends Observable implements View {
private List<String> logFile ;
private int numOfProcesses;
private HashMap<String,Integer> processesSelected;
private int i;
public MMUView() {
setLogFile(logFile);
}
private void createAndShowGUI()
{
//Create and set up the window.
JFrame Mframe = new JFrame("MMU Simulator");
Mframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Mframe.setPreferredSize(new Dimension(2500,300));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim =tk.getScreenSize();
int xPos = (dim.width/4)-(Mframe.getWidth()/4);
int yPos = (dim.height/4)-(Mframe.getHeight()/4);
Mframe.setLocation(xPos, yPos);
Container container = Mframe.getContentPane();
TablePanel tablePanel = new TablePanel(); //Table panel
tablePanel.setBounds(10, 10, 670, 175);
container.add(tablePanel,BorderLayout.CENTER);
i=1;
setNumOfProcesses(logFile.get(i));
i++;
ProcessesPanel processesPanel = new ProcessesPanel(numOfProcesses,this); //Processes list panel
processesPanel.setBounds(700, 100, 150, 200);
container.add(processesPanel,BorderLayout.WEST);
ButtonsPlayPanel playpanel = new ButtonsPlayPanel(this); //Play and Play all buttons
playpanel.setBounds(30, 200, 200, 200);
playpanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(playpanel,BorderLayout.SOUTH);
PageFaultReplacementAmountPanel PFRFPanel = new PageFaultReplacementAmountPanel(); // PF/PR counters panel
PFRFPanel.setBounds(690,50,200,150);
container.add(PFRFPanel,BorderLayout.EAST);
Mframe.pack();
Mframe.setVisible(true);
}
@Override
public void start()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
public void setLogFile(List<String> log)
{
this.logFile =log;
}
public void setNumOfProcesses(String numOfProcesses)
{
String s = numOfProcesses.substring(3);
this.numOfProcesses = Integer.parseInt(s);
}
public void setProcessesSelected(HashMap<String,Integer> processesSelected)
{
this.processesSelected = processesSelected;
}
public void playLog()
{
if (i==logFile.size())
{
System.out.println("No more commands");
return;
}
if(processesSelected==null)
{
System.out.println("No Process was selected");
return;
}
if (logFile.get(i).contains("PF"))
{ //page fault
PageFaultReplacementAmountPanel.setPageFaultCount(PageFaultReplacementAmountPanel.getPageFaultCount()+1); //changing the Page-Fault count
}
else if (logFile.get(i).contains("PR"))
{ //page replacement
PageFaultReplacementAmountPanel.setPageReplacementCount(PageFaultReplacementAmountPanel.getPageReplacementCount()+1); //changing the Page-replacement count
String pagetoremove = logFile.get(i).substring(logFile.get(i).indexOf(" ")+1,logFile.get(i).indexOf("MTR")-1);//Extracting the MTH page
TablePanel.editColumn(Integer.parseInt(pagetoremove)," ","0,0,0,0,0");
}
else if(logFile.get(i).contains("GP"))
{ //get pages
String processnum = logFile.get(i).substring(logFile.get(i).indexOf("P")+3,logFile.get(i).indexOf(" ")); //extracting the process number from the string
String pagenum = logFile.get(i).substring(logFile.get(i).indexOf(" ")+1,logFile.get(i).indexOf("[")-1); //extracting the page number from the string
if(processesSelected.containsKey(processnum))
{ //if it is a process the user wish to see
TablePanel.editColumn(Integer.parseInt(pagenum),pagenum,logFile.get(i).substring(logFile.get(i).indexOf("[")+1, logFile.get(i).indexOf("]")));
}
}
i++;
}
public void playAllLog()
{
if(i==logFile.size())
{
System.out.println("No more commands");
return;
}
if(processesSelected==null)
{
System.out.println("No Process was selected");
return;
}
for(;i<logFile.size();i++)
{
if (logFile.get(i).contains("PF"))
{ //page fault
PageFaultReplacementAmountPanel.setPageFaultCount(PageFaultReplacementAmountPanel.getPageFaultCount()+1); //changing the Page-Fault count
}
else if (logFile.get(i).contains("PR"))
{ //page replacement
PageFaultReplacementAmountPanel.setPageReplacementCount(PageFaultReplacementAmountPanel.getPageReplacementCount()+1); //changing the Page-replacement count
String pagetoremove = logFile.get(i).substring(logFile.get(i).indexOf(" ")+1,logFile.get(i).indexOf("MTR")-1);//Extracting the MTH page
TablePanel.editColumn(Integer.parseInt(pagetoremove)," ","0,0,0,0,0");
}
else if(logFile.get(i).contains("GP"))
{ //get pages
String processnum = logFile.get(i).substring(logFile.get(i).indexOf("P")+3,logFile.get(i).indexOf(" ")); //extracting the process number from the string
String pagenum = logFile.get(i).substring(logFile.get(i).indexOf(" ")+1,logFile.get(i).indexOf("[")-1); //extracting the page number from the string
if(processesSelected.containsKey(processnum))
{ //if it is a process the user wish to see
TablePanel.editColumn(Integer.parseInt(pagenum),pagenum,logFile.get(i).substring(logFile.get(i).indexOf("[")+1, logFile.get(i).indexOf("]")));
}
}
}
}
}<file_sep>package com.hit.processes;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import com.hit.memoryunits.MemoryManagementUnit;
import com.hit.memoryunits.Page;
import com.hit.util.MMULogger;
public class Process implements Callable <Boolean>
{
private int processId;
private MemoryManagementUnit mmu;
private ProcessCycles processCycles;
public Process(int id, MemoryManagementUnit mmu, ProcessCycles processCycles)
{
this.processId = id;
this.mmu = mmu;
this.processCycles = processCycles;
}
public int getId()
{
return this.processId;
}
public void setId(int Id)
{
this.processId = Id;
}
@Override
public Boolean call()
{
for (ProcessCycle cycle : this.processCycles.getProcessCycles())
{
Object pagesObject[] = cycle.getPages().toArray();
Long[] pagesIds = Arrays.copyOf(pagesObject, pagesObject.length, Long[].class);
Page<byte[]>[] pages = this.mmu.getPages(pagesIds);
for (int i = 0; i < pages.length; i++)
{
pages[i].setContent(cycle.getData().get(i));
MMULogger.getInstance().write("GP:p"+this.getId()+" "+pages[i].getPageId()+" "+Arrays.toString(pages[i].getContent())+"\n", Level.INFO);
}
}
return true;
}
}
/*
@Override
public Boolean call()
{
final String EMPTY_STRING = "";
List<ProcessCycle> cycles = this.processCycles.getProcessCycles();
List<Long> pagesId;
List<byte[]> data;
Page<byte[]> page;
Page<byte[]>[] pages;
try
{
for(ProcessCycle cycle : cycles)
{
pagesId = cycle.getPages();
data = cycle.getData();
pages = this.mmu.getPages(pagesId.toArray(new Long[pagesId.size()]));
for(int i = 0; i < pages.length; i++)
{
page = pages[i];
page.setContent(data.get(i));
MMULogger.getInstance().write("GP:p"+this.getId()+" "+pages[i].getPageId()+" "+Arrays.toString(pages[i].getContent()), Level.INFO);
}
MMULogger.getInstance().write(EMPTY_STRING, Level.INFO);
}
}
catch(Exception e)
{
MMULogger.getInstance().write(e.getMessage(), Level.SEVERE);
return false;
}
return true;
}
}
*/
<file_sep>package com.hit.memoryunits;
import java.util.HashMap;
import java.util.Map;
public class RAM
{
private int initialCapacity;
private Map<Long, Page<byte[]>> pagesMapInRam;
public RAM(int initialCapacity)
{
this.initialCapacity = initialCapacity;
this.pagesMapInRam = new HashMap<>(this.initialCapacity);
}
public Map<Long, Page<byte[]>> getPages()
{
return this.pagesMapInRam;
}
public void setPages(Map<Long, Page<byte[]>> pages)
{
this.pagesMapInRam = pages;
}
public Page<byte[]> getPage(Long pageId)
{
return this.pagesMapInRam.get(pageId);
}
public void addPage(Page<byte[]> addPage)
{
this.pagesMapInRam.put(addPage.getPageId(), addPage);
}
public void removePage(Page<byte[]> pageToRemove)
{
this.pagesMapInRam.remove(pageToRemove.getPageId());
}
public Page<byte[]>[] getPages(Long[] pageIds)
{
@SuppressWarnings("unchecked")
Page<byte[]>[] requestedPagesArr = new Page[pageIds.length];
for (int i = 0; i < requestedPagesArr.length; i++)
{
if(this.pagesMapInRam.containsKey(pageIds[i]))
requestedPagesArr[i] = this.pagesMapInRam.get(pageIds[i]);
else
{
requestedPagesArr[i] = null;
}
}
return requestedPagesArr;
}
public void addPages(Page<byte[]>[] addPages)
{
for (Page<byte[]> page : addPages)
{
this.addPage(page);
}
}
public void removePages(Page<byte[]>[] remvoePages)
{
for (Page<byte[]> page : remvoePages)
{
this.removePage(page);
}
}
public int getInitialCapacity()
{
return this.initialCapacity;
}
public void setInitialCapacity(int initialCapacity)
{
this.initialCapacity = initialCapacity;
}
public int getMapSize()
{
return this.pagesMapInRam.size();
}
}<file_sep>package com.hit.memoryunits;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import com.hit.algorithm.IAlgoCache;
import com.hit.exception.HardDiskException;
import com.hit.util.MMULogger;
public class MemoryManagementUnit
{
private IAlgoCache<Long, Long> algo;
private RAM ram;
public MemoryManagementUnit(int ramCapacity, IAlgoCache<Long, Long> algo)
{
this.algo = algo;
ram = new RAM(ramCapacity);
MMULogger.getInstance().write("RC:" + ramCapacity, Level.INFO);
}
public IAlgoCache<Long, Long> getAlgo()
{
return this.algo;
}
public void SetAlgo(IAlgoCache<Long, Long> someAlgo)
{
this.algo = someAlgo;
}
public RAM getRam()
{
return this.ram;
}
public void setRam(RAM someRam)
{
this.ram = someRam;
}
public Page<byte[]>[] getPages(Long[] pageIds)
{
HardDisk hd = HardDisk.getInstance();
@SuppressWarnings("unchecked")
Page<byte[]>[] pageToReturn = new Page[pageIds.length];
Page<byte[]> moveToHdPage = null;
Long idPageReplace = null;
for(int i=0; i<pageIds.length;i++)
{
if(algo.getElement(pageIds[i]) == null)
{
//if RAM is not full
if(ram.getMapSize()<=ram.getInitialCapacity())
{
algo.putElement(pageIds[i],pageIds[i]);
try {
ram.addPage(hd.pageFault(pageIds[i]));
MMULogger.getInstance().write("PF:"+pageIds[i], Level.INFO);
} catch (HardDiskException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//else: Do logic of full RAM
else
{
idPageReplace = algo.putElement(pageIds[i],pageIds[i]);
moveToHdPage = ram.getPage(idPageReplace);
try {
ram.addPage(hd.pageReplacement(moveToHdPage, pageIds[i]));
} catch (HardDiskException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
pageToReturn[i] = ram.getPage(pageIds[i]);
}
return pageToReturn;
}
}<file_sep># MmuProject
a project that simulates a memory management unit, with user interface.
<file_sep>
package hit.memoryunits;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.hit.algorithm.IAlgoCache;
import com.hit.algorithm.LRUAlgoCacheImpl;
import com.hit.memoryunits.MemoryManagementUnit;
import com.hit.memoryunits.Page;
public class MMUTest
{
private IAlgoCache<Long,Long> algo = new LRUAlgoCacheImpl<>(30);
private MemoryManagementUnit mmu = new MemoryManagementUnit(30, algo);
@Test
public void testMemoryManagementUnit() throws IOException
{
//ram is empty - page_fulat
Long[] pages = new Long[30];
for (int i = 0; i < pages.length; i++)
{
pages[i] = new Long(i);
}
Page<byte[]>[] actual = mmu.getPages(pages);
for (int i = 0; i < actual.length; i++)
{
Assert.assertEquals(pages[i], actual[i].getPageId());
}
//insert an existing pages
Long[] existingPages = new Long[5];
for (int i = 0; i < existingPages.length; i++)
{
existingPages[i] = new Long(i+1);
}
mmu.getPages(existingPages);
//ram is full - page_remplacement
Long[] newPages = new Long[5];
for (int i = 0; i < newPages.length; i++)
{
newPages[i] = new Long(30+i);
}
}
/*@Test
public void testMemoryManagementUnitTest(){
IAlgoCache<Long, Long> algo = new LRUAlgoCacheImpl<>(5);
MemoryManagementUnit mmu = new MemoryManagementUnit(5, algo);
Page<byte[]>[] pages = null;
//Get 1-5 pages (RAM capacity equals to 5, only pageFault method is tested)
Long[] pageIds = new Long[] {(long) 1,(long) 2,(long) 3,(long) 4,(long) 5};
Long[] expected = new Long[] {(long) 1,(long) 2,(long) 3,(long) 4,(long) 5};
try {
pages = mmu.getPages(pageIds);
} catch (IOException e) {
System.out.println("HardDisk file is missing");
e.printStackTrace();
}
if(pages != null) {
for(int i = 0 ; i < pages.length ; i++) {
Assert.assertEquals(expected[i], pages[i].getPageId());
}
}
//Get 9-20 pages (RAM capacity is full, pageReplacement method is tested)
pageIds = new Long[13];
expected = new Long[13];
for(int i = 9 ; i < 21 ; i++) {
pageIds[i-9] = (long) i;
}
pageIds[12] = (long) 50;
for(int i = 9 ; i < 21 ; i++) {
expected[i-9] = (long) i;
}
expected[12] = (long) 50;
try {
pages = mmu.getPages(pageIds);
} catch (IOException e) {
System.out.println("HardDisk file is missing");
e.printStackTrace();
}
if(pages != null) {
for(int i = 0 ; i < pages.length ; i++) {
Assert.assertEquals(expected[i], pages[i].getPageId());
}
}
}*/
}
<file_sep>package com.hit.util;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class MMULogger
{
public final static String DEFAULT_FILE_NAME = "logs/log.txt";
private FileHandler handler;
private static MMULogger instance = new MMULogger();
private MMULogger()
{
try
{
handler = new FileHandler(DEFAULT_FILE_NAME);
handler.setFormatter(new OnlyMessageFormatter());
}
catch(Exception e)
{
System.out.println("MMULoger (Delete after ) ");
// e.printStackTrace();
}
}
public static MMULogger getInstance()
{
return instance;
}
public synchronized void write(String command, Level level)
{
LogRecord logRecord = new LogRecord(level, command);
handler.publish(logRecord);
}
public class OnlyMessageFormatter extends Formatter
{
public OnlyMessageFormatter()
{
super();
}
@Override
public String format(final LogRecord record)
{
return record.getMessage() + System.lineSeparator();
}
}
}
|
aa7771756690d49cc877989cf42e9d6e76e7cee2
|
[
"Markdown",
"Java"
] | 9
|
Java
|
elads11/MmuProject
|
cfecfd3c5b879fb55aff17ac0f0ed5e49952c88d
|
1e44f398064fe806309c95ac2b46bbcb0806ed01
|
refs/heads/master
|
<file_sep>package DAO;
import java.util.List;
import logica.AccesoDatosException;
import modelo.Cafe;
public interface CafeDAO {
public List<Cafe> verTabla() throws AccesoDatosException;
public void actualizarVentasCafe(String cafe, int ventas) throws AccesoDatosException;
public void BuscarCafe(String cafe) throws AccesoDatosException ;
public void BorrarCafe(String cafe) throws AccesoDatosException;
public void InsertarCafe(String nom, int ID, float precio, int ventas, int total) throws AccesoDatosException ;
public void cafesProveedor(int id_prov) throws AccesoDatosException;
public void transferencia(String nom1, String nom2) throws AccesoDatosException;
public void cerrar();
}
<file_sep>package DAO;
import logica.AccesoDatosException;
public class FactoriaDAO {
private static FactoriaDAO instance;
private static final String libroDAO = "JDBCLibroDAO";
public static FactoriaDAO getInstance() {
if (instance == null) {
instance = new FactoriaDAO();
}
return instance;
}
private FactoriaDAO() {
}
/**
* Devuelve un objeto DAO adecuado dependiendo de como est� implementada la
* persistencia a datos
*
* @return
* @throws AccesoDatosException
*/
public CafeDAO getCafeDAO() throws AccesoDatosException {
CafeDAO dao = null;
if (libroDAO.equals("JDBCLibroDAO")) {
dao = new JDBCCafeDAO();
}
return dao;
}
}<file_sep>package GUI;
import java.util.Scanner;
import DAO.Utilidades;
import logica.MercadoException;
import modelo.Cafes;
import modelo.Libros;
public class Pruebas {
public static void main(String[] args) {
Scanner lc = new Scanner(System.in);
System.out.print("Bienvenido a la aplicación de gestión de su base de datos:\n¿Qué desea hacer?");
int opcion = 0;
while (opcion != 3) {
Menu.menuPrincipal();
switch (lc.nextInt()) {
case 1:
try {
Cafes miCafe = new Cafes();
int opcionCaf = 0;
while (opcionCaf != 8) {
System.out.println("\n¿Qué desea hacer?");
Menu.menuCafes();
switch (lc.nextInt()) {
case 1:
InteraccionCaf.Ver(miCafe);
break;
case 2:
InteraccionCaf.Buscar(miCafe);
break;
case 3:
InteraccionCaf.Insertar(miCafe);
break;
case 4:
InteraccionCaf.Borrar(miCafe);
break;
case 5:
InteraccionCaf.updateVentas(miCafe);;
break;
case 6:
InteraccionCaf.BuscarDatosProv(miCafe);
break;
case 7:
InteraccionCaf.transferencia(miCafe);
break;
case 8:
opcionCaf = 8;
miCafe.cerrar();
break;
default:
System.out.println("introduzca un nº del 1 al 8");
}
}
} catch (MercadoException ex) {
System.out.println("Lo sentimos ocurrio un error en la apliacion" + ex.getMessage());
}
break;
case 2:
try {
Libros miLibro = new Libros();
int opcionLib = 0;
while (opcionLib != 13) {
System.out.println("\n¿Qué desea hacer?");
Menu.menuLibros();;
switch (lc.nextInt()) {
case 1:
InteraccionLib.Añadir(miLibro);
;
break;
case 2:
InteraccionLib.Borrar(miLibro);
;
break;
case 3:
InteraccionLib.Ver(miLibro);
;
break;
case 4:
InteraccionLib.update(miLibro);
break;
case 5:
InteraccionLib.obtener(miLibro);
break;
case 6:
InteraccionLib.VerInverso(miLibro);
break;
case 7:
InteraccionLib.updateVarios(miLibro);
break;
case 8:
InteraccionLib.mostrarFilas(miLibro);
break;
case 9:
InteraccionLib.updatePrecioPag(miLibro);
break;
case 10:
InteraccionLib.transaccionPrecio(miLibro);
break;
case 11:
InteraccionLib.añadirPag(miLibro);
break;
case 12:
InteraccionLib.duplicarLibro(miLibro);
break;
case 13:
opcionLib = 13;
miLibro.cerrar();
break;
default:
System.out.println("introduzca un nº del 1 al 13");
}
}
} catch (MercadoException ex) {
System.out.println("Lo sentimos ocurrio un error en la apliacion" + ex.getMessage());
}
break;
case 3:
System.out.println("Hasta Pronto!");
opcion=3;
break;
default:
System.out.println("introduzca un nº del 1 al 3");
}
}
}
}
|
6c1ddcdfe9f5c707cb80e62fe514b15ffc09609c
|
[
"Java"
] | 3
|
Java
|
Llorens92/AccesoDatos-Prac1
|
4a28001f4e77003b619d404c3c75ab4ac148f860
|
343bcb9fbca04c21cf4b34989e647e397c1b16d3
|
refs/heads/master
|
<repo_name>BassyKuo/GAN-tensorflow<file_sep>/01-VanillaGAN/README.md
# 01-VanillaGAN
## Python Version
* 3.6.0
## Python Packages Requirements
* tensorflow >= 1.1.0
* numpy >= 1.12.1
* scikit-learn >= 0.18.1
Pip insatll:
```sh
$ pip install -r requirements.txt
```
## Usage
Example:
* MNIST
```sh
$ python3 01-VanillaGAN_mnist.py train --max_epoch 1000 --out_dir mnist_output/
```
* CIFAR10
```sh
$ python3 01-VanillaGAN_cifar10.py train --max_epoch 1000 --out_dir cifar10_output/
```
Using `-h` or `--help` to see more information:
```sh
$ python3 01-VanillaGAN_mnist.py -h
$ python3 01-VanillaGAN_cifar10.py -h
```
<file_sep>/README.md
# GAN-tensorflow
Collect some GAN models on tensorflow. Read README.md first to get start.
<file_sep>/01-VanillaGAN/01-VanillaGAN_mnist.py
"""
**01-VanillaGAN**
[paper] https://arxiv.org/pdf/1406.2661.pdf
[dataset] MNIST
[reference] https://github.com/ckmarkoh/GAN-tensorflow
"""
import os, sys
import shutil
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from skimage.io import imsave
img_height = 28
img_width = 28
img_size = img_height * img_width
to_train = True
to_restore = False
output_path = "mnist_output"
max_epoch = 500
h1_size = 150
h2_size = 300
z_size = 100
batch_size = 256
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
def build_generator(z_prior):
"""
|| || || ||
|| w1 || w2 || w3 ||
z-> || ---> || ---> || ---> ||--> x
|| || || ||
|| || || ||
z h1 h2 h3
z: noise(=random samples) input layer
h1: RELU(w1.T * z + b1)
h2: RELU(w2.T * h1 + b2)
h3: w3.T * h2 + b3
x_fake: tanh(h3)
"""
w1 = tf.Variable(tf.truncated_normal([z_size, h1_size], stddev=0.1), name="g_w1", dtype=tf.float32)
b1 = tf.Variable(tf.zeros([h1_size]), name="g_b1", dtype=tf.float32)
h1 = tf.nn.relu(tf.matmul(z_prior, w1) + b1)
w2 = tf.Variable(tf.truncated_normal([h1_size, h2_size], stddev=0.1), name="g_w2", dtype=tf.float32)
b2 = tf.Variable(tf.zeros([h2_size]), name="g_b2", dtype=tf.float32)
h2 = tf.nn.relu(tf.matmul(h1, w2) + b2)
w3 = tf.Variable(tf.truncated_normal([h2_size, img_size], stddev=0.1), name="g_w3", dtype=tf.float32)
b3 = tf.Variable(tf.zeros([img_size]), name="g_b3", dtype=tf.float32)
h3 = tf.matmul(h2, w3) + b3
x_generate = tf.nn.tanh(h3)
g_params = [w1, b1, w2, b2, w3, b3]
return x_generate, g_params
def build_discriminator(x_data, x_generated, keep_prob):
"""
------ || || || || --------
x_data || w1 || w2 || w3 || y_data
--> || ---> || ---> || ---> ||--> y =
x_fake || || || || y_fake
------ || || || || --------
x_in h1 h2 h3
x_in: input layer
h1: RELU(w1.T * z + b1) + dropout
h2: RELU(w2.T * h1 + b2) + dropout
h3: w3.T * h2 + b3
y: predict the input data is true or fake (~0:fake, ~1:true)
|-- y_data = D(x)
\-- y_fake = D(G(z))
"""
x_in = tf.concat([x_data, x_generated], 0)
w1 = tf.Variable(tf.truncated_normal([img_size, h2_size], stddev=0.1), name="d_w1", dtype=tf.float32)
b1 = tf.Variable(tf.zeros([h2_size]), name="d_b1", dtype=tf.float32)
h1 = tf.nn.dropout(tf.nn.relu(tf.matmul(x_in, w1) + b1), keep_prob)
w2 = tf.Variable(tf.truncated_normal([h2_size, h1_size], stddev=0.1), name="d_w2", dtype=tf.float32)
b2 = tf.Variable(tf.zeros([h1_size]), name="d_b2", dtype=tf.float32)
h2 = tf.nn.dropout(tf.nn.relu(tf.matmul(h1, w2) + b2), keep_prob)
w3 = tf.Variable(tf.truncated_normal([h1_size, 1], stddev=0.1), name="d_w3", dtype=tf.float32)
b3 = tf.Variable(tf.zeros([1]), name="d_b3", dtype=tf.float32)
h3 = tf.matmul(h2, w3) + b3
y_data = tf.nn.sigmoid(tf.slice(h3, [0, 0], [batch_size, -1], name=None))
y_generated = tf.nn.sigmoid(tf.slice(h3, [batch_size, 0], [-1, -1], name=None))
d_params = [w1, b1, w2, b2, w3, b3]
return y_data, y_generated, d_params
def show_result(batch_res, fname, grid_size=(8, 8), grid_pad=5):
"""
Save generted image
"""
#####
## interval [-1,1] mapping to the interval [0,1]
#####
batch_res = 0.5 * batch_res.reshape((batch_res.shape[0], img_height, img_width)) + 0.5
img_h, img_w = batch_res.shape[1], batch_res.shape[2]
grid_h = img_h * grid_size[0] + grid_pad * (grid_size[0] - 1)
grid_w = img_w * grid_size[1] + grid_pad * (grid_size[1] - 1)
img_grid = np.zeros((grid_h, grid_w), dtype=np.uint8)
for i, res in enumerate(batch_res):
if i >= grid_size[0] * grid_size[1]:
break
img = (res) * 255
img = img.astype(np.uint8)
row = (i // grid_size[0]) * (img_h + grid_pad)
col = (i % grid_size[1]) * (img_w + grid_pad)
img_grid[row:row + img_h, col:col + img_w] = img
imsave(fname, img_grid)
def train():
mnist = input_data.read_data_sets('../MNIST_data', one_hot=True)
#####
## Model setting
#####
x_data = tf.placeholder(tf.float32, [batch_size, img_size], name="x_data")
z_prior = tf.placeholder(tf.float32, [batch_size, z_size], name="z_prior")
keep_prob = tf.placeholder(tf.float32, name="keep_prob")
global_step = tf.Variable(0, name="global_step", trainable=False)
x_generated, g_params = build_generator(z_prior) # `x_generated(tf.Variable)`: output of generator, i.e. x = G(z)
# `g_params(tf.Variable)`: weights and biases of generator
y_data, y_generated, d_params = build_discriminator(x_data, x_generated, keep_prob)
## discriminator loss function (max. `log D(x) + log(1-D(G(z)))` <===> min. `-(log D(x) + log(1-D(G(z)))`)
d_loss = - tf.reduce_mean(tf.log(y_data) + tf.log(1 - y_generated))
## generator loss function (min. log(1-D(G(z))) <===> max. log D(G(z)), since 0 < D(G(z)) < 1 <===> min. -log D(G(z)) )
g_loss = - tf.reduce_mean(tf.log(y_generated))
## value of C(G)
value_of_c = tf.reduce_mean(tf.log(y_data) / tf.log(2.)) + tf.reduce_mean(tf.log(1 - y_generated) / tf.log(2.))
## Gradient descent by Adam optimization method
optimizer = tf.train.AdamOptimizer(0.0001)
## adjust the parameters [ W1, b1, W2, b2, W3, b3 ] of discriminator to minimize `d_loss function
d_trainer = optimizer.minimize(d_loss, var_list=d_params)
## adjust the parameters [ W1, b1, W2, b2, W3, b3 ] of generator to minimize `g_loss function
g_trainer = optimizer.minimize(g_loss, var_list=g_params)
init = tf.initialize_all_variables()
saver = tf.train.Saver()
sess = tf.Session(config=config)
sess.run(init)
if to_restore:
chkpt_fname = tf.train.latest_checkpoint(output_path)
saver.restore(sess, chkpt_fname)
else:
if os.path.exists(output_path):
shutil.rmtree(output_path)
os.mkdir(output_path)
#####
## Start to train
#####
## Generate validation noise samples z_v
z_sample_val = np.random.normal(0, 1, size=(batch_size, z_size)).astype(np.float32)
## go training in 500 epoch
for i in range(sess.run(global_step), max_epoch):
## 233 iteration in each epoch
for j in range(int(60000 / batch_size)):
print("epoch:%s, iter:%s" % (i, j))
x_value, _ = mnist.train.next_batch(batch_size) # return image (shape=(batch, 784)) and label (shape=(batch,10))
x_value = 2 * x_value.astype(np.float32) - 1 # centralize
z_value = np.random.normal(0, 1, size=(batch_size, z_size)).astype(np.float32) # generate noise samples z
#####
## Update the discriminator
#####
_, d_minloss, Dx = sess.run([d_trainer, d_loss, y_data],
feed_dict={x_data: x_value, z_prior: z_value, keep_prob: np.sum(0.7).astype(np.float32)})
print("[batch {0}] discriminator loss: {1}".format(j, d_minloss))
print("[batch {0}] D(x) = {1}".format(j, np.mean(Dx)))
if j % 1 == 0: # [NOTICE] `j % 1 == 0` always TRUE
#####
## Update the generator
#####
_, g_minloss, value_c_min = sess.run([g_trainer, g_loss, value_of_c],
feed_dict={x_data: x_value, z_prior: z_value, keep_prob: np.sum(0.7).astype(np.float32)})
print("[batch {0}] generator loss: {1}".format(j, g_minloss))
print("[batch {0}] C(G) = {1}".format(j, value_c_min))
## Validation
x_gen_val = sess.run(x_generated, feed_dict={z_prior: z_sample_val}) # `x_gen_val` = G(z_v)
show_result(x_gen_val, "{0}/sample{1}.jpg".format(output_path,i))
## Random sample validation
z_random_sample_val = np.random.normal(0, 1, size=(batch_size, z_size)).astype(np.float32)
x_gen_val = sess.run(x_generated, feed_dict={z_prior: z_random_sample_val})
show_result(x_gen_val, "{0}/random_sample{1}.jpg".format(output_path,i))
sess.run(tf.assign(global_step, i + 1))
saver.save(sess, os.path.join(output_path, "model"), global_step=global_step)
def test():
z_prior = tf.placeholder(tf.float32, [batch_size, z_size], name="z_prior")
x_generated, _ = build_generator(z_prior)
chkpt_fname = tf.train.latest_checkpoint(output_path)
init = tf.initialize_all_variables()
sess = tf.Session(config=config)
saver = tf.train.Saver()
sess.run(init)
saver.restore(sess, chkpt_fname)
z_test_value = np.random.normal(0, 1, size=(batch_size, z_size)).astype(np.float32)
x_gen_val = sess.run(x_generated, feed_dict={z_prior: z_test_value})
show_result(x_gen_val, "{0}/test_result.jpg".format(output_path))
def main():
global max_epoch
global output_path
parser = argparse.ArgumentParser(description="%s uasge:" % sys.argv[0], formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('command', nargs='?', type=str,
choices=['train', 'test'],
help="train: training phase.\n"
"test: testing the latest training result.")
parser.add_argument('--max_epoch', help='the maximum epoch to train [default: %(default)s]', type=int, default=max_epoch)
parser.add_argument('--out_dir', help='the folder saved output images [default: %(default)s]', type=str, default=output_path)
args = parser.parse_args()
command = args.command
max_epoch = args.max_epoch
output_path = args.out_dir
if command == 'train':
train()
elif command == 'test':
test()
if __name__ == '__main__':
main()
<file_sep>/01-VanillaGAN/requirements.txt
tensorflow-gpu==1.1.0
numpy==1.12.1
scikit-learn==0.18.1
|
fb3438fc17659a38fcc0ad05248b10c24a939335
|
[
"Markdown",
"Python",
"Text"
] | 4
|
Markdown
|
BassyKuo/GAN-tensorflow
|
f11f0f4479f0a4be3435a9dc1a7897c4f2a37015
|
4a1a1a5c292ed13f6ec82366ef3a2e473773cb2f
|
refs/heads/master
|
<file_sep>package dev.arkav.ssgraves.events;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.world.World;
public interface PlayerDropDeathCallback {
Event<PlayerDropDeathCallback> EVENT = EventFactory.createArrayBacked(PlayerDropDeathCallback.class,
(listeners) -> (player, world) -> {
for (PlayerDropDeathCallback listener : listeners) {
ActionResult result = listener.drop(player, world);
if (result != ActionResult.PASS) {
return result;
}
}
return ActionResult.PASS;
});
ActionResult drop(PlayerEntity entity, World world);
}
<file_sep># Servers Sided Graves
This is a simple server sided graves mod for mc 1.15.2 (easily updatable to newer versions).
## Requirements
- FabricAPI 0.4.29+build.290-1.15 (or later)
## Usage
When a player dies they will replace their current position with a skull (this skull can be broken by other players but will not yeild items), the owner of the grave can punch it to claim the items inside (**WARNING:** this overwrites the contents of of their inventory)
## Todo
1. Add configuration options
* Change/disable sounds
* Allow other players (mabe teams) to claim graves
|
322dd90518d9e922274c84920174d9d9436e9f59
|
[
"Markdown",
"Java"
] | 2
|
Java
|
arkav/server-sided-graves
|
0451a7971779eb4271c53a7135e870195eb8788f
|
39330eeb012ab352bb21225edfffe5e650a45539
|
refs/heads/main
|
<file_sep>var searchData=
[
['x_916',['x',['../struct_cursor.html#a4dde988b1b2adba65ae3efa69f65d960',1,'Cursor::x()'],['../struct_mole.html#a6150e0515f7202e2fb518f7206ed97dc',1,'Mole::x()'],['../struct_avatar.html#a0f561e77fa0f040b637f4e04f6cd8078',1,'Avatar::x()']]],
['x_5fmole_917',['x_mole',['../struct_exit.html#a90e39179f310585053eec3a7714f6e3e',1,'Exit']]],
['xf_918',['xf',['../struct_button.html#ac7c26740690d71fe2b578d46661f26d7',1,'Button']]],
['xi_919',['xi',['../struct_button.html#a171d2442d41515d1398cca1302088332',1,'Button']]]
];
<file_sep>
#pragma once
#include <lcom/lcf.h>
#include <Sprites/numbers.xpm>
#include <Sprites/moles_hitted.xpm>
#include <Sprites/moles_missed.xpm>
#include <Sprites/numbers_moles.xpm>
#include <Sprites/game_over.xpm>
#include <Sprites/game_over_missed_moles.xpm>
#include <Sprites/game_over_hitted_moles.xpm>
#include <Sprites/game_over_numbers.xpm>
#include <Sprites/clock_icon.xpm>
#include <Sprites/instructions.xpm>
#include <Sprites/font_small.xpm>
#include <Sprites/background.xpm>
#include <Sprites/leaderboard_background.xpm>
#include <Sprites/player_background.xpm>
#include <Sprites/table.xpm>
#include <Sprites/good_bye_message.xpm>
#include <Sprites/good_bye_mole.xpm>
#include <Sprites/credits.xpm>
#include <Sprites/ballon.xpm>
#include <Sprites/enter_score.xpm>
#include<Sprites/waiting_for_player.xpm>
#include<Sprites/win.xpm>
#include<Sprites/lose.xpm>
#include "xpm_coordinates.h"
#include "i8042.h"
#include "i8254.h"
#include "keyboard.h"
#include "serial_port.h"
#include "uart_const.h"
#include "mole.h"
#include "menu.h"
#include "kbd_manager.h"
#include "mouse.h"
#include "rtc.h"
#include "player_settings.h"
#include "leaderboard.h"
typedef enum {MAIN_MENU, PLAYER_SETTINGS, WAITING, INSTRUCTIONS, SINGLE_PLAYER, MULTI_PLAYER, GAME_OVER, WIN, LOST, LEADERBOARD, EXIT} game_state;
typedef enum {TIMER, KEYBOARD, MOUSE, RTC, UART} device;
/**
* @struct GameOver
* @brief Struct relative to GameOver
* @var Gamelogo_game_over
* Game Over's logo xpm
* @var GameOver:: numbers
* Game Over's number xpm
* @var GameOver:: missed_moles
* Game Over's missed_moles xpm
* @var GameOver:: hitted_moles
* Game Over's hitted_moles xpm
* @var GameOver:: cursor
* Game Over's cursor
* @var GameOver:: buttons
* Game Over's buttons
* @var GameOver:: num_buttons
* how many buttons Game Over has
*/
typedef struct {
xpm_image_t logo_game_over;
xpm_image_t ballon;
xpm_image_t numbers;
xpm_image_t missed_moles;
xpm_image_t hitted_moles;
Cursor *cursor;
Button** buttons;
int num_buttons;
bool new_score;
} GameOver;
/**
* @struct Exit
* @bried Struct realtive to Exit
* @var GameOver:: logo
* Exit's logo xpm
* @var GameOver::mole
* Exit's mole xpm
* @var GameOver:: credits
* Exit's credits xpm
* @var GameOver:: x_mole
* Exit's mole's initial x axis position
*
*
* */
typedef struct {
xpm_image_t logo;
xpm_image_t mole;
xpm_image_t credits;
uint16_t x_mole;
int animation_timer;
} Exit;
/**
* @struct Instructions
* @var::instructions
* Instruction's xpm
* */
typedef struct {
xpm_image_t instructions;
} Instructions;
/**
* @struct WhackAMole
* @var GameOver:: numbers_font
* WhackAMole's numbers font xpm
* @var GameOver:: letters_small_font
* WhackAMole's small letters font xpm
* @var GameOver:: clock_icon
* WhackAMole's clock icon xpm
* @var GameOver:: moles_missed
* WhackAMole's moles missed xpm
* @var GameOver:: moles_hitted
* WhackAMole's moles hitted xpm
* @var GameOver:: table
* WhackAMole's table where missed moles and hitted moles will be displayed xpm
* @var GameOver::game_win
* WWhackAMole win message xpm
* @var GameOver:: game_lost
* WhackAMole's game lost message xpm
* @var GameOver:: timer_irq
* timer IRQ
* @var GameOver:: keyboard_irq
* keyboard IRQ
* @var GameOver:: mouse_irq
* mouse IRQ
* @var GameOver:: irq_rtc
* rtc IRQ
* @var GameOver:: game_time
* WhackAMole's game_time
* @var GameOver:: moles[6]
* WhackAMole's moles
* @var GameOver:: menu
* WhackAMole's menu
* @var GameOver:: player_settings
* WhackAMole's Player Settings
* @var GameOver:: player
* WhackAMole's Player
* @var GameOver:: cursor
* WhackAMole's Cursor
* @var GameOver:: instructions
* WhackAMole's Instructions
* @var GameOver:: game_over
* WhackAMole's Game Over
* @var GameOver:: leaderboard
* WhackAMole's Leaderboard
* @var GameOver:: good_bye
* WhackAMole's Good Bye
* @var GameOver:: game_state
* WhackAMole's game state
* @bool GameOver:: running
* Boolean : it's true while the user has not yet chosen to exit the game, else it's false
*
* */
typedef struct {
xpm_image_t background[3];
xpm_image_t game_time_numbers_font;
xpm_image_t numbers_font;
xpm_image_t letters_small_font;
xpm_image_t clock_icon;
xpm_image_t moles_missed;
xpm_image_t moles_hitted;
xpm_image_t table;
xpm_image_t game_win;
xpm_image_t game_lost;
xpm_image_t waiting_for_player;
uint8_t timer_irq, keyboard_irq, uart_irq;
uint16_t mouse_irq, irq_rtc;
uint8_t game_time;
Mole* moles;
int num_moles;
Menu* menu;
Player_Settings* player_settings;
Player* player;
Cursor* cursor;
Instructions *instructions;
GameOver* game_over;
Leaderboard* leaderboard;
Exit* exit;
game_state game_state;
bool multiplayer;
bool opponent_end;
bool host;
bool sent_hitted_moles;
bool running;
} WhacAMole;
/**
* @brief loads Game : Loads all Game's sprites, Creates Mole, Menu, Player_Settings, Player,Cursor, Instructions, Leaderboard, GoodBye, initializates the game at MAIN_MENU and set's bool running as true
*
* */
WhacAMole* load_game();
/**
* @brief loads Game over: loads all it's xpm, creates it's Curson and all it's Buttons
* */
GameOver* load_game_over();
/**
* @brief loads Exit : loads all it's sprites and sets it's moles first position
* */
Exit *load_exit();
/**
* @brief loads Instructions : loads it's sprite
* */
Instructions *load_instructions();
int game_main_loop(WhacAMole* game);
/**
* @brief General Interrupt Control for any device
* @param device device Device that generated interrupts
* */
void GeneralInterrupt(device device,WhacAMole* game);
/**
* @brief Main Menu's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Main_Menu_interrupt_handler(device device, WhacAMole *new_game);
/**
* @brief Instruction's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Instructions_interrupt_handler(device device, WhacAMole *new_game);
/**
* @brief Player_Setting's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Player_Settings_interrupt_handler(device device, WhacAMole *new_game);
void Waiting_interrupt_handler(device device, WhacAMole *new_game);
void Win_interrupt_handler(device device, WhacAMole *new_game);
void Lost_interrupt_handler(device device, WhacAMole *new_game);
/**
* @brief Single_Player's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Single_Player_interrupt_handler(device device, WhacAMole* game);
/**
* @brief Multi_Player's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Multi_Player_interrupt_handler(device device, WhacAMole* game);
/**
* @brief Game Over's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Game_Over_interrupt_handler(device device, WhacAMole* game);
/**
* @brief Leaderboard's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Leaderboard_interrupt_handler(device device, WhacAMole *new_game);
/**
* @brief Exit's Interrupt Handler for any of the devices
* @param device device Device that generated interrupts
* @param WhackAMole *new_game actual game
* */
void Exit_interrupt_handler(device device, WhacAMole* new_game);
/**
* @brief Draw a number at a given position through a given font
* @param xpm_image_t font xpm used to draw the number
* @param int font_info
* @param int xi upper left xpm's x position
* @param int yi upper left xpm's y position
* */
void draw_number(xpm_image_t font, int font_info, int xi, int yi, int number, bool left_number);
<file_sep>#include <lcom/lcf.h>
#include "serial_port.h"
#include "uart_const.h"
#include <stdint.h>
static int uart_com1_hook_id = COM1_IRQ; //hook id used for the mouse
uint8_t initial_lcr, initial_ier, initial_dlm, initial_dll;
uint8_t ser_byte;
bool error_reading = false;
/*void test(){
uint8_t iir;
util_sys_inb(COM1_ADDR+IIR,&iir);
if((iir &FIFO_STATUS) == FIFO_STATUS_NO_FIFO);
}*/
int ser_save_init_conf(){
uint32_t st;
if(util_sys_inb(COM1_ADDR + LCR, &initial_lcr)) return 1;
st = 0x000000FF & (initial_lcr | SEL_DL);
if(sys_outb(COM1_ADDR + LCR, st)) return 1;
if(util_sys_inb(COM1_ADDR+DLL, &initial_dll)) return 1;
if(util_sys_inb(COM1_ADDR+DLM, &initial_dlm)) return 1;
st = initial_lcr & (0x000000FF);
if(sys_outb(COM1_ADDR + LCR, st)) return 1;
if(util_sys_inb(COM1_ADDR + IER, &initial_ier)) return 1;
return 0;
}
int ser_restore_init_conf(){
uint32_t st = 0x000000FF & (initial_lcr | SEL_DL);
if(sys_outb(COM1_ADDR + LCR, st)) return 1;
if(sys_outb(COM1_ADDR + DLL, initial_dll & 0x000000FF)) return 1;
if(sys_outb(COM1_ADDR + DLM, initial_dlm & 0x000000FF)) return 1;
st = initial_lcr & (0x000000FF);
if(sys_outb(COM1_ADDR + LCR, initial_lcr )) return 1;
st = initial_ier & (0x000000FF);
if(sys_outb(COM1_ADDR + IER, initial_ier)) return 1;
return 0;
}
int ser_start_proj_config(){
if(ser_set_conf(NO_BITS_PROJ, NO_STOP_BITS_PROJ, PARITY_PROJ, BITRATE_PROJ)) return 1;
uint32_t proj_ier = 0x000000FF & ( initial_ier | EN_REC_DATA_INT | EN_REC_LINE_STATUS_INT );
proj_ier = proj_ier & (~EN_TRANS_EMPTY_INT);
if(sys_outb(COM1_ADDR + IER, proj_ier)) return 1;
return 0;
}
int ser_set_conf(unsigned long bits, unsigned long stop,
long parity, /* -1: none, 0: even, 1: odd */
unsigned long rate) {
uint32_t st, new_conf = 0;
if(sys_inb(COM1_ADDR + LCR, &st)) return 1;
switch(bits){
case 5:
new_conf |= WORD_LENGTH_5;
break;
case 6:
new_conf |= WORD_LENGTH_6;
break;
case 7:
new_conf |= WORD_LENGTH_7;
break;
case 8:
new_conf |= WORD_LENGTH_8;
break;
default:
return 1;
}
switch(stop){
case 1:
new_conf |= NO_STOP_BITS_1;
break;
case 2:
new_conf |= NO_STOP_BITS_2;
break;
default:
return 1;
}
switch(parity){
case -1:
new_conf |= PARITY_NONE;
break;
case 0:
new_conf |= PARITY_EVEN;
break;
case 1:
new_conf |= PARITY_ODD;
break;
default:
return 1;
}
if(sys_outb(COM1_ADDR + LCR, (st & BIT(6) | new_conf))) return 1;
uint16_t dl = DL_CONST / rate;
uint8_t dll , dlm;
if(util_get_LSB(dl,&dll)) return 1;
if(util_get_MSB(dl,&dlm)) return 1;
uint32_t st_lcr, st_dl;
if(sys_inb(COM1_ADDR + LCR, &st_lcr)) return 1;
st_dl = st_lcr|SEL_DL;
if(sys_outb(COM1_ADDR + LCR, st_dl)) return 1;
if(sys_outb(COM1_ADDR + DLL, dll & 0x000000FF)) return 1;
if(sys_outb(COM1_ADDR + DLM, dlm & 0x000000FF)) return 1;
if(sys_outb(COM1_ADDR + LCR, st_lcr)) return 1;
return 0;
}
int (ser_subscribe_int)(uint8_t* bit_no){
*bit_no = uart_com1_hook_id;
if (sys_irqsetpolicy(COM1_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &uart_com1_hook_id) != OK) {
printf("ser_subscribe_int::ERROR in setting policy!\n");
return FAIL;
}
if(ser_save_init_conf()) return 1;
if(ser_start_proj_config()) return 1;
return OK;
}
int (ser_unsubscribe_int)(){
if(ser_restore_init_conf()) return 1;
if (sys_irqrmpolicy(&uart_com1_hook_id) != OK) {
printf("ser_unsubscribe_int::ERROR removing policy!\n");
return FAIL;
};
return OK;
}
int ser_flush_rx(){
uint8_t dummy;
while(ser_can_read()){
if(ser_read_byte(&dummy)) return 1;
printf("treata %d\n", dummy);
}
return 0;
}
int ser_can_read(){
uint8_t lsr;
if(util_sys_inb(COM1_ADDR + LSR, &lsr)) return 1;
if(lsr & REC_DATA){
if (lsr & (OVERRUN_ERROR | PARITY_ERROR| FRAMING_ERROR)) return 2;
return 0;
}
return 1;
}
bool ser_error_read(){
uint8_t st;
if(util_sys_inb(COM1_ADDR + LSR, &st) != OK ) return true;
else if (st & (OVERRUN_ERROR | PARITY_ERROR| FRAMING_ERROR)){
return true;
}
return false;
}
bool ser_can_send(){
uint8_t lsr;
if(util_sys_inb(COM1_ADDR + LSR, &lsr)) return false;
if(lsr & TRANS_HOLD_REG_EMPTY) return true;
return false;
}
int ser_send_byte(uint8_t data){
int no_tries = MAX_NO_TRIES;
while((no_tries--)>0){
if(!ser_can_send()){
tickdelay(micros_to_ticks(DELAY_BYTE));
continue;
}
if(sys_outb(COM1_ADDR + THR, data)) return 1;
return 0;
}
return 1;
}
int ser_send_byte_wait(uint8_t data){
int no_tries = MAX_NO_TRIES;
while((no_tries--)>0){
if(!ser_can_send()){
tickdelay(micros_to_ticks(DELAY_BYTE));
continue;
}
tickdelay(micros_to_ticks(DELAY_BYTE));
if(sys_outb(COM1_ADDR + THR, data)) return 1;
return 0;
}
return 1;
}
int ser_send_info(uint8_t* data, unsigned int length){
for(unsigned int i = 0; i<length ; i++ ){
if(ser_send_byte(data[i])) return 1;
}
return 0;
}
int ser_read_byte(uint8_t* data){
int no_tries = MAX_NO_TRIES;
while((no_tries--)>0){
if(ser_can_read() == 2) {
error_reading = true;
return 1;
}
if(ser_can_read() == 1){
tickdelay(micros_to_ticks(DELAY_BYTE));
continue;
}
if(util_sys_inb(COM1_ADDR + RBR, data))
return 1;
return 0;
}
return 1;
}
void ser_ih(){
uint8_t iir;
if(util_sys_inb(COM1_ADDR + IIR, &iir)) {
error_reading = true;
return;
}
if( (iir & INT_STATUS) == INT_PENDING ) {
switch( iir & INT_ORIGIN ) {
case INT_ORIG_REC_DATA_AVAIL:
ser_read_byte(&ser_byte);
return;
case INT_ORIG_LINE_STATUS:
printf("ERROR ON UART's Receiver Buffer!\n");
ser_read_byte(&ser_byte);
return;
case INT_ORIG_MODEM_STATUS:
printf("MODEM STATUS \n");
return;
case INT_ORIG_TRANS_EMPTY:
printf("TRANS EMPTY\n");
return;
case INT_ORIG_CHAR_TIMEOUT:
printf("CHAR TIMEOUT\n");
return;
default:
printf("ANOTHER TYPE INTERRUPT!\n");
return;
}
}
error_reading = true;
}
<file_sep>#include <lcom/lcf.h>
#include <lcom/timer.h>
#include <stdint.h>
#include "i8254.h"
unsigned int timer_counter = 1; // declared extern at lab2.c, global variable to count interrupts from the timer
int timer_hook_id = TIMER0_IRQ; // global variable used in subscribe_int and unsubscribe_int
int (timer_set_frequency)(uint8_t timer, uint32_t freq) {
uint8_t status = 0, controlWord, lsb, msb;
uint16_t initial_cont_value;
if(freq > TIMER_FREQ || freq < TIMER_FREQ_MIN)
{
printf("timer_set_frequency::Invalid input, frequency must be between (19 and 1193182)Hz\n");
return 1;
}
if (timer_get_conf(timer, &status) != OK)
{
printf("timer_set_frequency::ERROR in getting the timer initial configuration!\n");
return FAIL;
} //Reading the timer initial configuration
status &= LST_4_BITS; //the first 4 bits from the previous configuration are preserved
controlWord = status | TIMER_LSB_MSB; //setting up the read back command
switch (timer) {
case 0:
controlWord |= TIMER_SEL0;
break;
case 1:
controlWord |= TIMER_SEL1;
break;
case 2:
controlWord |= TIMER_SEL2;
break;
}
//Writing the new configuration
if (sys_outb(TIMER_CTRL, controlWord) != OK)
{
printf("timer_set_frequency::ERROR in writing the new timer configuration!\n");
return FAIL;
}
initial_cont_value = TIMER_FREQ / freq;
if (util_get_LSB(initial_cont_value, &lsb) != OK) { return 1; }
if (util_get_MSB(initial_cont_value, &msb) != OK) { return 1; }
//writing lsb followed by the msb values of the frequency to the timer port
if(sys_outb(TIMER_PORT_SEL(timer), lsb)) {
printf("timer_set_frequency::ERROR in writing the lsb value to the timer port!\n");
return FAIL;
}
if(sys_outb(TIMER_PORT_SEL(timer), msb)) {
printf("timer_set_frequency::ERROR in writing the msb value to the timer port!\n");
return FAIL;
}
return OK;
}
int (timer_subscribe_int)(uint8_t *bit_no) {
*bit_no = BIT(timer_hook_id);
if(sys_irqsetpolicy(TIMER0_IRQ, IRQ_REENABLE, &timer_hook_id)!= OK){
printf("timer_subscribe_int::ERROR in setting policy !\n");
return FAIL;
}
return OK;
}
int (timer_unsubscribe_int)() {
if(sys_irqrmpolicy(&timer_hook_id)!= OK){
printf("timer_unsubscribe_int::ERROR in disabling IQR line!\n");
return FAIL;
}
return OK;
}
void (timer_int_handler)() {
timer_counter++;
}
int (timer_get_conf)(uint8_t timer, uint8_t *st) {
// testing the timer argument: 0,1,2 are the only valid timers
if(timer < 0 || timer > 2){
printf("timer_get_conf::Invalid input, timer index out of range!\n");
return FAIL;
}
// writing the ReadBack Command
uint8_t control_word = TIMER_RB_CMD | TIMER_RB_COUNT_ | TIMER_RB_SEL(timer);
if (sys_outb(TIMER_CTRL, control_word) != OK) {
printf("timer_get_conf::ERROR writing the control_word to the timer control register!\n");
return FAIL;
}
char TIMER; // auxiliar to hold the port of the timer pretended
//selects wich port will be read based on the timer passed as an argument
switch (timer) {
case 0:
TIMER = TIMER_0;
break;
case 1:
TIMER = TIMER_1;
break;
case 2:
TIMER = TIMER_2;
break;
}
if (util_sys_inb(TIMER, st) != OK) {
printf("timer_get_conf::ERROR receiving the output from the timer!\n");
return FAIL;
}
return OK;
}
int (timer_display_conf)(uint8_t timer, uint8_t st, enum timer_status_field field) {
// testing the timer argument: 0,1,2 are the only valid timers
if(timer < 0 || timer > 2){
printf("timer_display_conf::Invalid input, timer index out of range!\n");
return FAIL;
}
union timer_status_field_val config; // will hold the info about the configuration asked
if (field == tsf_all) { // configuration in hexadecimal
config.byte = st;
}
else if (field == tsf_initial) { // timer initialization mode
// select bits 4 and 5
switch (st & TIMER_LSB_MSB) {
case TIMER_LSB:
config.in_mode = LSB_only;
break;
case TIMER_MSB:
config.in_mode = MSB_only;
break;
case TIMER_LSB_MSB:
config.in_mode = MSB_after_LSB;
break;
default:
config.in_mode = INVAL_val;
}
}
else if (field == tsf_mode) { // timer counting mode
//selecting bits 3, 2 and 1
switch(st & TIMER_OPERATING_MODE) {
case(TIMER_INT_TERM_COUNT): // MODE 0
config.count_mode = 0;
break;
case(TIMER_HW_RETRIG_ONE_SH): // MODE 1
config.count_mode = 1;
break;
case(TIMER_RATE_GEN): // MODE 2
config.count_mode = 2;
break;
case(BIT(3) | TIMER_RATE_GEN): // because of don't care bits MODE 2 can also be 110
config.count_mode = 2;
break;
case(TIMER_SQR_WAVE): // MODE 3
config.count_mode = 3;
break;
case(BIT(3) | TIMER_SQR_WAVE): //because of don't care bits MODE 3 can also be 111
config.count_mode = 3;
break;
case(TIMER_SW_TRIG_STROBE): // MODE 4
config.count_mode = 4;
break;
case(TIMER_HW_TRIG_STROBE): // MODE 5
config.count_mode = 5;
break;
}
}
else if (field == tsf_base) { // timer counting base
if (st & TIMER_BCD) config.bcd = true;
else config.bcd = false;
}
else {
printf("timer_display_config::Invalid field to be read!\n");
return FAIL;
}
if (timer_print_config(timer, field, config) != OK) {
printf("timer_display_config::ERROR in timer_print_config!\n");
return FAIL;
}
return OK;
}
<file_sep>var searchData=
[
['leaderboard_862',['leaderboard',['../struct_whac_a_mole.html#a8d3befc871b99aea2eb0011acca32708',1,'WhacAMole']]],
['left_5fpress_863',['left_press',['../mouse_8c.html#a3b6c02fed94c4939be510341beaa4c5c',1,'left_press(): mouse.c'],['../state__machine_8c.html#a3b6c02fed94c4939be510341beaa4c5c',1,'left_press(): state_machine.c']]],
['letters_5fsmall_5ffont_864',['letters_small_font',['../struct_whac_a_mole.html#ad26fb528119e861bd49d2633026d9789',1,'WhacAMole']]],
['logo_865',['logo',['../struct_exit.html#ab5d2b2213d2b99d6a827a51ea16cc3f4',1,'Exit']]],
['logo_5fgame_5fover_866',['logo_game_over',['../struct_game_over.html#a132ed3ad4590f2ce6373b99fe8fa4757',1,'GameOver']]]
];
<file_sep>var searchData=
[
['score_5frecord_647',['Score_Record',['../struct_score___record.html',1,'']]]
];
<file_sep>var searchData=
[
['button_5fstate_924',['button_state',['../_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29b',1,'button_state(): Player.h'],['../button_8h.html#a01cda3effbb71c7c203e4f9716e8844d',1,'Button_state(): button.h'],['../menu_8h.html#a01cda3effbb71c7c203e4f9716e8844d',1,'Button_state(): menu.h']]]
];
<file_sep>#ifndef _LCOM_I8254_H_
#define _LCOM_I8254_H_
#include <lcom/lcf.h>
/** @defgroup i8254 i8254
* @{
*
* Constants for programming the i8254 Timer. Needs to be completed.
*/
#define FAIL 1
#define TIMER_FREQ 1193182 /**< @brief clock frequency for timer in PC and AT */
#define TIMER_FREQ_MIN 19 /**< @brief lowest working frequency the timer supports is 18.2Hz */
#define TIMER0_IRQ 0 /**< @brief Timer 0 IRQ line */
/* I/O port addresses */
#define TIMER_0 0x40 /**< @brief Timer 0 count register */
#define TIMER_1 0x41 /**< @brief Timer 1 count register */
#define TIMER_2 0x42 /**< @brief Timer 2 count register */
#define TIMER_CTRL 0x43 /**< @brief Control register */
#define SPEAKER_CTRL 0x61 /**< @brief Register for speaker control */
/* Timer control */
/* Timer selection: bits 7 and 6 */
#define TIMER_SEL0 0x00 /**< @brief Control Word for Timer 0 */
#define TIMER_SEL1 BIT(6) /**< @brief Control Word for Timer 1 */
#define TIMER_SEL2 BIT(7) /**< @brief Control Word for Timer 2 */
#define TIMER_RB_CMD (BIT(7) | BIT(6)) /**< @brief Read Back Command */
/* Register selection: bits 5 and 4 */
#define TIMER_LSB BIT(4) /**< @brief Initialize Counter LSB only */
#define TIMER_MSB BIT(5) /**< @brief Initialize Counter MSB only */
#define TIMER_LSB_MSB (TIMER_LSB | TIMER_MSB) /**< @brief Initialize LSB first and MSB afterwards */
/* Operating mode: bits 3, 2 and 1 */
#define TIMER_OPERATING_MODE (BIT(3)|BIT(2)|BIT(1)) /**< @brief selects bits with info about operating mode */
#define TIMER_HW_TRIG_STROBE (BIT(3)|BIT(1)) /**< @brief Mode 5: hardware triggered strobe */
#define TIMER_SW_TRIG_STROBE BIT(3) /**< @brief Mode 4: software triggered strobe */
#define TIMER_SQR_WAVE (BIT(2) | BIT(1)) /**< @brief Mode 3: square wave generator */
#define TIMER_RATE_GEN BIT(2) /**< @brief Mode 2: rate generator */
#define TIMER_HW_RETRIG_ONE_SH BIT(1) /**< @brief Mode 1: hardware retriggerable one-shot */
#define TIMER_INT_TERM_COUNT 0x00 /**< @brief Mode 0: interrupt on terminal count*/
/* Counting mode: bit 0 */
#define TIMER_COUTING_BASE BIT(0) /**< @brief selects bits with info about couting base */
#define TIMER_BCD BIT(0) /**< @brief Count in BCD */
#define TIMER_BIN 0x00 /**< @brief Count in binary */
/* READ-BACK COMMAND FORMAT */
#define TIMER_RB_COUNT_ BIT(5)
#define TIMER_RB_STATUS_ BIT(4)
#define TIMER_RB_SEL(n) BIT((n) + 1)
#define TIMER_PORT_SEL(i) ((0x40)+i) /**< @brief selects the port for timer i */
#define LST_4_BITS 0x0F /**< @brief Selects the four last bits */
/**@}*/
#endif /* _LCOM_I8254_H */
<file_sep>var searchData=
[
['ballon_5fx_966',['BALLON_X',['../xpm__coordinates_8h.html#ac343b29b3c7c890c0e423fe1c053e2a4',1,'xpm_coordinates.h']]],
['ballon_5fy_967',['BALLON_Y',['../xpm__coordinates_8h.html#a497c726790047eed01746e5a5bbe7f1e',1,'xpm_coordinates.h']]],
['bitrate_5fproj_968',['BITRATE_PROJ',['../uart__const_8h.html#a10e2fe99b4aced90aae6992400a119a6',1,'uart_const.h']]],
['break_5fint_969',['BREAK_INT',['../uart__const_8h.html#a632353c1e42f09c0454d8229be921cff',1,'uart_const.h']]]
];
<file_sep>#pragma once
#ifndef _VD_CARD_H_
#define _VD_CARD_H_
#include <lcom/lcf.h>
uint16_t vg_get_hres();
uint16_t vg_get_vres();
int (vbe_get_mode_info_remade)(uint16_t mode, vbe_mode_info_t *vmi_p);
void *vggg_init(unsigned short mode);
int vggg_exit();
int square_draw(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint32_t color);
int vg_draw_hlineee(uint16_t x, uint16_t y, uint16_t len, uint32_t color);
int vg_paint_pixel(uint16_t x_coord, uint16_t y_coord, uint32_t color);
void(vg_draw_xpm)(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y);
void(vg_draw_part_of_xpm)(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y, int x_start, int x_end, int y_start, int y_end);
void (update_buffer)();
#endif /* _VD_CARD_H_ */
<file_sep>var searchData=
[
['time_648',['Time',['../struct_time.html',1,'']]]
];
<file_sep>var searchData=
[
['cursor_2ec_653',['cursor.c',['../cursor_8c.html',1,'']]],
['cursor_2eh_654',['cursor.h',['../cursor_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['date_838',['date',['../struct_score___record.html#a1dc6df4f5eac6300e1bb1f8dce3a10fd',1,'Score_Record']]],
['day_839',['day',['../struct_date.html#a897ed87b95b7a37afeeb935ca0b2366b',1,'Date']]],
['delta_5fx_840',['delta_x',['../mouse_8c.html#acb240143623f671430840d2fe2d54b91',1,'delta_x(): mouse.c'],['../state__machine_8c.html#acb240143623f671430840d2fe2d54b91',1,'delta_x(): state_machine.c']]],
['delta_5fy_841',['delta_y',['../mouse_8c.html#acea06ea2a1bb215775659a444b16fe20',1,'delta_y(): mouse.c'],['../state__machine_8c.html#acea06ea2a1bb215775659a444b16fe20',1,'delta_y(): state_machine.c']]]
];
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "i8042.h"
#include "mouse.h"
static int mouse_hook_id = MOUSE_IRQ; //hook id used for the mouse
uint8_t packet[3]; //array of bytes, packet read from the mouse
bool mouse_last_byte_of_packet = false; //signals that the last byte of a packet was read
uint8_t delta_x, delta_y;
bool left_press = false, right_press = false, mid_press = false;
int mouse_subscribe_int(uint16_t *bit_no) {
*bit_no = BIT(mouse_hook_id);
if (sys_irqsetpolicy(MOUSE_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &mouse_hook_id) != OK) {
printf("mouse_subscribe_int::ERROR in setting policy!\n");
return FAIL;
}
return OK;
}
int mouse_unsubscribe_int() {
if (sys_irqrmpolicy(&mouse_hook_id) != OK) {
printf("kbd_unsubscribe_int::ERROR removing policy!\n");
return FAIL;
};
return OK;
}
void mouse_read_status_register(uint8_t *stat) {
if (util_sys_inb(STAT_REG, stat) != OK) {
printf("ERROR::Unable to read keyboard status register!\n");
}
}
int mouse_check_status_register() {
uint8_t temp=0; //hold the status
mouse_read_status_register(&temp);
if ((temp & (KBD_PAR_ERROR | KBD_TIME_ERROR)) != 0) {
return 1;
}
return 0;
}
int mouse_output_full() {
uint8_t st;
mouse_read_status_register(&st);
if (st & KBD_OBF && !mouse_check_status_register())
return OK;
return FAIL;
}
int mouse_input_empty() {
uint8_t st;
mouse_read_status_register(&st);
if (st & KBD_IBF && !mouse_check_status_register())
return FAIL;
return OK;
}
int mouse_read_out_buffer(uint8_t *info) {
if (util_sys_inb(OUT_BUFF, info) != OK) {
printf("ERROR::Error reading the out buffer!\n");
return FAIL;
}
return OK;
}
void(mouse_ih)(void) {
uint8_t aux;
static uint8_t index = 0;
if (mouse_last_byte_of_packet) {
index = 0;
mouse_last_byte_of_packet = false;
}
if (mouse_output_full() == OK) {
if (mouse_read_out_buffer(&aux) != OK) {
printf("ERROR::Error reading the out buffer!\n");
return;
}
packet[index++] = aux;
if (index == 3) {
mouse_last_byte_of_packet = true;
}
}
}
void mouse_parse_packet(uint8_t packet[], struct packet *new_packet) {
uint8_t first_byte = packet[0];
new_packet->bytes[0] = packet[0];
new_packet->bytes[1] = packet[1];
new_packet->bytes[2] = packet[2];
new_packet->rb = (first_byte & RB);
new_packet->lb = (first_byte & LB);
new_packet->mb = (first_byte & MB);
new_packet->x_ov = (first_byte & X_OVFL);
new_packet->y_ov = (first_byte & Y_OVFL);
new_packet->delta_x = (uint16_t) packet[1];
new_packet->delta_y = (uint16_t) packet[2];
if (first_byte & MSB_X_DELTA)
new_packet->delta_x |= (0xFF<<8);
if (first_byte & MSB_Y_DELTA)
new_packet->delta_y |= (0xFF<<8);
}
int issue_command_to_kbc(uint8_t command, uint8_t arguments) {
uint8_t attemps = 0; //number of attemps the function will try to issue the command
//stops after 4 attemps
while (attemps < 4) {
attemps++;
// input buffer should not be full
if (mouse_input_empty() == OK) {
//writtes command
if (sys_outb(CMD_REG, command) == OK) {
//in case the command is WriteCommandByte it needs the new command (arguments)
if (command == WRITE_CMD_BYTE) {
if (sys_outb(CMD_ARG_REG, arguments) == OK) {
return OK;
}
}
else {
return OK;
}
}
}
tickdelay(micros_to_ticks(DELAY_US));
}
return 0;
}
int mouse_issue_cmd_to_kbc(uint8_t command, uint8_t argument) {
uint8_t mouse_response, tries=4;
while (tries > 0) {
if (mouse_kbc_write_cmd(command) != OK) {
printf("ERROR::writing the command!\n");
return 1;
}
if (command == WRITE_CMD_BYTE) {
if (mouse_kbc_write_argument(argument) != OK)
printf("ERROR::writing the new command byte!\n");
return 1;
}
if (command == WRITE_BYTE_TO_MOUSE) {
if (mouse_write_command(argument,&mouse_response) != OK)
return 1;
if (mouse_response == ACK)
return OK;
else if (mouse_response == ERROR)
return 1;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("After 4 tries, kbc was not ready to receive the command\n");
return 1;
}
int issue_command_to_mouse(uint8_t command) {
while (true) {
if(mouse_issue_cmd_to_kbc(WRITE_BYTE_TO_MOUSE, 0) != OK)
return 1;
if (mouse_input_empty() == OK)
if(sys_outb(IN_BUFF,command) != OK)
return 1;
uint8_t response;
//if (output_full() == OK) {
if (util_sys_inb(OUT_BUFF, &response) != OK)
return 1;
if (response == ACK)
return OK;
if (response == ERROR)
return 1;
//}
tickdelay(micros_to_ticks(DELAY_US));
}
}
int mouse_kbc_write_cmd(uint8_t command) {
uint8_t status, tries=4;
if (util_sys_inb(STAT_REG,&status) != OK) {
printf("ERROR::Unable to read the status register!\n");
return 1;
}
while (tries > 0) {
if ((status & KBD_IBF) == 0) {
if (sys_outb(CMD_REG, command) != OK)
return 1;
return OK;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("mouse_kbc_write_cmd\n");
printf("After 4 tries, kbc was not ready to receive the command\n");
return 1;
}
int mouse_kbc_write_argument(uint8_t argument) {
uint8_t status, tries = 4;
if (util_sys_inb(STAT_REG,&status) != OK ) {
printf("ERROR::Unable to read the status register!\n");
return 1;
}
while (tries > 0) {
if((status & KBD_IBF) == 0) {
if (sys_outb(CMD_ARG_REG,argument) != OK) {
return 1;
}
return OK;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("mouse_kbc_write_argument \n");
printf("After 4 tries, kbc was not ready to receive the argument\n");
return 1;
}
int mouse_write_command(uint8_t command, uint8_t*response) {
uint8_t status, tries=4;
if (util_sys_inb(STAT_REG,&status) != OK) {
printf("ERROR::Unable to read the status register!\n");
return 1;
}
while (tries > 0) {
if ((status & KBD_IBF) == 0) {
if (sys_outb(CMD_ARG_REG,command) != OK) {
return 1;
}
tickdelay(micros_to_ticks(DELAY_US));
if (util_sys_inb(OUT_BUFF,response) != OK) {
return 1;
}
printf("OK!\n");
return OK;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("After 4 tries, mouse was not ready\n");
return 1;
}
struct mouse_ev mouse_get_event(struct packet *packet) {
struct mouse_ev mouse_event;
mouse_event.delta_x = packet->delta_x;
mouse_event.delta_y = packet->delta_y;
if (left_press && !packet->lb && !right_press && !packet->rb && !mid_press && !packet->mb) {
left_press = false;
mouse_event.type = LB_RELEASED;
}
else if (!left_press && packet->lb && !right_press && !packet->rb && !mid_press && !packet->mb) {
left_press = true;
mouse_event.type = LB_PRESSED;
}
else if (!left_press && !packet->lb && right_press && !packet->rb && !mid_press && !packet->mb) {
right_press = false;
mouse_event.type = RB_RELEASED;
}
else if (!left_press && !packet->lb && !right_press && packet->rb && !mid_press && !packet->mb) {
right_press = true;
mouse_event.type = RB_PRESSED;
}
else if (!mid_press && packet->mb) {
mid_press = true;
mouse_event.type = BUTTON_EV;
}
else if (mid_press && !packet->mb) {
mid_press = false;
mouse_event.type = BUTTON_EV;
}
else {
mouse_event.type = MOUSE_MOV;
}
return mouse_event;
}
<file_sep>#pragma once
#include <lcom/lcf.h>
#include <Sprites/leaderboard_crown.xpm>
#include <Sprites/leaderboard_table.xpm>
#include <Sprites/score_numbers.xpm>
#include <Sprites/Buttons_img/normal/score_close_normal.xpm>
#include <Sprites/Buttons_img/active/score_close_active.xpm>
#include "rtc.h"
#include "player_settings.h"
/**
* @struct Score_Record
* @var Score_Record:: player_name
* Player's name
* @var Score_Record:: player_name_size
* Player name's size
* @var Score_Record:: date
* Game date
* @var Score_Record:: score
* Player's score
* */
typedef struct {
char* player_name;
int player_name_size;
Date date;
int score;
} Score_Record;
/**
* @struct Leaderboard
* @var Leaderboard:: crown
* Leaderboard's crown xpm
* @var Leaderboard:: table
* Leaderboard's crown xpm
* @var Leaderboard:: numbers
* Leaderboard's numbers xpm
* @var Leaderboard:: buttons
* Leaderboard's buttons
* @var Leaderboard:: num_buttons
* Number of Buttons of LeaderBoard
* @var Leaderboard:: score_records
* Leaderboard's Score_Record
* @var Leaderboard:: num_score_records
* Leaderboard's num of score records
* @var Leaderboard:: max_name_length
* Leaderboard's max name lenght
* */
typedef struct {
xpm_image_t crown;
xpm_image_t table;
xpm_image_t numbers;
Button** buttons;
int num_buttons;
Score_Record* score_records;
int num_score_records;
int max_name_length;
} Leaderboard;
/**
* @brief: loads leaderboard and sets it's variables
* @return: leaderboard
* */
Leaderboard* load_leaderboard();
/**
* @brief draws leaderboard's table
* @param leaderboard
* */
void draw_leaderboard_table(Leaderboard* leaderboard);
/**
* @brief draws leaderboard's player names
* @param font font that will be used to draw the names
* @param score_records
* @param num_records
* */
void draw_player_names(xpm_image_t font, Score_Record* score_records, uint8_t num_records);
/**
* @brief draws players's scores
* @param leaderboard
* */
void draw_player_scores(Leaderboard* leaderboard);
/**
* @brief draws players's dates
* @param leaderboard
* */
void draw_player_dates(Leaderboard *leaderboard);
/**
* @brief draws players's score
* @param font font that will be used to draw the score
* @param xi
* @param yi
* @param score
*
* */
void draw_player_score(xpm_image_t font, int xi, int yi, int score);
/**
* @brief: Function that saves scores information on txt file
* @param leaderboard
* */
void save_scores(Leaderboard* leaderboard);
/**
* @brief: Function that reads scores information of txt file
* @param leaderboard
* */
void load_scores(Leaderboard* leaderboard);
/**
* @brief: Function that adds new score to stuct if the score is better than the last placed scoree
* @param leaderboard
* @param player
* */
bool add_new_score(Leaderboard* leaderboard, Player* player);
<file_sep>var searchData=
[
['y_920',['y',['../struct_cursor.html#ab0580f504a7428539be299fa71565f30',1,'Cursor::y()'],['../struct_mole.html#a0a2f84ed7838f07779ae24c5a9086d33',1,'Mole::y()'],['../struct_avatar.html#a17f97f62d93bc8cfb4a2b5d273a2aa72',1,'Avatar::y()']]],
['year_921',['year',['../struct_date.html#aac3a162d2f192fe2360aba534eac7198',1,'Date']]],
['yf_922',['yf',['../struct_button.html#a8c406c4586cd5582bf61ae19a4f6b163',1,'Button']]],
['yi_923',['yi',['../struct_button.html#a7cff74f47b6a00e9abbe5ee3c6a01279',1,'Button']]]
];
<file_sep>var searchData=
[
['timer_952',['TIMER',['../game_8h.html#adbdec58595587fea1750c91cd18315fba17ba9bae1b8d7e8d6c12d46ec58e0769',1,'game.h']]]
];
<file_sep>#pragma once
#include <lcom/lcf.h>
#include <Sprites/hole.xpm>
#include <Sprites/mole_up1.xpm>
#include <Sprites/mole_up2.xpm>
#include <Sprites/mole_up3.xpm>
#include <Sprites/mole_up4.xpm>
#include <Sprites/mole_down_miss1.xpm>
#include <Sprites/mole_down_miss2.xpm>
#include <Sprites/mole_down_miss3.xpm>
#include <Sprites/mole_down_miss4.xpm>
#include <Sprites/mole_down_hit1.xpm>
#include <Sprites/mole_down_hit2.xpm>
#include <Sprites/mole_down_hit3.xpm>
#include <Sprites/mole_down_hit4.xpm>
#include "vd_card.h"
#define GAME_FPS 30
#define MOLE_UP_TIME GAME_FPS*3
#define GAME_DURATION GAME_FPS*30
#define MOLE_PROBABILITY 9800
#define MOLE_PROBABILITY_MULTIPLAYER 9700
#define TIME_UP_LIMIT_DECREMENT 1
#define PROBABILITY_LIMIT_DECREMENT 50
#define MAX_NO_MOLES 62
#define KBD_KEY_0 'A'
#define KBD_KEY_1 'S'
#define KBD_KEY_2 'D'
#define KBD_KEY_3 'J'
#define KBD_KEY_4 'K'
#define KBD_KEY_5 'L'
typedef enum {HIDED = 0, UP_1, UP_2, UP_3, UP_4, DOWN_MISSED_4, DOWN_MISSED_3, DOWN_MISSED_2, DOWN_MISSED_1, DOWN_HIT_4, DOWN_HIT_3, DOWN_HIT_2, DOWN_HIT_1} Position;
/**
* @struct Mole
* @var Mole:: sprites[13]
* Mole's xpm for all it's possible positions
* @var Mole::index
* Mole index on the game
* @var Mole::kbd_key
* Kbd key corresponding to that mole
* @var Mole::x
* Mole's position on x axis
* @var Mole::y
* Mole's position on y axis
* @var Mole::time_up
* Time that the Mole is up
* @var Mole::position
* Mole's current position
* */
typedef struct {
xpm_image_t sprites[13];
uint8_t index;
char kbd_key;
int x,y;
int time_up;
Position position;
} Mole;
/**
* @brief Function that create a Mole: loads all mole sprites(for every different mole Position) and sets up all moles variables
* */
Mole* createMole();
/**
* @brief Function that draws the mole at it's current position
* @param Mole* the mole to be drawn
* */
void draw_mole(Mole* mole);
/**
* @brief Function that draws some moles at it's current positions
* @param Mole* the moles to be drawn
* @param int the number of moles to be drawn
* */
void draw_all_moles(Mole* moles, int num_moles);
/**
* @brief checks if cursor its over mole
* @param Mole* the mole to be checked
* @param int cursor_x the x position of the cursor
* @param int cursor_y the y position of the cursor
* @return bool - true if the cursor is over the mole, false otherwise
* */
bool check_over_mole(Mole *mole, int cursor_x, int cursor_y);
void reset_moles(Mole* moles, int num_moles);
<file_sep>#include <lcom/lcf.h>
#include "menu.h"
Menu *load_menu()
{
Menu *menu = malloc(sizeof(Menu));
xpm_load(logo_xpm, XPM_8_8_8_8, &(menu->sprites[0]));
menu->num_buttons = 7;
menu->buttons = (Button**) malloc(sizeof(Button*) * menu->num_buttons);
menu->buttons[0] = load_button(SINGLE_PLR_X, SINGLE_PLR_Y, singleplayer_normal_xpm, singleplayer_active_xpm);
menu->buttons[1] = load_button(MULTI_PLR_X, MULTI_PLR_Y, multiplayer_normal_xpm, multiplayer_active_xpm);
menu->buttons[2] = load_button(LEADERB_MENU_X, LEADERB_MENU_Y, leaderboard_normal_xpm, leaderboard_active_xpm);
menu->buttons[3] = load_button(INSTRC_X, INSTRC_Y, instructions_normal_xpm, instructions_active_xpm);
menu->buttons[4] = load_button(EXIT_MENU_X, EXIT_MENU_Y, exit_normal_xpm, exit_active_xpm);
menu->buttons[5] = load_button(CALLENDAR_X, CALLENDAR_Y, calendar_normal_xpm, calendar_active_xpm);
menu->buttons[6] = load_button(CLOCK_X, CLOCK_Y, clock_normal_xpm, clock_active_xpm);
return menu;
}
void draw_logo(Menu *menu)
{
uint32_t *logo_map = (uint32_t *)menu->sprites[0].bytes;
vg_draw_xpm(logo_map, menu->sprites[0], MENU_LOGO_X, MENU_LOGO_Y);
}
void draw_date(xpm_image_t font, int xi, int yi, Date date)
{
int number_width = font.width / 13; // 10 numbers plus slash, two points and percentage symbol
int number_height = font.height;
int left_day_number, right_day_number;
left_day_number = date.day / 10;
right_day_number = date.day % 10;
int left_month_number, right_month_number;
left_month_number = date.month / 10;
right_month_number = date.month % 10;
int left_year_number, right_year_number;
left_year_number = date.year / 10;
right_year_number = date.year % 10;
//DAY
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi, yi, left_day_number * number_width, (left_day_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+number_width, yi, right_day_number * number_width, (right_day_number + 1) * number_width, 0, number_height);
//SLASH BAR
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+2*number_width, yi, 11 * number_width, 12 * number_width, 0, number_height);
//MONTH
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+3*number_width, yi, left_month_number * number_width, (left_month_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+4*number_width, yi, right_month_number * number_width, (right_month_number + 1) * number_width, 0, number_height);
//SLASH BAR
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+5*number_width, yi, 11 * number_width, 12 * number_width, 0, number_height);
//YEAR
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+6*number_width, yi, left_year_number * number_width, (left_year_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+7*number_width, yi, right_year_number * number_width, (right_year_number + 1) * number_width, 0, number_height);
}
void draw_time(xpm_image_t font, int xi, int yi, Time time)
{
int number_width = font.width / 13; // 10 numbers plus slash, two points and percentage symbol
int number_height = font.height;
int left_hour_number, right_hour_number;
left_hour_number = time.hour / 10;
right_hour_number = time.hour % 10;
int left_minutes_number, right_minutes_number;
left_minutes_number = time.minute / 10;
right_minutes_number = time.minute % 10;
int left_seconds_number, right_seconds_number;
left_seconds_number = time.second / 10;
right_seconds_number = time.second % 10;
//HOUR
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi, yi, left_hour_number * number_width, (left_hour_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+number_width, yi, right_hour_number * number_width, (right_hour_number + 1) * number_width, 0, number_height);
//TWO POINTS
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+2*number_width, yi, 10 * number_width, 11 * number_width, 0, number_height);
//MINUTES
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+3*number_width, yi, left_minutes_number * number_width, (left_minutes_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+4*number_width, yi, right_minutes_number * number_width, (right_minutes_number + 1) * number_width, 0, number_height);
//TWO POINTS
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+5*number_width, yi, 10 * number_width, 11 * number_width, 0, number_height);
//SECONDS
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+6*number_width, yi, left_seconds_number * number_width, (left_seconds_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi+7*number_width, yi, right_seconds_number * number_width, (right_seconds_number + 1) * number_width, 0, number_height);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Button *load_button(uint16_t xi, uint16_t yi, xpm_row_t *normal, xpm_row_t *bright)
{
Button *button = (Button *) malloc(sizeof(Button));
if (button == NULL)
return NULL;
xpm_load(normal, XPM_8_8_8_8, &(button->sprites[0]));
xpm_load(bright, XPM_8_8_8_8, &(button->sprites[1]));
button->xi = xi;
button->yi = yi;
button->xf = xi + button->sprites[0].width;
button->yf = yi + button->sprites[0].height;
button->state = NORMAL;
return button;
}
void update_buttons(Cursor* cursor, Button** buttons, int num_buttons) {
for (int i = 0; i < num_buttons; i++) {
if (mouse_over(buttons[i], cursor))
buttons[i]->state = ACTIVE;
else
buttons[i]->state = NORMAL;
}
}
void draw_button(Button *button)
{
xpm_image_t current_img = button->sprites[(int) button->state];
vg_draw_xpm((uint32_t*) current_img.bytes, current_img, button->xi, button->yi);
}
void draw_buttons(Button** buttons, int num_buttons)
{
for (int i = 0; i < num_buttons; i++) {
draw_button(buttons[i]);
}
}
int mouse_over(Button *button, Cursor *cursor)
{
if (button->xi <= cursor->x && cursor->x <= button->xf && button->yi <= cursor->y && cursor->y <= button->yf)
return 1;
else
return 0;
}
////////////////////////////////////////////////////////////////
Cursor *load_cursor(xpm_row_t *img_cursor)
{
Cursor *cursor = malloc(sizeof(Cursor));
if (cursor == NULL)
return NULL;
xpm_load(cursor_xpm, XPM_8_8_8_8, &(cursor->cursor_image_default));
xpm_load(cursor_xpm, XPM_8_8_8_8, &(cursor->cursor_image));
cursor->x = 400;
cursor->y = 300;
return cursor;
}
void draw_cursor(Cursor *cursor)
{
uint32_t *cursor_map = (uint32_t *)cursor->cursor_image.bytes;
vg_draw_xpm(cursor_map, cursor->cursor_image, cursor->x, cursor->y);
}
void move_cursor(struct packet *packet, Cursor *cursor) {
if (cursor->x + packet->delta_x < 0)
cursor->x = 0;
else {
cursor->x += packet->delta_x;
if (cursor->x > 800)
cursor->x = 795;
}
if (cursor->y - packet->delta_y < 0)
cursor->y = 0;
else {
cursor->y -= packet->delta_y;
if (cursor->y > 600)
cursor->y = 595;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
<file_sep>var searchData=
[
['hided_939',['HIDED',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83ab3e067935be2134cacd106e7e463954c',1,'mole.h']]]
];
<file_sep>var searchData=
[
['active_928',['ACTIVE',['../button_8h.html#a01cda3effbb71c7c203e4f9716e8844da33cf1d8ef1d06ee698a7fabf40eb3a7f',1,'ACTIVE(): button.h'],['../menu_8h.html#a01cda3effbb71c7c203e4f9716e8844da33cf1d8ef1d06ee698a7fabf40eb3a7f',1,'ACTIVE(): menu.h']]]
];
<file_sep>#ifndef _LCOM_UART_CONST__H_
#define _LCOM_UART_CONST__H_
#include <lcom/lcf.h>
//COMMUNICATION BYTES
#define UNREQUESTED_BYTE 0xFF
#define GAME_OVER_BYTE 0x3F
#define READY_TO_PLAY_FROM_HOST 0x10
#define CONFIRMATION 0x11
#define IRRELEVANT_BYTE BIT(7)
//MOLE BYTES
#define MOLE_DOWN 0
#define MOLE_UP BIT(3)
#define MOLE_NO (BIT(2)|BIT(1)|BIT(0))
#define FAIL 1
#define MAX_NO_TRIES 20
#define DELAY_BYTE 150000
//PROJ
#define NO_BITS_PROJ 8
#define NO_STOP_BITS_PROJ 2
#define PARITY_PROJ -1 //NONE
#define BITRATE_PROJ 115200
//UART
#define COM1_ADDR 0x3F8
#define COM1_IRQ 4
#define COM2_ADDR 0x2F8
#define COM2_IRQ 3
//UART REGS
#define RBR 0
#define THR 0
#define IER 1
#define IIR 2
#define FCR 2
#define LCR 3
#define MCR 4
#define LSR 5
#define MSR 6
#define SR 7
#define DLM 1
#define DLL 0
//LCR
#define WORLD_LENGTH_SEL (BIT(1)|BIT(0))
#define NO_STOP_BITS BIT(2)
#define PARITY (BIT(5)|BIT(4)|BIT(3))
#define SET_BREAK_ENABLE BIT(6)
#define DLAB BIT(7)
#define WORD_LENGTH_5 0
#define WORD_LENGTH_6 BIT(0)
#define WORD_LENGTH_7 BIT(1)
#define WORD_LENGTH_8 (BIT(1)|BIT(0))
#define NO_STOP_BITS_1 0
#define NO_STOP_BITS_2 BIT(2)
#define PARITY_NONE 0 //VER convençao
#define PARITY_ODD BIT(3)
#define PARITY_EVEN (BIT(4)|BIT(3))
#define PARITY_1 (BIT(5)|BIT(3))
#define PARITY_0 (BIT(5)|BIT(4)|BIT(3))
#define SET_BREAK_EN BIT(6)
#define SEL_DL BIT(7)
#define SEL_DATA 0
#define DL_CONST 115200
//LSR
#define REC_DATA BIT(0)
#define OVERRUN_ERROR BIT(1)
#define PARITY_ERROR BIT(2)
#define FRAMING_ERROR BIT(3)
#define BREAK_INT BIT(4)
#define TRANS_HOLD_REG_EMPTY BIT(5)
#define TRANS_EMPTY_REG BIT(6)
#define FIFO_ERROR BIT(7)
//IER
#define EN_REC_DATA_INT BIT(0)
#define EN_TRANS_EMPTY_INT BIT(1)
#define EN_REC_LINE_STATUS_INT BIT(2)
#define EN_MODEM_STATUS_INT BIT(3)
//IIR
#define INT_STATUS BIT(0)
#define INT_ORIGIN (BIT(3)|BIT(2)|BIT(1))
#define _64_BYTE_FIFO BIT(5)
#define FIFO_STATUS (BIT(7)|BIT(6))
#define INT_PENDING 0
#define INT_NOT_PENDING BIT(0)
#define INT_ORIG_MODEM_STATUS 0
#define INT_ORIG_TRANS_EMPTY BIT(1)
#define INT_ORIG_CHAR_TIMEOUT BIT(3)
#define INT_ORIG_REC_DATA_AVAIL BIT(2)
#define INT_ORIG_LINE_STATUS (BIT(2)|BIT(1))
#define _64_BYTE_FIFO_ BIT(5)
#define FIFO_STATUS_NO_FIFO 0
#define FIFO_STATUS_UNUSABLE BIT(7)
#define FIFO_STATUS_EN (BIT(7)|BIT(6))
//FCR
#define EN_FIFO BIT(0)
#define CLEAR_REC_FIFO BIT(1)
#define CLEAR_TRANS_FIFO BIT(2)
#define DMA_MODE_SEL BIT(3)
#define EN_64_BYTE_FIFO BIT(5)
#define RX_INFO_INT_TRIG_LEVEL (BIT(7)|BIT(6))
#define RX_FIFO_INT_TRIG_LEVEL_1 0
#define RX_FIFO_INT_TRIG_LEVEL_4 BIT(6)
#define RX_FIFO_INT_TRIG_LEVEL_8 BIT(7)
#define RX_FIFO_INT_TRIG_LEVEL_16 (BIT(7)|BIT(6))
#endif /* _LCOM_UART_H */
<file_sep>var searchData=
[
['o_5fbreak_402',['O_BREAK',['../group__i8042.html#ga5a03349f44ec55a1cfc17be9b2bd8ffc',1,'i8042.h']]],
['offset_5ffor_5fpm_5ftime_403',['OFFSET_FOR_PM_TIME',['../rtc__macros_8h.html#a38b754da51185de5ccb15604b55678f2',1,'rtc_macros.h']]],
['out_5fbuff_404',['OUT_BUFF',['../group__i8042.html#ga21e5185acdcf7bf1005d75ec14590186',1,'i8042.h']]],
['output_5ffull_405',['output_full',['../keyboard_8c.html#a51c888063d1f117f3af4a65ae37e075b',1,'output_full(): keyboard.c'],['../keyboard_8h.html#a51c888063d1f117f3af4a65ae37e075b',1,'output_full(): keyboard.c']]],
['overrun_5ferror_406',['OVERRUN_ERROR',['../uart__const_8h.html#a71c26bc752960acd5308f21b05a13714',1,'uart_const.h']]]
];
<file_sep>#ifndef _LCOM_I8042_H_
#define _LCOM_I8042_H_
#include <lcom/lcf.h>
/** @defgroup i8042 i8042
* @{
*
* Constants for programming the i8254 Timer. Needs to be completed.
*/
#define FAIL 1
#define DELAY_US 20000
#define KBD_IRQ 1 /**< @brief KBD IRQ line */
#define MOUSE_IRQ 12 /**< @brief KBD IRQ line */
// Registers
#define STAT_REG 0x64 /**< @brief keyboard status register port */
#define CMD_REG 0x64 /**< @brief keyboard commands register port */
#define CMD_ARG_REG 0x60 /**< @brief keyboard command arguments register port */
#define OUT_BUFF 0x60 /**< @brief keyboard output buffer port */
#define IN_BUFF 0x60 /**< @brief keyboard input buffer port */
// KBC Status Register
#define KBD_PAR_ERROR BIT(7) /**< @brief Status register parity error */
#define KBD_TIME_ERROR BIT(6) /**< @brief Status register timeout error */
#define KBD_AUX BIT(5) /**< @brief Status register mouse data */
#define KBD_INH BIT(4) /**< @brief Status register inhibit flag */
#define KBD_A2 BIT(3) /**< @brief Status register A2 input line */
#define KBD_SYS BIT(2) /**< @brief Status register system flag */
#define KBD_IBF BIT(1) /**< @brief Status register input buffer full */
#define KBD_OBF BIT(0) /**< @brief Status register output buffer full */
// KBC Commands
#define READ_CMD_BYTE 0x20 /**< @brief return command byte */
#define WRITE_CMD_BYTE 0x60 /**< @brief writes new command byte passed as argument (to port 0x60) */
#define CHECK_KBC 0xAA /**< @brief self-test: returns 0x55 if OK, returns 0xFC if error */
#define CHECK_KB_IFC 0xAB /**< @brief check keyboard interface: returns 0, if OK */
#define DISABLE_KBD 0xAD /**< @brief disables keyboard interface */
#define ENABLE_KBD 0xAE /**< @brief enables keyboard interface */
#define DISABLE_MOUSE 0xA7 /**< @brief disables mouse interface */
#define ENABLE_MOUSE 0xA8 /**< @brief enables mouse interface */
#define CHEK_MOUSE_INTERFACE 0xA9 /**< @brief checks mouse interface */
#define WRITE_BYTE_TO_MOUSE 0xD4 /**< @brief writes bytes to mouse */
// KBC Command Byte
#define CMD_BYTE_DIS_M BIT(5) /**< @brief disable mouse interface */
#define CMD_BYTE_DIS_K BIT(4) /**< @brief disable keyboard interface */
#define CMD_BYTE_EN_INT_M BIT(1) /**< @brief enable interrupt on OBF, from mouse */
#define CMD_BYTE_EN_INT_K BIT(0) /**< @brief enable interrupt on OBF, from keyboard */
// Mouse Commands
#define RESET 0XFF /**< @brief mouse reset */
#define RESEND 0XFE /**< @brief for serial communications errors */
#define SET_DEFAULTS 0XF6 /**< @brief set default values */
#define DIS_DATA_REPORT 0XF5 /**< @brief in stream mode, should be sent before any other command */
#define EN_DATA_REPORT 0XF4 /**< @brief in stream mode only */
#define SET_SAMPLE_RATE 0XF3 /**< @brief sets state sampling rate */
#define SET_REMOTE_MODE 0XF0 /**< @brief send data on request only */
#define READ_DATA 0XEB /**< @brief send data packet request */
#define SET_STREAM_MODE 0XEA /**< @brief send data on events */
#define STAT_REQUEST 0XE9 /**< @brief */
#define SET_RESOLUTION 0XE8 /**< @brief get mouse configuration (3 bytes) */
#define SET_SCALING_2_1 0XE7 /**< @brief acceleration mode */
#define SET_SCALING_1_1 0XE6 /**< @brief linear mode */
// Mouse Responses
#define ACK 0XFA /**< @brief enable interrupt on OBF, from keyboard */
#define NACK 0XFE /**< @brief enable interrupt on OBF, from keyboard */
#define ERROR 0XFC /**< @brief enable interrupt on OBF, from keyboard */
// Parsing packet
#define Y_OVFL BIT(7) /**< @brief */
#define X_OVFL BIT(6) /**< @brief */
#define MSB_Y_DELTA BIT(5) /**< @brief */
#define MSB_X_DELTA BIT(4) /**< @brief */
#define FIRST_OF_PACKET BIT(3) /**< @brief checks if its the first byte of a packet (of 3 bytes) */
#define MB BIT(2) /**< @brief midle button pressed */
#define RB BIT(1) /**< @brief right button pressed */
#define LB BIT(0) /**< @brief left button pressed */
// Other important macros
#define TWO_BYTES_CODE 0xE0 /**< @brief two bytes scan code always starts with 0xE0 */
#define BREAK_CODE BIT(7) /**< @brief break codes always have bit 7 high */
// Break codes
#define ESC_BREAK 0x81
#define ENTER_BREAK 0x9C
#define BACK_SPACE_BREAK 0x8E
#define A_BREAK 0x9E
#define B_BREAK 0xB0
#define C_BREAK 0xAE
#define D_BREAK 0xA0
#define E_BREAK 0x92
#define F_BREAK 0xA1
#define G_BREAK 0xA2
#define H_BREAK 0xA3
#define I_BREAK 0x97
#define J_BREAK 0xA4
#define K_BREAK 0xA5
#define L_BREAK 0xA6
#define M_BREAK 0xB2
#define N_BREAK 0xB1
#define O_BREAK 0x98
#define P_BREAK 0x99
#define Q_BREAK 0x90
#define R_BREAK 0x93
#define S_BREAK 0x9F
#define T_BREAK 0x94
#define U_BREAK 0x96
#define V_BREAK 0xAF
#define W_BREAK 0x91
#define X_BREAK 0xAD
#define Y_BREAK 0x95
#define Z_BREAK 0xAC
/**@}*/
#endif /* _LCOM_I8042_H */
<file_sep>#ifndef _LCOM_SERIAL_PORT__H_
#define _LCOM_SERIAL_PORT__H_
#include <lcom/lcf.h>
//void test();
/**
Saves the initial configuration of the serial port (COM 1) into local variables
@return int - 1 if there was an error, 0 otherwise
*/
int ser_save_init_conf();
/**
Restores the initial configuration of the serial port (COM 1)
@return int - 1 if there was an error, 0 otherwise
*/
int ser_restore_init_conf();
/**
Sets the serial port (COM 1) configurations into the project's configuration
@return int - 1 if there was an error, 0 otherwise
*/
int ser_start_proj_config();
/**
Changes the configuration of the serial port (COM 1)
@param unsigned long - Word Length in bits
@param unsigned long - Number of stop bits
@param long - Parity -1: none, 0: even, 1: odd
@param unsigned long - Bitrate
@return int - 1 if there was an error, 0 otherwise
*/
int ser_set_conf(unsigned long bits, unsigned long stop,long parity, unsigned long rate);
/**
Subscribes and enables the interrupts of the Serial Port (COM 1)
and enables the Received Data and Receiver Line Status interrupts in the Serial Port (COM 1)
@param uint8_t* - will change to the position of the IRQ_SET bit
@return int - 1 if there was an error, 0 otherwise
*/
int (ser_subscribe_int)(uint8_t* bit_no);
/**
Unsubscribes and disables the interrupts of the Serial Port (COM 1)
and disables the Received Data and Receiver Line Status interrupts in the Serial Port (COM 1)
@return int - 1 if there was an error, 0 otherwise
*/
int (ser_unsubscribe_int)();
/**
Checks if it is possible to read the ReceiverBuffer, and checks for errors
@return int - 2 if there is an error in the Receiver Buffer, 1 if there was an error, 0 otherwise
*/
int ser_can_read();
/**
Cleans the Receiver Buffer.
@return int - 1 if there was an error, 0 otherwise
*/
int ser_flush_rx();
/**
Checks if there is an error in the Receiver Buffer
@return bool - true if there is an error, false otherwise
*/
bool ser_error_read();
/**
Checks if it is possible to send information by writing into the Transmitter Holding
@return int - true if it is possible to send info, false otherwise
*/
bool ser_can_send();
/**
Sends a byte to the Serial Port (COM 1)'s Transmitter Holding
@param uint8_t - byte to send
@return int - 1 if there was an error, 0 otherwise
*/
int ser_send_byte(uint8_t data);
/**
Sends a byte to the Serial Port (COM 1)'s Transmitter Holding and the waits
@param uint8_t - byte to send
@return int - 1 if there was an error, 0 otherwise
*/
int ser_send_byte_wait(uint8_t data);
/**
Sends a number of bytes to the Serial Port (COM 1)'s Transmitter Holding
@param uint8_t* - bytes to send
@param unsigned int - number of bytes to send
@return int - 1 if there was an error, 0 otherwise
*/
int ser_send_info(uint8_t* data, unsigned int length);
/**
Reads a byte of the Serial Port (COM 1)'s Receiver Buffer
@param uint8_t* - byte where will be written the info in the Receiver Buffer
@return int - 1 if there was an error, 0 otherwise
*/
int ser_read_byte(uint8_t* data);
/**
Handles the Serial Port (COM 1) interrupts by reading the Receiver Buffer
*/
void ser_ih();
#endif /* _LCOM_SERIAL_PORT_H */
<file_sep>var searchData=
[
['player_645',['Player',['../struct_player.html',1,'']]],
['player_5fsettings_646',['Player_Settings',['../struct_player___settings.html',1,'']]]
];
<file_sep>var searchData=
[
['menu_2ec_664',['menu.c',['../menu_8c.html',1,'']]],
['menu_2eh_665',['menu.h',['../menu_8h.html',1,'']]],
['mole_2ec_666',['mole.c',['../mole_8c.html',1,'']]],
['mole_2eh_667',['mole.h',['../mole_8h.html',1,'']]],
['mouse_2ec_668',['mouse.c',['../mouse_8c.html',1,'']]],
['mouse_2eh_669',['mouse.h',['../mouse_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['game_5fover_938',['GAME_OVER',['../game_8h.html#a24c6cf001751e215986feed57efec3fca871723195985a4ae22d7e10d99bf8a00',1,'game.h']]]
];
<file_sep>var searchData=
[
['uie_1163',['UIE',['../rtc__macros_8h.html#a2c276876faf62c1b29fe2383ce4ccfda',1,'rtc_macros.h']]],
['uip_1164',['UIP',['../rtc__macros_8h.html#a3289eebd69837790d4aacaccd18d46db',1,'rtc_macros.h']]],
['unrequested_5fbyte_1165',['UNREQUESTED_BYTE',['../uart__const_8h.html#a2cee58bb7447045d62b4b48f6601775f',1,'uart_const.h']]]
];
<file_sep>var searchData=
[
['j_5fbreak_221',['J_BREAK',['../group__i8042.html#ga9503cf55f6fa08d947698b7ba9396063',1,'i8042.h']]]
];
<file_sep>var searchData=
[
['parity_1121',['PARITY',['../uart__const_8h.html#af6996d12e71a534569c41a25de7d6d52',1,'uart_const.h']]],
['parity_5f0_1122',['PARITY_0',['../uart__const_8h.html#a57f7b655b1274561bc74c9a1577993ef',1,'uart_const.h']]],
['parity_5f1_1123',['PARITY_1',['../uart__const_8h.html#a4f9b492e0e63843bc12c8b175df8dfaf',1,'uart_const.h']]],
['parity_5ferror_1124',['PARITY_ERROR',['../uart__const_8h.html#a81d2ca6759f3f3bf04556b7558aea6bc',1,'uart_const.h']]],
['parity_5feven_1125',['PARITY_EVEN',['../uart__const_8h.html#a64de75e13d62a653f2a2b5c41e0374c2',1,'uart_const.h']]],
['parity_5fnone_1126',['PARITY_NONE',['../uart__const_8h.html#a8342f22c7fd72713629efcf411a0d04b',1,'uart_const.h']]],
['parity_5fodd_1127',['PARITY_ODD',['../uart__const_8h.html#a25e17ce6ba7124885e170c47bcd833e5',1,'uart_const.h']]],
['parity_5fproj_1128',['PARITY_PROJ',['../uart__const_8h.html#a0f1bd549405422922233680b77a499a1',1,'uart_const.h']]],
['probability_5flimit_5fdecrement_1129',['PROBABILITY_LIMIT_DECREMENT',['../mole_8h.html#a9c94ba793815058d8ca10d678f9b3ae8',1,'mole.h']]]
];
<file_sep>// IMPORTANT: you must include the following line in all your C files
#include <lcom/lcf.h>
#include <lcom/liblm.h>
#include <lcom/proj.h>
#include <stdbool.h>
#include <stdint.h>
#include "game.h"
// Any header files included below this line should have been created by you
int main(int argc, char *argv[])
{
// sets the language of LCF messages (can be either EN-US or PT-PT)
lcf_set_language("EN-US");
// enables to log function invocations that are being "wrapped" by LCF
// [comment this out if you don't want/need it]
lcf_trace_calls("/home/lcom/labs/proj/trace.txt");
// enables to save the output of printf function calls on a file
// [comment this out if you don't want/need it]
lcf_log_output("/home/lcom/labs/proj/output.txt");
// handles control over to LCF
// [LCF handles command line arguments and invokes the right function]
if (lcf_start(argc, argv))
return 1;
// LCF clean up tasks
// [must be the last statement before return]
lcf_cleanup();
return 0;
}
int(proj_main_loop)(int argc, char *argv[]) {
if (vggg_init(0x115) == NULL)
return 1;
WhacAMole* new_game = load_game();
game_main_loop(new_game);
vg_exit();
// int ipc_status;
// message msg;
// uint8_t bit_no = 0;
// unsigned long r;
// rtc_start(); //initializes variables rtc_time e rtc_date
// extern Time rtc_time;
// extern Date rtc_date;
// if (rtc_subscribe_int(&bit_no) != 0) {
// printf("ERROR: Subscribe failed");
// return 1;
// }
// uint16_t irq_rtc = BIT(bit_no); /// ATENCAO 16bits pois 0 RTC_IRQ = 8
// while (rtc_time.second != 0) { // para nao durar para sempre, nao relevante
// if ((r = driver_receive(ANY, &msg, &ipc_status)) != 0) {
// printf("driver_receive failed with: %d", r);
// continue;
// }
// if (is_ipc_notify(ipc_status)) { // received notification
// switch (_ENDPOINT_P(msg.m_source)) {
// case HARDWARE: // hardware interrupt notification
// if (msg.m_notify.interrupts & irq_rtc) { // subscribed interrupt BIT MASK
// rtc_int_handler(); //ATUALIZA VARIAVEL GLOBAL DO TEMPO
// printf("Time ---- %d:%d:%d\n", rtc_time.hour,rtc_time.minute, rtc_time.second);
// }
// break;
// default:
// break; /* no other notifications expected: do nothing */
// }
// } else { /* received a standard message, not a notification */
// /* no standard messages expected: do nothing */
// }
// }
// if (rtc_unsubscribe_int() != 0) {
// printf("ERROR: Unsubscribe failed");
// return 1;
// }
return OK;
}
<file_sep>#pragma once
#include <lcom/lcf.h>
#include "state_machine.h"
int mouse_subscribe_int(uint16_t *bit_no);
int mouse_unsubscribe_int();
void mouse_read_status_register(uint8_t *stat);
int mouse_check_status_register();
int mouse_output_full();
int mouse_input_empty();
int mouse_read_out_buffer(uint8_t *info);
void (mouse_ih)(void);
void mouse_parse_packet(uint8_t packet[], struct packet *new_packet);
int mouse_issue_command_to_kbc(uint8_t command, uint8_t arguments);
int issue_command_to_mouse(uint8_t command);
uint8_t mouse_read_response();
int mouse_issue_cmd_to_kbc(uint8_t command, uint8_t argument);
int mouse_kbc_write_cmd(uint8_t command);
int mouse_kbc_write_argument(uint8_t argument);
int mouse_write_command(uint8_t command, uint8_t*response);
struct mouse_ev mouse_get_event(struct packet *packet);
<file_sep>var searchData=
[
['game_5fover_845',['game_over',['../struct_whac_a_mole.html#a7e120da3119c328a4120e8d61ba31f23',1,'WhacAMole']]],
['game_5fstate_846',['game_state',['../struct_whac_a_mole.html#a400aae76c97dda52f78346d03abaef67',1,'WhacAMole']]],
['game_5ftime_847',['game_time',['../struct_whac_a_mole.html#ad8f0cd194569c58c7f4af4b2c740cc11',1,'WhacAMole']]],
['game_5ftime_5fnumbers_5ffont_848',['game_time_numbers_font',['../struct_whac_a_mole.html#acd43ab6bbbe565a94a879257274ef25a',1,'WhacAMole']]]
];
<file_sep>var searchData=
[
['menu_643',['Menu',['../struct_menu.html',1,'']]],
['mole_644',['Mole',['../struct_mole.html',1,'']]]
];
<file_sep>var searchData=
[
['button_636',['Button',['../struct_button.html',1,'']]]
];
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "keyboard.h"
#include "i8042.h"
static int kbd_hook_id = KBD_IRQ; //hook id used for the keyboard
bool keyboard_done_getting_scancodes = false; //signals that there is one more byte to read from the outbuuf
uint8_t bytes_read[2];
int scan_code_size=0;
uint8_t scan_code;
int kbd_subscribe_int(uint8_t *bit_no) {
*bit_no = BIT(kbd_hook_id);
if (sys_irqsetpolicy(KBD_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &kbd_hook_id) != OK) {
printf("kbd_subscribe_int::ERROR in setting policy!\n");
return FAIL;
}
return OK;
}
int kbd_unsubscribe_int() {
if (sys_irqrmpolicy(&kbd_hook_id) != OK) {
printf("kbd_unsubscribe_int::ERROR removing policy!\n");
return FAIL;
}
return OK;
}
void read_status_register(uint8_t *stat) {
if (util_sys_inb(STAT_REG, stat) != OK) {
printf("ERROR::Unable to read keyboard status register!\n");
}
}
int check_status_register() {
uint8_t temp=0; //hold the status
read_status_register(&temp);
if ((temp & (KBD_PAR_ERROR | KBD_TIME_ERROR | KBD_AUX)) != 0) {
return FAIL;
}
return OK;
}
int output_full() {
uint8_t st;
read_status_register(&st);
if(st & KBD_OBF)
return OK;
return FAIL;
}
int input_empty() {
uint8_t st;
read_status_register(&st);
if(st & KBD_IBF)
return FAIL;
return OK;
}
int read_out_buffer(uint8_t *info) {
if (util_sys_inb(OUT_BUFF, info) != OK) {
printf("ERROR::Error reading the out buffer!\n");
return FAIL;
}
return OK;
}
void(kbc_ih)(void) {
if (keyboard_done_getting_scancodes) {
keyboard_done_getting_scancodes = false;
scan_code_size = 0;
}
// checks if the output buffer is full
if (output_full()==OK) {
//reads scan code from output buffer
if (read_out_buffer(&scan_code) != OK) {
scan_code = 0;
return;
}
//checks if there is signal of an error
if (check_status_register() != OK) {
// discards the scan code
scan_code = 0;
return;
}
bytes_read[scan_code_size++] = scan_code;
if (scan_code != TWO_BYTES_CODE)
keyboard_done_getting_scancodes = true;
}
}
int issue_cmd_to_kbc(uint8_t command, uint8_t argument) {
uint8_t tries=4;
while (tries > 0) {
if (kbc_write_cmd(command) != OK) {
printf("ERROR::writing the command!\n");
return FAIL;
}
if (command == WRITE_CMD_BYTE) {
if (kbc_write_argument(argument) != OK)
printf("ERROR::writing the new command byte!\n");
return FAIL;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf(" issue_cmd_to_kbc ");
printf("After 4 tries, kbc was not ready to receive the command\n");
return FAIL;
}
int kbc_write_cmd(uint8_t command) {
uint8_t status, tries=4;
if (util_sys_inb(STAT_REG,&status) != OK) {
printf("ERROR::Unable to read the status register!\n");
return 1;
}
while (tries > 0) {
if ((status & KBD_IBF) == 0) {
if (sys_outb(CMD_REG, command) != OK)
return 1;
return OK;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("kbc_write_cmd");
printf("After 4 tries, kbc was not ready to receive the command\n");
return 1;
}
int kbc_write_argument(uint8_t argument) {
uint8_t status, tries = 4;
if (util_sys_inb(STAT_REG,&status) != OK ) {
printf("ERROR::Unable to read the status register!\n");
return 1;
}
while (tries > 0) {
if((status & KBD_IBF) == 0) {
if (sys_outb(CMD_ARG_REG,argument) != OK) {
return 1;
}
return OK;
}
tries--;
tickdelay(micros_to_ticks(DELAY_US));
}
printf("After 4 tries, kbc was not ready to receive the argument\n");
return 1;
}
<file_sep>#include <lcom/lcf.h>
#include "rtc.h"
#include "rtc_macros.h"
#include <stdint.h>
int rtc_hook_id = RTC_IRQ;
Time rtc_time;
Date rtc_date;
void bcd_to_dec(uint32_t* bcd){
*bcd = *bcd -6*(*bcd >> 4);
}
void wait_valid_rtc() {
uint32_t reg_a_data = 0;
do {
disable_rtc_int();
sys_outb(RTC_ADDR_REG, RTC_REGISTER_A);
sys_inb(RTC_DATA_REG, ®_a_data);
enable_rtc_int();
} while ( reg_a_data & UIP);
}
bool updating_rtc(){
uint32_t reg_a_data;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_A)) return true;
if(sys_inb(RTC_DATA_REG, ®_a_data)) return true;
if(reg_a_data & UIP) return true;
return false;
}
bool bcd_format(){
uint32_t reg_b_data=0;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return true;
if(sys_inb(RTC_DATA_REG, ®_b_data)) return true;
if(!(reg_b_data & DM)) return true;
return false;
}
bool military_time(){
uint32_t reg_b_data=0;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return true;
if(sys_inb(RTC_DATA_REG, ®_b_data)) return true;
if(reg_b_data & MILITARY_TIME) return true;
return false;
}
int read_date(Date* date){
if(sys_outb(RTC_ADDR_REG,YEAR_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(date->year))) return 1;
if(sys_outb(RTC_ADDR_REG,MONTH_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(date->month))) return 1;
if(sys_outb(RTC_ADDR_REG,DAY_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(date->day))) return 1;
if(bcd_format()){
bcd_to_dec(&(date->year));
bcd_to_dec(&(date->month));
bcd_to_dec(&(date->day));
}
return 0;
}
int read_time(Time* time){
if(sys_outb(RTC_ADDR_REG,HOUR_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(time->hour))) return 1;
if(sys_outb(RTC_ADDR_REG,MIN_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(time->minute))) return 1;
if(sys_outb(RTC_ADDR_REG,SEC_REG)) return 1;
if(sys_inb(RTC_DATA_REG, &(time->second))) return 1;
if(!military_time() && time->hour > LIMIT_HOUR){ // not military time and PM
time->hour -= OFFSET_FOR_PM_TIME;
}
if(bcd_format()){
bcd_to_dec(&(time->hour));
bcd_to_dec(&(time->minute));
bcd_to_dec(&(time->second));
}
return 0;
}
Date get_date(){
Date res;
while(true){
if(!updating_rtc()){
read_date(&res);
return res;
}
}
}
Time get_time(){
Time res;
while(true){
if(!updating_rtc()){
read_time(&res);
return res;
}
}
}
int (enable_rtc_int)(){
if(sys_irqenable(&rtc_hook_id)) return 1;
return 0;
}
int (disable_rtc_int)(){
if(sys_irqdisable(&rtc_hook_id)) return 1;
return 0;
}
int enable_rtc_UI(){
uint32_t reg_b_data=0;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return 1;
if(sys_inb(RTC_DATA_REG, ®_b_data)) return 1;
reg_b_data |= UIE;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return 1;
if(sys_outb(RTC_DATA_REG, reg_b_data)) return 1;
return 0;
}
int disable_rtc_UI(){
uint32_t reg_b_data=0;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return 1;
if(sys_inb(RTC_DATA_REG, ®_b_data)) return 1;
reg_b_data &= ~UIE;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_B)) return 1;
if(sys_outb(RTC_DATA_REG, reg_b_data)) return 1;
return 0;
}
int (rtc_subscribe_int)(uint8_t *bit_no) {
*bit_no = rtc_hook_id;
if(sys_irqsetpolicy(RTC_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &rtc_hook_id)!= OK){
printf("rtc_subscribe_int::ERROR in setting policy !\n");
return FAIL;
}
if(enable_rtc_UI()) return FAIL;
return OK;
}
int (rtc_unsubscribe_int)() {
if(sys_irqrmpolicy(&rtc_hook_id)!= OK){
printf("rtc_unsubscribe_int::ERROR in disabling IQR line!\n");
return FAIL;
}
if(disable_rtc_UI()) return FAIL;
return OK;
}
void (rtc_int_handler)(){
uint32_t reg_c_data=0;
if(sys_outb(RTC_ADDR_REG, RTC_REGISTER_C)) return;
if(sys_inb(RTC_DATA_REG, ®_c_data)) return;
if(reg_c_data & RTC_UF){
wait_valid_rtc();
read_time(&rtc_time);
}
}
void rtc_start(){
rtc_time = get_time();
rtc_date = get_date();
}
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "game.h"
//TIMER
extern unsigned int timer_counter;
//KEYBOARD
extern bool keyboard_done_getting_scancodes;
extern uint8_t scan_code;
//MOUSE
extern bool mouse_last_byte_of_packet;
extern uint8_t packet[];
//RTC
extern Time rtc_time;
extern Date rtc_date;
//UART
extern uint8_t ser_byte;
extern bool error_reading;
WhacAMole *load_game()
{
//srand(time(NULL)); // Initialization, should only be called once.
WhacAMole *new_game = (WhacAMole *)malloc(sizeof(WhacAMole));
new_game->game_time = 30;
new_game->cursor = load_cursor(cursor_xpm);
xpm_load(background_xpm, XPM_8_8_8_8, &(new_game->background[0]));
xpm_load(leaderboard_background_xpm, XPM_8_8_8_8, &(new_game->background[1]));
xpm_load(player_background_xpm, XPM_8_8_8_8, &(new_game->background[2]));
xpm_load(numbers_xpm, XPM_8_8_8_8, &new_game->game_time_numbers_font);
xpm_load(moles_missed_xpm, XPM_8_8_8_8, &new_game->moles_missed);
xpm_load(moles_hitted_xpm, XPM_8_8_8_8, &new_game->moles_hitted);
xpm_load(score_numbers_xpm, XPM_8_8_8_8, &new_game->numbers_font);
xpm_load(table_xpm, XPM_8_8_8_8, &new_game->table);
xpm_load(clock_icon_xpm, XPM_8_8_8_8, &new_game->clock_icon);
xpm_load(font_small_xpm, XPM_8_8_8_8, &(new_game->letters_small_font));
xpm_load(win_xpm, XPM_8_8_8_8, &(new_game->game_win));
xpm_load(waiting_for_player_xpm, XPM_8_8_8_8, &(new_game->waiting_for_player));
xpm_load(lose_xpm, XPM_8_8_8_8, &(new_game->game_lost));
new_game->num_moles = 6;
new_game->moles = (Mole *)malloc(sizeof(Mole) * new_game->num_moles);
for (int i = 0; i < 6; i++)
{
Mole *new_mole = createMole(i);
new_game->moles[i] = *new_mole;
}
new_game->menu = load_menu();
new_game->player_settings = load_player_settings();
new_game->player = load_player(new_game->player_settings->avatars[0]);
new_game->leaderboard = load_leaderboard();
new_game->cursor = load_cursor(cursor_xpm);
new_game->game_over = load_game_over();
new_game->exit = load_exit();
new_game->instructions = load_instructions();
new_game->game_state = MAIN_MENU;
new_game->host = true;
new_game->multiplayer = false;
new_game->opponent_end = false;
new_game->sent_hitted_moles = false;
new_game->running = true;
return new_game;
}
GameOver *load_game_over()
{
GameOver *game_over = (GameOver *)malloc(sizeof(GameOver));
xpm_load(game_over_xpm, XPM_8_8_8_8, &(game_over->logo_game_over));
xpm_load(ballon_xpm, XPM_8_8_8_8, &(game_over->ballon));
xpm_load(game_over_missed_moles_xpm, XPM_8_8_8_8, &(game_over->missed_moles));
xpm_load(game_over_hitted_moles_xpm, XPM_8_8_8_8, &(game_over->hitted_moles));
xpm_load(game_over_numbers_xpm, XPM_8_8_8_8, &(game_over->numbers));
game_over->cursor = load_cursor(cursor_xpm);
game_over->num_buttons = 3;
game_over->buttons = (Button **)malloc(sizeof(Button *) * game_over->num_buttons);
game_over->buttons[0] = load_button(MAIN_MENU_X, MAIN_MENU_Y, main_menu_normal_xpm, main_menu_active_xpm);
game_over->buttons[1] = load_button(LEADERB_GM_OV_X, LEADERB_GM_OV_Y, leaderboard_normal_xpm, leaderboard_active_xpm);
game_over->buttons[2] = load_button(EXIT_GM_OV_X, EXIT_GM_OV_Y, exit_normal_xpm, exit_active_xpm);
game_over->new_score = false;
return game_over;
}
Instructions *load_instructions()
{
Instructions *instructions = (Instructions *)malloc(sizeof(Instructions));
xpm_load(instructions_xpm, XPM_8_8_8_8, &(instructions->instructions));
return instructions;
}
Exit *load_exit()
{
Exit *exit = (Exit *)malloc(sizeof(Exit));
xpm_load(good_bye_message_xpm, XPM_8_8_8_8, &(exit->logo));
xpm_load(good_bye_mole_xpm, XPM_8_8_8_8, &(exit->mole));
xpm_load(credits_xpm, XPM_8_8_8_8, &(exit->credits));
exit->x_mole = 0;
exit->animation_timer = 3;
return exit;
}
int game_main_loop(WhacAMole *new_game)
{
int ipc_status, r;
message msg;
uint8_t irq_auxiliar = 0;
rtc_start();
//Subscribing all devices
if (timer_subscribe_int(&new_game->timer_irq) != OK)
{
return 1;
}
if (mouse_issue_cmd_to_kbc(WRITE_BYTE_TO_MOUSE, EN_DATA_REPORT) != OK)
{
return 1;
}
if (mouse_subscribe_int(&new_game->mouse_irq) != OK)
{
return 1;
}
if (kbd_subscribe_int(&new_game->keyboard_irq) != OK)
{
return 1;
}
if (rtc_subscribe_int(&irq_auxiliar) != OK)
{
return 1;
}
new_game->irq_rtc = BIT(irq_auxiliar);
if (ser_subscribe_int(&irq_auxiliar) != OK)
{
return 1;
}
new_game->uart_irq = BIT(irq_auxiliar);
ser_flush_rx();
while (new_game->running)
{
if ((r = driver_receive(ANY, &msg, &ipc_status)) != 0)
{
printf("driver_receive failed with: %d", r);
continue;
}
if (is_ipc_notify(ipc_status))
{ // received notification
switch (_ENDPOINT_P(msg.m_source))
{
case HARDWARE: // hardware interrupt notification
if (msg.m_notify.interrupts & new_game->keyboard_irq)
{
kbc_ih();
if (keyboard_done_getting_scancodes)
GeneralInterrupt(KEYBOARD, new_game);
}
if (msg.m_notify.interrupts & new_game->timer_irq)
{
timer_int_handler();
if (timer_counter % (60 / GAME_FPS) == 0)
GeneralInterrupt(TIMER, new_game);
update_buffer();
}
if (msg.m_notify.interrupts & new_game->mouse_irq)
{
mouse_ih();
if (mouse_last_byte_of_packet)
GeneralInterrupt(MOUSE, new_game);
}
if (msg.m_notify.interrupts & new_game->irq_rtc)
{
rtc_int_handler();
GeneralInterrupt(RTC, new_game);
}
if (msg.m_notify.interrupts & new_game->uart_irq)
{
rtc_int_handler();
GeneralInterrupt(UART, new_game);
}
break;
default:
break;
}
}
}
free(new_game->moles);
free(new_game->menu->buttons);
free(new_game->menu);
free(new_game->player_settings->avatars);
free(new_game->player_settings->buttons);
free(new_game->player_settings);
free(new_game->player);
free(new_game->cursor);
free(new_game->instructions);
free(new_game->game_over->buttons);
free(new_game->game_over->cursor);
free(new_game->game_over);
free(new_game->leaderboard->buttons);
free(new_game->leaderboard->score_records);
free(new_game->leaderboard);
free(new_game->exit);
free(new_game);
//Unsubscribing all devices
if (kbd_unsubscribe_int() != OK)
{
return 1;
}
if (timer_unsubscribe_int() != OK)
{
return 1;
}
if (mouse_unsubscribe_int() != OK)
{
return 1;
}
if (issue_command_to_mouse(DIS_DATA_REPORT) != OK)
{
return 1;
}
if (rtc_unsubscribe_int() != OK)
{
return 1;
}
if (ser_unsubscribe_int() != OK)
{
return 1;
}
return OK;
}
void GeneralInterrupt(device device, WhacAMole *new_game)
{
switch (new_game->game_state)
{
case MAIN_MENU:
Main_Menu_interrupt_handler(device, new_game);
break;
case INSTRUCTIONS:
Instructions_interrupt_handler(device, new_game);
break;
case PLAYER_SETTINGS:
Player_Settings_interrupt_handler(device, new_game);
break;
case WAITING:
Waiting_interrupt_handler(device, new_game);
break;
case SINGLE_PLAYER:
Single_Player_interrupt_handler(device, new_game);
break;
case MULTI_PLAYER:
Multi_Player_interrupt_handler(device, new_game);
break;
case GAME_OVER:
Game_Over_interrupt_handler(device, new_game);
break;
case WIN:
Win_interrupt_handler(device, new_game);
break;
case LOST:
Lost_interrupt_handler(device, new_game);
break;
case LEADERBOARD:
Leaderboard_interrupt_handler(device, new_game);
break;
case EXIT:
Exit_interrupt_handler(device, new_game);
break;
default:
break;
}
}
void Main_Menu_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
draw_logo(game->menu);
draw_buttons(game->menu->buttons, game->menu->num_buttons);
if (game->menu->buttons[5]->state == ACTIVE)
draw_date(game->numbers_font, CALLENDAR_NUM_X, CALLENDAR_NUM_Y, rtc_date);
if (game->menu->buttons[6]->state == ACTIVE)
{
draw_time(game->numbers_font, CLOCK_NUM_X, CLOCK_NUM_Y, rtc_time);
}
draw_cursor(game->cursor);
break;
case KEYBOARD:
break;
case MOUSE:
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
update_buttons(game->cursor, game->menu->buttons, game->menu->num_buttons);
if (game->menu->buttons[0]->state == ACTIVE && mouse_event.type == LB_RELEASED)
{
game->game_state = PLAYER_SETTINGS;
game->multiplayer = false;
}
else if (game->menu->buttons[1]->state == ACTIVE && mouse_event.type == LB_RELEASED)
{
game->game_state = PLAYER_SETTINGS;
game->multiplayer = true;
}
else if (game->menu->buttons[2]->state == ACTIVE && mouse_event.type == LB_RELEASED)
game->game_state = LEADERBOARD;
else if (game->menu->buttons[3]->state == ACTIVE && mouse_event.type == LB_RELEASED)
game->game_state = INSTRUCTIONS;
else if (game->menu->buttons[4]->state == ACTIVE && mouse_event.type == LB_RELEASED)
game->game_state = EXIT;
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Instructions_interrupt_handler(device device, WhacAMole *game)
{
Instructions *instructions = game->instructions;
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)instructions->instructions.bytes, instructions->instructions, X_ORIGIN, Y_ORIGIN);
break;
case KEYBOARD:
if (scan_code == ESC_BREAK)
game->game_state = MAIN_MENU;
break;
case MOUSE:
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Player_Settings_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
Player_Settings *player_sets = game->player_settings;
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)game->background[2].bytes, game->background[2], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)player_sets->background_title.bytes, player_sets->background_title, X_ORIGIN, Y_ORIGIN);
draw_avatars(player_sets->avatars);
draw_buttons(player_sets->buttons, player_sets->num_buttons);
draw_player_name(player_sets->font, NM_PLACE_X, NM_PLACE_Y, game->player->name, game->player->max_name_length);
if (player_sets->name_maximum_length)
draw_name_lenght_warning(player_sets);
draw_cursor(game->cursor);
break;
case KEYBOARD:
if (player_sets->buttons[2]->state == ACTIVE)
{
if (scan_code == BACK_SPACE_BREAK)
{
update_player_name(player_sets, game->player, true, ' ');
}
else
{
char new_letter = kbd_manager(scan_code);
if (new_letter != '.')
update_player_name(player_sets, game->player, false, kbd_manager(scan_code));
}
}
if (scan_code == ENTER_BREAK)
{
player_sets->buttons[2]->state = NORMAL;
player_sets->name_maximum_length = false;
}
break;
case MOUSE:
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
update_buttons(game->cursor, player_sets->buttons, player_sets->num_buttons);
if (mouse_over(player_sets->buttons[0], game->cursor) && mouse_event.type == LB_RELEASED)
move_left_avatar(player_sets);
else if (mouse_over(player_sets->buttons[1], game->cursor) && mouse_event.type == LB_RELEASED)
move_right_avatar(player_sets);
else if (mouse_over(player_sets->buttons[2], game->cursor) && mouse_event.type == LB_RELEASED)
{
if (game->player->name[game->player->max_name_length - 1] != ' ')
player_sets->name_maximum_length = true;
}
else if (mouse_over(player_sets->buttons[3], game->cursor) && mouse_event.type == LB_RELEASED)
{
game->cursor->cursor_image = get_hammer(player_sets);
if (!game->multiplayer)
game->game_state = SINGLE_PLAYER;
else if (game->host)
{
game->game_state = WAITING;
}
else
{
ser_send_byte_wait(CONFIRMATION);
game->game_state = MULTI_PLAYER;
}
}
break;
case RTC:
break;
case UART:
ser_ih();
if (ser_byte == READY_TO_PLAY_FROM_HOST)
{
game->host = false;
}
else
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Waiting_interrupt_handler(device device, WhacAMole *game)
{
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)game->background[1].bytes, game->background[1], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)game->waiting_for_player.bytes, game->waiting_for_player, 10, 300);
ser_send_byte_wait(READY_TO_PLAY_FROM_HOST);
break;
case KEYBOARD:
if (scan_code == ESC_BREAK)
game->game_state = EXIT;
break;
case MOUSE:
break;
case RTC:
break;
case UART:
ser_ih();
switch (ser_byte)
{
case CONFIRMATION:
game->host = true;
game->game_state = MULTI_PLAYER;
break;
default:
ser_byte = UNREQUESTED_BYTE;
break;
}
break;
}
}
void Single_Player_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
Position mole_position;
static int time_duration = 0;
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
draw_all_moles(game->moles, game->num_moles);
vg_draw_xpm((uint32_t *)game->table.bytes, game->table, SCORE_TABLE_X, SCORE_TABLE_Y);
vg_draw_xpm((uint32_t *)game->moles_hitted.bytes, game->moles_missed, MOLES_MISS_FRAME_X, MOLES_MISS_FRAME_Y);
vg_draw_xpm((uint32_t *)game->moles_missed.bytes, game->moles_hitted, MOLES_HIT_FRAME_X, MOLES_HIT_FRAME_Y);
draw_number(game->numbers_font, 13, MOLES_MISS_NUM_X, MOLES_MISS_NUM_Y, game->player->missed_moles, false);
draw_number(game->numbers_font, 13, MOLES_HIT_NUM_X, MOLES_HIT_NUM_Y, game->player->hitted_moles, false);
vg_draw_xpm((uint32_t *)game->clock_icon.bytes, game->clock_icon, CLOCK_ICON_X, CLOCK_ICON_Y);
draw_number(game->game_time_numbers_font, 10, GAME_TIMER_X, GAME_TIMER_Y, time_duration / GAME_FPS, true);
draw_cursor(game->cursor);
time_duration++;
for (int mole_index = 0; mole_index < 6; mole_index++)
{
Mole *ml = &game->moles[mole_index];
//if (rand() % 10000 > MOLE_PROBABILITY - (((timer_counter / (sys_hz() / GAME_FPS)) / GAME_DURATION) * PROBABILITY_LIMIT_DECREMENT))
if (ml->position == HIDED && (rand() % 10000 > MOLE_PROBABILITY))
{
ml->position = UP_1;
ml->time_up = 0;
}
else if (ml->position == UP_4)
{
ml->time_up++;
//if (ml->time_up >= (MOLE_UP_TIME - ((double)(timer_counter / (sys_hz() / GAME_FPS)) / GAME_DURATION) * TIME_UP_LIMIT_DECREMENT))
if (ml->time_up >= MOLE_UP_TIME)
{
ml->position = DOWN_MISSED_4;
ml->time_up = 0;
}
}
else if (ml->position != HIDED)
{
ml->position++;
if (ml->position == DOWN_MISSED_1 || ml->position == DOWN_HIT_1)
ml->position = HIDED;
}
}
if (time_duration / GAME_FPS >= game->game_time)
{
game->game_state = GAME_OVER;
time_duration = 0;
game->cursor->cursor_image = game->cursor->cursor_image_default;
}
break;
case KEYBOARD:
for (int mole_index = 0; mole_index < 6; mole_index++)
{
mole_position = game->moles[mole_index].position;
if (game->moles[mole_index].kbd_key == kbd_manager(scan_code))
{
if (mole_position == UP_4)
{
game->moles[mole_index].time_up = 0;
game->moles[mole_index].position = DOWN_HIT_4;
game->player->hitted_moles++;
break;
}
else
{
game->player->missed_moles++;
}
}
}
break;
case MOUSE:
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
if (mouse_event.type == LB_RELEASED)
{
game->player->missed_moles++;
for (int i = 0; i < game->num_moles; i++)
{
if (game->moles[i].position == UP_4 && check_over_mole(&game->moles[i], game->cursor->x, game->cursor->y) && mouse_event.type == LB_RELEASED)
{
game->moles[i].time_up = 0;
game->moles[i].position = DOWN_HIT_4;
game->player->hitted_moles++;
game->player->missed_moles--;
break;
}
}
}
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
default:
break;
}
}
void Multi_Player_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
Position mole_position;
static int time_duration = 0;
switch (device)
{
case TIMER:
/*if (game->host)
{
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
}
else
{
vg_draw_xpm((uint32_t *)game->background[1].bytes, game->background[1], X_ORIGIN, Y_ORIGIN);
}*/
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
draw_all_moles(game->moles, game->num_moles);
vg_draw_xpm((uint32_t *)game->table.bytes, game->table, SCORE_TABLE_X, SCORE_TABLE_Y);
vg_draw_xpm((uint32_t *)game->moles_hitted.bytes, game->moles_hitted, MOLES_MISS_FRAME_X, MOLES_MISS_FRAME_Y);
vg_draw_xpm((uint32_t *)game->moles_missed.bytes, game->moles_missed, MOLES_HIT_FRAME_X, MOLES_HIT_FRAME_Y);
draw_number(game->numbers_font, 13, MOLES_MISS_NUM_X, MOLES_MISS_NUM_Y, game->player->missed_moles, false);
draw_number(game->numbers_font, 13, MOLES_HIT_NUM_X, MOLES_HIT_NUM_Y, game->player->hitted_moles, false);
vg_draw_xpm((uint32_t *)game->clock_icon.bytes, game->clock_icon, CLOCK_ICON_X, CLOCK_ICON_Y);
draw_number(game->game_time_numbers_font, 10, GAME_TIMER_X, GAME_TIMER_Y, time_duration / GAME_FPS, true);
draw_cursor(game->cursor);
time_duration++;
bool created_mole = false;
for (uint8_t mole_index = 0; mole_index < 6; mole_index++)
{
Mole *ml = &game->moles[mole_index];
//if (rand() % 10000 > MOLE_PROBABILITY - (((timer_counter / (sys_hz() / GAME_FPS)) / GAME_DURATION) * PROBABILITY_LIMIT_DECREMENT))
if (game->host && !created_mole && ml->position == HIDED && (rand() % 10000 > MOLE_PROBABILITY_MULTIPLAYER))
{
ml->position = UP_1;
ml->time_up = 0;
created_mole = true;
ser_send_byte(MOLE_UP | mole_index);
}
else if (ml->position == UP_4)
{
ml->time_up++;
//if (ml->time_up >= (MOLE_UP_TIME - ((double)(timer_counter / (sys_hz() / GAME_FPS)) / GAME_DURATION) * TIME_UP_LIMIT_DECREMENT))
if (ml->time_up >= MOLE_UP_TIME)
{
ml->position = DOWN_MISSED_4;
ml->time_up = 0;
}
}
else if (ml->position != HIDED)
{
ml->position++;
if (ml->position == DOWN_MISSED_1 || ml->position == DOWN_HIT_1)
ml->position = HIDED;
}
}
if (time_duration / GAME_FPS >= game->game_time)
{
ser_send_byte_wait(GAME_OVER_BYTE);
game->game_state = GAME_OVER;
game->cursor->cursor_image = game->cursor->cursor_image_default;
}
break;
case KEYBOARD:
for (uint8_t mole_index = 0; mole_index < 6; mole_index++)
{
mole_position = game->moles[mole_index].position;
if (game->moles[mole_index].kbd_key == kbd_manager(scan_code))
{
if (mole_position == UP_4)
{
ser_send_byte(MOLE_DOWN | mole_index);
game->moles[mole_index].time_up = 0;
game->moles[mole_index].position = DOWN_HIT_4;
game->player->hitted_moles++;
break;
}
else
{
game->player->missed_moles++;
}
}
}
break;
case MOUSE:
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
if (mouse_event.type == LB_RELEASED)
{
game->player->missed_moles++;
for (uint8_t mole_index = 0; mole_index < game->num_moles; mole_index++)
{
if (game->moles[mole_index].position == UP_4 && check_over_mole(&game->moles[mole_index], game->cursor->x, game->cursor->y) && mouse_event.type == LB_RELEASED)
{
ser_send_byte(MOLE_DOWN | mole_index);
game->moles[mole_index].time_up = 0;
game->moles[mole_index].position = DOWN_HIT_4;
game->player->hitted_moles++;
game->player->missed_moles--;
break;
}
}
}
break;
case RTC:
break;
case UART:
ser_ih();
if (ser_byte & IRRELEVANT_BYTE)
{
ser_byte = UNREQUESTED_BYTE;
break;
}
else if (ser_byte == GAME_OVER_BYTE)
{
ser_send_byte_wait(GAME_OVER_BYTE);
game->game_state = GAME_OVER;
game->opponent_end = true;
game->cursor->cursor_image = game->cursor->cursor_image_default;
break;
}
else if (ser_byte & MOLE_UP)
{
if (game->moles[ser_byte & MOLE_NO].position == HIDED)
{
game->moles[ser_byte & MOLE_NO].position = UP_1;
game->moles[ser_byte & MOLE_NO].time_up = 0;
}
}
else
{
if (game->moles[ser_byte & MOLE_NO].position == UP_4)
{
game->moles[ser_byte & MOLE_NO].time_up = 0;
game->moles[ser_byte & MOLE_NO].position = DOWN_HIT_4;
}
}
break;
default:
break;
}
}
void Game_Over_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
static int y_auxiliar = 0;
GameOver *game_over = game->game_over;
switch (device)
{
case TIMER:
if (game->multiplayer && game->opponent_end)
{
ser_send_byte_wait(game->player->hitted_moles);
break;
}
if (game->multiplayer)
break;
if (add_new_score(game->leaderboard, game->player) && !game_over->new_score)
{
game_over->new_score = true;
}
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)game_over->logo_game_over.bytes, game_over->logo_game_over, GM_OV_LOGO_X, GM_OV_LOGO_Y);
vg_draw_xpm((uint32_t *)game_over->hitted_moles.bytes, game_over->hitted_moles, HIT_MOLES_TITLE_X, HIT_MOLES_TITLE_Y);
vg_draw_xpm((uint32_t *)game_over->missed_moles.bytes, game_over->missed_moles, MISS_MOLES_TITLE_X, MISS_MOLES_TITLE_Y);
draw_number(game->numbers_font, 13, HIT_MOLES_CT_X, HIT_MOLES_CT_Y, game->player->hitted_moles, false);
draw_number(game->numbers_font, 13, MISS_MOLES_CT_X, MISS_MOLES_CT_Y, game->player->missed_moles, false);
for (int i = 0; i < game_over->num_buttons; i++)
{
draw_button(game_over->buttons[i]);
}
draw_cursor(game->cursor);
if (game_over->new_score)
{
y_auxiliar += 25;
vg_draw_xpm((uint32_t *)game_over->ballon.bytes, game_over->ballon, BALLON_X, BALLON_Y - y_auxiliar);
}
break;
case KEYBOARD:
break;
case MOUSE:
if (game->multiplayer)
{
break;
}
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
update_buttons(game->cursor, game->game_over->buttons, game->game_over->num_buttons);
if (game->game_over->buttons[0]->state == ACTIVE && mouse_event.type == LB_RELEASED)
{
game->player_settings = load_player_settings();
game->game_state = MAIN_MENU;
reset_moles(game->moles, game->num_moles);
game->player->hitted_moles = 0;
game->player->missed_moles = 0;
}
if (game->game_over->buttons[1]->state == ACTIVE && mouse_event.type == LB_RELEASED)
{
game->game_state = LEADERBOARD;
reset_moles(game->moles, game->num_moles);
game->player->hitted_moles = 0;
game->player->missed_moles = 0;
}
if (game->game_over->buttons[2]->state == ACTIVE && mouse_event.type == LB_RELEASED)
game->game_state = EXIT;
break;
case RTC:
break;
case UART:
ser_ih();
if (ser_byte & IRRELEVANT_BYTE)
{
ser_byte = UNREQUESTED_BYTE;
break;
}
else if (ser_byte == GAME_OVER_BYTE)
{
game->opponent_end = true;
ser_byte = UNREQUESTED_BYTE;
break;
}
if (ser_byte < MAX_NO_MOLES)
{
if (ser_byte > game->player->hitted_moles)
game->game_state = LOST;
else
game->game_state = WIN;
}
break;
}
}
void Leaderboard_interrupt_handler(device device, WhacAMole *game)
{
struct mouse_ev mouse_event;
struct packet new_packet;
Leaderboard *leaderboard = game->leaderboard;
switch (device)
{
case TIMER:
vg_draw_xpm((uint32_t *)game->background[1].bytes, game->background[1], X_ORIGIN, Y_ORIGIN);
draw_leaderboard_table(leaderboard);
draw_buttons(leaderboard->buttons, leaderboard->num_buttons);
draw_player_names(game->letters_small_font, leaderboard->score_records, leaderboard->num_score_records);
draw_player_scores(leaderboard);
draw_player_dates(leaderboard);
draw_cursor(game->cursor);
break;
case KEYBOARD:
break;
case MOUSE:
mouse_parse_packet(packet, &new_packet);
mouse_event = mouse_get_event(&new_packet);
move_cursor(&new_packet, game->cursor);
update_buttons(game->cursor, leaderboard->buttons, leaderboard->num_buttons);
if (leaderboard->buttons[0]->state == ACTIVE && mouse_event.type == LB_RELEASED)
game->game_state = MAIN_MENU;
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Exit_interrupt_handler(device device, WhacAMole *game)
{
static int exit_time = 0;
Exit *exit = game->exit;
switch (device)
{
case TIMER:
exit_time++;
if ((exit_time / GAME_FPS) < exit->animation_timer)
{
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)exit->logo.bytes, exit->logo, GD_BYE_LOGO_X, GD_BYE_LOGO_Y);
vg_draw_xpm((uint32_t *)exit->credits.bytes, exit->credits, CREDITS_X, CREDITS_Y);
if (timer_counter % 5 == 0)
exit->x_mole += 18;
vg_draw_xpm((uint32_t *)exit->mole.bytes, exit->mole, exit->x_mole, MOLE_ANIMATION_Y);
}
else
{
save_scores(game->leaderboard);
game->running = false;
}
break;
case KEYBOARD:
break;
case MOUSE:
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Win_interrupt_handler(device device, WhacAMole *game)
{
switch (device)
{
case TIMER:
if(!game->sent_hitted_moles){
ser_send_byte_wait(game->player->hitted_moles);
game->sent_hitted_moles = true;
}
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)game->game_win.bytes, game->game_win, WIN_LOSE_X, WIN_LOSE_Y);
break;
case KEYBOARD:
if (scan_code == ESC_BREAK)
game->game_state = EXIT;
break;
case MOUSE:
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void Lost_interrupt_handler(device device, WhacAMole *game)
{
switch (device)
{
case TIMER:
if(!game->sent_hitted_moles){
ser_send_byte_wait(game->player->hitted_moles);
game->sent_hitted_moles = true;
}
vg_draw_xpm((uint32_t *)game->background[0].bytes, game->background[0], X_ORIGIN, Y_ORIGIN);
vg_draw_xpm((uint32_t *)game->game_lost.bytes, game->game_lost, WIN_LOSE_X, WIN_LOSE_Y);
break;
case KEYBOARD:
if (scan_code == ESC_BREAK)
game->game_state = EXIT;
break;
case MOUSE:
break;
case RTC:
break;
case UART:
ser_ih();
ser_byte = UNREQUESTED_BYTE;
break;
}
}
void draw_number(xpm_image_t font, int font_info, int xi, int yi, int number, bool left_number_drawing)
{
int left_number = number / 10;
int right_number = number % 10;
int number_width = font.width / font_info;
int number_height = font.height;
if (left_number != 0)
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi, yi, left_number * number_width, (left_number + 1) * number_width, 0, number_height);
else if (left_number_drawing)
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi, yi, left_number * number_width, (left_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi + number_width, yi, right_number * number_width, (right_number + 1) * number_width, 0, number_height);
}
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "player_settings.h"
#include "xpm_coordinates.h"
Player *load_player(Avatar *default_avatar)
{
//Allocating memory
Player *player = (Player *)malloc(sizeof(Player));
player->name = (char *)malloc(player->max_name_length);
player->name[0] = 'P';
player->name[1] = 'L';
player->name[2] = 'A';
player->name[3] = 'Y';
player->name[4] = 'E';
player->name[5] = 'R';
player->name[6] = ' ';
player->hitted_moles = 0;
player->missed_moles = 0;
player->max_name_length = 7;
player->avatar = default_avatar->sprites[0];
return player;
}
Avatar *load_avatar(xpm_row_t *normal, xpm_row_t *selected, xpm_row_t *small)
{
Avatar *avatar = malloc(sizeof(Avatar));
if (avatar == NULL)
return NULL;
xpm_load(normal, XPM_8_8_8_8, &(avatar->sprites[0]));
xpm_load(selected, XPM_8_8_8_8, &(avatar->sprites[1]));
xpm_load(small, XPM_8_8_8_8, &(avatar->sprites[2]));
avatar->state = NOT_SELECTED;
return avatar;
}
Player_Settings *load_player_settings()
{
Player_Settings *player_sets = malloc(sizeof(Player_Settings));
xpm_load(player_title_xpm, XPM_8_8_8_8, &(player_sets->background_title));
xpm_load(font_xpm, XPM_8_8_8_8, &(player_sets->font));
xpm_load(name_length_warning_xpm, XPM_8_8_8_8, &(player_sets->name_length_warning));
player_sets->avatars[0] = load_avatar(hammer_0_big_xpm, hammer_0_big_bright_xpm, hammer_0_small_xpm);
player_sets->avatars[1] = load_avatar(hammer_1_big_xpm, hammer_1_big_bright_xpm, hammer_1_small_xpm);
player_sets->avatars[2] = load_avatar(hammer_2_big_xpm, hammer_2_big_bright_xpm, hammer_2_small_xpm);
player_sets->avatars[3] = load_avatar(hammer_3_big_xpm, hammer_3_big_bright_xpm, hammer_3_small_xpm);
player_sets->avatars[0]->state = SELECTED;
player_sets->num_buttons = 4;
player_sets->buttons = (Button **) malloc(sizeof(Button *) * player_sets->num_buttons);
player_sets->buttons[0] = load_button(ARROW_LEFT_X, ARROW_LEFT_Y, arrow_left_normal_xpm, arrow_left_active_xpm);
player_sets->buttons[1] = load_button(ARROW_RIGHT_X, ARROW_RIGHT_Y, arrow_right_normal_xpm, arrow_right_active_xpm);
player_sets->buttons[2] = load_button(NAME_BOX_X, NAME_BOX_Y, name_box_normal_xpm, name_box_active_xpm);
player_sets->buttons[3] = load_button(START_X, START_Y, start_normal_xpm, start_active_xpm);
player_sets->name_maximum_length = false;
return player_sets;
}
void draw_name_lenght_warning(Player_Settings *player_sets)
{
vg_draw_xpm((uint32_t *)player_sets->name_length_warning.bytes, player_sets->name_length_warning, NM_LENGTH_WR_X, NM_LENGTH_WR_Y);
}
void draw_avatars(Avatar *avatars[4])
{
for (int i = 0; i < 4; i++)
{
xpm_image_t current_img = avatars[i]->sprites[(int)avatars[i]->state];
vg_draw_xpm((uint32_t *)current_img.bytes, current_img, i * STEP_AVT_X + FIRST_AVT_Y, i * STEP_AVT_Y + FIRST_AVT_Y);
}
}
void move_left_avatar(Player_Settings *player_sets)
{
if (player_sets->avatars[0]->state == SELECTED)
return;
for (int i = 1; i <= 3; i++)
{
if (player_sets->avatars[i]->state == SELECTED)
{
player_sets->avatars[i]->state = NOT_SELECTED;
player_sets->avatars[i - 1]->state = SELECTED;
}
}
}
void move_right_avatar(Player_Settings *player_sets)
{
if (player_sets->avatars[3]->state == SELECTED)
return;
for (int i = 2; i >= 0; i--)
{
if (player_sets->avatars[i]->state == SELECTED)
{
player_sets->avatars[i]->state = NOT_SELECTED;
player_sets->avatars[i + 1]->state = SELECTED;
}
}
}
xpm_image_t get_hammer(Player_Settings *player_sets)
{
for (int i = 0; i < 4; i++)
{
if (player_sets->avatars[i]->state == SELECTED)
{
return player_sets->avatars[i]->sprites[2];
}
}
return player_sets->avatars[0]->sprites[2];
}
void draw_player_name(xpm_image_t font, int xi, int yi, char name[], int name_size)
{
int letter_width = font.width / (26 / 2); // 26 letters in two rows equals 13 letter per row
int letter_height = font.height / 2; //two rows of letters
int index = 0;
for (int i = 0; i < name_size; i++)
{
if (name[i] == ' ')
break;
index = (int)name[i] - (int)'A';
if (index < 13)
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi + i * letter_width, yi, index * letter_width, index * letter_width + letter_width, 0, letter_height);
else
vg_draw_part_of_xpm((uint32_t *)font.bytes, font, xi + i * letter_width, yi, index * letter_width, index * letter_width + letter_width, letter_height, letter_height * 2);
}
}
void update_player_name(Player_Settings* player_sets, Player *player, bool delete_letter, char new_letter)
{
if (delete_letter)
{ //searches for the first empty space and deletes the letter before this space
if (player->name[player->max_name_length - 1] != ' ')
{
player->name[player->max_name_length - 1] = ' ';
player_sets->name_maximum_length = false;
return;
}
for (int i = 0; i < player->max_name_length; i++)
{
if (player->name[i] == ' ' && i != 0)
{
player->name[i - 1] = ' ';
player_sets->name_maximum_length = false;
return;
}
}
}
else
{ //search for the first empty space to add a new letter
for (int i = 0; i < player->max_name_length; i++)
{
if (player->name[i] == ' ')
{
player->name[i] = new_letter;
if (i == (player->max_name_length - 1))
player_sets->name_maximum_length = true;
return;
}
}
}
}
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "leaderboard.h"
Leaderboard *load_leaderboard()
{
//Allocating memory
Leaderboard *leaderboard = (Leaderboard *)malloc(sizeof(Leaderboard));
xpm_load(leaderboard_crown_xpm, XPM_8_8_8_8, &(leaderboard->crown));
xpm_load(leaderboard_table_xpm, XPM_8_8_8_8, &(leaderboard->table));
xpm_load(score_numbers_xpm, XPM_8_8_8_8, &(leaderboard->numbers));
leaderboard->max_name_length = 7;
leaderboard->num_score_records = 5;
leaderboard->score_records = (Score_Record *)malloc(sizeof(Score_Record) * leaderboard->num_score_records);
leaderboard->score_records[0].player_name = (char *)malloc(leaderboard->max_name_length);
leaderboard->score_records[1].player_name = (char *)malloc(leaderboard->max_name_length);
leaderboard->score_records[2].player_name = (char *)malloc(leaderboard->max_name_length);
leaderboard->score_records[3].player_name = (char *)malloc(leaderboard->max_name_length);
leaderboard->score_records[4].player_name = (char *)malloc(leaderboard->max_name_length);
load_scores(leaderboard);
leaderboard->num_buttons = 1;
leaderboard->buttons = (Button **)malloc(sizeof(Button *) * leaderboard->num_buttons);
leaderboard->buttons[0] = load_button(CLOSE_X, CLOSE_Y, score_close_normal_xpm, score_close_active_xpm);
return leaderboard;
}
void draw_leaderboard_table(Leaderboard *leaderboard)
{
uint32_t *crown_map = (uint32_t *)leaderboard->crown.bytes;
vg_draw_xpm(crown_map, leaderboard->crown, LDBRD_CROWN_X, LDBRD_CROWN_Y);
uint32_t *table_map = (uint32_t *)leaderboard->table.bytes;
vg_draw_xpm(table_map, leaderboard->table, LDBRD_TABLE_X, LDBRD_TABLE_Y);
}
void draw_player_names(xpm_image_t font, Score_Record* score_records, uint8_t num_records)
{
for (int i = 0; i < num_records; i++)
{
Score_Record *curr_score_record = &score_records[i];
if (curr_score_record->player_name_size != 0)
draw_player_name(font, LDBRD_NAME_STEP_FROM_X, i * LDBRD_NAME_STEP_FROM_LINE + LDBRD_NAME_STEP_FROM_Y, curr_score_record->player_name, curr_score_record->player_name_size);
}
}
void draw_player_scores(Leaderboard *leaderboard)
{
for (int i = 0; i < leaderboard->num_score_records; i++)
{
Score_Record *curr_score_record = &leaderboard->score_records[i];
if (curr_score_record->player_name_size != 0)
draw_player_score(leaderboard->numbers, LDBRD_SCORE_STEP_FROM_X, i * LDBRD_SCORE_STEP_FROM_LINE + LDBRD_SCORE_STEP_FROM_Y, curr_score_record->score);
}
}
void draw_player_dates(Leaderboard *leaderboard)
{
for (int i = 0; i < leaderboard->num_score_records; i++)
{
Score_Record *curr_score_record = &leaderboard->score_records[i];
if (curr_score_record->player_name_size != 0)
draw_date(leaderboard->numbers, LDBRD_DATE_STEP_FROM_X, i * LDBRD_DATE_STEP_FROM_LINE + LDBRD_DATE_STEP_FROM_Y, curr_score_record->date);
}
}
void draw_player_score(xpm_image_t font, int xi, int yi, int score)
{
uint32_t *font_pixmap = (uint32_t *)font.bytes;
int number_width = font.width / 13; // 10 numbers plus slash, two points and percentage symbol
int number_height = font.height;
int left_score_number, mid_score_number, right_score_number;
right_score_number = score % 10;
mid_score_number = (score / 10) % 10;
left_score_number = score / 100;
vg_draw_part_of_xpm(font_pixmap, font, xi, yi, 12 * number_width, 13 * number_width, 0, number_height); //Percentage symbol
vg_draw_part_of_xpm(font_pixmap, font, xi - number_width, yi, right_score_number * number_width, (right_score_number + 1) * number_width, 0, number_height);
if (mid_score_number == 0 && left_score_number - 2 != 0)
{
vg_draw_part_of_xpm(font_pixmap, font, xi - 2 * number_width, yi, mid_score_number * number_width, (mid_score_number + 1) * number_width, 0, number_height);
vg_draw_part_of_xpm(font_pixmap, font, xi - number_width * 3, yi, left_score_number * number_width, (left_score_number + 1) * number_width, 0, number_height);
}
else if (mid_score_number != 0)
{
vg_draw_part_of_xpm(font_pixmap, font, xi - 2 * number_width, yi, mid_score_number * number_width, (mid_score_number + 1) * number_width, 0, number_height);
}
}
void save_scores(Leaderboard *leaderboard)
{
FILE *leaderboard_file;
leaderboard_file = fopen("/home/lcom/labs/proj/src/leaderboard.txt", "w");
if (leaderboard_file == NULL) //SEE LATER
return;
for (int i = 0; i < leaderboard->num_score_records; i++)
{
Score_Record *curr_score_record = &(leaderboard->score_records[i]);
fprintf(leaderboard_file, "%s\n", curr_score_record->player_name);
fprintf(leaderboard_file, "%d\n", curr_score_record->score);
fprintf(leaderboard_file, "%d/%d/%d\n", curr_score_record->date.day, curr_score_record->date.month, curr_score_record->date.year);
}
fclose(leaderboard_file);
}
void load_scores(Leaderboard *leaderboard)
{
FILE *leaderboard_file;
leaderboard_file = fopen("/home/lcom/labs/proj/src/leaderboard.txt", "r");
if (leaderboard_file == NULL)
{
for (int i = 0; i < leaderboard->num_score_records; i++)
{
leaderboard->score_records[i].score = 0;
leaderboard->score_records[i].player_name_size = 0;
leaderboard->score_records[i].player_name[0] = ' ';
}
return;
}
for (int i = 0; i < leaderboard->num_score_records; i++)
{
fgets(leaderboard->score_records[i].player_name, leaderboard->max_name_length, leaderboard_file);
strtok(leaderboard->score_records[i].player_name, "\n");
if(strncmp(leaderboard->score_records[i].player_name, "nobody", 6) == 0) leaderboard->score_records[i].player_name_size = 0;
else leaderboard->score_records[i].player_name_size = strlen(leaderboard->score_records[i].player_name);
fscanf(leaderboard_file, "%d", &leaderboard->score_records[i].score);
fgetc(leaderboard_file);
fscanf(leaderboard_file, "%d/%d/%d", &leaderboard->score_records[i].date.day, &leaderboard->score_records[i].date.month, &leaderboard->score_records[i].date.year);
fgetc(leaderboard_file);
}
fclose(leaderboard_file);
}
bool add_new_score(Leaderboard* leaderboard, Player* player) {
if(player->hitted_moles == 0)
return false;
int aux = player->hitted_moles*100;
int score = 0;
while (aux >= (player->hitted_moles + player->missed_moles)) {
aux -= player->hitted_moles + player->missed_moles;
score++;
}
int index_new_score = -1;
for (int i = leaderboard->num_score_records-1; i >= 0; i--) {
Score_Record* curr_score_record = &leaderboard->score_records[i];
if (score > curr_score_record->score) {
index_new_score = i;
}
}
if (index_new_score == -1)
return false;
for (int i = leaderboard->num_score_records-1; i > index_new_score; i--) {
if (leaderboard->score_records[i-1].score == 0)
continue;
leaderboard->score_records[i] = leaderboard->score_records[i-1];
}
leaderboard->score_records[index_new_score].player_name = player->name;
leaderboard->score_records[index_new_score].player_name_size = player->max_name_length;
leaderboard->score_records[index_new_score].score = score;
leaderboard->score_records[index_new_score].date = get_date();
return true;
}
<file_sep>var searchData=
[
['rtc_2ec_673',['rtc.c',['../rtc_8c.html',1,'']]],
['rtc_2eh_674',['rtc.h',['../rtc_8h.html',1,'']]],
['rtc_5fmacros_2eh_675',['rtc_macros.h',['../rtc__macros_8h.html',1,'']]]
];
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include <stdio.h>
struct mouse_ev mouse_get_event(struct packet *packet);
<file_sep>var searchData=
[
['font_844',['font',['../struct_player___settings.html#a632b0a796c388aa5cf8a762ff0790256',1,'Player_Settings']]]
];
<file_sep>var searchData=
[
['down_5fhit_5f1_929',['DOWN_HIT_1',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83af116809b0271088443db3bac76462276',1,'mole.h']]],
['down_5fhit_5f2_930',['DOWN_HIT_2',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83a2200a00a33e48d4bfcc472fc9e8126bf',1,'mole.h']]],
['down_5fhit_5f3_931',['DOWN_HIT_3',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83a05311f9d5f951ac5273b4380fe6f8b45',1,'mole.h']]],
['down_5fhit_5f4_932',['DOWN_HIT_4',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83aa9653419ca9908c6929a8b2fea1d6c82',1,'mole.h']]],
['down_5fmissed_5f1_933',['DOWN_MISSED_1',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83a1d45179ca0dbadd9794e28a3be019f66',1,'mole.h']]],
['down_5fmissed_5f2_934',['DOWN_MISSED_2',['../mole_8h.html#ab91b34ae6<KEY>',1,'mole.h']]],
['down_5fmissed_5f3_935',['DOWN_MISSED_3',['../mole_8h.html#ab91b34ae619fcdfcba<KEY>add02d498a94509e57708030f50',1,'mole.h']]],
['down_5fmissed_5f4_936',['DOWN_MISSED_4',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83a1ec40fd352e93c619315f671cc4c7f18',1,'mole.h']]]
];
<file_sep>var searchData=
[
['q_5fbreak_428',['Q_BREAK',['../group__i8042.html#ga6a2eb960cdda5887902f55fb5d356deb',1,'i8042.h']]]
];
<file_sep>var searchData=
[
['_5f64_5fbyte_5ffifo_959',['_64_BYTE_FIFO',['../uart__const_8h.html#a626740fb3085313c5bf770cb0f2bb07b',1,'uart_const.h']]],
['_5f64_5fbyte_5ffifo_5f_960',['_64_BYTE_FIFO_',['../uart__const_8h.html#ad11bf13170910f8277f06811d93479c9',1,'uart_const.h']]],
['_5fvd_5fcard_5fh_5f_961',['_VD_CARD_H_',['../vd__card_8h.html#a2876e968398d55190b6e11ead3cffc0c',1,'vd_card.h']]]
];
<file_sep> #include <lcom/lcf.h>
#include <stdint.h>
#include "vd_card.h"
static char *video_mem; /* virtual address to which VRAM is mapped */
static char *double_buffer;
static uint16_t hres; /* XResolution */
static uint16_t vres; /* YResolution */
static uint16_t bits_per_pixel; /* VRAM bits per pixel */
static uint8_t red_mask_size, green_mask_size, blue_mask_size;
static uint8_t red_field_position, green_field_position, blue_field_position;
uint16_t vg_get_hres() { return hres; }
uint16_t vg_get_vres() { return vres; }
int (vbe_get_mode_info_remade)(uint16_t mode, vbe_mode_info_t *vmi_p) {
mmap_t buff;
int tries = 4;
while(tries > 0) {
tries--;
if (lm_alloc(sizeof(vbe_mode_info_t),&buff) != NULL)
break;
}
if (tries == 0) {
printf("ERROR\n");
return 1;
}
reg86_t r;
memset(&r,0,sizeof(r));
r.intno = 0x10;
r.cx = mode;
r.ax = 0x4F01;
r.es = PB2BASE(buff.phys);
r.di = PB2OFF(buff.phys);
if (sys_int86(&r) != OK) {
printf("set_vbe_mode: sys_int86() failed \n");
if (lm_free(&buff) != OK)
return 1;
return 1;
}
if (r.al != 0x4F || r.ah != 0x00) {
return 1;
}
*vmi_p = *((vbe_mode_info_t*) buff.virt);
if (lm_free(&buff) != OK)
return 1;
return 0;
}
void* vggg_init(unsigned short mode) {
vbe_mode_info_t vbe_mode;
vbe_get_mode_info_remade(mode, &vbe_mode);
hres = vbe_mode.XResolution;
vres = vbe_mode.YResolution;
bits_per_pixel = vbe_mode.BitsPerPixel;
red_mask_size = vbe_mode.RedMaskSize;
green_mask_size = vbe_mode.GreenMaskSize;
blue_mask_size = vbe_mode.BlueMaskSize;
red_field_position = vbe_mode.RedFieldPosition;
green_field_position = vbe_mode.GreenFieldPosition;
blue_field_position = vbe_mode.BlueFieldPosition;
unsigned vram_size = hres * vres * ((bits_per_pixel + 7) / 8);
int r;
struct minix_mem_range mr;
/* Allow memory mapping */
mr.mr_base = (phys_bytes) vbe_mode.PhysBasePtr;
mr.mr_limit = mr.mr_base + vram_size;
if( OK != (r = sys_privctl(SELF, SYS_PRIV_ADD_MEM, &mr)))
panic("sys_privctl (ADD_MEM) failed: %d\n", r);
/* Map memory */
video_mem = vm_map_phys(SELF, (void *)mr.mr_base, vram_size);
if(video_mem == MAP_FAILED)
panic("couldn't map video memory");
double_buffer = malloc(vram_size);
reg86_t t;
memset(&t, 0, sizeof(t)); /* wipe the struct */
t.ax = 0x4F02; // VBE call, function 02 -- set VBE mode
t.bx = 1 << 14 | mode; // set bit 14: linear framebuffer
t.intno = 0x10;
if (sys_int86(&t) != OK) {
printf("set_vbe_mode: sys_int86() failed \n");
return NULL;
}
return (void*) vbe_mode.PhysBasePtr;
}
int square_draw(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint32_t color) {
for (int l = 0; l < height; l++) {
if (vg_draw_hlineee(x , y+l, width, color) != OK)
return 1;
}
return OK;
}
int vg_draw_hlineee(uint16_t x, uint16_t y, uint16_t len, uint32_t color) {
for (int i = 0; i < len;i++) {
if (vg_paint_pixel(x+i,y,color) != OK)
return 1;
}
return OK;
}
int vg_paint_pixel(uint16_t x_coord, uint16_t y_coord, uint32_t color) {
if (x_coord > hres || y_coord > vres) {
return 1;
}
if (bits_per_pixel == 8) {
memset(double_buffer + hres*y_coord + x_coord, color, 1);
}
else if (bits_per_pixel == 15) {
memcpy(double_buffer + hres*y_coord*2 + x_coord*2, &color, 2);
}
else {
memcpy(double_buffer + hres*y_coord*(bits_per_pixel/8) + x_coord*(bits_per_pixel/8), &color, (bits_per_pixel/8));
}
return OK;
}
void(vg_draw_xpm)(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y) {
int width = img.width;
int height = img.height;
for(int dy = 0; dy < height; dy++) {
for(int dx = 0; dx < width ; dx++) {
if (pixmap[(dx + width*dy)] != xpm_transparency_color(XPM_8_8_8_8))
vg_paint_pixel(x+dx, y+dy, pixmap[(dx + width*dy)]);
}
}
}
void(vg_draw_part_of_xpm)(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y, int x_start, int x_end, int y_start, int y_end) {
int width = img.width;
for(int dy = y_start; dy < y_end; dy++){
for(int dx = x_start; dx < x_end ; dx++){
if (pixmap[(dx + width*dy)] != xpm_transparency_color(XPM_8_8_8_8))
vg_paint_pixel(x+(dx-x_start), y+(dy-y_start), pixmap[(dx + width*dy)]);
}
}
}
void (update_buffer)() {
memcpy(video_mem, double_buffer, hres * vres * ((bits_per_pixel + 7) / 8));
}
<file_sep>#ifndef _LCOM_RTC_H_
#define _LCOM_RTC_H_
#include <lcom/lcf.h>
/**
* @struct Date
* @var Date::year
* Actual year
* @var Date::month
* Acual month
* @var Date::day
* Actual day
* */
typedef struct{
uint32_t year;
uint32_t month;
uint32_t day;
} Date;
/**
* @struct Time
* @var Time:: hour
* Actual hour
* @var Time:: minute
* Actual minute
* @var Time:: second
* Actual second
* */
typedef struct{
uint32_t hour;
uint32_t minute;
uint32_t second;
} Time;
/**
Waits until it is possible to read the rtc without it being in the middle of an update
*/
void wait_valid_rtc();
/**
Converts a number in Binary-coded decimal format to binary
@param uint32_t* - the number to be conveted
*/
void bcd_to_dec(uint32_t* bcd);
/**
Check if the rtc is in the middle of an update
@return bool - true if the rtc is in the middle of an update false otherwise
*/
bool updating_rtc();
/**
Checks if the rtc is in Binary-coded decimal format
@return bool - true if the rtc is in Binary-coded decimal format, false otherwise
*/
bool bcd_format();
/**
Checks if the rtc is in military time format
@return bool - true if the rtc is in military format, false otherwise
*/
bool military_time();
/**
Reads the current date
@param Date* - Date to be changed into the current date
@return int - 1 if there was an error, 0 otherwise
*/
int read_date(Date* date);
/**
Reads the current time
@param Time* - Time to be changed into the current time
@return int - 1 if there was an error, 0 otherwise
*/
int read_time(Time* time);
/**
Reads the current date, when it is possible
@return Date - Current date
*/
Date get_date();
/**
Reads the current time, when it is possible
@return Time - Current time
*/
Time get_time();
/**
Enables interrupts of the RTC
@return int - 1 if there was an error, 0 otherwise
*/
int (enable_rtc_int)();
/**
Disables interrupts of the RTC
@return int - 1 if there was an error, 0 otherwise
*/
int (disable_rtc_int)();
/**
Enables the Update-ended interrupts of the RTC
@return int - 1 if there was an error, 0 otherwise
*/
int enable_rtc_UI();
/**
Disables the Update-ended interrupts of the RTC
@return int - 1 if there was an error, 0 otherwise
*/
int disable_rtc_UI();
/**
Subscribes and enables the interrupts of the RTC
and enables the Update-ended interrupts in the RTC
@param uint8_t* - will change to the position of the IRQ_SET bit
@return int - 1 if there was an error, 0 otherwise
*/
int (rtc_subscribe_int)(uint8_t *bit_no);
/**
Unsubscribes and disables the interrupts of the RTC
and disaables the Update-ended interrupts in the RTC
@return int - 1 if there was an error, 0 otherwise
*/
int (rtc_unsubscribe_int)();
/**
Handles the RTC interrupts by the reading the time
*/
void (rtc_int_handler)();
/**
Initializes variables that track the time and date
*/
void rtc_start();
#endif
<file_sep>var searchData=
[
['instructions_940',['INSTRUCTIONS',['../game_8h.html#a24c6cf001751e215986feed57efec3fca2a3b2d79801adcf99fc1d4565dc6f825',1,'game.h']]]
];
<file_sep>var searchData=
[
['z_5fbreak_634',['Z_BREAK',['../group__i8042.html#ga50ffeb6e62d9f40f723b19984e3ed81b',1,'i8042.h']]]
];
<file_sep>var searchData=
[
['i8042_1174',['i8042',['../group__i8042.html',1,'']]],
['i8254_1175',['i8254',['../group__i8254.html',1,'']]]
];
<file_sep>#pragma once
#include <lcom/lcf.h>
#include <Sprites/logo.xpm>
#include <Sprites/Buttons_img/normal/singleplayer_normal.xpm>
#include <Sprites/Buttons_img/active/singleplayer_active.xpm>
#include <Sprites/Buttons_img/normal/multiplayer_normal.xpm>
#include <Sprites/Buttons_img/active/multiplayer_active.xpm>
#include <Sprites/Buttons_img/normal/leaderboard_normal.xpm>
#include <Sprites/Buttons_img/active/leaderboard_active.xpm>
#include <Sprites/Buttons_img/normal/instructions_normal.xpm>
#include <Sprites/Buttons_img/active/instructions_active.xpm>
#include <Sprites/Buttons_img/normal/exit_normal.xpm>
#include <Sprites/Buttons_img/active/exit_active.xpm>
#include <Sprites/Buttons_img/normal/calendar_normal.xpm>
#include <Sprites/Buttons_img/active/calendar_active.xpm>
#include <Sprites/Buttons_img/normal/clock_normal.xpm>
#include <Sprites/Buttons_img/active/clock_active.xpm>
/////////////////////////////////////////////////////////////////////////////
#include <Sprites/Buttons_img/normal/main_menu_normal.xpm>
#include <Sprites/Buttons_img/active/main_menu_active.xpm>
#include <Sprites/cursor.xpm>
#include "xpm_coordinates.h"
#include "rtc.h"
#include <vd_card.h>
#include <mouse.h>
typedef enum {NORMAL=0, ACTIVE} Button_state;
typedef struct {
xpm_image_t sprites[2];
Button_state state;
uint16_t xi, xf, yi, yf;
} Button;
typedef struct{
xpm_image_t cursor_image;
xpm_image_t cursor_image_default;
uint16_t x;
uint16_t y;
} Cursor;
Button *load_button(uint16_t xi, uint16_t yi, xpm_row_t *normal, xpm_row_t *active);
void update_buttons(Cursor* cursor, Button** buttons, int num_buttons);
void draw_button(Button *button);
void draw_buttons(Button** buttons, int num_buttons);
int mouse_over(Button *button, Cursor *cursor);
Cursor *load_cursor(xpm_row_t *img_cursor);
void draw_cursor(Cursor *cursor);
void move_cursor(struct packet *packet, Cursor *cursor);
/////////////////////////////////////////////////////////////////////////////////
/**
* @struct Menu
* @var Menu:: sprites[2]
* Menu's sprites xpm
* @var Menu:: buttons
* Menu's buttons
* @var Menu::num_buttons
* Menu's number of buttons
* */
typedef struct {
xpm_image_t sprites[1];
Button** buttons;
int num_buttons;
} Menu;
void load_background();
/**
* @brief Function that creates a menu: loads the background xpm, the WhackaMole's logo and all menu's buttons
* @param xmp_row_t *img_cursor
* @return Cursor *cursor
* */
Menu *load_menu();
/**
* @brief Function that draws the game's logo
* @param Menu * menu
* */
void draw_logo(Menu *menu);
/**
* @brief Function that draws the game's date
* @param xpm_image_t font
* @param int xi
* @param int yi
* @param Date date
* */
void draw_date(xpm_image_t font, int xi, int yi, Date date);
/**
* @brief Function that draws the current's time
* @param xpm_image_t font
* @param int xi
* @param int yi
* @param Time time
* */
void draw_time(xpm_image_t font, int xi, int yi, Time time);
<file_sep>var searchData=
[
['x_5forigin_1171',['X_ORIGIN',['../xpm__coordinates_8h.html#a9a53d60d71a8c2920bb2542057634aae',1,'xpm_coordinates.h']]]
];
<file_sep>PROG=proj
SRCS = proj.c timer.c utils.c keyboard.c vd_card.c kbd_manager.c mole.c game.c mouse.c menu.c rtc.c player_settings.c leaderboard.c serial_port.c
CPPFLAGS += -pedantic #-D __LCOM_OPTIMIZED__
DPADD += ${LIBLCF}
LDADD += -llcf
.include <minix.lcom.mk>
<file_sep>var searchData=
[
['kbd_5fmanager_2ec_659',['kbd_manager.c',['../kbd__manager_8c.html',1,'']]],
['kbd_5fmanager_2eh_660',['kbd_manager.h',['../kbd__manager_8h.html',1,'']]],
['keyboard_2ec_661',['keyboard.c',['../keyboard_8c.html',1,'']]],
['keyboard_2eh_662',['keyboard.h',['../keyboard_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['animation_5ftimer_824',['animation_timer',['../struct_exit.html#aebc14eb705733f0dd2f9a96b00eb81f3',1,'Exit']]],
['avatar_825',['avatar',['../struct_player.html#a0f8c87a9b0ac652a9fd8ef5c11ce4cf3',1,'Player']]],
['avatars_826',['avatars',['../struct_player___settings.html#afee39b84b792600e34560fb1408cb2ff',1,'Player_Settings']]]
];
<file_sep>var searchData=
[
['kbd_5fkey_5f0_1048',['KBD_KEY_0',['../mole_8h.html#a7475e2e7728279e259e8d27d2b9d201d',1,'mole.h']]],
['kbd_5fkey_5f1_1049',['KBD_KEY_1',['../mole_8h.html#ad6b0e50ed9647aade1c52c6dbb19a187',1,'mole.h']]],
['kbd_5fkey_5f2_1050',['KBD_KEY_2',['../mole_8h.html#a8c86b26f70a1de9dcc21f21393167121',1,'mole.h']]],
['kbd_5fkey_5f3_1051',['KBD_KEY_3',['../mole_8h.html#ad2d23080b02d60e4f79100e5a2a29372',1,'mole.h']]],
['kbd_5fkey_5f4_1052',['KBD_KEY_4',['../mole_8h.html#a4426385d8dca25bf43caef9c6135c552',1,'mole.h']]],
['kbd_5fkey_5f5_1053',['KBD_KEY_5',['../mole_8h.html#afe664bde9f46e002ecb0baa9a052f017',1,'mole.h']]]
];
<file_sep>var searchData=
[
['avatar_635',['Avatar',['../struct_avatar.html',1,'']]]
];
<file_sep>var searchData=
[
['word_5flength_5f5_1166',['WORD_LENGTH_5',['../uart__const_8h.html#a9e7d8bcd7eb1e99715a3eb9b41b0e2c1',1,'uart_const.h']]],
['word_5flength_5f6_1167',['WORD_LENGTH_6',['../uart__const_8h.html#ab62e5769f836beaec79e4988225edaa5',1,'uart_const.h']]],
['word_5flength_5f7_1168',['WORD_LENGTH_7',['../uart__const_8h.html#a2d1d51fc34bf77ac01bb8c287a767a2b',1,'uart_const.h']]],
['word_5flength_5f8_1169',['WORD_LENGTH_8',['../uart__const_8h.html#a808120bf2c70c9fe3acc7376180b36c9',1,'uart_const.h']]],
['world_5flength_5fsel_1170',['WORLD_LENGTH_SEL',['../uart__const_8h.html#a1f22639596c0f5a3f9a31948a7602054',1,'uart_const.h']]]
];
<file_sep>var searchData=
[
['position_927',['Position',['../mole_8h.html#ab91b34ae619fcdfcba4522b4f335bf83',1,'mole.h']]]
];
<file_sep>var searchData=
[
['i8042_2eh_657',['i8042.h',['../i8042_8h.html',1,'']]],
['i8254_2eh_658',['i8254.h',['../i8254_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['player_2ec_670',['Player.c',['../_player_8c.html',1,'']]],
['player_2eh_671',['Player.h',['../_player_8h.html',1,'']]],
['proj_2ec_672',['proj.c',['../proj_8c.html',1,'']]]
];
<file_sep>var searchData=
[
['arrow_5fleft_5fx_962',['ARROW_LEFT_X',['../xpm__coordinates_8h.html#a25fb6e1acf0727372676a6ae18c7bd1b',1,'xpm_coordinates.h']]],
['arrow_5fleft_5fy_963',['ARROW_LEFT_Y',['../xpm__coordinates_8h.html#a7b040c5474088c264005e0d9dcdc3931',1,'xpm_coordinates.h']]],
['arrow_5fright_5fx_964',['ARROW_RIGHT_X',['../xpm__coordinates_8h.html#a0ca0d2754923a7f76c8ae3bcbf16da1c',1,'xpm_coordinates.h']]],
['arrow_5fright_5fy_965',['ARROW_RIGHT_Y',['../xpm__coordinates_8h.html#a022bab2d589c864de9ec5451571b13db',1,'xpm_coordinates.h']]]
];
<file_sep>var searchData=
[
['uart_5fconst_2eh_683',['uart_const.h',['../uart__const_8h.html',1,'']]],
['utils_2ec_684',['utils.c',['../utils_8c.html',1,'']]]
];
<file_sep>var searchData=
[
['thr_1159',['THR',['../uart__const_8h.html#a5e9787adf3c9afcc4b781e85bb545b35',1,'uart_const.h']]],
['time_5fup_5flimit_5fdecrement_1160',['TIME_UP_LIMIT_DECREMENT',['../mole_8h.html#a0852f8ec105499fa2c512916ad7bc831',1,'mole.h']]],
['trans_5fempty_5freg_1161',['TRANS_EMPTY_REG',['../uart__const_8h.html#ad8802d21b2273072d7800cf60cff80fc',1,'uart_const.h']]],
['trans_5fhold_5freg_5fempty_1162',['TRANS_HOLD_REG_EMPTY',['../uart__const_8h.html#ae3d4728797f9c978588c17ad5fa192bd',1,'uart_const.h']]]
];
<file_sep>var searchData=
[
['output_5ffull_773',['output_full',['../keyboard_8c.html#a51c888063d1f117f3af4a65ae37e075b',1,'output_full(): keyboard.c'],['../keyboard_8h.html#a51c888063d1f117f3af4a65ae37e075b',1,'output_full(): keyboard.c']]]
];
<file_sep>var searchData=
[
['game_5fduration_1021',['GAME_DURATION',['../mole_8h.html#ac64422ec6aecd8e2b1ed9e5edefb0976',1,'mole.h']]],
['game_5ffps_1022',['GAME_FPS',['../mole_8h.html#a63a780eb9590cbea188494a74c8eb79e',1,'mole.h']]],
['game_5ftimer_5fx_1023',['GAME_TIMER_X',['../xpm__coordinates_8h.html#a009de5bfa5a675a949805fb3654d13ed',1,'xpm_coordinates.h']]],
['game_5ftimer_5fy_1024',['GAME_TIMER_Y',['../xpm__coordinates_8h.html#a15d6e32acbd27ee05f9a9c6bc258781e',1,'xpm_coordinates.h']]],
['gd_5fbye_5flogo_5fx_1025',['GD_BYE_LOGO_X',['../xpm__coordinates_8h.html#ae3cc709ad8fef45516387ee626d49d65',1,'xpm_coordinates.h']]],
['gd_5fbye_5flogo_5fy_1026',['GD_BYE_LOGO_Y',['../xpm__coordinates_8h.html#a58c43be325fac2e3a6521ad4832fc441',1,'xpm_coordinates.h']]],
['gm_5fov_5flogo_5fx_1027',['GM_OV_LOGO_X',['../xpm__coordinates_8h.html#a9611a85575ebddf76085f0edb4be86cb',1,'xpm_coordinates.h']]],
['gm_5fov_5flogo_5fy_1028',['GM_OV_LOGO_Y',['../xpm__coordinates_8h.html#ab19db2858f4ecbd7a1399523d3baae30',1,'xpm_coordinates.h']]]
];
<file_sep>var searchData=
[
['offset_5ffor_5fpm_5ftime_1119',['OFFSET_FOR_PM_TIME',['../rtc__macros_8h.html#a38b754da51185de5ccb15604b55678f2',1,'rtc_macros.h']]],
['overrun_5ferror_1120',['OVERRUN_ERROR',['../uart__const_8h.html#a71c26bc752960acd5308f21b05a13714',1,'uart_const.h']]]
];
<file_sep>var searchData=
[
['bcd_5fformat_689',['bcd_format',['../rtc_8c.html#abebbbc3f690198409b3002caa2fb9fb7',1,'bcd_format(): rtc.c'],['../rtc_8h.html#abebbbc3f690198409b3002caa2fb9fb7',1,'bcd_format(): rtc.c']]],
['bcd_5fto_5fdec_690',['bcd_to_dec',['../rtc_8c.html#a2a4ff1e5e524072f27f629aa09b72f04',1,'bcd_to_dec(uint32_t *bcd): rtc.c'],['../rtc_8h.html#a2a4ff1e5e524072f27f629aa09b72f04',1,'bcd_to_dec(uint32_t *bcd): rtc.c']]]
];
<file_sep>#pragma once
#include <lcom/lcf.h>
#include <Sprites/player_title.xpm>
#include <Sprites/name_length_warning.xpm>
#include <Sprites/font.xpm>
#include <Sprites/player_avatars/hammer_0_big.xpm>
#include <Sprites/player_avatars/hammer_1_big.xpm>
#include <Sprites/player_avatars/hammer_2_big.xpm>
#include <Sprites/player_avatars/hammer_3_big.xpm>
#include <Sprites/player_avatars/hammer_0_big_bright.xpm>
#include <Sprites/player_avatars/hammer_1_big_bright.xpm>
#include <Sprites/player_avatars/hammer_2_big_bright.xpm>
#include <Sprites/player_avatars/hammer_3_big_bright.xpm>
#include <Sprites/player_avatars/hammer_0_small.xpm>
#include <Sprites/player_avatars/hammer_1_small.xpm>
#include <Sprites/player_avatars/hammer_2_small.xpm>
#include <Sprites/player_avatars/hammer_3_small.xpm>
#include <Sprites/Buttons_img/normal/name_box_normal.xpm>
#include <Sprites/Buttons_img/active/name_box_active.xpm>
#include <Sprites/Buttons_img/normal/arrow_left_normal.xpm>
#include <Sprites/Buttons_img/active/arrow_left_active.xpm>
#include <Sprites/Buttons_img/normal/arrow_right_normal.xpm>
#include <Sprites/Buttons_img/active/arrow_right_active.xpm>
#include <Sprites/Buttons_img/normal/start_normal.xpm>
#include <Sprites/Buttons_img/active/start_active.xpm>
#include "menu.h"
typedef enum {NOT_SELECTED, SELECTED} button_state;
/**
* @struct Player
* @var Player:: avatar
* Player's avatar
* @var Player:: missed_moles
* How many moles the Player has missed
* @var Player:: hitted_moles
* How many moles the Player has hitted
* @var Player:: name
* Player's name
* @var Player:: max_name_length
* Player's name max size
* */
typedef struct {
xpm_image_t avatar;
int missed_moles;
int hitted_moles;
char* name;
int max_name_length;
} Player;
/**
* @struct Avatar
* @var: sprites[3]
* @var: state
* @var:x
* @var:y
* */
typedef struct {
xpm_image_t sprites[3];
button_state state;
uint8_t x,y;
} Avatar;
/**
* @struct Player_Settings
* @var Player_Settins:: background
* Player Setting's backgound xpm
* @var Player_Settins:: background_title
* Player Setting's backgound title xpm
* @var Player_Settins:: name_length_warning
* Player Setting's name has reached maximum length warning xpm
* @var Player_Settins:: font
* Player Setting's font xpm
* @var Player_Settins:: name_maximum_length
* Boolean: false if not reached maximum lenght; else true
* @var Player_Settins:: avatars[4]
* Player Setting's avatars
* @var Player_Settins:: buttons
* Player Setting's buttons
* @var Player_Settins:: num_buttons
* Player Setting's number of buttonfs
* */
typedef struct {
xpm_image_t background;
xpm_image_t background_title;
xpm_image_t name_length_warning;
xpm_image_t font;
bool name_maximum_length;
//Player* player;
Avatar* avatars[4];
Button** buttons;
int num_buttons;
} Player_Settings;
/**
* @brief: loads Player's xpm, sets hitted and missed moles both as null, set's PLayers initial default name and it's name's maximum lenght
* @param:default_avatar
* @return: player
* */
Player* load_player(Avatar* default_avatar);
/**
* @brief: loads Avatars's xpm, sets avatars initial state
* @param:default_avatar
* @return: player
* */
Avatar* load_avatar(xpm_row_t *normal, xpm_row_t *selected, xpm_row_t *small);
/**
* @brief loads Player Settings : loads it's xpm and sets it's variavles
* @return: player_settings
* */
Player_Settings *load_player_settings();
/**
* @brief: draws Player Settings mode background
* @param player_sets
* */
void draw_background__(Player_Settings *player_sets);
/**
* @brief: draws Player Settings name lennght waring
* @param player_sets
* */
void draw_name_lenght_warning(Player_Settings* player_sets);
/**
* @brief: draws Player Settings avatar's according to their state
* @param player_sets
* */
void draw_avatars(Avatar* avatars[]);
/**
* @brief: moves one avatar to left, defining it as SELECTED and the other ones as NOT_SELECTED
* @param player_sets
* */
void move_left_avatar(Player_Settings* player_sets);
/**
* @brief: moves one avatar to right, defining it as SELECTED and the other ones as NOT_SELECTED
* @param player_sets
* */
void move_right_avatar(Player_Settings* player_sets);
/**
* @brief: get the hammer sellected by the player
* @param player_sets
* @return choosen hammer xpm
* */
xpm_image_t get_hammer(Player_Settings* player_sets);
/**
* @brief: draws Player Nmae
* @param font xpm of letter to bue used to right the name
* @param xi
* @param yi
* @param name
* @param name_size
* */
void draw_player_name(xpm_image_t font, int xi, int yi, char name[], int name_size);
/**
* @brief:
* @param player_settings
* @param player
* @param delete_letter Bool that is true if the Player wants to delete a lette of his name
* @param new_letter letter to be added to Player's name
* */
void update_player_name(Player_Settings* player_settings, Player *player, bool delete_letter, char new_letter);
<file_sep>var searchData=
[
['leaderboard_642',['Leaderboard',['../struct_leaderboard.html',1,'']]]
];
<file_sep>#include <lcom/lcf.h>
#define X_ORIGIN 0
#define Y_ORIGIN 0
///////////////////* MAIN MENU *//////////////////////
// LOGO
#define MENU_LOGO_X 168
#define MENU_LOGO_Y 118
//* BUTTONS *//
// CALENDAR
#define CALLENDAR_X 0
#define CALLENDAR_Y 0
#define CALLENDAR_NUM_X 55
#define CALLENDAR_NUM_Y 15
// CLOCK
#define CLOCK_X 556
#define CLOCK_Y 0
#define CLOCK_NUM_X 616
#define CLOCK_NUM_Y 23
// SINGLEPLAYER
#define SINGLE_PLR_X 192
#define SINGLE_PLR_Y 441
// MULTIPLAYER
#define MULTI_PLR_X 192
#define MULTI_PLR_Y 494
// LEADERBOARD
#define LEADERB_MENU_X 192
#define LEADERB_MENU_Y 547
// INSTRUCTIONS
#define INSTRC_X 430
#define INSTRC_Y 441
//WIN/LOSE
#define WIN_LOSE_X 150
#define WIN_LOSE_Y 150
// EXIT
#define EXIT_MENU_X 430
#define EXIT_MENU_Y 494
//////////////////* LEADERBOARD *//////////////////
// TABLE
#define LDBRD_TABLE_X 180
#define LDBRD_TABLE_Y 50
// CROWN
#define LDBRD_CROWN_X 380
#define LDBRD_CROWN_Y 15
// PLAYER NAMES
#define LDBRD_NAME_STEP_FROM_X 342
#define LDBRD_NAME_STEP_FROM_Y 151
#define LDBRD_NAME_STEP_FROM_LINE 88
// PLAYER SCORES
#define LDBRD_SCORE_STEP_FROM_X 550
#define LDBRD_SCORE_STEP_FROM_Y 151
#define LDBRD_SCORE_STEP_FROM_LINE 88
// PLAYER DATES
#define LDBRD_DATE_STEP_FROM_X 337
#define LDBRD_DATE_STEP_FROM_Y 178
#define LDBRD_DATE_STEP_FROM_LINE 90
//* BUTTONS *//
// CLOSE
#define CLOSE_X 580
#define CLOSE_Y 52
//////////////////* PLAYER SETTINGS *//////////////////
//* BUTTONS *//
// ARROW LEFT
#define ARROW_LEFT_X 275
#define ARROW_LEFT_Y 300
// ARROW RIGHT
#define ARROW_RIGHT_X 450
#define ARROW_RIGHT_Y 300
// NAME BOX
#define NAME_BOX_X 0
#define NAME_BOX_Y 375
// START
#define START_X 677
#define START_Y 415
//* AVATARS *//
// FIRST
#define FIRST_AVT_X 80
#define FIRST_AVT_Y 150
// STEP
#define STEP_AVT_X 150
#define STEP_AVT_Y 0
//* OTHERS *//
//NAME LENGTH WARNING
#define NM_LENGTH_WR_X 300
#define NM_LENGTH_WR_Y 550
//NAME PLACE
#define NM_PLACE_X 0
#define NM_PLACE_Y 420
//////////////////* GAME OVER *//////////////////
//* BUTTONS *//
// MAIN MENU
#define MAIN_MENU_X 300
#define MAIN_MENU_Y 450
// LEADERBOARD
#define LEADERB_GM_OV_X 300
#define LEADERB_GM_OV_Y 500
// EXIT
#define EXIT_GM_OV_X 300
#define EXIT_GM_OV_Y 550
// LOGO
#define GM_OV_LOGO_X 90
#define GM_OV_LOGO_Y 150
//HIT MOLES TITLE
#define HIT_MOLES_TITLE_X 110
#define HIT_MOLES_TITLE_Y 290
//MISS MOLES TITLE
#define MISS_MOLES_TITLE_X 110
#define MISS_MOLES_TITLE_Y 350
//HIT MOLES COUNTER
#define HIT_MOLES_CT_X 500
#define HIT_MOLES_CT_Y 311
//MISS MOLES TITLE
#define MISS_MOLES_CT_X 500
#define MISS_MOLES_CT_Y 370
// BALLON
#define BALLON_X 400
#define BALLON_Y 600
//////////////////* SINGLE PLAYER *//////////////////
//* MOLES *//
#define FIRST_MOLE_X 150
#define FIRST_MOLE_Y 140
#define MOLE_STEP_COL 15
#define MOLE_STEP_LINE 10
#define MOLE_WIDTH 175
#define MOLE_HEIGHT 150
//* GAME TIMER *//
#define CLOCK_ICON_X 325
#define CLOCK_ICON_Y 0
#define GAME_TIMER_X 375
#define GAME_TIMER_Y 0
//* SCORE INFO *//
#define SCORE_TABLE_X 0
#define SCORE_TABLE_Y 470
#define MOLES_HIT_FRAME_X 25
#define MOLES_HIT_FRAME_Y 530
#define MOLES_HIT_NUM_X 165
#define MOLES_HIT_NUM_Y 537
#define MOLES_MISS_FRAME_X 25
#define MOLES_MISS_FRAME_Y 555
#define MOLES_MISS_NUM_X 165
#define MOLES_MISS_NUM_Y 557
//////////////////* EXIT *//////////////////
#define GD_BYE_LOGO_X 0
#define GD_BYE_LOGO_Y 230
#define CREDITS_X 550
#define CREDITS_Y 80
#define MOLE_ANIMATION_Y 450
<file_sep>var searchData=
[
['timer_5fdisplay_5fconf_800',['timer_display_conf',['../timer_8c.html#a140d8f092c0913cabdca949c4a1cc650',1,'timer.c']]],
['timer_5fget_5fconf_801',['timer_get_conf',['../timer_8c.html#a703c60b40c8c49607d6ecb6fef82d27a',1,'timer.c']]],
['timer_5fint_5fhandler_802',['timer_int_handler',['../timer_8c.html#a91a2072306c68353712a6b771287dc2c',1,'timer.c']]],
['timer_5fset_5ffrequency_803',['timer_set_frequency',['../timer_8c.html#af2c04fa8e97ffa748fd3f612886a92a7',1,'timer.c']]],
['timer_5fsubscribe_5fint_804',['timer_subscribe_int',['../timer_8c.html#ac57a7e1140a7e00ad95ac5488d2a671b',1,'timer.c']]],
['timer_5funsubscribe_5fint_805',['timer_unsubscribe_int',['../timer_8c.html#afabd21de449be154dd65d5fdb2d8045d',1,'timer.c']]]
];
<file_sep>var searchData=
[
['exit_639',['Exit',['../struct_exit.html',1,'']]]
];
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "mole.h"
#include "xpm_coordinates.h"
static char kbd_keys [6] = {KBD_KEY_0, KBD_KEY_1, KBD_KEY_2, KBD_KEY_3, KBD_KEY_4, KBD_KEY_5};
Mole *createMole(int index)
{
//Allocating memory
Mole *mole = (Mole *)malloc(sizeof(Mole));
//Setting up mole variables
mole->position = HIDED;
mole->time_up = 0;
mole->kbd_key = kbd_keys[index];
if(index<3) {
mole->x = FIRST_MOLE_X + index * (MOLE_WIDTH + MOLE_STEP_COL);
mole->y = FIRST_MOLE_Y;
}
else {
index -= 3;
mole->x = FIRST_MOLE_X + index * (MOLE_WIDTH + MOLE_STEP_COL);
mole->y = FIRST_MOLE_Y + MOLE_HEIGHT + MOLE_STEP_LINE;
}
//Loading xpm images for a mole. NOTE: this assumes the sprites are being loaded in the same order as the enum
//hole
xpm_load(hole_xpm, XPM_8_8_8_8, &(mole->sprites[0]));
//mole up
xpm_load(mole_up1_xpm, XPM_8_8_8_8, &(mole->sprites[1]));
xpm_load(mole_up2_xpm, XPM_8_8_8_8, &(mole->sprites[2]));
xpm_load(mole_up3_xpm, XPM_8_8_8_8, &(mole->sprites[3]));
xpm_load(mole_up4_xpm, XPM_8_8_8_8, &(mole->sprites[4]));
//mole down miss
xpm_load(mole_down_miss4_xpm, XPM_8_8_8_8, &(mole->sprites[5]));
xpm_load(mole_down_miss3_xpm, XPM_8_8_8_8, &(mole->sprites[6]));
xpm_load(mole_down_miss2_xpm, XPM_8_8_8_8, &(mole->sprites[7]));
xpm_load(mole_down_miss1_xpm, XPM_8_8_8_8, &(mole->sprites[8]));
//mole down hit
xpm_load(mole_down_hit4_xpm, XPM_8_8_8_8, &(mole->sprites[9]));
xpm_load(mole_down_hit3_xpm, XPM_8_8_8_8, &(mole->sprites[10]));
xpm_load(mole_down_hit2_xpm, XPM_8_8_8_8, &(mole->sprites[11]));
xpm_load(mole_down_hit1_xpm, XPM_8_8_8_8, &(mole->sprites[12]));
return mole;
}
void draw_mole(Mole *mole)
{
xpm_image_t current_img = mole->sprites[(int) mole->position];
vg_draw_xpm((uint32_t *) current_img.bytes, current_img, mole->x, mole->y);
}
void draw_all_moles(Mole* moles, int num_moles)
{
for (int i = 0; i < num_moles; i++)
{
draw_mole(&moles[i]);
}
}
bool check_over_mole(Mole *mole, int cursor_x, int cursor_y)
{
int xi, xf, yi, yf;
xi = mole->x + 42;
yi = mole->y;
xf = xi + 90;
yf = yi + 60;
if (xi <= cursor_x && cursor_x <= xf && yi <= cursor_y && cursor_y <= yf)
{
return true;
}
return false;
}
void reset_moles(Mole* moles, int num_moles) {
for (int i = 0; i < num_moles; i++) {
moles[i].position = HIDED;
moles[i].time_up = 0;
}
}
<file_sep>#include <lcom/lcf.h>
#include <stdint.h>
#include "i8042.h"
#include "keyboard.h"
char kbd_manager(uint8_t scanCode) {
char letter;
switch (scanCode) {
case A_BREAK:
letter = 'A';
break;
case B_BREAK:
letter = 'B';
break;
case C_BREAK:
letter = 'C';
break;
case D_BREAK:
letter = 'D';
break;
case E_BREAK:
letter = 'E';
break;
case F_BREAK:
letter = 'F';
break;
case G_BREAK:
letter = 'G';
break;
case H_BREAK:
letter = 'H';
break;
case I_BREAK:
letter = 'I';
break;
case J_BREAK:
letter = 'J';
break;
case K_BREAK:
letter = 'K';
break;
case L_BREAK:
letter = 'L';
break;
case M_BREAK:
letter = 'M';
break;
case N_BREAK:
letter = 'N';
break;
case O_BREAK:
letter = 'O';
break;
case P_BREAK:
letter = 'P';
break;
case Q_BREAK:
letter = 'Q';
break;
case R_BREAK:
letter = 'R';
break;
case S_BREAK:
letter = 'S';
break;
case T_BREAK:
letter = 'T';
break;
case U_BREAK:
letter = 'U';
break;
case V_BREAK:
letter = 'V';
break;
case W_BREAK:
letter = 'W';
break;
case X_BREAK:
letter = 'X';
break;
case Y_BREAK:
letter = 'Y';
break;
case Z_BREAK:
letter = 'Z';
break;
default:
letter = '.';
break;
}
return letter;
}
<file_sep>#ifndef _LCOM_RTC_MACROS_H_
#define _LCOM_RTC_MACROS_H_
#include <lcom/lcf.h>
#define FAIL 1
#define RTC_IRQ 8
#define UIE BIT(4)
#define RTC_UF BIT(4)
#define RTC_ADDR_REG 0x70
#define RTC_DATA_REG 0x71
#define RTC_REGISTER_A 10
#define RTC_REGISTER_B 11
#define RTC_REGISTER_C 12
#define UIP BIT(7)
#define DM BIT(2)
#define MILITARY_TIME BIT(1)
#define SEC_REG 0
#define MIN_REG 2
#define HOUR_REG 4
#define DAY_REG 7
#define MONTH_REG 8
#define YEAR_REG 9
#define LIMIT_HOUR 0x12
#define OFFSET_FOR_PM_TIME 0x80
#endif
<file_sep>var searchData=
[
['hitted_5fmoles_849',['hitted_moles',['../struct_game_over.html#aa93b7609a9cdfc002798634cf22e11ba',1,'GameOver::hitted_moles()'],['../struct_player.html#a72ac136ed3f036a4f0a3c41aa5b57542',1,'Player::hitted_moles()']]],
['host_850',['host',['../struct_whac_a_mole.html#a4f63d54450207faa0b56186bef691a33',1,'WhacAMole']]],
['hour_851',['hour',['../struct_time.html#a26d5bae76d83086900174b266fd2cd82',1,'Time']]]
];
<file_sep>#include <lcom/lcf.h>
char kbd_manager(uint8_t scanCode);
<file_sep>var searchData=
[
['day_5freg_991',['DAY_REG',['../rtc__macros_8h.html#aeffd8cec7eae259d17fdb3604269bcc5',1,'rtc_macros.h']]],
['delay_5fus_992',['DELAY_US',['../uart__const_8h.html#a1a522aa19bcb695a9df30032a893bee3',1,'uart_const.h']]],
['dl_5fconst_993',['DL_CONST',['../uart__const_8h.html#a0aab64b58cbd9cb750e5f14ea36900e8',1,'uart_const.h']]],
['dlab_994',['DLAB',['../uart__const_8h.html#aeacff95e17799eeacbff843e63ead9d3',1,'uart_const.h']]],
['dll_995',['DLL',['../uart__const_8h.html#a4466639cd64ebf372a621168c5e25964',1,'uart_const.h']]],
['dlm_996',['DLM',['../uart__const_8h.html#a3b48b12dc65f62dd40ab1163fe7997fb',1,'uart_const.h']]],
['dm_997',['DM',['../rtc__macros_8h.html#a9a9aac904e687286501946469e2903d6',1,'rtc_macros.h']]],
['dma_5fmode_5fsel_998',['DMA_MODE_SEL',['../uart__const_8h.html#ab6e898d696951cd94ee59b4f8e9f4a34',1,'uart_const.h']]]
];
<file_sep>var searchData=
[
['x_618',['x',['../struct_cursor.html#a4dde988b1b2adba65ae3efa69f65d960',1,'Cursor::x()'],['../struct_mole.html#a6150e0515f7202e2fb518f7206ed97dc',1,'Mole::x()'],['../struct_avatar.html#a0f561e77fa0f040b637f4e04f6cd8078',1,'Avatar::x()']]],
['x_5fbreak_619',['X_BREAK',['../group__i8042.html#ga9c273d3928004114553508394fefdf90',1,'i8042.h']]],
['x_5fmole_620',['x_mole',['../struct_exit.html#a90e39179f310585053eec3a7714f6e3e',1,'Exit']]],
['x_5forigin_621',['X_ORIGIN',['../xpm__coordinates_8h.html#a9a53d60d71a8c2920bb2542057634aae',1,'xpm_coordinates.h']]],
['x_5fovfl_622',['X_OVFL',['../group__i8042.html#gaf329f104f7167317fe4d99fc6819501d',1,'i8042.h']]],
['xf_623',['xf',['../struct_button.html#ac7c26740690d71fe2b578d46661f26d7',1,'Button']]],
['xi_624',['xi',['../struct_button.html#a171d2442d41515d1398cca1302088332',1,'Button']]],
['xpm_5fcoordinates_2eh_625',['xpm_coordinates.h',['../xpm__coordinates_8h.html',1,'']]]
];
<file_sep>#pragma once
#include <lcom/lcf.h>
int cnt_sys_inb(port_t port, uint8_t *byte);
int kbd_subscribe_int(uint8_t *bit_no);
int kbd_unsubscribe_int();
void read_status_register(uint8_t *stat);
int check_status_register();
int output_full();
int input_empty();
int read_out_buffer(uint8_t *info);
void (kbc_ih)(void);
int issue_cmd_to_kbc(uint8_t command, uint8_t argument);
int kbc_write_cmd(uint8_t command);
int kbc_write_argument(uint8_t argument);
<file_sep>var searchData=
[
['keyboard_941',['KEYBOARD',['../game_8h.html#adbdec58595587fea1750c91cd18315fbad14e2514427609da194a72091721f4c7',1,'game.h']]]
];
<file_sep>var searchData=
[
['button_2ec_651',['button.c',['../button_8c.html',1,'']]],
['button_2eh_652',['button.h',['../button_8h.html',1,'']]]
];
<file_sep>#include "state_machine.h"
uint8_t delta_x, delta_y;
bool left_press = false, right_press = false, mid_press = false;
struct mouse_ev mouse_get_event(struct packet *packet) {
struct mouse_ev mouse_event;
mouse_event.delta_x = packet->delta_x;
mouse_event.delta_y = packet->delta_y;
if (left_press && !packet->lb && !right_press && !packet->rb && !mid_press && !packet->mb) {
left_press = false;
mouse_event.type = LB_RELEASED;
}
else if (!left_press && packet->lb && !right_press && !packet->rb && !mid_press && !packet->mb) {
left_press = true;
mouse_event.type = LB_PRESSED;
}
else if (!left_press && !packet->lb && right_press && !packet->rb && !mid_press && !packet->mb) {
right_press = false;
mouse_event.type = RB_RELEASED;
}
else if (!left_press && !packet->lb && !right_press && packet->rb && !mid_press && !packet->mb) {
right_press = true;
mouse_event.type = RB_PRESSED;
}
else if (!mid_press && packet->mb) {
mid_press = true;
mouse_event.type = BUTTON_EV;
}
else if (mid_press && !packet->mb) {
mid_press = false;
mouse_event.type = BUTTON_EV;
}
else {
mouse_event.type = MOUSE_MOV;
}
return mouse_event;
}
<file_sep>var searchData=
[
['main_5fmenu_943',['MAIN_MENU',['../game_8h.html#a24c6cf001751e215986feed57efec3fcac22743f1fc74de09544ecc9bab74a17b',1,'game.h']]],
['mouse_944',['MOUSE',['../game_8h.html#adbdec58595587fea1750c91cd18315fba6abd13b0a6bf7894c7ceb5ff45ddbc14',1,'game.h']]],
['multi_5fplayer_945',['MULTI_PLAYER',['../game_8h.html#a24c6cf001751e215986feed57efec3fcaf64ffcc804f85cc65366369011db5768',1,'game.h']]]
];
<file_sep>var searchData=
[
['index_852',['index',['../struct_mole.html#aae5a12e607d0f782506d9e6ec6179c64',1,'Mole']]],
['initial_5fdll_853',['initial_dll',['../serial__port_8c.html#a830c6ffb6ca546e0fba2a2c02e117da8',1,'serial_port.c']]],
['initial_5fdlm_854',['initial_dlm',['../serial__port_8c.html#adfd2ed2407ea95303beaea7c2b007a2c',1,'serial_port.c']]],
['initial_5fier_855',['initial_ier',['../serial__port_8c.html#acb795d3f3600130d4938ac9bcfe38e17',1,'serial_port.c']]],
['initial_5flcr_856',['initial_lcr',['../serial__port_8c.html#a9eb6349ad93373ae945abc00148a1359',1,'serial_port.c']]],
['instructions_857',['instructions',['../struct_instructions.html#a1c0240459b1214d30e12fe1837c71c2d',1,'Instructions::instructions()'],['../struct_whac_a_mole.html#ae691758a3d9d769acae1e288bbc0ec32',1,'WhacAMole::instructions()']]],
['irq_5frtc_858',['irq_rtc',['../struct_whac_a_mole.html#ad159c145f30d34f20a0d48687d437b07',1,'WhacAMole']]]
];
<file_sep>var searchData=
[
['rtc_949',['RTC',['../game_8h.html#adbdec58595587fea1750c91cd18315fba24073a11916b946561b8cb5c9dfe9bce',1,'game.h']]]
];
<file_sep>var searchData=
[
['cursor_637',['Cursor',['../struct_cursor.html',1,'']]]
];
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.20"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: C:/Users/PCPEDRO/OneDrive/Ambiente de Trabalho/g08-master-proj-src/g08-master-proj-src/proj/src/Player.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">My Project
 <span id="projectnumber">1</span>
</div>
<div id="projectbrief">111</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.20 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_ded2a7f905c2d34630c595c5cf4eb434.html">OneDrive</a></li><li class="navelem"><a class="el" href="dir_38f9253fc60506f65c1a72a4ff32eb17.html">Ambiente de Trabalho</a></li><li class="navelem"><a class="el" href="dir_14eff947584062e6353db3aa9936d3b4.html">g08-master-proj-src</a></li><li class="navelem"><a class="el" href="dir_ed3b7aa745db512461d20c4f88da6755.html">g08-master-proj-src</a></li><li class="navelem"><a class="el" href="dir_bf235b448f85712a667a3097b6dd28c6.html">proj</a></li><li class="navelem"><a class="el" href="dir_a625976adc794d7835406aa0171feb4c.html">src</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Player.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="_player_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="preprocessor">#pragma once</span></div>
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="preprocessor">#include <lcom/lcf.h></span></div>
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span>  </div>
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> <span class="preprocessor">#include <Sprites/player_title.xpm></span></div>
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> <span class="preprocessor">#include <Sprites/name_length_warning.xpm></span></div>
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> <span class="preprocessor">#include <Sprites/font.xpm></span></div>
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_0_big.xpm></span></div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_1_big.xpm></span></div>
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_2_big.xpm></span></div>
<div class="line"><a name="l00010"></a><span class="lineno"> 10</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_3_big.xpm></span></div>
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_0_big_bright.xpm></span></div>
<div class="line"><a name="l00012"></a><span class="lineno"> 12</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_1_big_bright.xpm></span></div>
<div class="line"><a name="l00013"></a><span class="lineno"> 13</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_2_big_bright.xpm></span></div>
<div class="line"><a name="l00014"></a><span class="lineno"> 14</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_3_big_bright.xpm></span></div>
<div class="line"><a name="l00015"></a><span class="lineno"> 15</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_0_small.xpm></span></div>
<div class="line"><a name="l00016"></a><span class="lineno"> 16</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_1_small.xpm></span></div>
<div class="line"><a name="l00017"></a><span class="lineno"> 17</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_2_small.xpm></span></div>
<div class="line"><a name="l00018"></a><span class="lineno"> 18</span> <span class="preprocessor">#include <Sprites/player_avatars/hammer_3_small.xpm></span></div>
<div class="line"><a name="l00019"></a><span class="lineno"> 19</span> <span class="preprocessor">#include <Sprites/Buttons_img/normal/name_box_normal.xpm></span></div>
<div class="line"><a name="l00020"></a><span class="lineno"> 20</span> <span class="preprocessor">#include <Sprites/Buttons_img/active/name_box_active.xpm></span></div>
<div class="line"><a name="l00021"></a><span class="lineno"> 21</span> <span class="preprocessor">#include <Sprites/Buttons_img/normal/arrow_left_normal.xpm></span></div>
<div class="line"><a name="l00022"></a><span class="lineno"> 22</span> <span class="preprocessor">#include <Sprites/Buttons_img/active/arrow_left_active.xpm></span></div>
<div class="line"><a name="l00023"></a><span class="lineno"> 23</span> <span class="preprocessor">#include <Sprites/Buttons_img/normal/arrow_right_normal.xpm></span></div>
<div class="line"><a name="l00024"></a><span class="lineno"> 24</span> <span class="preprocessor">#include <Sprites/Buttons_img/active/arrow_right_active.xpm></span></div>
<div class="line"><a name="l00025"></a><span class="lineno"> 25</span> <span class="preprocessor">#include <Sprites/Buttons_img/normal/start_normal.xpm></span></div>
<div class="line"><a name="l00026"></a><span class="lineno"> 26</span> <span class="preprocessor">#include <Sprites/Buttons_img/active/start_active.xpm></span></div>
<div class="line"><a name="l00027"></a><span class="lineno"> 27</span>  </div>
<div class="line"><a name="l00028"></a><span class="lineno"> 28</span> <span class="preprocessor">#include "<a class="code" href="menu_8h.html">menu.h</a>"</span></div>
<div class="line"><a name="l00029"></a><span class="lineno"> 29</span>  </div>
<div class="line"><a name="l00030"></a><span class="lineno"><a class="line" href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29ba02b0fb84d46d585b477a6509abf32b5d"> 30</a></span> <span class="keyword">typedef</span> <span class="keyword">enum</span> {<a class="code" href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29ba616ede6b6f3a1d38a724d1168ddf1adf">NOT_SELECTED</a>, <a class="code" href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29ba02b0fb84d46d585b477a6509abf32b5d">SELECTED</a>} <a class="code" href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29b">button_state</a>;</div>
<div class="line"><a name="l00031"></a><span class="lineno"> 31</span>  </div>
<div class="line"><a name="l00045"></a><span class="lineno"><a class="line" href="struct_player.html"> 45</a></span> <span class="keyword">typedef</span> <span class="keyword">struct </span>{</div>
<div class="line"><a name="l00046"></a><span class="lineno"><a class="line" href="struct_player.html#a0f8c87a9b0ac652a9fd8ef5c11ce4cf3"> 46</a></span>  xpm_image_t <a class="code" href="struct_player.html#a0f8c87a9b0ac652a9fd8ef5c11ce4cf3">avatar</a>;</div>
<div class="line"><a name="l00047"></a><span class="lineno"><a class="line" href="struct_player.html#a28f28a491a23b6d052d96bfebaed65e7"> 47</a></span>  <span class="keywordtype">int</span> <a class="code" href="struct_player.html#a28f28a491a23b6d052d96bfebaed65e7">missed_moles</a>;</div>
<div class="line"><a name="l00048"></a><span class="lineno"><a class="line" href="struct_player.html#a72ac136ed3f036a4f0a3c41aa5b57542"> 48</a></span>  <span class="keywordtype">int</span> <a class="code" href="struct_player.html#a72ac136ed3f036a4f0a3c41aa5b57542">hitted_moles</a>;</div>
<div class="line"><a name="l00049"></a><span class="lineno"><a class="line" href="struct_player.html#a5ac083a645d964373f022d03df4849c8"> 49</a></span>  <span class="keywordtype">char</span>* <a class="code" href="struct_player.html#a5ac083a645d964373f022d03df4849c8">name</a>;</div>
<div class="line"><a name="l00050"></a><span class="lineno"><a class="line" href="struct_player.html#a3ee1186574dc0333a88e1388a1259c85"> 50</a></span>  <span class="keywordtype">int</span> <a class="code" href="struct_player.html#a3ee1186574dc0333a88e1388a1259c85">max_name_length</a>;</div>
<div class="line"><a name="l00051"></a><span class="lineno"> 51</span> } <a class="code" href="struct_player.html">Player</a>;</div>
<div class="line"><a name="l00052"></a><span class="lineno"> 52</span>  </div>
<div class="line"><a name="l00060"></a><span class="lineno"><a class="line" href="struct_avatar.html"> 60</a></span> <span class="keyword">typedef</span> <span class="keyword">struct </span>{</div>
<div class="line"><a name="l00061"></a><span class="lineno"><a class="line" href="struct_avatar.html#ac8aa102f20962644d3345f02928d102e"> 61</a></span>  xpm_image_t sprites[3];</div>
<div class="line"><a name="l00062"></a><span class="lineno"><a class="line" href="struct_avatar.html#a3bcf222aa943af46be04be6ec0b7f9d1"> 62</a></span>  <a class="code" href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29b">button_state</a> <a class="code" href="struct_avatar.html#a3bcf222aa943af46be04be6ec0b7f9d1">state</a>;</div>
<div class="line"><a name="l00063"></a><span class="lineno"><a class="line" href="struct_avatar.html#a17f97f62d93bc8cfb4a2b5d273a2aa72"> 63</a></span>  uint8_t x,<a class="code" href="struct_avatar.html#a17f97f62d93bc8cfb4a2b5d273a2aa72">y</a>;</div>
<div class="line"><a name="l00064"></a><span class="lineno"> 64</span> } <a class="code" href="struct_avatar.html">Avatar</a>;</div>
<div class="line"><a name="l00065"></a><span class="lineno"> 65</span>  </div>
<div class="line"><a name="l00085"></a><span class="lineno"><a class="line" href="struct_player___settings.html"> 85</a></span> <span class="keyword">typedef</span> <span class="keyword">struct </span>{</div>
<div class="line"><a name="l00086"></a><span class="lineno"><a class="line" href="struct_player___settings.html#afcc5d2a6543b5baba632d506d2bc6a7e"> 86</a></span>  xpm_image_t <a class="code" href="struct_player___settings.html#afcc5d2a6543b5baba632d506d2bc6a7e">background</a>;</div>
<div class="line"><a name="l00087"></a><span class="lineno"><a class="line" href="struct_player___settings.html#a63975485af4c10cb1f6b2d907a380835"> 87</a></span>  xpm_image_t <a class="code" href="struct_player___settings.html#a63975485af4c10cb1f6b2d907a380835">background_title</a>;</div>
<div class="line"><a name="l00088"></a><span class="lineno"><a class="line" href="struct_player___settings.html#ac583c6394290b364a241d843995222a2"> 88</a></span>  xpm_image_t <a class="code" href="struct_player___settings.html#ac583c6394290b364a241d843995222a2">name_length_warning</a>;</div>
<div class="line"><a name="l00089"></a><span class="lineno"><a class="line" href="struct_player___settings.html#a632b0a796c388aa5cf8a762ff0790256"> 89</a></span>  xpm_image_t <a class="code" href="struct_player___settings.html#a632b0a796c388aa5cf8a762ff0790256">font</a>;</div>
<div class="line"><a name="l00090"></a><span class="lineno"><a class="line" href="struct_player___settings.html#a6af72b62a1de802ee6a722a3119a30fb"> 90</a></span>  <span class="keywordtype">bool</span> <a class="code" href="struct_player___settings.html#a6af72b62a1de802ee6a722a3119a30fb">name_maximum_length</a>;</div>
<div class="line"><a name="l00091"></a><span class="lineno"> 91</span>  <span class="comment">//Player* player;</span></div>
<div class="line"><a name="l00092"></a><span class="lineno"><a class="line" href="struct_player___settings.html#afee39b84b792600e34560fb1408cb2ff"> 92</a></span>  <a class="code" href="struct_avatar.html">Avatar</a>* avatars[4];</div>
<div class="line"><a name="l00093"></a><span class="lineno"><a class="line" href="struct_player___settings.html#a51e185b2d801d09f112b105a95eac423"> 93</a></span>  <a class="code" href="struct_button.html">Button</a>** <a class="code" href="struct_player___settings.html#a51e185b2d801d09f112b105a95eac423">buttons</a>;</div>
<div class="line"><a name="l00094"></a><span class="lineno"><a class="line" href="struct_player___settings.html#a5102affcad09978206de39f861f50ca6"> 94</a></span>  <span class="keywordtype">int</span> <a class="code" href="struct_player___settings.html#a5102affcad09978206de39f861f50ca6">num_buttons</a>;</div>
<div class="line"><a name="l00095"></a><span class="lineno"> 95</span> } <a class="code" href="struct_player___settings.html">Player_Settings</a>;</div>
<div class="line"><a name="l00096"></a><span class="lineno"> 96</span>  </div>
<div class="line"><a name="l00102"></a><span class="lineno"> 102</span> <a class="code" href="struct_player.html">Player</a>* <a class="code" href="_player_8h.html#a2b7148cd49fc0e0d9c93d8f1e36b29ac">load_player</a>(<a class="code" href="struct_avatar.html">Avatar</a>* default_avatar);</div>
<div class="line"><a name="l00103"></a><span class="lineno"> 103</span>  </div>
<div class="line"><a name="l00109"></a><span class="lineno"> 109</span> <a class="code" href="struct_avatar.html">Avatar</a>* <a class="code" href="_player_8h.html#a6873c31d8904de64e6f4f7cf3dc83982">load_avatar</a>(xpm_row_t *normal, xpm_row_t *selected, xpm_row_t *small);</div>
<div class="line"><a name="l00110"></a><span class="lineno"> 110</span>  </div>
<div class="line"><a name="l00115"></a><span class="lineno"> 115</span> <a class="code" href="struct_player___settings.html">Player_Settings</a> *<a class="code" href="_player_8h.html#a6d85d59dfb31c561dfb59f927bba63bc">load_player_settings</a>();</div>
<div class="line"><a name="l00116"></a><span class="lineno"> 116</span>  </div>
<div class="line"><a name="l00121"></a><span class="lineno"><a class="line" href="_player_8h.html#a3cfc2aaa30752c81dbf7198a74217698"> 121</a></span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a3cfc2aaa30752c81dbf7198a74217698">draw_background__</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a> *player_sets);</div>
<div class="line"><a name="l00122"></a><span class="lineno"> 122</span>  </div>
<div class="line"><a name="l00127"></a><span class="lineno"> 127</span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a6f315404e5a2795f04475b785d581c58">draw_name_lenght_warning</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a>* player_sets);</div>
<div class="line"><a name="l00128"></a><span class="lineno"> 128</span>  </div>
<div class="line"><a name="l00133"></a><span class="lineno"><a class="line" href="_player_8h.html#ab95a037825494b231b29e0011f4fbf29"> 133</a></span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#ab95a037825494b231b29e0011f4fbf29">draw_avatars</a>(<a class="code" href="struct_avatar.html">Avatar</a>* avatars[]);</div>
<div class="line"><a name="l00134"></a><span class="lineno"> 134</span>  </div>
<div class="line"><a name="l00139"></a><span class="lineno"> 139</span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a6edfb1a681fe3e25c530f883baf22e9a">move_left_avatar</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a>* player_sets);</div>
<div class="line"><a name="l00140"></a><span class="lineno"> 140</span>  </div>
<div class="line"><a name="l00145"></a><span class="lineno"> 145</span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a71c760196f9a13ae2da6049fcc873b00">move_right_avatar</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a>* player_sets);</div>
<div class="line"><a name="l00146"></a><span class="lineno"> 146</span>  </div>
<div class="line"><a name="l00153"></a><span class="lineno"> 153</span> xpm_image_t <a class="code" href="_player_8h.html#a18889494e66c36b5b6d99ae828a6e1f6">get_hammer</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a>* player_sets);</div>
<div class="line"><a name="l00154"></a><span class="lineno"> 154</span>  </div>
<div class="line"><a name="l00155"></a><span class="lineno"> 155</span>  </div>
<div class="line"><a name="l00165"></a><span class="lineno"> 165</span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a68726908922743aa8421780dc8e98c99">draw_player_name</a>(xpm_image_t font, <span class="keywordtype">int</span> xi, <span class="keywordtype">int</span> yi, <span class="keywordtype">char</span> name[], <span class="keywordtype">int</span> name_size);</div>
<div class="line"><a name="l00166"></a><span class="lineno"> 166</span>  </div>
<div class="line"><a name="l00175"></a><span class="lineno"> 175</span> <span class="keywordtype">void</span> <a class="code" href="_player_8h.html#a4846411729e20dc359a8ec6a9f5bbe32">update_player_name</a>(<a class="code" href="struct_player___settings.html">Player_Settings</a>* player_settings, <a class="code" href="struct_player.html">Player</a> *player, <span class="keywordtype">bool</span> delete_letter, <span class="keywordtype">char</span> new_letter);</div>
</div><!-- fragment --></div><!-- contents -->
<div class="ttc" id="astruct_player___settings_html_a51e185b2d801d09f112b105a95eac423"><div class="ttname"><a href="struct_player___settings.html#a51e185b2d801d09f112b105a95eac423">Player_Settings::buttons</a></div><div class="ttdeci">Button ** buttons</div><div class="ttdef"><b>Definition:</b> Player.h:93</div></div>
<div class="ttc" id="astruct_player_html"><div class="ttname"><a href="struct_player.html">Player</a></div><div class="ttdef"><b>Definition:</b> Player.h:45</div></div>
<div class="ttc" id="astruct_avatar_html_a3bcf222aa943af46be04be6ec0b7f9d1"><div class="ttname"><a href="struct_avatar.html#a3bcf222aa943af46be04be6ec0b7f9d1">Avatar::state</a></div><div class="ttdeci">button_state state</div><div class="ttdef"><b>Definition:</b> Player.h:62</div></div>
<div class="ttc" id="a_player_8c_html_a6edfb1a681fe3e25c530f883baf22e9a"><div class="ttname"><a href="_player_8c.html#a6edfb1a681fe3e25c530f883baf22e9a">move_left_avatar</a></div><div class="ttdeci">void move_left_avatar(Player_Settings *player_sets)</div><div class="ttdoc">: moves one avatar to left, defining it as SELECTED and the other ones as NOT_SELECTED</div><div class="ttdef"><b>Definition:</b> Player.c:78</div></div>
<div class="ttc" id="astruct_player___settings_html_a632b0a796c388aa5cf8a762ff0790256"><div class="ttname"><a href="struct_player___settings.html#a632b0a796c388aa5cf8a762ff0790256">Player_Settings::font</a></div><div class="ttdeci">xpm_image_t font</div><div class="ttdef"><b>Definition:</b> Player.h:89</div></div>
<div class="ttc" id="a_player_8h_html_a3cfc2aaa30752c81dbf7198a74217698"><div class="ttname"><a href="_player_8h.html#a3cfc2aaa30752c81dbf7198a74217698">draw_background__</a></div><div class="ttdeci">void draw_background__(Player_Settings *player_sets)</div><div class="ttdoc">: draws Player Settings mode background</div></div>
<div class="ttc" id="a_player_8h_html_a0bbab92f5605e16a4162b6c5ccc2c29ba02b0fb84d46d585b477a6509abf32b5d"><div class="ttname"><a href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29ba02b0fb84d46d585b477a6509abf32b5d">SELECTED</a></div><div class="ttdeci">@ SELECTED</div><div class="ttdef"><b>Definition:</b> Player.h:30</div></div>
<div class="ttc" id="amenu_8h_html"><div class="ttname"><a href="menu_8h.html">menu.h</a></div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a6aca6c136ab7eca03a0498cc15f89af7"><div class="ttname"><a href="xpm__coordinates_8h.html#a6aca6c136ab7eca03a0498cc15f89af7">NM_LENGTH_WR_X</a></div><div class="ttdeci">#define NM_LENGTH_WR_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:115</div></div>
<div class="ttc" id="astruct_avatar_html_ac8aa102f20962644d3345f02928d102e"><div class="ttname"><a href="struct_avatar.html#ac8aa102f20962644d3345f02928d102e">Avatar::sprites</a></div><div class="ttdeci">xpm_image_t sprites[3]</div><div class="ttdef"><b>Definition:</b> Player.h:61</div></div>
<div class="ttc" id="astruct_player_html_a28f28a491a23b6d052d96bfebaed65e7"><div class="ttname"><a href="struct_player.html#a28f28a491a23b6d052d96bfebaed65e7">Player::missed_moles</a></div><div class="ttdeci">int missed_moles</div><div class="ttdef"><b>Definition:</b> Player.h:47</div></div>
<div class="ttc" id="avd__card_8c_html_a960b8a6eaa33056b1caf46d2f3be5a78"><div class="ttname"><a href="vd__card_8c.html#a960b8a6eaa33056b1caf46d2f3be5a78">vg_draw_xpm</a></div><div class="ttdeci">void() vg_draw_xpm(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y)</div><div class="ttdef"><b>Definition:</b> vd_card.c:149</div></div>
<div class="ttc" id="astruct_player_html_a5ac083a645d964373f022d03df4849c8"><div class="ttname"><a href="struct_player.html#a5ac083a645d964373f022d03df4849c8">Player::name</a></div><div class="ttdeci">char * name</div><div class="ttdef"><b>Definition:</b> Player.h:49</div></div>
<div class="ttc" id="astruct_avatar_html_a17f97f62d93bc8cfb4a2b5d273a2aa72"><div class="ttname"><a href="struct_avatar.html#a17f97f62d93bc8cfb4a2b5d273a2aa72">Avatar::y</a></div><div class="ttdeci">uint8_t y</div><div class="ttdef"><b>Definition:</b> Player.h:63</div></div>
<div class="ttc" id="astruct_avatar_html"><div class="ttname"><a href="struct_avatar.html">Avatar</a></div><div class="ttdef"><b>Definition:</b> Player.h:60</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a0ca0d2754923a7f76c8ae3bcbf16da1c"><div class="ttname"><a href="xpm__coordinates_8h.html#a0ca0d2754923a7f76c8ae3bcbf16da1c">ARROW_RIGHT_X</a></div><div class="ttdeci">#define ARROW_RIGHT_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:91</div></div>
<div class="ttc" id="axpm__coordinates_8h_html"><div class="ttname"><a href="xpm__coordinates_8h.html">xpm_coordinates.h</a></div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a36f63efbd82e5a8de3a940ea3a1f03f3"><div class="ttname"><a href="xpm__coordinates_8h.html#a36f63efbd82e5a8de3a940ea3a1f03f3">NAME_BOX_Y</a></div><div class="ttdeci">#define NAME_BOX_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:96</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a4ca57c72014c5ab0a5019771f52b6b49"><div class="ttname"><a href="xpm__coordinates_8h.html#a4ca57c72014c5ab0a5019771f52b6b49">NM_LENGTH_WR_Y</a></div><div class="ttdeci">#define NM_LENGTH_WR_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:116</div></div>
<div class="ttc" id="a_player_8c_html_aa609c4cfbe283a80d63e4e8705f3df6d"><div class="ttname"><a href="_player_8c.html#aa609c4cfbe283a80d63e4e8705f3df6d">update_player_name</a></div><div class="ttdeci">void update_player_name(Player_Settings *player_sets, Player *player, bool delete_letter, char new_letter)</div><div class="ttdoc">:</div><div class="ttdef"><b>Definition:</b> Player.c:136</div></div>
<div class="ttc" id="a_player_8h_html_a0bbab92f5605e16a4162b6c5ccc2c29ba616ede6b6f3a1d38a724d1168ddf1adf"><div class="ttname"><a href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29ba616ede6b6f3a1d38a724d1168ddf1adf">NOT_SELECTED</a></div><div class="ttdeci">@ NOT_SELECTED</div><div class="ttdef"><b>Definition:</b> Player.h:30</div></div>
<div class="ttc" id="a_player_8c_html_a2b7148cd49fc0e0d9c93d8f1e36b29ac"><div class="ttname"><a href="_player_8c.html#a2b7148cd49fc0e0d9c93d8f1e36b29ac">load_player</a></div><div class="ttdeci">Player * load_player(Avatar *default_avatar)</div><div class="ttdoc">: loads Player's xpm, sets hitted and missed moles both as null, set's PLayers initial default name a...</div><div class="ttdef"><b>Definition:</b> Player.c:6</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a80584d1a89c82ff09cfcd5b1ac3404c5"><div class="ttname"><a href="xpm__coordinates_8h.html#a80584d1a89c82ff09cfcd5b1ac3404c5">STEP_AVT_X</a></div><div class="ttdeci">#define STEP_AVT_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:109</div></div>
<div class="ttc" id="a_player_8c_html_a6d85d59dfb31c561dfb59f927bba63bc"><div class="ttname"><a href="_player_8c.html#a6d85d59dfb31c561dfb59f927bba63bc">load_player_settings</a></div><div class="ttdeci">Player_Settings * load_player_settings()</div><div class="ttdoc">loads Player Settings : loads it's xpm and sets it's variavles</div><div class="ttdef"><b>Definition:</b> Player.c:38</div></div>
<div class="ttc" id="astruct_player_html_a72ac136ed3f036a4f0a3c41aa5b57542"><div class="ttname"><a href="struct_player.html#a72ac136ed3f036a4f0a3c41aa5b57542">Player::hitted_moles</a></div><div class="ttdeci">int hitted_moles</div><div class="ttdef"><b>Definition:</b> Player.h:48</div></div>
<div class="ttc" id="abutton_8c_html_acd37bde8c9ce5676f86ace96e44dfc24"><div class="ttname"><a href="button_8c.html#acd37bde8c9ce5676f86ace96e44dfc24">load_button</a></div><div class="ttdeci">Button * load_button(uint16_t xi, uint16_t yi, xpm_row_t *normal, xpm_row_t *bright)</div><div class="ttdef"><b>Definition:</b> button.c:6</div></div>
<div class="ttc" id="astruct_player___settings_html_afee39b84b792600e34560fb1408cb2ff"><div class="ttname"><a href="struct_player___settings.html#afee39b84b792600e34560fb1408cb2ff">Player_Settings::avatars</a></div><div class="ttdeci">Avatar * avatars[4]</div><div class="ttdef"><b>Definition:</b> Player.h:92</div></div>
<div class="ttc" id="a_player_8c_html_a18889494e66c36b5b6d99ae828a6e1f6"><div class="ttname"><a href="_player_8c.html#a18889494e66c36b5b6d99ae828a6e1f6">get_hammer</a></div><div class="ttdeci">xpm_image_t get_hammer(Player_Settings *player_sets)</div><div class="ttdoc">: get the hammer sellected by the player</div><div class="ttdef"><b>Definition:</b> Player.c:107</div></div>
<div class="ttc" id="a_player_8h_html_a0bbab92f5605e16a4162b6c5ccc2c29b"><div class="ttname"><a href="_player_8h.html#a0bbab92f5605e16a4162b6c5ccc2c29b">button_state</a></div><div class="ttdeci">button_state</div><div class="ttdef"><b>Definition:</b> Player.h:30</div></div>
<div class="ttc" id="a_player_8h_html_a4846411729e20dc359a8ec6a9f5bbe32"><div class="ttname"><a href="_player_8h.html#a4846411729e20dc359a8ec6a9f5bbe32">update_player_name</a></div><div class="ttdeci">void update_player_name(Player_Settings *player_settings, Player *player, bool delete_letter, char new_letter)</div><div class="ttdoc">:</div><div class="ttdef"><b>Definition:</b> Player.c:136</div></div>
<div class="ttc" id="a_player_8c_html_a71c760196f9a13ae2da6049fcc873b00"><div class="ttname"><a href="_player_8c.html#a71c760196f9a13ae2da6049fcc873b00">move_right_avatar</a></div><div class="ttdeci">void move_right_avatar(Player_Settings *player_sets)</div><div class="ttdoc">: moves one avatar to right, defining it as SELECTED and the other ones as NOT_SELECTED</div><div class="ttdef"><b>Definition:</b> Player.c:92</div></div>
<div class="ttc" id="a_player_8c_html_a68726908922743aa8421780dc8e98c99"><div class="ttname"><a href="_player_8c.html#a68726908922743aa8421780dc8e98c99">draw_player_name</a></div><div class="ttdeci">void draw_player_name(xpm_image_t font, int xi, int yi, char name[], int name_size)</div><div class="ttdoc">: draws Player Nmae</div><div class="ttdef"><b>Definition:</b> Player.c:119</div></div>
<div class="ttc" id="a_player_8c_html_ab7bf22d031fad1e7ccccf4746e9ff7bd"><div class="ttname"><a href="_player_8c.html#ab7bf22d031fad1e7ccccf4746e9ff7bd">draw_avatars</a></div><div class="ttdeci">void draw_avatars(Avatar *avatars[4])</div><div class="ttdef"><b>Definition:</b> Player.c:69</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_aa7f8bac4ff85ad501e926167631749bb"><div class="ttname"><a href="xpm__coordinates_8h.html#aa7f8bac4ff85ad501e926167631749bb">START_X</a></div><div class="ttdeci">#define START_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:99</div></div>
<div class="ttc" id="a_player_8h_html_a18889494e66c36b5b6d99ae828a6e1f6"><div class="ttname"><a href="_player_8h.html#a18889494e66c36b5b6d99ae828a6e1f6">get_hammer</a></div><div class="ttdeci">xpm_image_t get_hammer(Player_Settings *player_sets)</div><div class="ttdoc">: get the hammer sellected by the player</div><div class="ttdef"><b>Definition:</b> Player.c:107</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a7ed8d9db0d2a834c04ea297a7c14bdd6"><div class="ttname"><a href="xpm__coordinates_8h.html#a7ed8d9db0d2a834c04ea297a7c14bdd6">NAME_BOX_X</a></div><div class="ttdeci">#define NAME_BOX_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:95</div></div>
<div class="ttc" id="astruct_player___settings_html"><div class="ttname"><a href="struct_player___settings.html">Player_Settings</a></div><div class="ttdef"><b>Definition:</b> Player.h:85</div></div>
<div class="ttc" id="a_player_8h_html_a6f315404e5a2795f04475b785d581c58"><div class="ttname"><a href="_player_8h.html#a6f315404e5a2795f04475b785d581c58">draw_name_lenght_warning</a></div><div class="ttdeci">void draw_name_lenght_warning(Player_Settings *player_sets)</div><div class="ttdoc">: draws Player Settings name lennght waring</div><div class="ttdef"><b>Definition:</b> Player.c:64</div></div>
<div class="ttc" id="a_player_8h_html_a6d85d59dfb31c561dfb59f927bba63bc"><div class="ttname"><a href="_player_8h.html#a6d85d59dfb31c561dfb59f927bba63bc">load_player_settings</a></div><div class="ttdeci">Player_Settings * load_player_settings()</div><div class="ttdoc">loads Player Settings : loads it's xpm and sets it's variavles</div><div class="ttdef"><b>Definition:</b> Player.c:38</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a3d22ce6512ae6970212c63b87f8fe495"><div class="ttname"><a href="xpm__coordinates_8h.html#a3d22ce6512ae6970212c63b87f8fe495">FIRST_AVT_Y</a></div><div class="ttdeci">#define FIRST_AVT_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:106</div></div>
<div class="ttc" id="a_player_8c_html_a6f315404e5a2795f04475b785d581c58"><div class="ttname"><a href="_player_8c.html#a6f315404e5a2795f04475b785d581c58">draw_name_lenght_warning</a></div><div class="ttdeci">void draw_name_lenght_warning(Player_Settings *player_sets)</div><div class="ttdoc">: draws Player Settings name lennght waring</div><div class="ttdef"><b>Definition:</b> Player.c:64</div></div>
<div class="ttc" id="astruct_player___settings_html_a6af72b62a1de802ee6a722a3119a30fb"><div class="ttname"><a href="struct_player___settings.html#a6af72b62a1de802ee6a722a3119a30fb">Player_Settings::name_maximum_length</a></div><div class="ttdeci">bool name_maximum_length</div><div class="ttdef"><b>Definition:</b> Player.h:90</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a7b040c5474088c264005e0d9dcdc3931"><div class="ttname"><a href="xpm__coordinates_8h.html#a7b040c5474088c264005e0d9dcdc3931">ARROW_LEFT_Y</a></div><div class="ttdeci">#define ARROW_LEFT_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:88</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a7cb775755d88d9ba43b8e3d2d12605d9"><div class="ttname"><a href="xpm__coordinates_8h.html#a7cb775755d88d9ba43b8e3d2d12605d9">STEP_AVT_Y</a></div><div class="ttdeci">#define STEP_AVT_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:110</div></div>
<div class="ttc" id="astruct_player___settings_html_ac583c6394290b364a241d843995222a2"><div class="ttname"><a href="struct_player___settings.html#ac583c6394290b364a241d843995222a2">Player_Settings::name_length_warning</a></div><div class="ttdeci">xpm_image_t name_length_warning</div><div class="ttdef"><b>Definition:</b> Player.h:88</div></div>
<div class="ttc" id="astruct_player___settings_html_a63975485af4c10cb1f6b2d907a380835"><div class="ttname"><a href="struct_player___settings.html#a63975485af4c10cb1f6b2d907a380835">Player_Settings::background_title</a></div><div class="ttdeci">xpm_image_t background_title</div><div class="ttdef"><b>Definition:</b> Player.h:87</div></div>
<div class="ttc" id="astruct_player___settings_html_a5102affcad09978206de39f861f50ca6"><div class="ttname"><a href="struct_player___settings.html#a5102affcad09978206de39f861f50ca6">Player_Settings::num_buttons</a></div><div class="ttdeci">int num_buttons</div><div class="ttdef"><b>Definition:</b> Player.h:94</div></div>
<div class="ttc" id="avd__card_8c_html_a6bdae1bbe2550249fad35c5fb5c6a850"><div class="ttname"><a href="vd__card_8c.html#a6bdae1bbe2550249fad35c5fb5c6a850">vg_draw_part_of_xpm</a></div><div class="ttdeci">void() vg_draw_part_of_xpm(uint32_t *pixmap, xpm_image_t img, uint16_t x, uint16_t y, int x_start, int x_end, int y_start, int y_end)</div><div class="ttdef"><b>Definition:</b> vd_card.c:160</div></div>
<div class="ttc" id="a_player_8h_html_a6873c31d8904de64e6f4f7cf3dc83982"><div class="ttname"><a href="_player_8h.html#a6873c31d8904de64e6f4f7cf3dc83982">load_avatar</a></div><div class="ttdeci">Avatar * load_avatar(xpm_row_t *normal, xpm_row_t *selected, xpm_row_t *small)</div><div class="ttdoc">: loads Avatars's xpm, sets avatars initial state</div><div class="ttdef"><b>Definition:</b> Player.c:25</div></div>
<div class="ttc" id="a_player_8h_html"><div class="ttname"><a href="_player_8h.html">Player.h</a></div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a022bab2d589c864de9ec5451571b13db"><div class="ttname"><a href="xpm__coordinates_8h.html#a022bab2d589c864de9ec5451571b13db">ARROW_RIGHT_Y</a></div><div class="ttdeci">#define ARROW_RIGHT_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:92</div></div>
<div class="ttc" id="a_player_8c_html_a6873c31d8904de64e6f4f7cf3dc83982"><div class="ttname"><a href="_player_8c.html#a6873c31d8904de64e6f4f7cf3dc83982">load_avatar</a></div><div class="ttdeci">Avatar * load_avatar(xpm_row_t *normal, xpm_row_t *selected, xpm_row_t *small)</div><div class="ttdoc">: loads Avatars's xpm, sets avatars initial state</div><div class="ttdef"><b>Definition:</b> Player.c:25</div></div>
<div class="ttc" id="a_player_8h_html_a68726908922743aa8421780dc8e98c99"><div class="ttname"><a href="_player_8h.html#a68726908922743aa8421780dc8e98c99">draw_player_name</a></div><div class="ttdeci">void draw_player_name(xpm_image_t font, int xi, int yi, char name[], int name_size)</div><div class="ttdoc">: draws Player Nmae</div><div class="ttdef"><b>Definition:</b> Player.c:119</div></div>
<div class="ttc" id="astruct_button_html"><div class="ttname"><a href="struct_button.html">Button</a></div><div class="ttdef"><b>Definition:</b> button.h:15</div></div>
<div class="ttc" id="a_player_8h_html_a2b7148cd49fc0e0d9c93d8f1e36b29ac"><div class="ttname"><a href="_player_8h.html#a2b7148cd49fc0e0d9c93d8f1e36b29ac">load_player</a></div><div class="ttdeci">Player * load_player(Avatar *default_avatar)</div><div class="ttdoc">: loads Player's xpm, sets hitted and missed moles both as null, set's PLayers initial default name a...</div><div class="ttdef"><b>Definition:</b> Player.c:6</div></div>
<div class="ttc" id="a_player_8h_html_ab95a037825494b231b29e0011f4fbf29"><div class="ttname"><a href="_player_8h.html#ab95a037825494b231b29e0011f4fbf29">draw_avatars</a></div><div class="ttdeci">void draw_avatars(Avatar *avatars[])</div><div class="ttdoc">: draws Player Settings avatar's according to their state</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_a25fb6e1acf0727372676a6ae18c7bd1b"><div class="ttname"><a href="xpm__coordinates_8h.html#a25fb6e1acf0727372676a6ae18c7bd1b">ARROW_LEFT_X</a></div><div class="ttdeci">#define ARROW_LEFT_X</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:87</div></div>
<div class="ttc" id="astruct_player___settings_html_afcc5d2a6543b5baba632d506d2bc6a7e"><div class="ttname"><a href="struct_player___settings.html#afcc5d2a6543b5baba632d506d2bc6a7e">Player_Settings::background</a></div><div class="ttdeci">xpm_image_t background</div><div class="ttdef"><b>Definition:</b> Player.h:86</div></div>
<div class="ttc" id="axpm__coordinates_8h_html_ae28b1a95ee25def272409b9b8ce57f73"><div class="ttname"><a href="xpm__coordinates_8h.html#ae28b1a95ee25def272409b9b8ce57f73">START_Y</a></div><div class="ttdeci">#define START_Y</div><div class="ttdef"><b>Definition:</b> xpm_coordinates.h:100</div></div>
<div class="ttc" id="astruct_player_html_a0f8c87a9b0ac652a9fd8ef5c11ce4cf3"><div class="ttname"><a href="struct_player.html#a0f8c87a9b0ac652a9fd8ef5c11ce4cf3">Player::avatar</a></div><div class="ttdeci">xpm_image_t avatar</div><div class="ttdef"><b>Definition:</b> Player.h:46</div></div>
<div class="ttc" id="a_player_8h_html_a6edfb1a681fe3e25c530f883baf22e9a"><div class="ttname"><a href="_player_8h.html#a6edfb1a681fe3e25c530f883baf22e9a">move_left_avatar</a></div><div class="ttdeci">void move_left_avatar(Player_Settings *player_sets)</div><div class="ttdoc">: moves one avatar to left, defining it as SELECTED and the other ones as NOT_SELECTED</div><div class="ttdef"><b>Definition:</b> Player.c:78</div></div>
<div class="ttc" id="a_player_8h_html_a71c760196f9a13ae2da6049fcc873b00"><div class="ttname"><a href="_player_8h.html#a71c760196f9a13ae2da6049fcc873b00">move_right_avatar</a></div><div class="ttdeci">void move_right_avatar(Player_Settings *player_sets)</div><div class="ttdoc">: moves one avatar to right, defining it as SELECTED and the other ones as NOT_SELECTED</div><div class="ttdef"><b>Definition:</b> Player.c:92</div></div>
<div class="ttc" id="astruct_player_html_a3ee1186574dc0333a88e1388a1259c85"><div class="ttname"><a href="struct_player.html#a3ee1186574dc0333a88e1388a1259c85">Player::max_name_length</a></div><div class="ttdeci">int max_name_length</div><div class="ttdef"><b>Definition:</b> Player.h:50</div></div>
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by <a href="http://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.8.20
</small></address>
</body>
</html>
<file_sep>var searchData=
[
['y_626',['y',['../struct_cursor.html#ab0580f504a7428539be299fa71565f30',1,'Cursor::y()'],['../struct_mole.html#a0a2f84ed7838f07779ae24c5a9086d33',1,'Mole::y()'],['../struct_avatar.html#a17f97f62d93bc8cfb4a2b5d273a2aa72',1,'Avatar::y()']]],
['y_5fbreak_627',['Y_BREAK',['../group__i8042.html#ga10829b1f7f377cbeaed355eb0e09c29b',1,'i8042.h']]],
['y_5forigin_628',['Y_ORIGIN',['../xpm__coordinates_8h.html#aca9f2b6b463c704bb516cf2b6a5c4ca4',1,'xpm_coordinates.h']]],
['y_5fovfl_629',['Y_OVFL',['../group__i8042.html#gad49b33d3abadec53a57d09a7f255315f',1,'i8042.h']]],
['year_630',['year',['../struct_date.html#aac3a162d2f192fe2360aba534eac7198',1,'Date']]],
['year_5freg_631',['YEAR_REG',['../rtc__macros_8h.html#af54119cc0b644ea37bd26ac9206264a8',1,'rtc_macros.h']]],
['yf_632',['yf',['../struct_button.html#a8c406c4586cd5582bf61ae19a4f6b163',1,'Button']]],
['yi_633',['yi',['../struct_button.html#a7cff74f47b6a00e9abbe5ee3c6a01279',1,'Button']]]
];
|
82fe59f6e19aa10fe767fab95c8380b15f618156
|
[
"JavaScript",
"C",
"Makefile",
"HTML"
] | 92
|
JavaScript
|
sofiagermer/WHACK-A-MOLE
|
881b39ed4ce10abaaf6f74f9084ffc29b93f23af
|
d35f0391acae4596264703b6c915048d1fe289d5
|
refs/heads/master
|
<repo_name>sudheersingampalli/TodoList<file_sep>/accounts/views.py
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect
import Todoapp
from Todoapp.models import Todomodel
from django.contrib import messages
# Create your views here.
def home(request):
no_of_items = Todomodel.objects.latest('id').id
no_of_users = User.objects.latest('id').id
print ('no_of_items-->{}',format(no_of_users))
return render(request,'accounts/home.html',{'users':no_of_users,'items':no_of_items})
def signup(request):
if request.method == 'POST':
if request.POST['password1']==request.POST['password2']:
try:
user=User.objects.get(username = request.POST['username'])
messages.warning(request,"Username already exists")
return render(request,'accounts/signup.html')
except User.DoesNotExist:
user=User.objects.create_user(request.POST["username"], password=request.POST["<PASSWORD>"])
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return redirect('todoapp:register')
else:
messages.warning(request,"Passwords do not match")
return render(request,'accounts/signup.html');
else:
return render(request,'accounts/signup.html');
def loginview(request):
if request.method =='POST':
user = authenticate(username=request.POST.get('username', None),password=request.POST.get('password', None))
if user is not None:
login(request,user)
print ('next is {}',format(request.POST.get('next',None)))
if request.POST.get('next',None) is not None:
return redirect(request.POST['next'])
return redirect('todoapp:register')
else:
messages.warning(request, 'Incorrect username password')
return render(request,'accounts/login.html');
else:
return render(request,'accounts/login.html');
def logoutview(request):
if request.method =='POST':
logout(request)
return render(request,'accounts/logout.html');
return render(request,'accounts/login.html',{'info':'Not yet!!'});
def reset_password(request):
if request.method == 'POST':
if request.POST['password1']==request.POST['password2']:
try:
user=User.objects.get(username = request.POST['username'])
user.set_password(request.POST['<PASSWORD>1'])
user.save()
messages.success(request,"Password changed")
return redirect('accounts:login')
except User.DoesNotExist:
messages.warning(request,"User Does Not Exist")
return render(request,'accounts/reset_password.html')
else:
messages.warning(request,"Passwords do not match")
return render(request,'accounts/reset_password.html');
else:
return render(request,'accounts/reset_password.html');<file_sep>/Todoapp/views.py
from django.shortcuts import render,redirect,reverse
from . models import Todomodel
import datetime
from datetime import date
from .forms import Todoform
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.
@login_required
def register(request):
if request.method == 'POST': # for a form with data in it
todoform = Todoform(request.POST)
if todoform.is_valid():
item = todoform.save(commit = False)
item.employee_num = request.user
print('request choice-->{}'.format(request.POST['status']))
if request.POST['status'] == '4':
messages.warning(request, "Cannot delete an item unless it is saved...")
else:
item.save()
messages.success(request, 'Item saved')
# request.session.set_expiry(300)
# get_expire_at_browser_close
todoform = Todoform() #just for displaying empty form
list = Todomodel.objects.filter(date=datetime.date.today(),employee_num = request.user)
pending_list = Todomodel.objects.filter(status='1',employee_num = request.user).order_by('-date')
return render (request,'Todoapp/register.html',{'todoform':todoform,'list':list,'pending_list':pending_list})
def list(request):
list = Todomodel.objects.filter(employee_num = request.user).order_by('-date')
return render(request,'Todoapp/list.html',{'list':list})
def details(request,item_id):
item = get_object_or_404(Todomodel,id=item_id)
return render(request,'Todoapp/details.html',{'item':item})
def edit(request,item_id=None):
item = Todomodel.objects.get(pk = item_id)
todoform = Todoform(request.POST or None,instance = item)
context = { 'date' : item.date,
'description' : item.description,
'todoform' : todoform,
}
if todoform.is_valid():
if request.POST.get('status',None)=='4':
item = get_object_or_404(Todomodel,pk = item_id)
print ('deleting--->{}',format(item))
item.delete()
messages.success(request, 'Item deleted')
'''
A redirect will anyway fetch details from register function. So, no need to declare
the variables again.
'''
# todoform = Todoform() #just for displaying empty form
# list = Todomodel.objects.filter(date=datetime.date.today(),employee_num = request.user)
# pending_list = Todomodel.objects.filter(status='1',employee_num = request.user)
# print('before render')
# context = {
# 'todoform':todoform,'list':list,
# 'pending_list':pending_list,
# 'msg' : 'Deleted successfully!!!'
# }
return redirect('todoapp:register')
item = todoform.save(commit = False)
item.save()
messages.success(request, 'Item modified')
'''
after an item is edited, the url is in still in edit mode. Therefore the subsequest saves
are editing the same object. To over come it, redirect is used and the below variables
are commented.
'''
# print('should not come here')
# list = Todomodel.objects.filter(date=datetime.date.today(),employee_num = request.user)
# pending_list = Todomodel.objects.filter(status='1',employee_num = request.user).order_by('-date')
#return render (request,'Todoapp/register.html',{'todoform':Todoform(),'list':list,'pending_list':pending_list})
return redirect('todoapp:register')
return render(request,'Todoapp/register.html',context)
<file_sep>/accounts/urls.py
from django.conf.urls import url
from accounts import views
app_name = 'accounts'
urlpatterns = [
url(r'^signup/', views.signup, name ='signup'),
url(r'^login/', views.loginview, name ='login'),
url(r'^logout/', views.logoutview, name ='logout'),
url(r'^reset_password/', views.reset_password, name ='reset_password'),
url(r'^$', views.home, name ='home'),
]<file_sep>/Todoapp/migrations/0003_auto_20181025_1531.py
# Generated by Django 2.0.3 on 2018-10-25 06:31
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Todoapp', '0002_auto_20181024_2018'),
]
operations = [
migrations.AlterField(
model_name='todomodel',
name='date',
field=models.DateField(default=datetime.date(2018, 10, 25)),
),
]
<file_sep>/Todoapp/forms.py
from django import forms
from .models import Todomodel
class Todoform(forms.ModelForm):
class Meta:
model = Todomodel
fields = ['date','description','status']
<file_sep>/README.md
# TodoList
Track your day-to-day activities.
Built with <strong>Django</strong> and <strong>Sqllite</strong>
<file_sep>/Todoapp/migrations/0002_auto_20181024_2018.py
# Generated by Django 2.0.3 on 2018-10-24 11:18
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Todoapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='todomodel',
name='date',
field=models.DateField(default=datetime.date(2018, 10, 24)),
),
migrations.AlterField(
model_name='todomodel',
name='status',
field=models.CharField(choices=[('1', 'Pending'), ('2', 'Done'), ('3', 'Not Required'), ('4', 'Delete')], default='Pending', max_length=10),
),
]
<file_sep>/Todoapp/urls.py
from django.conf.urls import url
from . import views
app_name = 'todoapp'
urlpatterns = [
url(r'register/',views.register,name='register'),
url(r'list/',views.list,name = 'list'),
url(r'edit/(?P<item_id>[0-9]+)',views.edit,name = 'edit'),
url(r'details/(?P<item_id>[0-9]+)',views.details,name = 'details'),
]<file_sep>/Todoapp/models.py
from __future__ import unicode_literals
from django.db import models
from datetime import date
from django.contrib.auth.models import User
#from django.utils import timezone
# Create your models here.
class Todomodel(models.Model):
CHOICES_STATUS = (('1', 'Pending',), ('2', 'Done',), ('3','Not Required'), ('4','Delete'))
date = models.DateField(default = date.today) #date.today()
description = models.TextField(max_length = 500, blank=False)
status = models.CharField(choices=CHOICES_STATUS, max_length=10, default='Pending')
employee_num = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.date)+ " " +str(self.description) #+" "+str(self.pending)+" "+str(self.done)
|
3d43ff04f060c58c1c9a6771e4a890ecfb5099b9
|
[
"Markdown",
"Python"
] | 9
|
Python
|
sudheersingampalli/TodoList
|
427c32ac8dfbbfe6345289843a7049d823f50dcc
|
f48ed6eda73ca1567d1489e4cf36a316dc564c8a
|
refs/heads/master
|
<repo_name>mikemaccana/documentdb-arc-test<file_sep>/README.md
# DocumentDB/MongoDB calls in Express lambdas not returning
A reproduction case for https://github.com/arc-repos/architect/issues/354<file_sep>/src/http/get-index/index.js
const MongoClient = require('mongodb').MongoClient
exports.handler = async function http(req) {
console.log(`Got incoming request!`)
// The following line, if uncommented, will stop even the console.log above from working
// Instead the entire HTTP request will time out
await MongoClient.connect('REDACTED')
return {
headers: {'content-type': 'text/html; charset=utf8'},
body: '<h1>Hello world!</h1>'
}
}
<file_sep>/test-mongo-url-connection.js
const MongoClient = require('mongodb').MongoClient
;(async function(request, context) {
await MongoClient.connect('mongodb://localhost')
console.log(`I connected successfully!`)
})();
|
d5f2b24cc2d3957a4223f45b0acdb3dd9f178a80
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
mikemaccana/documentdb-arc-test
|
afa8342d22804b954e3259b3169402e5b2ce7121
|
1e927b38f4a0f4ef4c1f83aed6abe34175c96b45
|
refs/heads/master
|
<file_sep>dependencies {
compile project(':storage:spi')
}<file_sep>package com.github.slamdev.messageswatcher.packager.spi;
import com.google.inject.Module;
public interface PackagerModule extends Module {
}
<file_sep>plugins {
id 'java-gradle-plugin'
id 'codenarc'
}
repositories {
mavenCentral()
maven {
url 'http://repo.jenkins-ci.org/public'
}
}
codenarc {
toolVersion = '0.24.1'
configFile = project.file('src/main/resources/codenarc.groovy')
}
dependencies {
compile 'org.kohsuke:github-api:1.72'
}
<file_sep>plugins {
id 'application'
id 'com.github.johnrengelman.shadow' version '1.2.2'
}
subprojects {
apply plugin: 'java'
dependencies {
compile 'com.google.inject:guice:4.0'
compile 'com.google.inject.extensions:guice-multibindings:4.0'
compile 'ch.qos.logback:logback-classic:1.1.3'
}
}
assemble.dependsOn shadowJar
mainClassName = 'com.github.slamdev.messageswatcher.collector.runner.Runner'
<file_sep>dependencies {
compile project(':packager:spi')
}
<file_sep>package com.github.slamdev.messageswatcher.collector.capturer.viber;
import com.github.slamdev.messageswatcher.collector.capturer.spi.Collector;
import com.github.slamdev.messageswatcher.collector.capturer.spi.CollectorModule;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
public class ViberModule extends AbstractModule implements CollectorModule {
@Override
protected void configure() {
Multibinder<Collector> binder = Multibinder.newSetBinder(binder(), Collector.class);
binder.addBinding().to(ViberCollector.class);
}
}
<file_sep>dependencies {
compile project(':collector:capturer:spi')
runtime project(':collector:capturer:skype')
runtime project(':collector:capturer:viber')
compile project(':packager:spi')
runtime project(':packager:csv')
runtime project(':packager:json')
compile project(':storage:spi')
runtime project(':storage:dropbox')
runtime project(':storage:google-drive')
}
<file_sep>include ':packager'
include ':packager:spi'
include ':packager:json'
include ':packager:csv'
include ':storage'
include ':storage:spi'
include ':storage:dropbox'
include ':storage:google-drive'
include ':collector'
include ':collector:capturer:spi'
include ':collector:capturer:skype'
include ':collector:capturer:viber'
include ':collector:runner'
include ':watcher'
<file_sep>package com.github.slamdev.messageswatcher.storage.googledrive;
import com.github.slamdev.messageswatcher.storage.spi.Storage;
import com.github.slamdev.messageswatcher.storage.spi.StorageModule;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
public class GoogleDriveModule extends AbstractModule implements StorageModule {
@Override
protected void configure() {
Multibinder<Storage> binder = Multibinder.newSetBinder(binder(), Storage.class);
binder.addBinding().to(GoogleDriveStorage.class);
}
}
<file_sep>package com.github.slamdev.messageswatcher.collector.runner;
import com.github.slamdev.messageswatcher.collector.capturer.spi.CollectorModule;
import com.github.slamdev.messageswatcher.packager.spi.PackagerModule;
import com.github.slamdev.messageswatcher.storage.spi.StorageModule;
import com.google.inject.AbstractModule;
import java.util.ServiceLoader;
public class RunnerModule extends AbstractModule {
@Override
protected void configure() {
bind(Runner.class);
ServiceLoader<CollectorModule> collectors = ServiceLoader.load(CollectorModule.class);
collectors.forEach(this::install);
ServiceLoader<PackagerModule> packagers = ServiceLoader.load(PackagerModule.class);
packagers.forEach(this::install);
ServiceLoader<StorageModule> storages = ServiceLoader.load(StorageModule.class);
storages.forEach(this::install);
}
}
<file_sep>import com.github.slamdev.messageswatcher.plugin.GithubReleasePlugin
apply plugin: GithubReleasePlugin
group 'com.github.slamdev'
version '0.1-SNAPSHOT'
ext {
gradleWrapperVersion = project.gradleWrapperVersion
}
subprojects {
repositories {
mavenCentral()
}
}
githubRelease {
oAuthToken = RELEASE_KEY /* env variable */
}
task wrapper(type: Wrapper) {
gradleVersion = gradleWrapperVersion
}
<file_sep>package com.github.slamdev.messageswatcher.collector.capturer.spi;
import com.google.inject.Module;
public interface CollectorModule extends Module {
}
<file_sep>package com.github.slamdev.messageswatcher.collector.capturer.spi;
public interface Collector {
void collect();
}<file_sep>plugins {
id 'war'
}
dependencies {
compile project(':storage:dropbox')
compile project(':storage:google-drive')
}
<file_sep>package com.github.slamdev.messageswatcher.storage.dropbox;
import com.github.slamdev.messageswatcher.storage.spi.Storage;
public class DropboxStorage implements Storage {
@Override
public void store() {
System.out.println("Dropbox storage");
}
}
<file_sep>Platform that enables you to manage all of your communications from one place.
<file_sep>package com.github.slamdev.messageswatcher.packager.json;
import com.github.slamdev.messageswatcher.packager.spi.Packager;
import com.github.slamdev.messageswatcher.packager.spi.PackagerModule;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
public class JsonModule extends AbstractModule implements PackagerModule {
@Override
protected void configure() {
Multibinder<Packager> binder = Multibinder.newSetBinder(binder(), Packager.class);
binder.addBinding().to(JsonPackager.class);
}
}
<file_sep>package com.github.slamdev.messageswatcher.collector.capturer.skype;
import com.github.slamdev.messageswatcher.collector.capturer.spi.Collector;
public class SkypeCollector implements Collector {
@Override
public void collect() {
System.out.println("skype collecting");
}
}
<file_sep>implementation-class=com.github.slamdev.messageswatcher.plugin.GithubReleasePlugin
<file_sep>subprojects {
apply plugin: 'java'
dependencies {
compile 'com.google.inject:guice:4.0'
compile 'com.google.inject.extensions:guice-multibindings:4.0'
compile 'ch.qos.logback:logback-classic:1.1.3'
}
}
<file_sep>dependencies {
compile project(':collector:capturer:spi')
}
|
0f7ba2511855bae691608d3b7cd88d7f730edaf8
|
[
"Markdown",
"Java",
"INI",
"Gradle"
] | 21
|
Gradle
|
slamdev/messages-watcher
|
ee666611492e9a7f9c1df2bd92e36dce58b32ceb
|
28017831c725e45c2867310e3d7d5e3df27d92fd
|
refs/heads/master
|
<file_sep>BLK_INTV = 0.0001
#
# BOARD PIN CONF
LED = '1'
TPIN = '2'
#
# DB Credentials
DB_USR = 'test_bot'
DB_PASS = '<PASSWORD>'
DB_HOST = 'localhost'
DB_DbName = 'TrainDb'
#
# SLEEP TIMES
TIME_SL_SURV = 5
TIME_SL_SPR = 1
# TWILLO
SID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
AUTH_TOKEN = '<KEY>'
FROM_NUMBER = '+111111111111'
<file_sep>README for lock_dev
1. Import the 'TrainDb.sql' into your database
2. Run simultaneously 'api_listener.py'
'sleeper_routine.py'
'surveillence_routine.py'
3. API keys need to be modified to access the devices<file_sep>-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Feb 01, 2020 at 05:12 PM
-- Server version: 5.7.28-0ubuntu0.18.04.4
-- PHP Version: 7.2.24-0ubuntu0.18.04.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+05:30";
/*!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: `TrainDb`
--
DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `activate_device` () NO SQL
INSERT INTO `ActiveDevices` (`device_id`, `device_tamper`, `device_status`, `geo_latitude`, `geo_longitude`, `time_last_updated`) VALUES ('BOLT20001', '0', '1', NULL, NULL, CURRENT_TIMESTAMP)$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `deactivate_device` () MODIFIES SQL DATA
UPDATE `Device_details`
SET `ready` = '0'
WHERE `Device_details`.`device_id` = 'BOLT200001'$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `faulty_device` () NO SQL
UPDATE `Device_details` SET `ready` = '0' WHERE `Device_details`.`device_id` = 'BOLT200001'$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_active_devices` () READS SQL DATA
SELECT AD.device_id, AD.device_status, AD.time_last_updated from ActiveDevices as AD
WHERE AD.device_tamper = 0$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_active_device_with_api` () READS SQL DATA
BEGIN
if ( select NOT exists (select 1 from ActiveDevices) ) THEN
select 'None';
ELSE
SELECT AD.device_id, DD.device_api_token
FROM ActiveDevices as AD
INNER JOIN Device_details as DD
ON AD.device_id = DD.device_id AND
AD.device_tamper != '1';
END IF;
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_idle_devices` () NO SQL
BEGIN
if ( select NOT exists (select 1 from Device_details) ) THEN
select 'None';
ELSE
SELECT DD.device_id, DD.ready, DD.halting
FROM Device_details as DD
WHERE DD.ready = 1
AND
NOT EXISTS( SELECT * from ActiveDevices as AD WHERE AD.device_id = DD.device_id);
END IF;
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_ready_devices` () READS SQL DATA
BEGIN
if ( select NOT exists (select 1 from Device_details) ) THEN
select 'None';
ELSE
SELECT *
FROM Device_details as DD
WHERE DD.ready = 1
AND DD.halting != 1
AND
NOT EXISTS( SELECT * from ActiveDevices as AD WHERE AD.device_id = DD.device_id);
END IF;
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_subscribers` () READS SQL DATA
BEGIN
SELECT *
FROM device_BOLT200001_subscribers;
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `fetch_tampered_devices` () READS SQL DATA
SELECT AD.device_id, AD.time_last_updated
FROM ActiveDevices as AD
WHERE AD.device_tamper = 1$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `get_tamper_report` () MODIFIES SQL DATA
SELECT subs.subscriber_sms_number, time_last_updated
FROM
device_BOLT200001_subscribers as subs
JOIN ActiveDevices as AD$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `halt_device` () MODIFIES SQL DATA
UPDATE `Device_details` SET `halting` = '1' WHERE `Device_details`.`device_id` = 'BOLT200001'$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `log_update` (IN `g_device_status` BOOLEAN, IN `g_message` CHAR(250), IN `g_tamper` BOOLEAN) MODIFIES SQL DATA
BEGIN
INSERT INTO `device_BOLT200001_log` (`date_time_stamp`, `device_status`, `geo_longitude`, `geo_latitude`, `message`, `device_tamper`) VALUES (CURRENT_TIMESTAMP, g_device_status, NULL, NULL, g_message, g_tamper);
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `ready_device` () NO SQL
UPDATE `Device_details` SET `ready` = '1' WHERE `Device_details`.`device_id` = 'BOLT200001'$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `reset_device` () MODIFIES SQL DATA
BEGIN
DELETE FROM `ActiveDevices` WHERE `ActiveDevices`.`device_id` = 'BOLT200001';
UPDATE `Device_details` SET `ready` = '1' , `halting` = '0' WHERE `Device_details`.`device_id` = 'BOLT200001';
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `test_procedure` () MODIFIES SQL DATA
SELECT 'Something called test_procedure.'$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `update_device_log_msg` (IN `g_message` VARCHAR(256)) MODIFIES SQL DATA
INSERT INTO `device_BOLT200001_log` (`date_time_stamp`, `device_status`, `geo_longitude`, `geo_latitude`, `message`, `device_tamper`) VALUES (CURRENT_TIMESTAMP, NULL, NULL, NULL, g_message, NULL)$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `update_device_status` (IN `g_device_id` VARCHAR(10), IN `g_status` BOOLEAN, IN `g_tamper_status` BOOLEAN, IN `g_lat` DECIMAL(10,8), IN `g_lon` DECIMAL(11,8)) NO SQL
BEGIN
UPDATE ActiveDevices as AD
SET AD.device_status = g_status,
AD.device_tamper = g_tamper_status,
AD.geo_latitude = g_lat,
AD.geo_longitude = g_lon,
AD.time_last_updated = CURRENT_TIMESTAMP
WHERE AD.device_id = g_device_id;
END$$
CREATE DEFINER=`test_bot`@`localhost` PROCEDURE `update_status` (IN `g_status` BOOLEAN, IN `g_tamper` BOOLEAN) MODIFIES SQL DATA
BEGIN
UPDATE ActiveDevices
SET time_last_updated = CURRENT_TIMESTAMP,
device_status = g_status,
device_tamper = g_tamper
;
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `ActiveDevices`
--
CREATE TABLE `ActiveDevices` (
`device_id` varchar(10) NOT NULL,
`device_tamper` tinyint(1) NOT NULL COMMENT '0-No, 1-Yes',
`device_status` tinyint(1) NOT NULL COMMENT '0-offline 1-online',
`geo_latitude` decimal(10,8) DEFAULT NULL,
`geo_longitude` decimal(11,8) DEFAULT NULL,
`time_last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Dumping data for table `ActiveDevices`
--
INSERT INTO `ActiveDevices` (`device_id`, `device_tamper`, `device_status`, `geo_latitude`, `geo_longitude`, `time_last_updated`) VALUES
('BOLT200001', 1, 1, NULL, NULL, '2020-01-19 06:43:14');
-- --------------------------------------------------------
--
-- Table structure for table `device_BOLT200001_log`
--
CREATE TABLE `device_BOLT200001_log` (
`date_time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`device_status` tinyint(1) DEFAULT NULL,
`geo_longitude` decimal(11,8) DEFAULT NULL,
`geo_latitude` decimal(10,8) DEFAULT NULL,
`message` varchar(256) NOT NULL,
`device_tamper` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Dumping data for table `device_BOLT200001_log`
--
INSERT INTO `device_BOLT200001_log` (`date_time_stamp`, `device_status`, `geo_longitude`, `geo_latitude`, `message`, `device_tamper`) VALUES
('2020-01-19 03:46:35', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 03:46:40', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:46:46', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:46:53', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:47:00', 1, NULL, NULL, 'Lock tampered', 1),
('2020-01-19 03:47:36', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 03:47:47', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 03:47:53', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:48:00', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:48:01', NULL, NULL, NULL, 'Halt by API', NULL),
('2020-01-19 03:48:10', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 03:48:18', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 03:48:22', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:48:28', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:48:29', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 03:48:31', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 03:48:35', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 03:48:37', NULL, NULL, NULL, 'Halt by API', NULL),
('2020-01-19 03:48:41', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 05:58:14', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 05:58:18', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 05:58:26', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 05:58:32', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 05:58:37', NULL, NULL, NULL, 'Halt by API', NULL),
('2020-01-19 05:58:51', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 05:59:22', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 05:59:24', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 05:59:31', 1, NULL, NULL, 'Lock tampered', 1),
('2020-01-19 05:59:56', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 06:38:52', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 06:38:54', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:39:00', 1, NULL, NULL, 'Lock tampered', 1),
('2020-01-19 06:40:34', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 06:42:06', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 06:42:10', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:42:17', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:42:24', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:42:27', NULL, NULL, NULL, 'Halt by API', NULL),
('2020-01-19 06:42:44', NULL, NULL, NULL, 'Reset By API', NULL),
('2020-01-19 06:42:55', 1, NULL, NULL, 'Lock Activated', 0),
('2020-01-19 06:43:01', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:43:08', 1, NULL, NULL, 'Routine Check', 0),
('2020-01-19 06:43:15', 1, NULL, NULL, 'Lock tampered', 1);
-- --------------------------------------------------------
--
-- Table structure for table `device_BOLT200001_subscribers`
--
CREATE TABLE `device_BOLT200001_subscribers` (
`subscriber_id` int(11) NOT NULL,
`subscriber_name` varchar(30) NOT NULL,
`subcriber_email` varchar(30) NOT NULL,
`subscriber_sms_number` char(13) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Dumping data for table `device_BOLT200001_subscribers`
--
INSERT INTO `device_BOLT200001_subscribers` (`subscriber_id`, `subscriber_name`, `subcriber_email`, `subscriber_sms_number`) VALUES
(101, 'test_human', '<EMAIL>', '+919998887776');
-- --------------------------------------------------------
--
-- Table structure for table `Device_details`
--
CREATE TABLE `Device_details` (
`device_id` varchar(10) NOT NULL,
`device_api_token` varchar(256) NOT NULL,
`device_date_added` datetime NOT NULL,
`credentials_date_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ready` tinyint(1) NOT NULL COMMENT 'Ready = 1, Tampered= 0',
`halting` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Dumping data for table `Device_details`
--
INSERT INTO `Device_details` (`device_id`, `device_api_token`, `device_date_added`, `credentials_date_modified`, `ready`, `halting`) VALUES
('BOLT200001', 'xxxxx-xxxx-xxx-xxxx-xxxxxxx', '2020-01-16 07:30:16', '2020-01-16 07:30:16', 0, 0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `ActiveDevices`
--
ALTER TABLE `ActiveDevices`
ADD PRIMARY KEY (`device_id`);
--
-- Indexes for table `device_BOLT200001_log`
--
ALTER TABLE `device_BOLT200001_log`
ADD PRIMARY KEY (`date_time_stamp`);
--
-- Indexes for table `device_BOLT200001_subscribers`
--
ALTER TABLE `device_BOLT200001_subscribers`
ADD PRIMARY KEY (`subscriber_id`);
--
-- Indexes for table `Device_details`
--
ALTER TABLE `Device_details`
ADD PRIMARY KEY (`device_id`);
/*!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>#!/usr/bin/python3
# Creates api listener to process incoming REST api
from flask import Flask
from flask_restful import Resource, Api, reqparse
from flaskext.mysql import MySQL
from flask_cors import CORS
from datetime import datetime
app = Flask(__name__)
api = Api(app)
mysql = MySQL()
CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
return response
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'test_bot'
app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
app.config['MYSQL_DATABASE_DB'] = 'TrainDb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_SOCKET'] = ''
mysql.init_app(app)
class ActiveDevices(Resource):
def get(self):
conn = mysql.connect()
curr = conn.cursor()
curr.callproc('fetch_active_devices')
data = curr.fetchone()
if data is None:
conn.close()
return
else:
id = data[0]
if data[1] == 1:
status = 'online'
else:
status = 'offline'
time_upd = datetime.timestamp(data[2])
time_upd = datetime.fromtimestamp(time_upd)
conn.close()
return {'id': id, 'status':status, 'time':str(time_upd)}
class TamperedDevices(Resource):
def get(self):
conn = mysql.connect()
curr = conn.cursor()
curr.callproc('fetch_tampered_devices')
data = curr.fetchone()
if data is None:
conn.close()
return
else:
id = data[0]
time_upd = datetime.timestamp(data[1])
time_upd = datetime.fromtimestamp(time_upd)
conn.close()
return {'id': id, 'time':str(time_upd)}
class IdleDevices(Resource):
def get(self):
conn = mysql.connect()
curr = conn.cursor()
curr.callproc('fetch_idle_devices')
data = curr.fetchone()
if data is None:
conn.close()
return
else:
id = data[0]
ready = int(data[1])
halt = int(data[2])
if ready == 1 and halt == 0:
status = 'Ready'
elif ready == 1 and halt == 1:
status = 'Halt'
else:
status = 'UNKNOWN'
conn.close()
return {'id': id, 'status':status}
class ResetDevices(Resource):
def post(self):
conn = mysql.connect()
curr = conn.cursor()
curr.callproc('reset_device')
conn.commit()
curr.callproc('update_device_log_msg',('Reset By API',))
conn.commit()
conn.close()
return
class HaltDevices(Resource):
def post(self):
conn = mysql.connect()
curr = conn.cursor()
curr.callproc('reset_device')
conn.commit()
curr.callproc('halt_device')
conn.commit()
curr.callproc('update_device_log_msg',('Halt by API',))
conn.commit()
conn.close()
return
api.add_resource(ActiveDevices, '/active')
api.add_resource(TamperedDevices, '/tampered')
api.add_resource(IdleDevices, '/idle')
api.add_resource(ResetDevices, '/reset')
api.add_resource(HaltDevices, '/halt')
if __name__ == "__main__":
app.run(host='172.20.10.6', debug=True)
<file_sep>#!/usr/bin/python3
# Creates a program that routinely checks if any unlocked device requests for getting locked
from boltiot import Bolt
from conf import TIME_SL_SPR, BLK_INTV
from conf import DB_USR, DB_PASS, DB_HOST, DB_DbName, TIME_SL_SURV, TPIN, LED
from time import sleep
import json
import mysql.connector
def service_check(device_id, device_api, sql_curr, db):
# Init bolt instance
mydevice = Bolt(device_api, device_id)
# Check device status
response = mydevice.isOnline()
if 'online' in response:
# GLOW RESPONSE BULB
mydevice.digitalWrite(LED, 'HIGH')
# CHECK TAMPER PIN
tamper_pin = json.loads(mydevice.digitalRead(TPIN))
if tamper_pin['value'] == '1':
print ("LOCK INIT__DEVICE:", device_id)
# LOG UPDATE
sql_curr.callproc('log_update', ('1', 'Lock Activated', '0'))
db.commit()
# MOVE TO ACTIVE DEVICES
sql_curr.callproc('activate_device')
db.commit()
# BLINK RESPONSE BULB
for i in range(3):
mydevice.digitalWrite(LED, 'LOW')
sleep(BLK_INTV)
mydevice.digitalWrite(LED, 'HIGH')
sleep(BLK_INTV)
#else:
# REGISTERED TAMPER
#sql_curr.callproc('log_update', args = (1, 'Lock found tampered', 1))
#sql_curr.callproc('faulty_device')
del mydevice
return
if __name__ == "__main__":
print ('SLEEPER ROUTINE STARTER...')
# setup connection
try:
# Fetch Active Devices
while(True):
conn = mysql.connector.connect(user = DB_USR, password = <PASSWORD>, host = DB_HOST, database = DB_DbName)
curr = conn.cursor()
#conn.begin()
curr.callproc('fetch_ready_devices')
data = curr.stored_results()
for datum in data:
#print(dir(data))
while(True):
# For each active device
record = datum.fetchone()
#print (record)
if record == None:
break
if 'None' in record:
print("NONE: NO READY Devices yet!")
else:
# SERVICE_CHECK
service_check(record[0], record[1], curr, conn)
#curr.close()
conn.close()
sleep(TIME_SL_SPR)
# CLOSE CONNECTION
except Exception as err:
print(err)
<file_sep># Creates a program to send sms using twillo api
import conf, json, time
from boltiot import Sms, Bolt
def sendSms(phno, msg):
#print ('SMS')
print (type(phno))
print ("_",phno,"_")
#print (msg)
sms = Sms(conf.SID, conf.AUTH_TOKEN, phno, conf.FROM_NUMBER)
try:
print("SMS REQ")
response = sms.send_sms(msg)
print("RESP OF SMS TWIL: "+ str(response))
print(" RESP STATUS: "+ str(response.status))
except Exception as e:
print ("Error",e)
#sendSms('+919998887776', 'msg')
<file_sep>#!/usr/bin/python3
# Creates a program that routinly checks the active devices for tamper
#import modules
import mysql.connector, time, json
from conf import DB_USR, DB_PASS, DB_HOST, DB_DbName, TIME_SL_SURV, LED, TPIN
from boltiot import Bolt
from sms_routine import sendSms
def tamper_check(device_id, device_api, sql_curr, db):
# Init bolt instance
mydevice = Bolt(device_api, device_id)
# Check device status
response = mydevice.isOnline()
if 'online' in response:
mydevice.digitalWrite(LED, 'HIGH')
# CHECK TAMPER PIN
tamper_pin = json.loads(mydevice.digitalRead(TPIN))
if tamper_pin['value'] == '1':
print ("Status OK", device_id)
# LOG UPDATE
sql_curr.callproc('log_update', ('1', 'Routine Check', '0'))
db.commit()
# ActiveDevice TABLE update
sql_curr.callproc('update_status', ('1', '0'))
db.commit()
else:
print ("TAMPERED!!_,DEVICE_ID:", device_id)
# REGISTERED TAMPER
sql_curr.callproc('update_status', ('1', '1'))
db.commit()
sql_curr.callproc('log_update', ('1', 'Lock tampered', '1'))
db.commit()
sql_curr.callproc('deactivate_device')
db.commit()
# TURN OFF GLOW
mydevice.digitalWrite(LED, 'LOW')
# SEND SMS
sql_curr.callproc('get_tamper_report')
data = sql_curr.stored_results()
for d in data:
row = d.fetchone()
msg = "TAMPERED DEVICE ID {} TIME {}".format(device_id, row[1])
sendSms(row[0].strip(), msg)
break
else:
sql_curr.callproc('update_status', ('0', '0'))
db.commit()
sql_curr.callproc('log_update', ('0', 'Device OFFLINE', '0'))
db.commit()
del mydevice
return
if __name__ == "__main__":
# Fetch Active Devices
while(True):
# setup connection
conn = mysql.connector.connect(user = DB_USR, password = <PASSWORD>, host = DB_HOST, database = DB_DbName)
curr = conn.cursor()
curr.callproc('fetch_active_device_with_api')
data = curr.stored_results()
for datum in data:
#print(dir(data))
while(True):
# For each active device
row = datum.fetchone()
if row == None:
break
if 'None' in row:
print("No Active Devices yet!")
else:
# TAMPER CHECK
#print(row)
tamper_check(row[0], row[1], curr, conn)
time.sleep(TIME_SL_SURV)
# CLOSE CONNECTION
conn.close()
|
3eb97e369d783d38d9d5868aae53e693109d22e5
|
[
"SQL",
"Python",
"Text"
] | 7
|
Python
|
LunaticMaestro/lock_dev
|
a7f6fb610d2680f0b98a5d3ae0d906d58e44af52
|
6651385d3e5f886511a5ae09ee41e5c69e5e6b60
|
refs/heads/master
|
<file_sep><?php
$config['abiti']=[
"maglia"=>["peso"=>2,"volume"=>1, "nome"=>"Maglia"],
"pantaloni"=>["peso"=>6,"volume"=>2,"nome"=>"Pantaloni"],
"camicia"=>["peso"=>3,"volume"=>1,"nome"=>"Camicia"],
"scarpe"=>["peso"=>10,"volume"=>3,"nome"=>"Scarpe"],
"calze"=>["peso"=>1,"volume"=>0.2,"nome"=>"Calze"],
"giacche"=>["peso"=>4,"volume"=>3,"nome"=>"Giacche"]
];
$config['armadio']= [
"maglia"=>3,
"pantaloni"=>4,
"camicia"=>6,
"scarpe"=>2,
"calze"=>9,
"giacche"=>4
];
$config['valigia']= [];
$config['max']=6;
$config['max_vol']=50; //valigia da 50 litri
$msg="";
<file_sep><?php
function boot()
{
global $config;
session_start();
if( !isset($_SESSION['armadio'])){
$_SESSION['armadio'] = create_armadio();
}
if( !isset($_SESSION['valigia'])){
$_SESSION['valigia'] = create_valigia() ;
}
// riempi la valigia parse input
$action =(isset($_GET['action']) && ($_GET['action']=="move" OR $_GET['action']=="remove")) ? $_GET['action'] : "";
$id=isset($_GET['id']) ? trim($_GET['id']) : "-1";
return (["action"=>$action, "id"=> $id]);
}
function move($id)
{
// sposta l'elemento identificato dall'indice $id dall'array sorgente al destinatario
$src=$_SESSION['armadio'];
$dest=$_SESSION['valigia'];
//elementi massimi nella valigia
//$max=get_max();
$max_vol=get_max_vol();
if(is_valigia_full($id,$dest,$max_vol)){
// if (get_size($dest)>=$max ){ ------>vecchio controllo
return("la valigia è piena!");
}
// controlla che ci sia l'elemento origine
if (isset($src[$id])){
if(!isset($dest[$id])){
$dest[$id]=1;
}else {
$dest[$id]++;
}
$src[$id]--;
if ($src[$id]==0) {
unset($src[$id]);
}
}
$_SESSION['armadio']= $src ;
$_SESSION['valigia'] = $dest;
}
//rimuove da valigia e punta ad armadio
function remove($id)
{
// sposta l'elemento identificato dall'indice $id dall'array sorgente al destinatario
$src=$_SESSION['valigia'];
$dest=$_SESSION['armadio'];
// controlla che ci sia l'elemento origine
if (isset($src[$id])){
if(!isset($dest[$id])){
$dest[$id]=1;
}else {
$dest[$id]++;
}
$src[$id]--;
}
if ($src[$id]==0) {
unset($src[$id]);
}
$_SESSION['valigia']= $src ;
$_SESSION['armadio'] = $dest;
}
function display()
{
$abiti=get_abiti();
echo "<br>armadio";
$data=$_SESSION['armadio'];
echo "<ul>";
foreach($data as $abito=>$qta){
echo "<li>" . $abiti[$abito]['nome'] . " $qta <a href=\"?action=move&id=$abito\">Sposta giù</a> </li>";
}
echo "</ul>";
echo "valigia";
$data= $_SESSION['valigia'];
echo "<ul>";
foreach($data as$abito=>$qta){
echo "<li>" . $abiti[$abito]['nome'] . " $qta <a href=\"?action=remove&id=$abito&out=1\">Sposta su</li>";
}
echo "</ul>";
}
function create_valigia()
{
global $config;
return $config['valigia'];
}
function create_armadio()
{
global $config;
return $config['armadio'];
}
function debug()
{
echo "<pre>";
print_r($_SESSION);
}
function before(){
//se è settata la var reset, resetta la sessione e la fa ripartire
if(isset($_GET['reset'])){
session_destroy();
boot();
}
}
function get_max(){
global $config;
return $config['max'];
}
function get_size($data){
$tot=0;
foreach ($data as $qta) {
$tot+=$qta;
}
return $tot;
}
function get_abiti(){
global $config;
return $config['abiti'];
}
function get_max_vol(){
global $config;
return $config['max_vol'];
}
function is_valigia_full($abito,$valigia,$max_vol){
//somma i volumi di tutti gli abiti nella valigia e il nuovo abito da inserire
// e confronta il totale con il valore di max_vol
/*Controlla che tutto funzioni:
print_r($abito);
print_r($valigia);
return 0; ----->sempre true
die;*/
$abiti=get_abiti();
$tot_vol=$abiti[$abito]['volume'];
foreach ($valigia as $key => $value) {
$tot_vol +=$abiti[$abito]['volume'] * $value;
}
if($tot_vol >$max_vol){
return 1;
}
return 0;
}
<file_sep><?php
session_start();
echo "session_id: " . session_id();
echo "SID: ". SID;
<file_sep><?php
//include link per mostrare conuenuto sessione
?>
<!-- <pre> -->
<a href="print_session.php" target="_blank">stampa sessione</a></br>
<a href="?reset">reset della sessione</a></br>
<file_sep><?php
/* visualizza l'elenco degli elementi di due array, ad esempio gli abiti contenuti in un l'armadio e nella valigia,
e consente all'utente di selezionare cliccare su un abito dell'armadio spostandolo nella valigia.
al click su un abito la pagina viene ricaricata e mostra il contenuto dei due array aggiornato
la sessione è utilizzata per mantere il contenuto degli array tra le pagine
*/
// includi i file di configurazione e le funzioni
include "config/config.php";
include "functions/functions.php";
// avvia l'applicativo
$params= boot();
//include l' header
include "header.php";
//chiamo la funzione before()
before();
// controlla che cosa devi fare
switch ($params['action']) {
case 'move':
$msg=move($params['id']);
break;
case 'remove':
remove($params['id']);
break;
default:
echo "";
break;
}
echo $msg;
display();
|
37b205f124efa13f1fee848e07df891970e12210
|
[
"PHP"
] | 5
|
PHP
|
andreamathieu1992/move_array
|
23e5a14db060006b3d691e88129e8b2fe4613fae
|
259a1fdccde9288c944ebe235368436a7e485328
|
refs/heads/master
|
<repo_name>REABMAX/voodoo-module<file_sep>/src/Contracts/ConfigurationProvider.php
<?php
namespace Voodoo\Module\Contracts;
/**
* Interface ConfigurationProvider
* @package Voodoo\Module\Contracts
*/
interface ConfigurationProvider extends ModuleInterface
{
/**
* @return array
*/
public function configuration(): array;
}<file_sep>/src/Contracts/ModuleInterface.php
<?php
namespace Voodoo\Module\Contracts;
use Psr\Container\ContainerInterface;
/**
* Interface ModuleInterface
* @package Voodoo\Module\Contracts
*/
interface ModuleInterface
{
/**
* Perform some system bootstrap logic defined by this module using a service locator
* (the only part of a module where the service locator pattern is allowed)
* @param ContainerInterface $container
* @return mixed
*/
public function bootstrap(ContainerInterface $container);
}<file_sep>/tests/NewModuleResolverTest.php
<?php
namespace Voodoo\Module\Tests;
use Voodoo\Module\Contracts\ModuleInterface;
use Voodoo\Module\Exception\ModuleConfigurationException;
use Voodoo\Module\NewModuleResolver;
use Voodoo\Module\Tests\Example\ExampleModule;
use Voodoo\Module\Tests\Example\ExampleNotAModule;
class NewModuleResolverTest extends \Codeception\Test\Unit
{
protected function _before()
{
}
protected function _after()
{
}
// tests
public function test_load_module_loads_module()
{
$resolver = new NewModuleResolver();
$module = $resolver->loadModule(ExampleModule::class);
$this->assertNotEmpty($module);
$this->assertInstanceOf(ModuleInterface::class, $module);
}
public function test_load_module_throws_exception_on_class_is_not_a_module()
{
$resolver = new NewModuleResolver();
$this->expectException(ModuleConfigurationException::class);
$resolver->loadModule(ExampleNotAModule::class);
}
}<file_sep>/src/Contracts/EventProvider.php
<?php
namespace Voodoo\Module\Contracts;
/**
* Interface EventProvider
* @package Voodoo\Module\Contracts
*/
interface EventProvider extends ModuleInterface
{
/**
* Return event configuration array for this module
* @return array
*/
public function events(): array;
}<file_sep>/src/ContainerModuleResolver.php
<?php
namespace Voodoo\Module;
use Psr\Container\ContainerInterface;
use Voodoo\Module\Contracts\ModuleInterface;
use Voodoo\Module\Contracts\ModuleResolverInterface;
use Voodoo\Module\Exception\ModuleConfigurationException;
/**
* Class ContainerModuleLoader
* @package Voodoo\Module
*/
class ContainerModuleResolver implements ModuleResolverInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* ContainerModuleLoader constructor.
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @param string $fqdn
* @return ModuleInterface
* @throws ModuleConfigurationException
*/
public function loadModule(string $fqdn): ModuleInterface
{
$this->assertModuleExists($fqdn);
$module = $this->container->get($fqdn);
$this->assertModuleIsInstanceOfModuleInterface($module);
return $module;
}
/**
* @param string $fqdn
* @throws ModuleConfigurationException
*/
protected function assertModuleExists(string $fqdn)
{
if(!$this->container->has($fqdn)) {
throw new ModuleConfigurationException(printf("Module class %s could not be fetched by the container.", $fqdn));
}
}
/**
* @param mixed $module
* @throws ModuleConfigurationException
*/
protected function assertModuleIsInstanceOfModuleInterface($module)
{
if(false === $module instanceof ModuleInterface) {
throw new ModuleConfigurationException(printf("Module %s must be an instance of %s!", get_class($module), ModuleInterface::class));
}
}
}<file_sep>/src/ModuleManager.php
<?php
namespace Voodoo\Module;
use Psr\Container\ContainerInterface;
use Voodoo\Module\Contracts\ConfigurationProvider;
use Voodoo\Module\Contracts\DiProvider;
use Voodoo\Module\Contracts\EventProvider;
use Voodoo\Module\Contracts\MiddlewareProvider;
use Voodoo\Module\Contracts\ModuleInterface;
use Voodoo\Module\Contracts\ModuleResolverInterface;
use Voodoo\Module\Contracts\ModuleManagerInterface;
use Voodoo\Module\Contracts\RouteProvider;
/**
* Class ModuleManager
* @package Voodoo\Module
*/
class ModuleManager implements ModuleManagerInterface
{
/**
* @var array
*/
protected $configuration = [];
/**
* @var ModuleResolverInterface
*/
protected $loader;
/**
* @var array
*/
protected $modulesCache = [];
/**
* ModuleManager constructor.
* @param array $configuration
* @param ModuleResolverInterface $loader
*/
public function __construct(array $configuration, ModuleResolverInterface $loader)
{
$this->configuration = $configuration;
$this->loader = $loader;
}
/**
* @return array
*/
public function getContainerConfiguration(): array
{
$modules = $this->loadModules();
$containerConfiguration = [];
/** @var ModuleInterface $module */
foreach ($modules as $module) {
if ($module instanceof DiProvider) {
$containerConfiguration = array_merge_recursive($containerConfiguration, $module->di());
}
}
return $containerConfiguration;
}
/**
* @return array
*/
public function getModuleConfiguration(): array
{
$modules = $this->loadModules();
$moduleConfiguration = [];
/** @var ModuleInterface $module */
foreach ($modules as $module) {
if ($module instanceof ConfigurationProvider) {
$moduleConfiguration = array_merge_recursive($moduleConfiguration, $module->configuration());
}
}
return $moduleConfiguration;
}
/**
* @return array
*/
public function getEventConfiguration(): array
{
$modules = $this->loadModules();
$eventConfiguration = [];
/** @var ModuleInterface $module */
foreach ($modules as $module) {
if ($module instanceof EventProvider) {
$eventConfiguration = array_merge_recursive($eventConfiguration, $module->events());
}
}
return $eventConfiguration;
}
/**
* @return array
*/
public function getRouterConfiguration(): array
{
$modules = $this->loadModules();
$routerConfiguration = [];
/** @var ModuleInterface $module */
foreach ($modules as $module) {
if ($module instanceof RouteProvider) {
$routerConfiguration = array_merge($routerConfiguration, $module->routes());
}
}
return $routerConfiguration;
}
/**
* @return array
*/
public function getMiddlewareConfiguration(): array
{
$modules = $this->loadModules();
$middlewareConfiguration = [];
/** @var ModuleInterface $module */
foreach ($modules as $module) {
if ($module instanceof MiddlewareProvider) {
$middlewareConfiguration = array_merge($middlewareConfiguration, $module->middleware());
}
}
return $middlewareConfiguration;
}
/**
* @inheritdoc
*/
public function bootstrapModules(ContainerInterface $container)
{
$modules = $this->loadModules();
/** @var ModuleInterface $module */
foreach($modules as $module) {
$this->callModuleBootstrap($module, $container);
}
}
/**
* @param ModuleInterface $module
* @param ContainerInterface $container
*/
protected function callModuleBootstrap(ModuleInterface $module, ContainerInterface $container)
{
$module->bootstrap($container);
}
/**
* @param bool $useCache
* @return array
*/
protected function loadModules(bool $useCache = true): array
{
if (!$useCache || empty($this->modulesCache)) {
$modules = [];
if(!empty($this->configuration)) {
foreach($this->configuration as $fqcn) {
$modules[] = $this->loader->loadModule($fqcn);
}
}
if ($useCache) {
$this->modulesCache = $modules;
}
return $modules;
}
return $this->modulesCache;
}
}<file_sep>/src/Contracts/MiddlewareProvider.php
<?php
namespace Voodoo\Module\Contracts;
/**
* Interface MiddlewareProvider
* @package Voodoo\Module\Contracts
*/
interface MiddlewareProvider extends ModuleInterface
{
/**
* @return array
*/
public function middleware(): array;
}<file_sep>/tests/ContainerModuleResolverTest.php
<?php
namespace Voodoo\Module\Tests;
use Psr\Container\ContainerInterface;
use Voodoo\Module\ContainerModuleResolver;
use Voodoo\Module\Contracts\ModuleInterface;
use Voodoo\Module\Exception\ModuleConfigurationException;
use Voodoo\Module\Tests\Example\ExampleModule;
use Voodoo\Module\Tests\Example\ExampleNotAModule;
class ContainerModuleResolverTest extends \Codeception\Test\Unit
{
protected function _before()
{
}
protected function _after()
{
}
// tests
public function test_load_module_loads_module()
{
$containerMock = $this->makeEmpty(ContainerInterface::class, [
'get' => function() { return new ExampleModule(); },
'has' => function() { return true; }
]);
$resolver = new ContainerModuleResolver($containerMock);
$module = $resolver->loadModule(ExampleModule::class);
$this->assertNotEmpty($module);
$this->assertInstanceOf(ModuleInterface::class, $module);
}
public function test_load_module_throws_exception_on_class_is_not_a_module()
{
$containerMock = $this->makeEmpty(ContainerInterface::class, [
'get' => function() { return new ExampleNotAModule(); },
'has' => true,
]);
$resolver = new ContainerModuleResolver($containerMock);
$this->expectException(ModuleConfigurationException::class);
$resolver->loadModule(ExampleNotAModule::class);
}
}<file_sep>/src/NewModuleResolver.php
<?php
namespace Voodoo\Module;
use Voodoo\Module\Contracts\ModuleInterface;
use Voodoo\Module\Contracts\ModuleResolverInterface;
use Voodoo\Module\Exception\ModuleConfigurationException;
/**
* Class NewModuleLoader
* @package Voodoo\Module
*/
class NewModuleResolver implements ModuleResolverInterface
{
/**
* @param string $fqcn
* @return ModuleInterface
* @throws ModuleConfigurationException
*/
public function loadModule(string $fqcn): ModuleInterface
{
$this->assertModuleExists($fqcn);
$module = new $fqcn();
$this->assertModuleIsInstanceOfModuleInterface($module);
return $module;
}
/**
* @param string $fqcn
* @throws ModuleConfigurationException
*/
protected function assertModuleExists(string $fqcn)
{
if(!class_exists($fqcn)) {
throw new ModuleConfigurationException(printf("Module class %s does not exist.", $fqcn));
}
}
/**
* @param mixed $module
* @throws ModuleConfigurationException
*/
protected function assertModuleIsInstanceOfModuleInterface($module)
{
if(false === $module instanceof ModuleInterface) {
throw new ModuleConfigurationException(printf("Module %s must be an instance of %s!", get_class($module), ModuleInterface::class));
}
}
}<file_sep>/src/Contracts/DiProvider.php
<?php
namespace Voodoo\Module\Contracts;
/**
* Interface DiProvider
* @package Voodoo\Module\Contracts
*/
interface DiProvider extends ModuleInterface
{
/**
* Return dependency injection container configuration array for this module
* @return array
*/
public function di(): array;
}<file_sep>/tests/Example/ExampleNotAModule.php
<?php
namespace Voodoo\Module\Tests\Example;
/**
* Class ExampleNotAModule
* @package Voodoo\Module\Tests\Example
*/
class ExampleNotAModule
{
}<file_sep>/src/Contracts/ModuleResolverInterface.php
<?php
namespace Voodoo\Module\Contracts;
/**
* Interface ModuleLoaderInterface
* @package Voodoo\Module\Contracts
*/
interface ModuleResolverInterface
{
/**
* @param string $fqcn
* @return ModuleInterface
*/
public function loadModule(string $fqcn): ModuleInterface;
}<file_sep>/src/Contracts/RouteProvider.php
<?php
namespace Voodoo\Module\Contracts;
interface RouteProvider extends ModuleInterface
{
/**
* @return array
*/
public function routes(): array;
}<file_sep>/README.md
# voodoo-module
This package provides an implementation of the plugin pattern.
## Quick start
A module must implement `Voodoo\Module\Contracts\ModuleInterface` and/or implement one of the ProviderInterfaces specified in that
namespace.
The ModuleManager manages Modules and resolves them by using an implementation of `ModuleResolverInterface`
```php
<?php
$modules = [
FirstModule::class,
SecondModule::class,
];
$container = new DiContainer();
$resolver = new \Voodoo\Module\ContainerModuleResolver($container);
$moduleManager = new \Voodoo\Module\ModuleManager($modules, $resolver);
// calls di() method on modules implementing DiProvider
$diConfig = $moduleManager->getContainerConfiguration();
// calls routes() method on modules implementing RouteProvider
$routerConfig = $moduleManager->getRouterConfiguration();
// calls configuration() method on modules implementing ConfigurationProvider
$moduleConfig = $moduleManager->getModuleConfiguration();
// calls events() method on modules implementing EventProvider
$eventConfig = $moduleManager->getEventConfiguration();
// calls middleware() method on modules implementing MiddlewareProvider
$middleware = $moduleManager->getMiddlewareConfiguration();
// calls bootstrap($container) modules
$moduleManager->bootstrapModules($container);
```
This is what a module looks like:
```php
<?php
use Voodoo\Module\Contracts\DiProvider;
use Voodoo\Module\Contracts\RouteProvider;
use Voodoo\Module\Contracts\MiddlewareProvider;
class FirstModule implements DiProvider, RouteProvider, MiddlewareProvider
{
public function bootstrap(ContainerInterface $container)
{
// Some bootstrapping code for this module
}
public function di() : array
{
return [];
}
public function routes() : array
{
return [];
}
public function middleware() : array
{
return [];
}
}
```
<file_sep>/tests/Example/ExampleModule.php
<?php
namespace Voodoo\Module\Tests\Example;
use Psr\Container\ContainerInterface;
use Voodoo\Module\Contracts\ModuleInterface;
/**
* Class ExampleModule
* @package Voodoo\Module\Tests\Example
*/
class ExampleModule implements ModuleInterface
{
/**
* @param ContainerInterface $container
* @return mixed|void
*/
public function bootstrap(ContainerInterface $container)
{
//
}
}<file_sep>/src/Exception/ModuleConfigurationException.php
<?php
namespace Voodoo\Module\Exception;
/**
* Class ModuleConfigurationException
* @package Voodoo\Module\Exception
*/
class ModuleConfigurationException extends \Exception
{
}<file_sep>/src/Contracts/ModuleManagerInterface.php
<?php
namespace Voodoo\Module\Contracts;
use Psr\Container\ContainerInterface;
/**
* Interface ModuleManagerInterface
* @package Voodoo\Module\Contracts
*/
interface ModuleManagerInterface
{
/**
* @return array
*/
public function getContainerConfiguration(): array;
/**
* @return array
*/
public function getEventConfiguration(): array;
/**
* @return array
*/
public function getRouterConfiguration(): array;
/**
* @return array
*/
public function getModuleConfiguration(): array;
/**
* @return array
*/
public function getMiddlewareConfiguration(): array;
/**
* @param ContainerInterface $container
* @return mixed
*/
public function bootstrapModules(ContainerInterface $container);
}
|
1c1fa5dabfcfc6e5d30ccec018489fab92f34fea
|
[
"Markdown",
"PHP"
] | 17
|
PHP
|
REABMAX/voodoo-module
|
1fafa22d22875a4bba753ab30a4223bf9ef46a5f
|
9567edcfae430223555cdde0ef554e8bce157048
|
refs/heads/master
|
<repo_name>antoniotorres/hackernews<file_sep>/pages/api/posts.ts
import { NextApiRequest, NextApiResponse } from "next";
import { HNPost } from "../../types/post";
export default async (req: NextApiRequest, res: NextApiResponse) => {
const response = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json",
);
const data = await response.json();
if (!Array.isArray(data)) {
console.log("HN Response:", data);
throw new Error("Bad Respnse from Hacker News API");
}
const posts = data as string[];
const postsFiltered = posts.slice(0, 30);
const postsWithData = await Promise.all(
postsFiltered.map(async (post) => {
const response = await fetch(
`https://hacker-news.firebaseio.com/v0/item/${post}.json`,
);
const data = await response.json();
if (data.by === undefined) {
throw new Error("Bad Respnse from Hacker News API");
}
return data as HNPost;
}),
);
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.send(postsWithData);
};
|
f465f51e4bc8d48c8f0491d802b36c3230e3e662
|
[
"TypeScript"
] | 1
|
TypeScript
|
antoniotorres/hackernews
|
524bc399d163fd0c4af1ed227991982aabe76389
|
67ec15673e19c00bc726b9edcfa2534aba34faa5
|
refs/heads/master
|
<repo_name>russplaysguitar/wtf<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :load_current_user
private
def load_current_user
@current_user = User.find_by_id(session[:user_id])
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def is_current_user(user)
@current_user == user
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_secure_password
attr_accessible :username, :password, :password_confirmation
validates :username, :presence => true,
:uniqueness => {:case_sensitive => false},
:format => { :with => /\A\w+\Z/, :message => "is invalid"}
validates :password, :presence => true,
:length => { :in => 6..255 }
has_many :questions
has_many :answers
has_many :comments
end
<file_sep>/app/models/comment.rb
class Comment < ActiveRecord::Base
attr_accessible :description
belongs_to :user
belongs_to :question
belongs_to :answer
has_many :votes
end
<file_sep>/app/models/answer.rb
class Answer < ActiveRecord::Base
attr_accessible :description, :is_right
belongs_to :user
belongs_to :question
has_many :comments
has_many :votes
end
<file_sep>/db/migrate/20121209184549_change_default_on_answers.rb
class ChangeDefaultOnAnswers < ActiveRecord::Migration
def change
change_column_default(:answers, :is_right, false)
end
end
<file_sep>/app/models/vote.rb
class Vote < ActiveRecord::Base
attr_accessible :answer_id, :comment_id, :question_id, :user_id
belongs_to :user
belongs_to :question
belongs_to :answer
belongs_to :comment
end
<file_sep>/README.md
# WTF: A basic question & answer website
This is going to be a lot like Stack Overflow. It is still very much in progress, so don't even think about trying to actually use it or contribute. <file_sep>/app/models/question.rb
class Question < ActiveRecord::Base
attr_accessible :description, :title
belongs_to :user
has_many :answers
has_many :comments
has_many :taggings
has_many :tags, :through => :taggings
has_many :votes
end
<file_sep>/app/models/tagging.rb
class Tagging < ActiveRecord::Base
attr_accessible :name
belongs_to :question
belongs_to :tag
end
<file_sep>/app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
# GET /questions
# GET /questions.json
def index
if params[:unanswered]
@questions = Question.includes("answers").where(answers: {question_id: nil}).order("questions.created_at DESC")
else
@questions = Question.order("created_at DESC")
end
@tags = Tag.order("name")
respond_to do |format|
format.html # index.html.erb
format.json { render json: @questions }
end
end
# GET /questions/1
# GET /questions/1.json
def show
@question = Question.find(params[:id])
@answer = Answer.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @question }
end
end
def search
q = params[:q].upcase
questions = Question.where("upper(title) LIKE '%"+q.to_s+"%' OR upper(description) LIKE '%"+q.to_s+"%'")
answers = Answer.where("upper(description) LIKE '%"+q.to_s+"%'")
@questions = questions + answers.map {|a| a.question}
@questions.uniq!
end
# GET /questions/new
# GET /questions/new.json
def new
if !@current_user
redirect_to root_path
end
@question = Question.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @question }
end
end
# GET /questions/1/edit
def edit
@question = @current_user.questions.find(params[:id])
if !@question
redirect_to :action => "show", :id => params[:id]
end
end
# POST /questions
# POST /questions.json
def create
if !@current_user
redirect_to root_path
end
@question = @current_user.questions.build(params[:question])
@question.user_id = @current_user.id
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render json: @question, status: :created, location: @question }
else
format.html { render action: "new" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
# PUT /questions/1
# PUT /questions/1.json
def update
@question = @current_user.questions.find(params[:id])
respond_to do |format|
if @question.update_attributes(params[:question])
format.html { redirect_to @question, notice: 'Question was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
@question = @current_user.questions.find(params[:id])
@question.destroy
respond_to do |format|
format.html { redirect_to questions_url }
format.json { head :no_content }
end
end
end
<file_sep>/app/controllers/taggings_controller.rb
class TaggingsController < ApplicationController
def create
question = Question.find(params[:question_id])
if question.tags.where(:name => params[:tag][:name]).empty?
tag = Tag.find_or_create_by_name(params[:tag][:name])
begin
question.tags.push(tag)
rescue
flash[:notice] = "Error creating tag"
end
end
redirect_to question_path(question)
end
def destroy
question = @current_user.questions.find_by_id(params[:question_id])
tagging = question.taggings.find_by_id(params[:id])
tagging.destroy
redirect_to question_path(question)
end
end
|
8c8981d2d87bf6007e707fa17b9b48de8fe8acd1
|
[
"Markdown",
"Ruby"
] | 12
|
Ruby
|
russplaysguitar/wtf
|
3d5dc854061919ad7010b501635ba5776e154f17
|
5352521617bb3ae5cc48bd7d510693ce5f539e2e
|
refs/heads/master
|
<repo_name>xckoo/opsys2<file_sep>/README.md
# opsys2
炫彩新版管理端
可配置化应用页面
后端docker部署
<file_sep>/mysite/mysite/opsys.ini
[uwsgi]
socket = 127.0.0.1:8989
workers = 1
wsgi-file=wsgi.py
chdir=/data/docker/xckoo_site/mysite/mysite
daemonize=uwsgi.log
<file_sep>/mysite/opsys/utils/makeconx.py
#encoding:utf-8
import os,sys
import json
import commands
import make_plug
reload(sys)
sys.setdefaultencoding('utf8')
CONFPATH = os.path.join( os.path.dirname(os.path.dirname(__file__)),'conf','html_conf.json' )
NOTICEPATH = os.path.join( os.path.dirname(os.path.dirname(__file__)),'conf','notice.json' )
PhoneBookPATH = os.path.join( os.path.dirname(os.path.dirname(__file__)),'conf','phoneBook.json' )
def gen_html(list_info):
html_code = ''
for i, line in enumerate(list_info):
if line['type'] == 'input':
html_code = html_code + make_plug.gen_input(line)
elif line['type'] == 'select':
html_code = html_code + make_plug.gen_select(line)
elif line['type'] == 'sumbit':
html_code = html_code + make_plug.gen_sumbit(line)
elif line['type'] == 'textarea':
html_code = html_code + make_plug.gen_textarea(line)
elif line['type'] == 'checkbox':
html_code = html_code + make_plug.gen_checkbox(line)
elif line['type'] == 'svrselect':
html_code = html_code + make_plug.gen_svrselect(line)
elif line['type'] == 'date':
html_code = html_code + make_plug.gen_date(line)
elif line['type'] == 'html':
html_code = '+!+html+!+';
else:
html_code = html_code + '找不到匹配的type : %s' % line['type']
return html_code
def get_json(appid):
jsons = json.load(file(CONFPATH))
conf = jsons[int(appid)]
return conf
def conx(appid):
form_list = []
conf = get_json(appid)
for item in conf['form']:
form_list.append(item)
html_code = gen_html(form_list)
return conf['name'], html_code, conf['js']
def get_json_list():
jsons = json.load(file(CONFPATH))
return jsons
def get_notice_json():
jsons = json.load(file(NOTICEPATH))
return jsons
def get_phonebook_json():
jsons = json.load(file(PhoneBookPATH))
return jsons
if __name__ == '__main__':
print NOTICEPATH
print CONFPATH
get_notice_json()
#get_json_list()
<file_sep>/mysite/opsys/static/resources/plugin/jQuery.jWaterfall-loader-0.0.1.js
/*
* jQuery-jWaterfall-0.0.1.js
* name:<NAME>
* email:<EMAIL>
* qq:273142650
* time:2012/12.30 20:58
*
* this.宝贝在洗衣服,哈哈哈哈
*/
"use strict";
jQuery.extend({
jWaterfall: {
data: {
listSelected: null,
list: null,
urlFn: null,
config: null,
page: 0,
state: 0
},
init: function (list, urlFn, config) {
if ($(list).size() <= 0) {
return;
}
$(config.loading).hide();
this.setDefault(list, urlFn, config);
this.isScroll();
},
templateInit: function (config) {
this.setTemplateDefault(config);
this.columnSize();
this.getMargin();
this.setContainerWidth();
this.templateShow();
},
columnSize: function () {
var size = parseInt($(document.body).width() / this.templateData.itemWidth);
for (var i = 0; i < size; i++) {
this.templateData.columnList.push({
height: 0,
size: 0
});
}
},
getSmallColumn: function () {
var column = this.templateData.columnList;
var height = column[0].height;
var index = 0;
for (var i = 0; i < column.length; i++) {
if (column[i].height < height) {
height = column[i].height;
index = i;
}
}
return index;
},
getMargin: function () {
var margin = this.templateData.margin.split(/\s+/ig);
var array = ['top', 'right', 'bottom', 'left'];
var marginArray = {};
for (var i = 0; i < margin.length; i++) {
marginArray[array[i]] = margin[i];
}
switch (margin.length) {
case 1:
for (var i = 1; i < array.length; i++) {
marginArray[array[i]] = margin[0];
}
break;
case 2:
marginArray.bottom = margin[0];
marginArray.left = margin[1];
break;
case 3:
marginArray.left = margin[1];
break;
}
for (var e in marginArray) {
marginArray[e] = parseInt(marginArray[e]);
}
this.templateData.margin = marginArray;
},
setContainerWidth: function () {
var margin = this.templateData.margin;
var container = $(this.templateData.container);
var width = this.templateData.itemWidth;
var size = this.templateData.columnList.length;
container.css('width', (width * size + (margin.left + margin.right) * size) + 'px');
},
setContainerHeight: function () {
var maxHeight = 0;
var height = this.templateData.colnumList;
var container = $(this.templateData.container);
container.css('height', maxHeight + 'px');
},
templateShow: function () {
var temp = $(this.templateData.template);
this.addItem(temp.clone());
this.addItem(temp.clone());
this.addItem(temp.clone());
this.addItem(temp.clone());
this.addItem(temp.clone());
this.addItem(temp.clone());
},
addItem: function (template) {
var container = $(this.templateData.container);
var smallColumn = this.getSmallColumn();
var template = template.appendTo(container);
this.setPosition(template, smallColumn);
this.setContainerHeight();
},
setPosition: function (template, index) {
var column = this.templateData.columnList[index];
var margin = this.templateData.margin;
var itemWidth = this.templateData.itemWidth;
var itemTop = column.height + margin.top;
var itemLeft = itemWidth + margin.left;
if (column.size > 0) {
itemTop += margin.bottom;
}
if (index > 0) {
itemLeft += margin.right;
}
template.css({
top: itemTop + 'px',
left: itemLeft * index + 'px'
});
column.height += this.getItemHeight(template);
column.size++;
},
getItemHeight: function (itemData) {
var images = this.templateData.images;
var itemData = itemData.clone().hide().appendTo(this.templateData.container);
itemData.find(images).hide();
var height = itemData.height();
itemData.find(images).each(function () {
height += parseInt($(this).attr('height'));
});
return height;
},
setTemplateDefault: function (config) {
for (var e in config) {
this.templateData[e] = config[e];
}
},
setDefault: function (list, urlFn, config) {
if (typeof config.scope == 'undefined') {
config.scope = $(window);
}
this.data.listSelected = list;
this.data.list = $(list);
this.data.urlFn = urlFn;
this.data.config = config;
if (typeof this.data.config.data == 'undefined') {
this.data.config.data = {}
}
},
isScroll: function () {
var list = this.data.list;
var urlFn = this.data.urlFn;
var config = this.data.config;
var _this = this;
var scope = $(config.scope);
scope.scroll(function () {
var short = _this.getShort(list).height;
if (scope.scrollTop() >= short + config.tuning) {
if (_this.data.state == 0) {
_this.loadData(urlFn);
}
}
});
},
loadData: function () {
var urlFn = this.data.urlFn;
$(this.data.config.loading).show();
if (typeof urlFn == 'function') {
this.data.state = 1;
urlFn($.jWaterfall, this.data.page++, this.data.config.data);
}
},
setHtml: function (htmlArray) {
for (var i = 0; i < htmlArray.length; i++) {
var dom = this.getShort(this.data.list).dom;
if (typeof this.data.config.toFind != 'undefined') {
dom = dom.find(this.data.config.toFind);
}
$(htmlArray[i]).appendTo(dom).hide().fadeIn(500);
}
this.data.state = 0;
$(this.data.config.loading).hide();
},
getShort: function (list) {
var dom = list.eq(0);
var list = this.data.list;
var height = list.eq(0).height() + list.eq(0).offset().top - $(window).height();
list.each(function () {
var thisHeight = $(this).height() + $(this).offset().top - $(window).height();
if (thisHeight < height) {
height = thisHeight;
dom = $(this);
}
});
return {height: height, dom: dom};
},
load: function (list, urlFn, config) {
this.init(list, urlFn, config);
},
template: function (config) {
this.templateInit(config);
}
}
});<file_sep>/mysite/collectedstatic/resources/template/default/resources/service/jPushDocumentReady.js
/*
* jPushLanguage.js
* name:<NAME>
* email:<EMAIL>
* qq:27314265d0
* time:2012.4.10 16:27
*/
function AutoHideAlert(ret, str){
var note = $("#note");
note.html("");
note.removeClass("alert-success");
note.removeClass("alert-danger");
if (ret == 0){
note.addClass("alert-success");
$("<strong>Well done!</strong>").appendTo('#note');
}else{
note.addClass("alert-danger");
$("<strong>Danger!</strong>").appendTo('#note');
}
note.append(str);
var nowwidth = parseInt(note.css("width").split("px")[0]) + 40;
var notepos = ($(window).width() - nowwidth) / 2 + 'px';
note.css({display:'block', top:'-50px', 'left':notepos}).animate({top:'+50', opacity:1}, 200, function(){
setTimeout(out, 800);
});
}
function out(){
$("#note").animate({opacity:0, top:0}, 250, function(){
$(this).css({display:'none', top:'-50px'});
});
}
$(document).ready(
function () {
jPushInit.SelectVer();
}
);
function HtmlInit(){
jPush.loadingData.templateData.all = 4;
jPushLanguage.load();
jPush.loadingSuccess('templateData');
jPushApplication.getAppList();
jPush.loadingSuccess('templateData');
jPushInit.init();
jQuery.jLayer.getTemplate();
jPush.loadingSuccess('templateData');
jPushApplication.contextmenu();
jPush.loadingSuccess('templateData');
jPushInit.ie6PNG();
}
<file_sep>/mysite/collectedstatic/resources/template/default/resources/service/jPushPlugin.js
/*
* jPushPlugin.js
* name:<NAME>
* email:<EMAIL>
* qq:273142650
* time:2012.8.8 9:51
*/
jPushPlugin = {
data: {
menuData: null
},
init: function (def) {
this.menu(def);
},
systemSetInit: function () {
this.updateUserInfo();
this.userInfoEvent();
},
updateUserInfo: function () {
var body = $('.system-body');
jPushUser.refresh();
body.find('select:[name=defaultScreen] option:[value=' +this.getUserInfo('screen') + ']').attr('selected', true);
body.find(':radio:[name=defaultSearch]:[value="' + this.getUserInfo('searcher') + '"]').attr('checked', true);
},
userInfoEvent: function () {
var _this = this;
var body = $('.system-body');
var defaultScreen = body.find('select:[name=defaultScreen]');
var defaultSearch = body.find(':radio:[name=defaultSearch]');
defaultScreen.on('change', function () {
var screen = $("#defaultscreen").val();
$.ajax({
type : 'POST',
url : '/SetUserScreen/',
dataType:'json',
data : {screen:screen},
success: function(data, status){
AutoHideAlert(data.ret, data.msg);
}
});
});
defaultSearch.on('click', function () {
var searcher = $(this).val();
$.ajax({
url : '/SetUserSearch/',
data: {search: searcher},
type: 'POST',
dataType : 'json',
success: function(data, status){
jPushInit.SetSearch(searcher);
AutoHideAlert(data.ret, data.msg);
}
});
});
},
getUserInfo: function (key) {
if (key == 'screen')
return parseInt(jPushUser.userInfo().screen) + 1;
return jPushUser.userInfo()[key];
},
menuLang: function () {
var lang = jPushDefaultLanguage;
$('#PluginMenu_Theme div').html(lang.plugin.theme);
},
menuScrollBar: function () {
jQuery.jScroll.load('#application-center .applic-menu-list', {
margin: 'auto 0px 0 0'
});
},
bodyScrollBar: function () {
jQuery.jScroll.load('#application-center .applic-body');
},
menu: function (def) {
this.getMenuData();
this.menuEvent();
this.menuLang();
this.defaultMenu(def);
},
defaultMenu: function (def) {
if (typeof def != 'undefined') {
$('#PluginMenu_' + def).click();
} else {
$('#application-center .applic-menu-list ul li:eq(0) div').click();
}
},
menuEvent: function () {
var _this = this;
var time = 400;
var menuList = $('#application-center .applic-menu-list ul li:[class!=space]');
menuList.click(
function (e) {
if ($(e.target).is('span.less div')) {
return;
}
$('.applic-menu-title').html($(this).find('div:eq(0)').html());
$('div.active').removeClass('active');
$(this).find('div:eq(0)').addClass('active');
$('span.less').stop();
$('span.less').slideUp(time);
$(this).find('span.less').stop();
$(this).find('span.less').slideDown(time);
$('span.less div').removeClass('bold');
setTimeout(_this.menuScrollBar, time + 10);
}
);
menuList.find('span.less div').click(
function () {
$('span.less div').removeClass('bold');
$(this).addClass('bold');
}
);
$('#PluginMenu_Theme').click(
function () {
_this.getThemeList();
}
);
},
setApp: function (obj, screen) {
var state = false;
if (jPushUser.userState() == 200) {
var lang = jPushDefaultLanguage;
var id = $('#application_' + obj['id'] + '_list');
if (id.size() > 0) {
screen = id.parent().index() + 1;
$.jLayer.alert(lang.alert.addApp.replace(/{num}/ig, screen));
return;
}
pos = screen + 1;
//$.post(jPushTemplate.getUserData('addUserApp'), {appID: obj['id'], screen: screen});
$.ajax({
type: 'POST',
url: '/AddApp/',
data:{game:game, area:area, device:device, pos:pos, appid:obj['id']},
dataType: 'json',
async: false,
success: function (datas, status) {
AutoHideAlert(datas.ret, datas.msg);
if (datas.ret == 0)
{
screen = $('#app-main ul').eq(screen);
jPushApplication.setApp(obj, screen, pos);
state = true;
}
}
});
} else {
jPushInit.login();
}
return state;
},
appContextmenu: function (list, obj) {
var _this = this;
var lang = jPushDefaultLanguage;
list.click(
function (e) {
_this.setApp(obj, jPushInit.data.defaultScreen);
var id = 'jPush_ApplicationCenter';
$('#'+id+' .jqe-ui-jLayer-layer-head-fn-close').click();
$('.more-app').click();
}
);
jQuery.jContextmenu.load(list, 'contextmenu', [
[lang.plugin.addApp, function (th) {
th.click();
} ],
[lang.plugin.addAppTo, [
[jPushDefaultLanguage.contextmenu.screen1, function () {
_this.setApp(obj, 0);
} ],
[jPushDefaultLanguage.contextmenu.screen2, function () {
_this.setApp(obj, 1);
} ],
[jPushDefaultLanguage.contextmenu.screen3, function () {
_this.setApp(obj, 2);
} ],
[jPushDefaultLanguage.contextmenu.screen4, function () {
_this.setApp(obj, 3);
} ],
[jPushDefaultLanguage.contextmenu.screen5, function () {
_this.setApp(obj, 4);
} ]
]]
]);
},
getApplication: function (data) {
var list, obj, tr, tdSize;
var _this = this;
var wh = 80;
$.ajax({
type: 'POST',
url: '/GetAppList/',
data:{game:game, area:area, device:device},
dataType: 'json',
beforeSend: function () {
_this.beforeSend();
},
success: function (datas, status) {
var applist = datas.appList;
_this.newData();
if (applist.length == 0){
$('<h4 style="text-align:center; margin-top:200px;">木有应用可以添加了...</h4>').appendTo('.applic-body-data');
}
for (i = 0; i < applist.length; i++){
obj = applist[i];
if (obj['ico'] == '' || typeof obj['ico'] == 'undefined') {
obj['ico'] = '/static/img/application.png';
}
list = $('<li class="app-center-td" title="' + obj['title'] + '"><span class="hide">'+obj['searchname']+'</span><div class="applic-theme-img"><img src="' + obj['ico'] + '" width="' + wh + '" height="' + wh + '" /></div><div class="applic-theme-tit">' + obj['name'] + '</div><div class="applic-theme-explain">' + '2015-03-26 11:12:00' + '</div></li>').appendTo('.applic-body-data');
jPushPlugin.drawImage(list.find('img'), wh, wh, wh, wh);
_this.appContextmenu(list, obj);
}
_this.success();
$("#app-search").hideseek();
}
});
},
menuClick: function (obj, key, type) {
var _this = this;
obj.on('click', function (e) {
if (e.target == this) {
_this.getApplication({key: key, type: type});
}
});
},
menuData: function () {
var _this = this;
var xmlData = this.data.menuData.children('add');
var li, name, key;
var less, lessli, lessKey, lessName;
var menuList = $('#application-center .applic-menu-list ul li.space:last');
xmlData.each(
function () {
name = $(this).attr('name');
key = $(this).attr('key');
type = $(this).attr('menutype');
if (typeof name == 'undefined' && typeof key == 'undefined') {
$('<li class="space"></li>').insertBefore(menuList);
} else {
li = $('<li id="PluginMenu_' + key + '"><div>' + name + '</div></li>').insertBefore(menuList);
_this.menuClick(li.find('div'), key, type);
less = $(this).find('add');
if (less.size() > 0) {
less = $('<span class="less"></span>').appendTo(li);
$(this).find('add').each(
function () {
lessKey = $(this).attr('key');
lessName = $(this).attr('name');
lessType = $(this).attr('menutype');
lessli = $('<div id="PluginMenu_' + lessKey + '">' + lessName + '</div>').appendTo(less);
_this.menuClick(lessli, lessKey, lessType);
}
);
}
}
}
);
_this.menuScrollBar();
},
getMenuData: function () {
var _this = this;
$.ajax({
type: 'GET',
url: jPushTemplate.getXmlData('PluginMenu'),
async: false,
cache: false,
dataType: 'xml',
success: function (xmlHttp) {
_this.data.menuData = $(xmlHttp).find('PluginMenu');
_this.menuData();
}
});
},
drawImage: function (dom, width, height, fitWidth, fitHeight) {
if (width > 0 && height > 0) {
if (width / height >= fitWidth / fitHeight) {
if (width > fitWidth) {
$(dom).css('width', fitWidth + 'px');
$(dom).css('height', (height * fitWidth) / width + 'px');
} else {
$(dom).css('width', width + 'px');
$(dom).css('height', height + 'px');
}
} else {
if (height > fitHeight) {
$(dom).css('height', fitHeight + 'px');
$(dom).css('width', (width * fitHeight) / height + 'px');
} else {
$(dom).css('width', width + 'px');
$(dom).css('height', height + 'px');
}
}
}
},
beforeSend: function () {
$('.applic-beforeSend').fadeTo(300, 0.35);
},
success: function () {
$('.applic-beforeSend').fadeTo(300, 0, function () {
$(this).hide();
});
$('#application-center .applic-body').scrollTop(0);
this.bodyScrollBar();
},
newData: function () {
var body = $('#application-center .applic-body');
body.find('.applic-body-data').remove();
body.append('<ul class="applic-body-data"></ul>');
},
setTheme: function (list) {
list.bind('click',
function () {
jPushInit.data.theme.href = $(this).find('img').attr('class');
jPushInit.data.theme.width = $(this).find('img').attr('width');
jPushInit.data.theme.height = $(this).find('img').attr('height');
jPushInit.createTheme();
jPushInit.setUserTheme();
}
);
},
ThemeContextmenu: function (list) {
var lang = jPushDefaultLanguage;
jQuery.jContextmenu.load(list, 'contextmenu', [
[lang.themeMenu.set, function (obj) {
$(obj).click();
} ]
]);
},
getThemeList: function () {
var list, obj, tr;
var _this = this;
$.ajax({
type: 'GET',
url: jPushTemplate.getXmlData('ThemeData'),
dataType: 'xml',
beforeSend: function () {
_this.beforeSend();
},
success: function (xmlHttp) {
_this.newData();
$(xmlHttp).find('xmlData ThemeList add').each(
function () {
obj = $(this);
if (obj.index() % 3 == 0) {
tr = $('<tr></tr>').appendTo('.applic-body-data');
}
list = $('<td class="app-center-td" title="' + obj.attr('name') + '"><div class="applic-theme-img"><img src="' + obj.attr('thumbnail') + '" width="' + obj.attr('width') + '" height="' + obj.attr('height') + '" class="' + obj.attr('url') + '" /></div><div class="applic-theme-tit">' + obj.attr('name') + '</div><div class="applic-theme-explain">' + obj.attr('explain') + '</div></td>').appendTo(tr);
jPushPlugin.drawImage(list.find('img'), obj.attr('width'), obj.attr('height'), 207, 100);
list.find('img').show();
_this.setTheme(list);
_this.ThemeContextmenu(list);
}
);
tdSize = $('.applic-body-data').find('tr:last td').size();
if (tdSize < 3) {
for (var i = 0; i < 3 - tdSize; i++) {
$('.applic-body-data').find('tr:last').append('<td></td>');
}
}
_this.success();
}
});
}
}
<file_sep>/mysite/opsys/views/tools.py
#coding:utf-8
from django.shortcuts import render
from opsys.models.models import *
from opsys.utils.utils import *
from django.shortcuts import render_to_response
from django.template import loader, RequestContext
from django.contrib import auth
from django.contrib.auth.models import User
from opsys.utils import makeconx
from views import getcommpara
import sys
import os
import paramiko
import logging
def rl_logging(str):
logger = logging.getLogger('django')
logger.error(str)
def ssh_cmd(ip,port,cmd,user,passwd):
str = u"ip:%s cmd:%s" % (ip,cmd)
rl_logging(str)
result = ""
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,user,passwd,timeout=5)
stdio,stdout,stderr = ssh.exec_command(cmd.encode('utf-8'))
result = stdout.read()
ssh.close()
result = result.replace("\t", " ")
result = result.replace("\n", "<br>")
return 0,result
except Exception as e:
return -1,'ssh_cmd error'
def GetSvrInfo(request, onlyflag):
ret,game,area,device = getcommpara(request)
if not ret:
return ret ,'获得公共参数失败'
objlist = ServerList.objects.filter(game=game, area=area, onlyflag=onlyflag)
if len(objlist) > 1:
return -1, '数据库信息出错, 唯一数据记录:%d' % len(objlist)
return 0, objlist[0]
def GetGlobalInfo(request):
ret,game,area,device = getcommpara(request)
if not ret:
return ret ,'获得公共参数失败'
onlyflag = '%s_%s' % (game, area)
objlist = ServerList.objects.filter(game=game, area=area, onlyflag=onlyflag)
if len(objlist) > 1:
return -1, '数据库信息出错, 唯一数据记录:%d' % len(objlist)
return 0, objlist[0]
def GetDevInfo(request):
ret,game,area,device = getcommpara(request)
if not ret:
return ret ,'获得公共参数失败'
onlyflag = '%s_%s_d' % (game, area)
objlist = ServerList.objects.filter(game=game, area=area, onlyflag=onlyflag)
if len(objlist) > 1:
return -1, '数据库信息出错, 唯一数据记录:%d' % len(objlist)
return 0, objlist[0]
def GetPlayerInfoByUID(request):
try:
onlyflag = request.POST['onlyflag']
uid = request.POST['uid']
except:
return JsonResponse({'ret':-1, 'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/get_user %s %s %s' % (pt, areaid, uid)
ret,msg = ssh_cmd(svrinfo.outip, 22, cmd, svrinfo.user, svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def GetPlayerInfoByName(request):
try:
onlyflag = request.POST['onlyflag']
username = request.POST['username']
except:
return JsonResponse({'ret':-1, 'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/get_user_by_name %s %s %s' % (username, pt, areaid)
ret,msg = ssh_cmd(svrinfo.outip, 22, cmd, svrinfo.user, svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def Award(request):
try:
username = request.POST['username']
onlyflag = request.POST['serverid']
type = request.POST['type']
count = request.POST['count']
except:
return JsonResponse({'ret':-1, 'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
area = tmplist[1]
int_value = int(count)
#int_serverid = int(serverid)
int_serverid = len(tmplist)
allnames = username.split('\n')
returnmsg = '<br/>'
sendmailmsg = ''
cmd = ''
if len(allnames) > 20:
return JsonResponse({'ret':-1,'msg':u'一次性最多20个'})
if len(allnames) > 2 and type == '1' and int_value > 3000:
return JsonResponse({'ret':-1,'msg':u'批量增加元宝不得超过3000个'})
for oneuser in allnames:
if type == '0':
if int_value < 0 or int_value > 3000:
if int_serverid < 3:
return JsonResponse({'ret':-1,'msg':u'元宝非法'})
cmd = '/data/tool/add_cash_no_log %s %s %s %s' % (oneuser,count,pt,area)
if int_value >= 10 and int_serverid < 3:
sendmailmsg += u"为 %s 充值 %d 元宝,请注意!操作人:%s\n" % (oneuser,int_value,request.user.username)
elif type == '1':
if int_value < 0 or int_value > 50000:
return JsonResponse({'ret':-1,'msg':u'数目非法'})
cmd = '/data/tool/add_coin_no_log %s %s %s %s' % (oneuser,count,pt,area)
elif type == '2':
if int_value < 0 or int_value > 200:
return JsonResponse({'ret':-1,'msg':u'数目非法'})
try:
propid = request.POST['propid']
except:
return JsonResponse({'ret':-1,'msg':u'请传入道具id'})
int_val = int(propid)
if int_val < 0 or int_val > 40:
return JsonResponse({'ret':-1,'msg':u'道具id非法:%s'%int_val})
cmd = '/data/tool/add_shopbag %s %s %s %s %s' % (oneuser,propid,count,pt,area)
ret,msg = ssh_cmd(svrinfo.outip, 22, cmd, svrinfo.user, svrinfo.passwd)
if ret != 0:
returnmsg += u'用户名:[%s]失败:%d-%s\n' % (ret,msg)
else:
returnmsg += u'<br/>用户名:[%s] msg:%s' % (oneuser,msg)
#这里判断系统消息
if 'msg' in request.POST and request.POST['msg']:
cmd_msg = '/data/tool/add_sys_msg %s %s %s %s' % (oneuser,request.POST['msg'],pt,area)
ret2,msg2 = ssh_cmd(ip,22,cmd_msg,'root',passwd)
if type == '1' and int_serverid < 3:
send_mail(u'%s批量元宝%d 充值人数:%d'%(request.user.first_name,int_value,len(allnames)),sendmailmsg.encode('utf-8'))
return JsonResponse({'ret':0,'msg':returnmsg})
def GetPwd(request):
try:
username = request.POST['username']
except:
return JsonResponse({'ret':-1,'msg':u'请传入username'})
ip="127.0.0.1"
passwd = '<PASSWORD>'
cmd= '/root/get_xkuser %s' % username
ret,msg = ssh_cmd(ip,22,cmd,'root',passwd)
return JsonResponse({'ret':ret,'msg':msg})
def ChangePwd(request):
try:
name = request.POST['name']
newpwd = request.POST['newpwd']
except:
return JsonResponse({'ret':-1,'msg':u'请输入所需字段'})
ip='127.0.0.1'
passwd = '<PASSWORD>'
cmd = '/data/tool/change_pwd %s %s' % (name,newpwd)
ret,msg = ssh_cmd(ip,22,cmd,'root',passwd)
return JsonResponse({'ret':ret,'msg':msg})
def QueryTotal(request):
try:
username = request.POST['username']
needdate = request.POST['needdate']
onlyflag = request.POST['serverid']
except:
return JsonResponse({'ret':-1,'msg':u'请传入所需数据'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/get_order_byname %s %s %s' % (pt,areaid,username)
ret,msg = ssh_cmd(svrinfo.outip, 22, cmd, svrinfo.user, svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def ConvertTxt(msg):
msg = msg.replace("[type:1|",u"[type:招募消耗")
msg = msg.replace("[type:2|",u"[type:道具消耗")
msg = msg.replace("[type:3|",u"[type:礼包消耗")
msg = msg.replace("[type:4|",u"[type:复活消耗")
msg = msg.replace("[type:5|",u"[type:闯关消耗")
msg = msg.replace("[type:6|",u"[type:国家宝藏")
msg = msg.replace("[type:7|",u"[type:财神消耗")
msg = msg.replace("[type:8|",u"[type:抢夺官职")
msg = msg.replace("[type:9|",u"[type:国战宣战")
msg = msg.replace("[type:10|",u"[type:竞技cd")
msg = msg.replace("[type:11|",u"[type:玩摇钱树")
msg = msg.replace("[type:12|",u"[type:全局聊天")
msg = msg.replace("[type:13|",u"[type:大大转盘")
msg = msg.replace("[type:14|",u"[type:vip礼包")
msg = msg.replace("[type:15|",u"[type:转国消耗")
msg = msg.replace("[type:16|",u"[type:刮刮乐乐")
msg = msg.replace("[type:17|",u"[type:自动国战")
msg = msg.replace("[type:18|",u"[type:购买生命")
msg = msg.replace("[type:19|",u"[type:购买连击")
msg = msg.replace("[type:20|",u"[type:限购礼包")
msg = msg.replace("[type:21|",u"[type:开百宝箱")
msg = msg.replace("[type:22|",u"[type:富豪活动")
msg = msg.replace("[type:23|",u"[type:忍者培养")
msg = msg.replace("[type:24|",u"[type:pve官邸")
msg = msg.replace("[type:25|",u"[type:边境之战")
msg = msg.replace("[type:26|",u"[type:跨服门票")
msg = msg.replace("[type:27|",u"[type:跨服押宝")
msg = msg.replace("[type:28|",u"[type:跨服激励")
msg = msg.replace("[type:29|",u"[type:立即合成")
msg = msg.replace("[type:30|",u"[type:神秘商店")
return msg
def CashLog(request):
try:
username = request.POST['username']
needdate = request.POST['needdate']
onlyflag = request.POST['onlyflag']
except:
return JsonResponse({'ret':-1,'msg':u'请传入所需数据'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
#获得uid
ip = svrinfo.outip
cmd = '/data/tool/nickinfonew %s %s %s' % (username,pt,areaid)
ret,msg = ssh_cmd(ip,22,cmd,svrinfo.user,svrinfo.passwd)
if ret != 0 :
return JsonResponse({'ret':ret,'msg':msg})
if msg.find("error") == 0:
return JsonResponse({'ret':-1,'msg':u'用户名不存在'})
msg = msg.replace('\n','')
msg = msg.replace('\r','')
msg = msg.replace('<br>','')
id=msg
cmd = '/data/tool/get_cashlog.sh %s %s' % (msg,needdate)
ret,msg = ssh_cmd(ip,22,cmd,svrinfo.user,svrinfo.passwd)
msg = msg.replace("\n","<br/>")
msg = "<br/>"+msg
#msg = msg.split("rpt")[0]
msg = ConvertTxt(msg)
msg = msg.replace("[%s]"%id,"")
msg = msg.replace("|rpt","---")
msg = msg.replace("|rsvr","")
msg = msg.replace("][","--")
msg = msg.replace("|","--")
msg = msg.replace("subtype:","--")
msg = msg.replace("count:1","")
msg = msg.replace("amount:",u"--数目:")
msg = msg.replace("type:","-")
msg = msg.replace("%s"%needdate,"")
return JsonResponse({'ret':ret,'msg':msg})
def AddCard(request):
try:
username = request.POST['username']
cardtype = str(int(request.POST['cardtype'])+1)
cardid = request.POST['cardid']
exp = request.POST['exp']
starlevel = request.POST['starlevel']
newlife = request.POST['newlife']
onlyflag = request.POST['onlyflag']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/add_card_byname %s %s %s %s %s %s %s %s' % (username,cardtype,cardid,pt,areaid,exp,starlevel,newlife)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
#if ret == 0:
#send_mail(u"%s正式服加卡%s" % (request.user.username,cardid),u"为 %s 加卡 id:%s,type:%s,exp:%s,starlevel:%s,newlife:%s,请注意!操作人:%s" % (username,cardid,cardtype,exp,starlevel,newlife,request.user.username))
return JsonResponse({'ret':ret,'msg':msg})
def GenCode(request):
try:
serverid = request.POST['serverid']
type = request.POST['type']
count = request.POST['count']
game = request.POST['game']
area = request.POST['area']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
int_value = int(count)
if int_value <= 0 or int_value >50000:
return JsonResponse({'ret':-1,'msg':u'数目非法'})
int_value = int(type)
if (int_value <=0):
return JsonResponse({'ret':-1,'msg':u'类型非法'})
onlyflag = '%s_%s' % (game, area)
if int(serverid) == '0': #测试服
onlyflag = '%s_d' % onlyflag
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = ''
if int(serverid) == 0: #测试服
cmd = '/data/tool/GenInvite %s %s %s %s' % (pt,areaid,type,count)
elif int(serverid) == 1:
cmd = '/data/tool/GenGlobalInvite %s %s' % (type,count)
ret,msg=ssh_cmd(svrinfo.outip, 22, cmd,svrinfo.user, svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def GambleGet(request):
try:
onlyflag = request.POST['onlyflag']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/get_gambleconf %s %s' % (pt,areaid)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def FengHao(request):
try:
onlyflag = request.POST['onlyflag']
name = request.POST['name']
type = request.POST['type']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/set_closeuser_byname %s %s %s %s' % (name,pt,areaid,type)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def AddExp(request):
try:
onlyflag = request.POST['onlyflag']
name = request.POST['name']
val = request.POST['val']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
if int(val) < 1 or int(val)>100000:
return JsonResponse({'ret':-1,'msg':u'经验值必须在1到10w之间'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/add_exp_by_name %s %s %s %s' % (pt,areaid,name,val)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def SetVip(request):
try:
onlyflag = request.POST['onlyflag']
name = request.POST['name']
score = request.POST['score']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
if int(score) < 1 or int(score)>2000000:
return JsonResponse({'ret':-1,'msg':u'积分必须在1到200w之间'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/set_vipinfo_byname %s %s %s %d' % (pt,areaid,name,score)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def AddCumulate(request):
try:
onlyflag = request.POST['onlyflag']
username = request.POST['username']
num = request.POST['num']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/add_pay_cumu_sum_byname %s %s %s %s' % (pt,areaid,username,num)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def AddFlower(request):
try:
onlyflag = request.POST['onlyflag']
username = request.POST['username']
num = request.POST['num']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/add_flower_by_name %s %s %s %s' % (pt,area,username,num)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def CheckMaxId(request):
try:
onlyflag = request.POST['onlyflag']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/get_max_id %s %s' % (pt,areaid)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def CheckSvrTime(request):
servertime = ''
try:
optype = request.POST['optype']
if optype != '1':
servertime = request.POST['servertime']
servertime = servertime.replace(" ", "\ ")
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetDevInfo(request)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
cmd = '/data/tool/check_servertime.sh %s %s' % (optype, servertime)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
msg = msg.replace("\n", "<br/>")
msg = "<br/>"+msg
return JsonResponse({'ret':ret,'msg':msg})
def ResetChap(request):
try:
onlyflag = request.POST['onlyflag']
username = request.POST['username']
chapid = request.POST['chapid']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
ret, svrinfo = GetSvrInfo(request, onlyflag)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
tmplist = onlyflag.split("_")
pt = tmplist[0]
areaid = tmplist[1]
cmd = '/data/tool/set_chapworld %s %s 1 1 2 %s %s' % (username,chapid,pt,areaid)
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
def PubCsv(request):
try:
server_type = request.POST['server_type']
group_type = request.POST['group_type']
restart = request.POST['restart']
csvfile = request.POST['csvfile']
except:
return JsonResponse({'ret':-1,'msg':'请传入正确参数'})
group = 'ios'
restartdes = 'norestart'
if group_type == '1':
group = 'and'
if group_type == '2':
group = 'apple'
if restart == '1':
restartdes = 'restart'
ret, svrinfo = GetDevInfo(request)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': svrinfo})
filename = '/data/release/renlong/csv/' + csvfile
if server_type=='0':
csvpath = '/data/home/publish_csv/update_csvdev.sh'
else:
csvpath = '/data/home/publish_csv/update_csvidc.sh'
cmd = "%s %s %s %s" % (csvpath, group, restartdes, csvfile )
ret,msg = ssh_cmd(svrinfo.outip,22,cmd,svrinfo.user,svrinfo.passwd)
return JsonResponse({'ret':ret,'msg':msg})
<file_sep>/mysite/opsys/views/views.py
#coding:utf-8
from django.shortcuts import render
from opsys.models.models import *
from opsys.utils.utils import *
from django.shortcuts import render_to_response
from django.template import loader, RequestContext
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect,Http404
from opsys.utils import makeconx
import sys
#GAME_RENLONG = 1
GAME_MAP = {'1':'renlong', '2':'gulong'}
GAME_MAP_CN = {'1':u'火影', '2':u'古龙'}
#AREA_GUONEI = 1
AREA_MAP = {'1':'ch', '2':'tw', '3':'yn', '4':'th', '5':'rzwd', '6':'yw'}
AREA_MAP_CN = {'1':u'简中', '2':u'台湾', '3':u'越南', '4':u'泰国', '5':u'忍者无敌', '6':u'英文'}
#DEVICE_YUEYU = 1
#DEVICE_AND = 2
DEVICE_MAP = {'1':'and','2':'ios', '3':'app', '4':'mix', '5':'wp'}
DEVICE_MAP_CN = {'1':u'安卓','2':u'越狱', '3':u'正版', '4':u'混服', '5':u'微软'}
def get_right_str(game,area,device):
if game not in GAME_MAP:
return False,''
if area not in AREA_MAP:
return False,''
if device not in DEVICE_MAP:
return False,''
right_str = '%s_%s_%s' % (game,area,device)
return True, right_str
def get_rights_str(game,area,device,rights):
if game not in GAME_MAP:
return False,''
if area not in AREA_MAP:
return False,''
if device not in DEVICE_MAP:
return False,''
right_str = "%s_%s_%s_%s" % (GAME_MAP[game],AREA_MAP[area], DEVICE_MAP[device], rights)
return True,right_str
def checklogin(view):
def new_view(request, *args, **kwargs):
if not request.user.is_authenticated():
return render_to_response('login.html')
return view(request,*args,**kwargs)
return new_view
def logout(request):
auth.logout(request)
return HttpResponseRedirect("/")
def getcommpara(request):
try:
game = request.POST['game']
area = request.POST['area']
device = request.POST['device']
except:
return False,None,None,None
return True,game,area,device
def checkloginandright(view,rightstr):
def new_view(request, *args, **kwargs):
if not request.user.is_authenticated():
return JsonResponse({'ret':-1, 'msg':u'未登录'})
#return render_to_response('login.html')
#return view(request,*args,**kwargs)
try:
game = request.POST['game']
area = request.POST['area']
device = request.POST['device']
except:
return JsonResponse({'ret':-1, 'msg':u'对不起,参数错误,请联系伟大哥!!'})
#两级权限,先判断一级权限
ret, top_right = get_right_str(game,area,device)
#ret = False
if not ret:
return JsonResponse({'ret':-1, 'msg':u'对不起,该权限尚未开通'})
userrightlist = UserRight.objects.filter(userid=request.user)
if len(userrightlist) == 0:
return JsonResponse({'ret':-1, 'msg':u'对不起,此用户暂无权限信息,请联系伟大哥'})
myright = userrightlist[0]
topright_list = []
for onetopright in myright.right.all():
topright = onetopright.right.replace(" ", "")
topright_list.append(topright)
if top_right in topright_list:
pass
else:
return JsonResponse({'ret':-1, 'msg':'您无此一级权限,请联系伟大哥'})
#下面判断二级细分权限
ret, sed_right = get_rights_str(game,area, device, rightstr)
if not ret:
return JsonResponse({'ret':-1,'msg':u'对不起,该细分权限出错'})
grouplist = []
for group in request.user.groups.all():
grouplist.append(group.name)
if sed_right in grouplist:
pass
else:
return JsonResponse({'ret':-1,'msg':'您无此细分权限,请联系伟大哥'})
return view(request,*args,**kwargs)
return new_view
def login(request):
try:
username = request.POST['username']
pwd = request.POST['<PASSWORD>']
except:
return JsonResponse({'ret':-1,'msg':u'参数错误!'})
user = auth.authenticate(username=username,password=pwd)
if user is not None and user.is_active:
auth.login(request,user)
return JsonResponse({'ret':0, 'msg':u'登陆成功'})
return JsonResponse({'ret':-1,'msg':u'密码错误'})
#获取用户相关信息
def userInfo(request):
myscreen = 3
mysearcher = ''
mylastlogin = ''
str_cn = ''
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
myscreen = myprefer.screen
mysearcher = myprefer.searcher
if myprefer.lastlogin: #如果已存储了最后一次登录地区
ret, topright_list = getTopRight(request.user)
if not ret:
return JsonResponse({'ret':-1, 'msg':topright_list})
#判断该记录是否还有权限登录
if myprefer.lastlogin in topright_list:
mylastlogin = myprefer.lastlogin
str_cn = getGAD_cn(mylastlogin);
if myscreen not in [1,2,3,4,5]:
return JsonResponse({'ret':-1,'msg': u'后台数据出错,screen:%s' % defaultscreen})
return JsonResponse({'ret':0,'screen': myscreen - 1, 'searcher':mysearcher, 'lastlogin':mylastlogin,'str_cn':str_cn, 'username':request.user.username})
# 分割game,area,device组成中文返回
def getGAD_cn(str):
items = str.split("_")
game = items[0]
area = items[1]
device = items[2]
str_cn = '%s_%s_%s' % (GAME_MAP_CN[game], AREA_MAP_CN[area],DEVICE_MAP_CN[device])
return str_cn
def getTopRight(user):
userrightlist = UserRight.objects.filter(userid=user)
if len(userrightlist) == 0:
return False, u'对不起,此用户暂无权限信息,请联系伟大哥'
myright = userrightlist[0]
topright_list = []
for onetopright in myright.right.all():
topright_list.append(onetopright.right)
return True, topright_list
#获取用户可使用的权限
def SelectRight(request):
try:
islogin = request.POST['islogin']
except:
return JsonResponse({'ret':-1, 'msg':u'传入参数有误..'})
ret, topright_list = getTopRight(request.user)
if not ret:
return JsonResponse({'ret':-1, 'msg':topright_list})
strCode = ''
for top_right in topright_list:
top_right = top_right.replace(" ", "")
str_cn = getGAD_cn(top_right);
#如果只有一个地区且是登录时请求,直接返回地区编码,不用选择
if len(topright_list) == 1 and islogin == 'true':
return JsonResponse({'ret':1, 'str':topright_list[0],'str_cn':str_cn})
option = '<option value="%s">%s</option>\n'
strCode += option % (top_right, str_cn)
return JsonResponse({'ret':0,'options':strCode})
def savelastlogin(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
#存储用户最新选择的版本
lastlogin = '%s_%s_%s' % (game, area, device)
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
if not myprefer:
myprefer =UserPreference(userid=request.user, lastlogin=lastlogin)
else:
myprefer.lastlogin = lastlogin
myprefer.save()
return JsonResponse({'ret':0, 'msg':'lastlogin:%s' % myprefer.lastlogin})
#获取用户应用列表
def getmyapplist(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
myapplist = MyAppList.objects.filter(userid=request.user, game=game,area=area, device=device)
applist = {'0':[], '1':[], '2':[], '3':[], '4':[], '5':[]}
for appitem in myapplist:
tmplist = []
if appitem.allapp != '':
tmplist = appitem.allapp.split('_')
pos = '%s' % appitem.position
applist[pos] = tmplist
retlist = {}
for keystr in applist:
tmpapplist = []
for i in applist[keystr]:
app = {}
conf = makeconx.get_json(i)
app['id'] = conf['id']
app['ico'] = conf['ico']
app['title'] = conf['title']
app['name'] = conf['name']
tmpapplist.append(app)
retlist[keystr] = tmpapplist
return JsonResponse({'ret':0,'content':retlist})
def showbox(request):
try:
conf = makeconx.get_notice_json()
except:
return JsonResponse({'ret':-1, 'msg':'conf配置文件出错'})
if int(conf['show']) == 0:
return JsonResponse({'ret':-1, 'msg':u'无需显示'})
return JsonResponse({'ret':0, 'conf':conf })
#添加应用
def addapp(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
try:
pos = request.POST['pos']
appid = request.POST['appid']
except:
return JsonResponse({'ret':-1,'msg':u'请传入正确的参数'})
posint = int(pos)
if posint < 0 or posint > 5:
return JsonResponse({'ret':-1, 'msg':u'pos参数越界'})
ret, myapp, newappstr = logic_addapp(request.user, game, area, device, posint, appid)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': newappstr})
#保存
if not myapp:
myapp = MyAppList(userid=request.user, game=game, area=area, device=device, position=pos, allapp=newappstr)
myapp.save()
else:
myapp.allapp = newappstr
myapp.save()
conf = makeconx.get_json(appid)
return JsonResponse({'ret':0, 'msg':u'添加应用"%s"成功!' % conf['name']})
def logic_addapp(user, game, area, device, posint, appid):
myapplist = MyAppList.objects.filter(userid=user,game=game,area=area,device=device, position=posint)
myapp = None
if len(myapplist):
myapp = myapplist[0]
allappstr = ''
if myapp:
allappstr = myapp.allapp
allapp = []
newapp = []
if allappstr != '':
allapp = allappstr.split('_')
newapp = allapp
if appid in allapp:
return -1, myapp, '此应用已经添加'
newapp.append(appid)
newappstr = '_'.join(newapp)
return 0, myapp, newappstr
def logic_removeapp(user, game, area, device, posint, appid):
myapplist = MyAppList.objects.filter(userid=user,game=game,area=area,device=device, position=posint)
myapp = None
if len(myapplist):
myapp = myapplist[0]
allappstr = ''
if myapp:
allappstr = myapp.allapp
else:
return -1, myapp, '无应用可删除'
allapp = []
newapp = []
if allappstr != '':
allapp = allappstr.split('_')
newapp = []
for myid in allapp:
if int(appid) != int(myid):
newapp.append(myid)
if len(newapp) == len(allapp):
return -1, myapp, '此应用未添加,不需要删除'
newappstr = ''
if len(newapp):
newappstr = '_'.join(newapp)
return 0, myapp, newappstr
#删除应用
def removeapp(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
try:
pos = request.POST['pos']
appid = request.POST['appid']
except:
return JsonResponse({'ret':-1,'msg':u'请传入正确的参数'})
posint = int(pos)
if posint < 0 or posint > 5:
return JsonResponse({'ret':-1, 'msg':u'pos参数越界'})
ret,myapp, newappstr = logic_removeapp(request.user, game, area, device, posint, appid)
if ret != 0:
return JsonResponse({'ret':ret, 'msg':newappstr})
#保存
myapp.allapp = newappstr
myapp.save()
conf = makeconx.get_json(appid)
return JsonResponse({'ret':0, 'msg':u'删除应用"%s"成功!' % conf['name']})
def moveapp(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
try:
from_pos = request.POST['from_pos']
to_pos = request.POST['to_pos']
appid = request.POST['appid']
except:
return JsonResponse({'ret':-1,'msg':u'请传入正确的参数'})
from_posint = int(from_pos)
to_posint = int(to_pos)
if from_posint == to_posint:
return JsonResponse({'ret':-1, 'msg':u' 操作有误,不能移动到同一屏幕'})
if from_posint < 0 or from_posint > 5 or to_posint < 0 or to_posint > 5:
return JsonResponse({'ret':-1, 'msg':u'pos参数越界'})
ret,from_myapp, from_newappstr = logic_removeapp(request.user, game, area, device, from_posint, appid)
if ret != 0:
return JsonResponse({'ret':ret, 'msg':from_newappstr})
ret, to_myapp, to_newappstr = logic_addapp(request.user, game, area, device, to_posint, appid)
if ret != 0:
return JsonResponse({'ret':ret, 'msg': to_newappstr})
#删除保存
from_myapp.allapp = from_newappstr
from_myapp.save()
#增加保存
if not to_myapp:
to_myapp = MyAppList(userid=request.user, game=game, area=area, device=device, position=to_pos, allapp=to_newappstr)
to_myapp.save()
else:
to_myapp.allapp = to_newappstr
to_myapp.save()
conf = makeconx.get_json(appid)
return JsonResponse({'ret':0, 'msg':u'移动应用"%s"至屏幕%d成功' % (conf['name'], to_posint)})
#得到应用市场
def getapplist(request):
ret,game,area,device = getcommpara(request)
if not ret:
return JsonResponse({'ret':-1,'msg':u'获得公共参数失败'})
savedlist = [] #已添加应用id列表
myapplist = MyAppList.objects.filter(userid=request.user, game=game,area=area, device=device)
for appitem in myapplist:
tmplist = []
if appitem.allapp != '':
tmplist = appitem.allapp.split('_')
for item in tmplist:
savedlist.append(int(item))
applist = []
jsons = makeconx.get_json_list()
for i, item in enumerate(jsons):
if i == 0:
continue
if int(item['id']) in savedlist: #若已添加则不出现在应用市场上
continue
app = {}
app['ico'] = item['ico']
app['title'] = item['title']
app['id'] = item['id']
app['searchname'] = item['search']
app['name'] = item['name']
applist.append(app)
return JsonResponse({'ret':0, 'appList':applist})
def comm_get(request):
try:
game = request.GET['game']
area = request.GET['area']
device = request.GET['device']
except:
return False,None,None,None
return True,game,area,device
#获取每个应用的页面
def getoneapp(request):
ret, game, area, device = comm_get(request)
if not ret:
return JsonResponse({'ret':-1,'msg':'请传入公共参数'})
try:
appid = int(request.GET['appid'])
except:
return JsonResponse({'ret':-1,'msg':'请传入应用id'})
name, strCode, js = makeconx.conx(appid)
commstr = 'var game=%s;var area=%s; var device=%s;' % (game, area, device)
js = '%s%s' % (commstr, js)
tmp_option = '<option value="0">svrlist</option>'
if tmp_option in strCode:
ret, slcode = makesvrlist(request)
if not ret:
return render_to_response('app_admin.html',{'name':name, 'form_group':slcode, 'js':js}, context_instance=RequestContext(request))
strCode = strCode.replace(tmp_option, slcode)
ishtml = '+!+html+!+'
if ishtml in strCode:
strCode = strCode.replace(ishtml, '')
html = 'app_%d.html' % appid
return render_to_response(html,{'name':name, 'form_group':strCode, 'js':js}, context_instance=RequestContext(request))
return render_to_response('app_admin.html',{'name':name, 'form_group':strCode, 'js':js}, context_instance=RequestContext(request))
def getphonebook(request):
try:
conf = makeconx.get_phonebook_json()
except:
return JsonResponse({'ret':-1, 'msg':'conf配置文件出错'})
strcode = ''
for item in conf:
tmpstr = '''
<li class="namebox">
<img src="%s">
<div class="name">%s<span class="hide">%s</span></div>
<div class="phone">%s</div>
</li>
'''
strcode += tmpstr % (item['src'],item['name'],item['search'],item['phone'])
return render_to_response('phonebook.html',{'li':strcode},context_instance=RequestContext(request))
#return JsonResponse({'ret':0, 'conf':conf })
def makesvrlist(request):
ret, game, area, device = comm_get(request)
if not ret:
return False, '获得公共参数失败'
objlist = ServerList.objects.filter(game=game, area=area)
strcode = ''
itemlist = []
for item in objlist:
if item.info in ['global', 'dev']: #页面不显示global和开发机的选项
continue
items = item.info.split(" ")
tt = items[0]
pos = int(items[1][:-1])
op_code = '<option value="%s">%s</option>' % (item.onlyflag, item.info)
itemlist.append([tt, pos, op_code])
itemlist = sorted(itemlist, key=lambda x:(x[0], x[1]))
for item in itemlist:
strcode = strcode + item[2]
return True, strcode
def GetUserScreen(request):
defaultscreen = 3;
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
defaultscreen = myprefer.screen
if defaultscreen not in [1,2,3,4,5]:
return JsonResponse({'ret':-1,'msg': u'后台数据出错,screen:%s' % defaultscreen})
return JsonResponse({'ret':0,'screen': defaultscreen - 1})
def SetUserScreen(request):
try:
screen = int(request.POST['screen'])
except:
return JsonResponse({'ret':-1, 'msg':u'无法获取设置的参数!'})
if screen not in [1,2,3,4,5]:
return JsonResponse({'ret':-1, 'msg':u'设置的屏幕参数错误,请检查'})
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
if not myprefer:
myprefer =UserPreference(userid=request.user, screen=screen)
else:
myprefer.screen = screen
myprefer.save()
return JsonResponse({'ret':0, 'msg':u'设置默认屏幕为%d成功!' % screen})
def GetUserSearch(request):
searcher = '';
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
searcher = myprefer.searcher
if not searcher:
return JsonResponse({'ret':-1, 'msg': '获取设置的搜索引擎失败'})
return JsonResponse({'ret':0,'searcher': searcher})
def SetUserSearch(request):
try:
search = request.POST['search']
except:
return JsonResponse({'ret':-1, 'msg':u'无法获取设置的参数!'})
prefer = UserPreference.objects.filter(userid=request.user)
myprefer = None
if len(prefer):
myprefer = prefer[0]
if not myprefer:
myprefer =UserPreference(userid=request.user, searcher=search)
else:
myprefer.searcher = search
myprefer.save()
return JsonResponse({'ret':0, 'msg':u'设置默认搜索引擎成功!'})
def index(request):
return render_to_response('index.html', context_instance=RequestContext(request))
<file_sep>/mysite/opsys/utils/utils.py
#coding:utf-8
import json
from django.http import HttpResponse
from django.db import models
import types
from decimal import *
from datetime import *
from math import ceil
def JsonResponse(val):
def _any(data):
ret = None
if type(data) is types.ListType:
ret = _list(data)
elif type(data) is types.DictType:
ret = _dict(data)
elif isinstance(data, Decimal):
ret = str(data)
elif isinstance(data,models.query.QuerySet):
ret = _list(data)
elif isinstance(data,models.Model):
ret = _model(data)
elif isinstance(data, datetime):
ret = data.strftime('%Y-%m-%d %H:%M:%S')
else:
ret = data
return ret
def _model(data):
ret = {}
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data,f.attname))
return ret
def _list(data):
ret = []
for v in data:
ret.append(_any(v))
return ret
def _dict(data):
ret = {}
for k,v in data.items():
ret[k] = _any(v)
return ret
ret = _any(val)
return HttpResponse(json.dumps(ret,ensure_ascii = False));
def dic2urlpar(dicval):
if type(dicval) is types.DictType:
if len(dicval) == 0:
return ''
ret = ''
for key,val in dicval.items() :
ret += str(key)
ret += '='
ret += val
ret += '_'
return ret[:-1]
else:
return dicval
def urlpar2dic(urlpar):
args = {}
parlist = urlpar.split('&')
for onepar in parlist:
pars = onepar.split('=')
if len(pars) != 2:
continue
args[pars[0]] = pars[1]
return args
#pagenum代表出现多少个页码
def getpagenum(all_count,one_page_count,current_page,pagenumber):
pagedict = {}
totle_page = int(ceil(all_count/one_page_count))
if totle_page == 0:
pagedict['close'] = True
return pagedict
pagedict['close'] = False
if current_page != 1 and current_page < totle_page + 1:
pagedict['hasprev'] = True
pagedict['prev'] = current_page - 1
if current_page != totle_page and current_page < totle_page:
pagedict['hasnext'] = True
pagedict['next'] = current_page + 1
#构建页码
if current_page < 1 or current_page > totle_page:
current_page = 1
number = [current_page]
page_front = current_page
page_back = current_page
while page_front > 1 or page_back < totle_page:
page_front = page_front - 1
page_back = page_back + 1
if page_front >= 1:
number.append(page_front)
if page_back <=totle_page:
number.append(page_back)
if len(number) >= pagenumber:
break
number.sort()
pagedict['pages'] = number
return pagedict
<file_sep>/mysite/collectedstatic/resources/template/default/resources/service/jPushApplication.js
/*
* jPushApplication.js
* name:<NAME>
* email:<EMAIL>
* qq:273142650
* time:2012.4.1 10:32 愚人节~
*/
var jPushApplication = {
debug: true,
data: {
nowApp: null,
applicationlist: null
},
refresh: function () {
this.data.applicationlist = null;
},
getWindow: function (windowID) {
return $(windowID).contents();
},
setApp: function (app, ul, pos) {
var id = 'application_' + app['id'] + '_list';
if (app['ico'] == '' || typeof app['ico'] == 'undefined') {
app['ico'] = '/static/img/application.png';
}
var dom = $('<li class="app-main-li" key="' + app['id'] + '" id="' + id + '" title="' + app['title'] + '"><div class="ico"><img src="' + app['ico'] + '"/></div><div class="tit-bg"></div><div class="tit-tx">' + app['name'] + '</div><div class="transparent"></div></li>').insertBefore(ul.find('.more-app'));
jQuery.jSwap.load(ul, dom);
jPushApplication.bind(dom, app, 2, pos);
},
moveApp: function (dom, to_screen, from_screen, appid) {
var state = jPushUser.userState();
if (state == 200) {
$.ajax({
type: 'POST',
url: '/MoveApp/',
dataType : 'json',
data:{game:game, area:area, device:device, from_pos:from_screen, to_pos:to_screen, appid:appid},
success : function (datas, status){
AutoHideAlert(datas.ret, datas.msg);
if (datas.ret == 0){
to_screen --;
$(dom).insertBefore($('#app-main ul').eq(to_screen).find('.more-app'));
}
}
});
} else {
jPushInit.login();
}
},
removeApp: function (dom, appid, pos) {
var state = jPushUser.userState();
if (state == 200) {
$.ajax({
type: 'POST',
url: '/RemoveApp/',
dataType : 'json',
data:{game:game, area:area, device:device, pos:pos, appid:appid},
success : function (datas, status){
AutoHideAlert(datas.ret, datas.msg);
if(datas.ret == 0){
dom.remove();
}
}
});
} else {
jPushInit.login();
}
},
moreApp: function (ul) {
var lang = jPushDefaultLanguage;
var dom = $('<li class="app-main-li more-app"><div class="ico"><img src="/static/resources/template/default/resources/style/images/more-app.png"/></div><div class="tit-bg"></div><div class="tit-tx">' + lang.moreApp + '</div><div class="transparent"></div></li>').appendTo(ul);
dom.on('click', function () {
jPushInit.applicationCenter();
});
},
getAppList: function () {
var appXml;
var ul;
var _this = this;
myscreen = this.getUserApps();
for (i = 1; i <= 5; i++){
pos = '' + i;
perscreen = myscreen[pos];
ul = $('<ul style="display:none;"></ul>').appendTo('#app-main');
_this.moreApp(ul);
for (j = 0; j < perscreen.length; j++){
_this.setApp(perscreen[j], ul, pos);
}
}
shortcut = myscreen['0'];
for (i= 0; i < shortcut.length; i++){
var dom;
var app = shortcut[i];
if (app['ico'] == '' || typeof app['ico'] == 'undefined') {
app['ico'] = '/static/img/application.png';
}
dom = $('<li class="app-menu-li" key="' + app['id'] + '" id="application_' + app['id'] + '_list" title="' + app['title'] + '"><div class="app-menu-ico"><img src="' + app['ico'] + '"/></div><div class="transparent"></div></li>').appendTo('#menu-left .app-list ul:eq(0)');
jPushApplication.bind(dom, app, 1, '0');
}
},
contextmenu: function () {
var _this = this;
var lang = jPushDefaultLanguage;
jQuery.jContextmenu.load(document.body, 'contextmenu', [
[lang.contextmenu.ShowDesktop, function () {
var domList = jQuery.jLayer.domList;
for (var val in domList) {
$('#' + val).hide();
}
} ],
[lang.theme, function () {
$('.oper-list .o4').click();
}, '|'],
[lang.operation, function () {
$('.oper-list .o3').click();
} ],
[lang.applicationcenter, function () {
jPushInit.screenMenuSet();
} ],
[lang.contextmenu.process, function () {
var layerData = {
id: 'jPush_SystemProcess',
title: lang.contextmenu.process,
MenuData: {
name: lang.contextmenu.process,
icon: jPushTemplate.getConfig().find('add:[key=SystemIcon]').attr('value')
},
width: '430px',
height: '570px',
minWidth: 430,
minHeight: 570
};
var url = jPushTemplate.getFilePages().find('plugin add:[key=process]').attr('value');
jPushApplication.getLayer(layerData, url);
}, '|'],
[lang.changeArea, function () {
jPushInit.SelectVer(false);
}],
[lang.logout, function () {
$.get('/logout/', function () {
location.reload();
});
} ],
[lang.about, function () {
msg = '欢迎 '+jPushUser.userName() +' 使用炫彩酷游管理端';
AutoHideAlert(0, msg);
}, '|']
]);
$(document).bind('click',
function () {
jQuery.jContextmenu.close(0);
}
);
},
bind: function (dom, app, type, pos) {
var _this = this;
var state = jPushUser.userState();
if (type != 1) {
var menuList = [
[jPushDefaultLanguage.contextmenu.open, function () {
dom.click();
} ]
];
menuList.push([jPushDefaultLanguage.contextmenu.move, [
[jPushDefaultLanguage.contextmenu.screen1, function () {
_this.moveApp(dom, 1, pos, app['id']);
} ],
[jPushDefaultLanguage.contextmenu.screen2, function () {
_this.moveApp(dom, 2, pos, app['id']);
} ],
[jPushDefaultLanguage.contextmenu.screen3, function () {
_this.moveApp(dom, 3, pos, app['id']);
} ],
[jPushDefaultLanguage.contextmenu.screen4, function () {
_this.moveApp(dom, 4, pos, app['id']);
} ],
[jPushDefaultLanguage.contextmenu.screen5, function () {
_this.moveApp(dom, 5, pos, app['id']);
} ]
]]);
menuList.push([jPushDefaultLanguage.contextmenu.uninstall, function () {
_this.removeApp(dom, app['id'], pos);
}]);
jQuery.jContextmenu.load(dom, 'contextmenu', menuList);
}
dom.bind('click',
function () {
if (state != 200) {
jPushInit.login();
} else {
var id = 'application_' + app['id'];
var _this = $(this);
var iframe, parent, url, layerData, key;
appConf = {
'src' : '/GetOneApp/',
'size' : '1',
'width' : '680px',
'height': '600px'
};
url = appConf['src'];
var hash = url.match(/#.*/ig);
url = url.replace(/#.*/ig, '');
if (url.search(/\?/ig) != -1) {
url += '&layerID=' + id;
} else {
url += '?layerID=' + id;
}
url += hash;
//url += '&appid=' + app.attr('id');
url += '&appid='+ app['id'] +'&game='+game + '&area='+area+'&device='+device ;
layerData = {
title: app['name'],
id: id,
MenuData: {
name: app['name'],
icon: app['ico']
}
}
for (key in appConf){
if (key != 'src')
{
layerData[key] = appConf[key];
}
}
jPushApplication.getLayer(layerData, url);
$('#'+id).css('display', 'none'); //配合加载应用页面高度调整,在应用页面display:block
}
}
);
},
getLayer: function (json, url, callback) {
json['close'] = function () {
jPushApplication.menu();
jPushApplication.hash('');
}
json['drag'] = function () {
jPushApplication.menu(json.id);
}
var MenuDataName = jPushDefaultLanguage.nullWindowName;
if (typeof json['title'] != 'undefined') {
MenuDataName = json['title'];
}
if (typeof json.MenuData == 'undefined') {
json.MenuData = {
name: MenuDataName,
icon: jPushTemplate.getConfig().find('add:[key=ApplicationIcon]').attr('value')
};
} else {
if (typeof json.MenuData.name == 'undefined' ) {
json.MenuData.name = MenuDataName;
}
if (typeof json.MenuData.icon == 'undefined') {
json.MenuData.icon = jPushTemplate.getConfig().find('add:[key=ApplicationIcon]').attr('value');
}
}
var box = $.jLayer.layer(json);
if (typeof box != 'object') {
return;
}
var body = box.find('.jqe-ui-jLayer-layer-body');
var success = function () {
box.find('.jqe-ui-jLayer-layer-body .loading').fadeOut(500, function () {
$(this).remove();
});
}
if (typeof json.windowID == 'undefined') {
var iframeID = json.id + '_iframe';
} else {
var iframeID = json.windowID;
}
if (url.search(/\?/ig) > -1) {
url += '&';
} else {
url += '?';
}
url += 'webosWindowID=' + iframeID;
if (typeof callback != 'undefined') {
$.get(url, function (xmlHttp) {
$(xmlHttp).appendTo(body);
callback();
success();
});
} else {
var iframe = $('<iframe id="' + iframeID + '" frameborder="0" allowtransparency="true" width="100%" height="100%" src="' + url + '"></iframe>').appendTo(body);
}
if (typeof json.notWebos == 'undefined') {
jPushApplication.hash(json.id + '_list');
}
jPushApplication.menu(json.id);
$('#app-search').css("display", "none");
},
menu: function (id) {
var dom, style;
var menu = $('#menu-bottom ul');
var domList = jQuery.jLayer.domList;
menu.html('');
for (var val in domList) {
dom = $('#' + val + '_list');
if (val == id) {
style = 'cur';
this.data.nowApp = val;
} else {
style = 'nor';
}
app = $('<li class="' + style + '" title="' + domList[val].config.MenuData.name + '"><div class="big"><img src="' + domList[val].config.MenuData.icon + '" /></div><div class="tit">' + domList[val].config.MenuData.name + '</div><div class="transparent"></div></li>').appendTo(menu);
jPushInit.menuBottomMouse(app, val);
}
},
hash: function (value) {
if (typeof value == 'undefined') {
return top.location.hash;
} else {
top.location.hash = value;
}
},
appScreen: function (app) {
return $('#app-main ul').index(app.parent());
},
getUserApps: function () {
var _applicationlist;
if (this.data.applicationlist != null) {
return this.data.applicationlist;
} else {
$.ajax({
type: 'POST',
url: '/GetUserApps/',
async: false,
dataType: 'json',
data:{game:game, area:area, device:device},
success: function (data, status) {
if (data.ret == 0){
_applicationlist = data.content;
}
else{
alert("请求失败:" + data.msg + ",请更换帐号或联系伟大哥");
window.location.href = '/logout/';
}
}
});
}
this.data.applicationlist = _applicationlist;
return this.data.applicationlist;
}
}
<file_sep>/mysite/opsys/utils/make_plug.py
#encoding:utf-8
FORMS = {
'input':'''<div class="form-group">
<label >%s</label>
<div class="input"><input class="form-control" id="%s" placeholder="%s"></div>
</div>\n''',
'select':'''<div class="form-group">
<label >%s</label>
<div class="input"><select class="form-control" id="%s">%s</select></div>
</div>\n''',
'svrselect':'''<div class="form-group">
<label >%s</label>
<div class="input"><select class="form-control" id="%s">%s</select></div>
</div>\n''',
'textarea':'''
<div class="form-group">
<label >%s</label>
<div class="input"><textarea class="form-control" id="%s" rows="5"></textarea></div>
</div>\n''',
'checkbox':'''
<div class="form-group">
<label >%s</label>
<div class="input"><input type='checkbox' class="checkbox" id="%s"></div>
</div>\n''',
'sumbit':'''<div class="form-group">
<label ></label>
<div class="input"><button type="submit" id="%s" onclick="return click_button();" class="btn btn-primary">提交</button></div>
</div>\n''',
'date': '''<div class="form-group">
<label>%s</label>
<div class="input-group input date form_datetime">
<input id="%s" size="16" type="text" class="form-control" value="" readonly>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
</div>\n'''
}
def gen_input(line):
html = FORMS['input'] % (line['label'], line['id'], line['placeholder'])
return html.encode("utf-8")
def gen_select(line):
base_code = ''
for i, option in enumerate(line['option']):
base_code = base_code + '<option value="%d">%s</option>' % (i, option)
html = FORMS['select'] % (line['label'],line['id'], base_code)
return html.encode("utf-8")
def gen_sumbit(line):
html = FORMS['sumbit'] % line['id'].encode("utf-8")
return html.encode("utf-8")
def gen_textarea(line):
html = FORMS['textarea'] % (line['label'], line['id'])
return html.encode("utf-8")
def gen_checkbox(line):
html = FORMS['checkbox'] % (line['label'], line['id'])
return html.encode("utf-8")
def gen_date(line):
html = FORMS['date'] % ( line['label'], line['id'])
return html.encode("utf-8")
<file_sep>/mysite/opsys/admin.py
from django.contrib import admin
from models.models import ServerList
from models.models import UserRight
from models.models import MyAppList
from models.models import TopRight
from models.models import UserPreference
admin.site.register(ServerList)
admin.site.register(UserRight)
admin.site.register(MyAppList)
admin.site.register(TopRight)
admin.site.register(UserPreference)
# Register your models here.
<file_sep>/mysite/collectedstatic/resources/plugin/jQuery.jWaterfall-0.0.1.js
/*
* jQuery-jWaterfall-0.0.1.js
* name:<NAME>
* email:<EMAIL>
* qq:273142650
* time:2012/12.30 20:58
*
* this.宝贝在洗衣服,哈哈哈哈
*/
"use strict";
(function ($, undefined) {
var itemArray = [];
var columnArray = [];
var windowResize;
var ajaxLoadState = 0;
var setItemPositoin = function (container, config) {
for (var i = 0; i < itemArray.length; i++) {
addItemData(itemArray[i], container, config);
}
}
var addItemData = function (itemData, container, config) {
var padding = config.padding;
var height = getItemHeight(itemData.itemData, padding, container, config);
var position = getItemPosition(itemData.itemData, config, height);
itemData.top = position.top;
itemData.left = position.left;
itemData.column = position.column;
itemData.height = height;
return itemData;
}
var setItemArray = function (container, config) {
if (itemArray.length <= 0) {
$(container).children(config.itemData).each(function () {
itemArray.push({
itemData: $(this),
top: 0,
left: 0,
column: null,
height: 0
});
});
}
}
var getItemPosition = function (itemData, config, height) {
var columnIndex = getMinColumn();
var margin = config.margin;
var column = columnArray[columnIndex];
var itemWidth = config.itemWidth;
var itemTop = 0;
var itemLeft = 0;
if (column.size > 0) {
itemTop += column.height + margin.top + margin.bottom;
height += margin.top + margin.bottom;
}
if (columnIndex > 0) {
itemLeft += (itemWidth + margin.left + margin.right) * columnIndex;
}
column.height += height;
column.size++;
return {top: itemTop, left: itemLeft, column: columnIndex}
}
var getMinColumn = function () {
var column = columnArray;
var height = column[0].height;
var index = 0;
for (var i = 0; i < column.length; i++) {
if (column[i].height < height) {
height = column[i].height;
index = i;
}
}
return index;
}
var getMaxColumn = function () {
var column = columnArray;
var height = 0;
var index = 0;
for (var i = 0; i < column.length; i++) {
if (column[i].height > height) {
height = column[i].height;
index = i;
}
}
return index;
}
var setColumn = function (container, config) {
var margin = config.margin;
var size = parseInt($(window).width() / (config.itemWidth + margin.left + margin.right));
if (size < config.minColumn) {
size = config.minColumn;
}
columnArray = [];
for (var i = 0; i < size; i++) {
columnArray.push({
height: 0,
size: 0
});
}
}
var getItemHeight = function (itemData, padding, container, config) {
var height = 0;
itemData.find(config.images).each(function () {
$(this).hide();
height += parseInt($(this).attr('height'));
});
height += itemData.height() + padding.top + padding.bottom;
itemData.find(config.images).show();
return height;
}
var getMargin = function (margin) {
var margin = margin.split(/\s+/ig);
var array = ['top', 'right', 'bottom', 'left'];
var marginArray = {};
for (var i = 0; i < margin.length; i++) {
marginArray[array[i]] = margin[i];
}
switch (margin.length) {
case 1:
for (var i = 1; i < array.length; i++) {
marginArray[array[i]] = margin[0];
}
break;
case 2:
marginArray.bottom = margin[0];
marginArray.left = margin[1];
break;
case 3:
marginArray.left = margin[1];
break;
}
for (var e in marginArray) {
marginArray[e] = parseInt(marginArray[e]);
}
return marginArray;
}
var showItem = function (itemArray) {
for (var i = 0; i < itemArray.length; i++) {
itemArray[i].itemData.stop();
itemArray[i].itemData.animate({
top: itemArray[i].top + 'px',
left: itemArray[i].left + 'px'
}, 750);
}
}
var setContainer = function (container, config) {
var width = (config.itemWidth + config.margin.left + config.margin.right) * columnArray.length - config.margin.left - config.margin.right;
var height = columnArray[getMaxColumn()].height + config.margin.bottom;
$(container).css({
width: width + 'px',
height: height + 'px',
margin: '0'
});
$(container).stop();
$(container).animate({
left: $(window).width() / 2 - width / 2 + 'px'
});
return {width: width}
}
var loadData = function (loader, container, config) {
if (typeof loader == 'function') {
ajaxLoadState = 1;
loader($.jWaterfall, {
page: config.page,
data: config.data,
container: container,
config: config
});
}
}
var Event = function (container, loader, config) {
$(window).resize(function () {
clearTimeout(windowResize);
var fn = function () {
init(container, loader, config);
}
windowResize = setTimeout(fn, 80);
});
$(window).scroll(function () {
var height = columnArray[getMinColumn()].height;
if ($(window).scrollTop() >= ((height + $(container).offset().top - $(window).height()) + config.tuning)) {
if (ajaxLoadState == 0) {
loadData(loader, container, config);
}
}
});
}
var init = function (container, loader, config) {
setColumn(container, config);
setItemArray(container, config);
setItemPositoin(container, config);
var size = setContainer(container, config);
showItem(itemArray);
config.callback(size);
}
jQuery.extend({
jWaterfall: {
setHtml: function (htmlArray, data) {
var newItemArray = [];
for (var i = 0; i < htmlArray.length; i++) {
var itemData = $(htmlArray[i]).appendTo(data.container).hide();
var index = itemArray.push({
itemData: itemData
});
index--;
itemData = addItemData(itemArray[index], data.container, data.config);
itemData.itemData.css({
top: itemData.top + 'px',
left: itemData.left + 'px'
}).fadeIn(1000);
}
ajaxLoadState = 0;
},
waterfall: function (container, loader, config) {
config.margin = getMargin(config.margin);
config.padding = getMargin(config.padding);
init(container, loader, config);
Event(container, loader, config);
}
}
});
})(window.jQuery, 'undefined');<file_sep>/mysite/opsys/views/templates.py
#coding:utf-8
from django.shortcuts import render_to_response
from report.utils.utils import *
from django.shortcuts import get_object_or_404
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect,Http404
from django.utils import simplejson
from decimal import *
from datetime import *
from math import ceil
from django.db import models
from django.template import loader, RequestContext
import makeconx
def admincenter(request):
return render_to_response('index.html', context_instance=RequestContext(request))
def GetOneApp(request):
if 'appid' in request.GET and request.GET['appid']:
appid = int(request.GET['appid'])
else:
return JsonResponse({'ret':-1,'msg':'请传入应用id'})
title, strCode, js = makeconx.conx(appid)
return render_to_response('app_admin.html',{'title':title, 'form_group':strCode, 'js':js}, context_instance=RequestContext(request))
<file_sep>/mysite/mysite/start.sh
killall uwsgi
sleep 1
uwsgi --ini /data/docker/xckoo_site/mysite/mysite/opsys.ini
<file_sep>/mysite/opsys/models/models.py
#coding:utf-8
from django.db import models
from django.contrib.auth.models import User
class ServerList(models.Model):
game = models.CharField(max_length=20, blank=False,null=False)
area = models.CharField(max_length=20, blank=False,null=False)
device = models.CharField(max_length=20, blank=False,null=False)
innerip = models.CharField(max_length=25, blank=False,null=False)
outip = models.CharField(max_length=25, blank=False,null=False)
user = models.CharField(max_length=25, blank=False,null=False)
passwd = models.CharField(max_length=30,blank=False,null=False)
info = models.CharField(max_length=200,blank=False,null=False)
onlyflag = models.CharField(max_length=20,blank=False,null=False,unique=True)
class Meta:
db_table = u'serverlist'
app_label = 'opsys'
def __unicode__(self):
return u'%s_%s_%s' % (self.game, self.area, self.info)
#这个权限代表的是用户开通了哪些地方的权限
class TopRight(models.Model):
right = models.CharField(max_length=200,blank=False,null=False)
def __unicode__(self):
return u'%s' % (self.right)
class UserRight(models.Model):
userid = models.ForeignKey(User)
right = models.ManyToManyField(TopRight)
class Meta:
db_table = u'userright'
app_label = 'opsys'
def __unicode__(self):
return u'%s' % self.userid
class UserOpRecord(models.Model):
userid = models.ForeignKey(User)
optime = models.DateField(blank=False,null=False,auto_now_add=True)
type = models.IntegerField(blank=False,null=False)
opobject = models.TextField()
class Meta:
db_table = u'useroprecord'
app_label = 'opsys'
#用户偏好
class UserPreference(models.Model):
userid = models.ForeignKey(User, unique=True)
lastlogin = models.CharField(max_length=30)
screen = models.IntegerField(default=3)
searcher = models.CharField(max_length=1024, default="http://www.baidu.com/s?wd=")
def __unicode__(self):
return u'%s' % self.userid
class MyAppList(models.Model):
userid = models.ForeignKey(User)
game = models.CharField(max_length=20,default="")
area = models.CharField(max_length=20,default="")
device = models.CharField(max_length=20,default="")
allapp = models.TextField()
position = models.IntegerField(blank=False,null=False,default=0)
class Meta:
db_table = u'myapplist'
app_label = 'opsys'
def __unicode__(self):
return u'%s_%s_%s_%s_%d' % (self.userid,self.game,self.area,self.device,self.position)
# Create your models here.
<file_sep>/mysite/mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from opsys.views.views import *
from opsys.views.tools import *
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$',login),
url(r'^logout/$',logout),
url(r'^ShowBox/$', showbox),
#views
url(r'^$',checklogin(index)),
url(r'^index/$',checklogin(index)),
#app Operater
url(r'^AddApp/$',checkloginandright(addapp, 'makeapp')),
url(r'^RemoveApp/$',checkloginandright(removeapp, 'makeapp')),
url(r'^MoveApp/$',checkloginandright(moveapp, 'makeapp')),
#index loading
url(r'^GetUserApps/$', checklogin(getmyapplist)),
url(r'^GetAppList/$', checklogin(getapplist)),
url(r'^GetOneApp/$', checklogin(getoneapp)),
url(r'^SelectRight/$', checklogin(SelectRight)),
url(r'^LastLogin/$', checklogin(savelastlogin)),
url(r'^PhoneBook/$', checklogin(getphonebook)),
url(r'^userInfo/$', checklogin(userInfo)),
url(r'^SetUserScreen/$', checklogin(SetUserScreen)),
url(r'^SetUserSearch/$', checklogin(SetUserSearch)),
#tools
url(r'^playerinfo_byuid/$', checkloginandright(GetPlayerInfoByUID, 'readdata')),
url(r'^playerinfo_byname/$', checkloginandright(GetPlayerInfoByName, 'readdata')),
url(r'^Award/$', checkloginandright(Award, 'readdata')),
url(r'^pwd/$', checkloginandright(GetPwd, 'readdata')),
url(r'^changepwd/$', checkloginandright(ChangePwd, 'writedata')),
url(r'^querytotal/$', checkloginandright(QueryTotal, 'readdata')),
url(r'^cashlog/$', checkloginandright(CashLog, 'readdata')),
url(r'^AddCardNew/$', checkloginandright(AddCard, 'writedata')),
url(r'^gencode/$', checkloginandright(GenCode, 'writedata')),
url(r'^gambleget/$', checkloginandright(GambleGet, 'readdata')),
url(r'^fenghao/$', checkloginandright(FengHao, 'writedata')),
url(r'^add_exp/$', checkloginandright(AddExp, 'writedata')),
url(r'^setvip/$', checkloginandright(SetVip, 'writedata')),
url(r'^addcumulat/$', checkloginandright(AddCumulate, 'writedata')),
url(r'^addflower/$', checkloginandright(AddFlower, 'writedata')),
url(r'^checkmaxid/$', checkloginandright(CheckMaxId, 'writedata')),
url(r'^checksvrtime/$', checkloginandright(CheckSvrTime, 'writedata')),
url(r'^ResetChap/$', checkloginandright(ResetChap, 'writedata')),
url(r'^pubcsv/$', checkloginandright(PubCsv, 'writedata')),
)
|
85cfeda86e8b828c1749959db9932cc9208a014a
|
[
"Markdown",
"JavaScript",
"INI",
"Python",
"Shell"
] | 17
|
Markdown
|
xckoo/opsys2
|
9daccf69e22f2af8837b35e4aab4e3748d72b4d0
|
bf82a9d8665cb946845dd94a49d7a9f9ff10587f
|
refs/heads/master
|
<repo_name>biojppm/c4cfd<file_sep>/src/c4/cfd/cfd.hpp
#ifndef _C4_CFD_HPP_
#define _C4_CFD_HPP_
/** @file grid.hpp this is a skeleton sketch for a CFD solver:
* -custom number of dimensions
* -custom storage: Structure-Of-Arrays vs Array-Of-Structures
* -row-major vs col-major tensors
* -cartesian and unstructured grids
* */
#include <vector>
#include "c4/config.hpp"
#include "c4/memory_resource.hpp"
#include "c4/restrict.hpp"
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdollar-in-identifier-extension"
#elif defined(__GNUC__)
#endif
namespace c4 {
// utilities to tell the compiler the memory is SIMD-aligned
/** @todo this assumes AVX512. Needs fix. */
constexpr size_t get_simd_size()
{
return size_t(64);
}
constexpr const size_t simd_alignment = get_simd_size(); ///< align for AVX512.
#define C4_SIMD_ALIGNED(ptr) C4_ASSUME_ALIGNED(ptr, simd_alignment);
#define C4_SIMD_ALIGNED_OFFS(ptr, offs) C4_ASSUME_ALIGNED_OFFS(ptr, simd_alignment. offs);
#define C4_ASSUME_ALIGNED(ptr, align) __builtin_assume_aligned(ptr, align)
#define C4_ASSUME_ALIGNED_OFFS(ptr, align, offs) __builtin_assume_aligned(ptr, align, offs)
} // namespace c4
namespace c4 {
namespace cfd {
template<int N, typename T>
struct vec_
{
T data[N];
};
template<typename T>
struct vec_<1,T>
{
union {
T data[1];
T x;
};
};
template<typename T>
struct vec_<2,T>
{
union {
T data[2];
T x, y;
};
};
template<typename T>
struct vec_<3,T>
{
union {
T data[3];
T x, y, z;
};
};
template<typename T>
struct vec_<4,T>
{
union {
T data[4];
T x, y, z, w;
};
};
template<int N, typename T>
struct vec : public vec_<N,T>
{
template <class I> T $$ operator[] (I i) { C4_XASSERT(i >= 0 && i < N); return this->data[i]; }
template <class I> T c$$ operator[] (I i) const { C4_XASSERT(i >= 0 && i < N); return this->data[i]; }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** @todo assert that T is memcpy-able */
template<typename T, typename I=size_t>
struct memblock
{
T $ m_val;
I m_size;
bool m_owner;
inline T $$ operator[] (I i) { C4_ASSERT(i >= 0 && i < m_size); return m_val[i]; }
inline T c$$ operator[] (I i) const { C4_ASSERT(i >= 0 && i < m_size); return m_val[i]; }
memblock() : m_val(nullptr), m_size(0), m_owner(false) {}
memblock(I sz) : memblock() { resize(sz); }
memblock(I sz, T $ arr) : memblock() { borrow(sz, arr); }
~memblock() { release(); }
// TODO rule of 5
void borrow(I sz, T $ mem)
{
if(m_owner)
{
release();
}
m_size = sz;
m_val = mem;
m_owner = false;
}
void release()
{
if(m_owner)
{
c4::afree(m_val);
}
m_val = nullptr;
m_size = 0;
m_owner = false;
}
void resize(I sz)
{
if(sz == m_size) return;
T *mem = C4_ASSUME_ALIGNED(c4::aalloc(sz * sizeof(T), simd_alignment), simd_alignment);
if(m_val)
{
T *aval = C4_ASSUME_ALIGNED(m_val, simd_alignment);
I min = sz < m_size ? sz : m_size;
memcpy(mem, aval, min);
}
if(m_owner)
{
release();
}
m_val = mem;
m_size = sz;
m_owner = true;
}
// etc
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace detail {
template<typename I, size_t N>
struct mat_addr_indices;
template<typename I>
struct mat_addr_indices<I, 1>
{
using mpos = I;
static constexpr const I s_sym2lin[1][1] = {{0}};
static constexpr const mpos s_lin2sym_rm[1] = {0};
static constexpr const mpos s_lin2sym_cm[1] = {0};
};
template<typename I>
struct mat_addr_indices<I, 2>
{
using mpos = vec<2,I>;
static constexpr const I s_sym2lin[2][2] = {{0,1},{1,2}};
static constexpr const mpos s_lin2sym_rm[3] = {{0,0},{0,1},{1,1}};
static constexpr const mpos s_lin2sym_cm[3] = {{0,0},{1,0},{1,1}};
};
template<typename I>
struct mat_addr_indices<I, 3>
{
using mpos = vec<2,I>;
static constexpr const I s_sym2lin[3][3] = {{0,1,2}, {1,3,4}, {2,4,5}};
static constexpr const mpos s_lin2sym_rm[6] = {{0,0},{0,1},{0,2},{1,1},{1,2},{2,2}};
static constexpr const mpos s_lin2sym_cm[6] = {{0,0},{1,0},{2,0},{1,1},{2,1},{2,2}};
};
} // namespace detail
/** dense matrix addressing
* lin := linear
* rm := row major
* cm := col major
* sym := symmetric
*/
template<typename I, I N>
inline I rm2lin(I i, I j)
{
return (i * N) + j;
}
template<typename I, I N>
inline vec<2,I> lin2rm(vec<2,I> p)
{
return {p/N, p%N};
}
template<typename I, I N>
inline I cm2lin(I i, I j)
{
return (j * N) + i;
}
template<typename I, I N>
inline vec<2,I> lin2cm(vec<2,I> p)
{
return {p%N, p/N};
}
// https://stackoverflow.com/questions/19143657/linear-indexing-in-symmetric-matrices
template<typename I, I N>
inline I sym2lin(I i, I j)
{
C4_XASSERT(i < 3);
C4_XASSERT(j < 3);
return detail::mat_addr_indices<I,N>::s_sym2lin[i][j];
}
template<typename I, I N>
inline I sym2lin(vec<2,I> i)
{
return sym2lin<I,N>(i.x, i.y);
}
template<typename I, I N>
inline vec<2,I> lin2sym_rm(I p)
{
C4_XASSERT(p < 6);
return detail::mat_addr_indices<I,N>::s_lin2sym_rm[p];
}
template<typename I, I N>
inline vec<2,I> lin2sym_cm(I p)
{
C4_XASSERT(p < 6);
return detail::mat_addr_indices<I,N>::s_lin2sym_cm[p];
}
template<typename I, I N>
struct row_major
{
using mpos = vec<2,I>;
static inline I mpos2lin(I i, I j) { return rm2lin<I,N>(i, j); }
static inline I mpos2lin(mpos i) { return rm2lin<I,N>(i.x, i.y); }
static inline I mpos2lin_sym(I i, I j) { return sym2lin<I,N>(i, j); }
static inline I mpos2lin_sym(mpos i) { return sym2lin<I,N>(i.x, i.j); }
static inline mpos lin2mpos(I i) { return lin2rm<I,N>(i); }
static inline mpos lin2mpos_sym(I i) { return lin2sym_rm<I,N>(i); }
};
template<typename I, I N>
struct col_major
{
using mpos = vec<2,I>;
static inline I mpos2lin(I i, I j) { return cm2lin<I,N>(i, j); }
static inline I mpos2lin(mpos i) { return cm2lin<I,N>(i.x, i.y); }
static inline I mpos2lin_sym(I i, I j) { return sym2lin<I,N>(i, j); }
static inline I mpos2lin_sym(mpos i) { return sym2lin<I,N>(i.x, i.j); }
static inline mpos lin2mpos(I i) { return lin2cm<I,N>(i); }
static inline mpos lin2mpos_sym(I i) { return lin2sym_cm<I,N>(i); }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<typename T=double, typename I=size_t>
struct _var
{
using value_type = T;
using index_type = I;
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<int N, typename T=double, typename I=size_t>
struct basic_var;
/** scalar */
template<typename T, typename I>
struct basic_var<1,T,I>
{
memblock<T,I> m_val;
using mpos = vec<1,I>;
inline T $$ operator() (I elm) { return this->m_val[elm]; }
inline T c$$ operator() (I elm) const { return this->m_val[elm]; }
inline T $$ operator() (I elm, mpos dim) { C4_UNUSED(dim); C4_ASSERT(dim.x == 0); return this->m_val.m_val[elm]; }
inline T c$$ operator() (I elm, mpos dim) const { C4_UNUSED(dim); C4_ASSERT(dim.x == 0); return this->m_val.m_val[elm]; }
};
/** non-scalar */
template<int N, typename T, typename I>
struct basic_var
{
memblock<T,I> m_val[N];
using mpos = vec<1,I>;
inline T $$ operator() (I elm, mpos dim) { C4_UNUSED(dim); C4_ASSERT(dim >= 0 && dim.x < N); return this->m_val[dim].m_val[elm]; }
inline T c$$ operator() (I elm, mpos dim) const { C4_UNUSED(dim); C4_ASSERT(dim >= 0 && dim.x < N); return this->m_val[dim].m_val[elm]; }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define C4_STORAGE_TYPES() \
using T = typename Storage::value_type; \
using I = typename Storage::value_type; \
static constexpr const I num_dims = Storage::num_dims; \
using value_type = typename Storage::value_type; \
using index_type = typename Storage::index_type; \
using scalar = typename Storage::scalar; \
using vector = typename Storage::vector; \
using tensor_rm = typename Storage::tensor_rm; \
using tensor_cm = typename Storage::tensor_cm; \
using symtensor_rm = typename Storage::symtensor_rm; \
using symtensor_cm = typename Storage::symtensor_cm
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<int D, typename T=double, typename I=size_t>
struct aos
{
static constexpr const I num_dims = D;
using value_type = T;
using index_type = I;
using mpos = vec<D,I>;
struct scalar : public _var<T,I>
{
enum : int { N = 1 };
basic_var<1, T, I> val;
inline T $$ operator() (I elm) { return val(elm); }
inline T c$$ operator() (I elm) const { return val(elm); }
inline T $$ operator() (I elm, I dim) { C4_XASSERT(dim == 0); C4_UNUSED(dim); return val(elm); }
inline T c$$ operator() (I elm, I dim) const { C4_XASSERT(dim == 0); C4_UNUSED(dim); return val(elm); }
inline T $$ operator() (I elm, mpos dim) { C4_XASSERT(dim.x == 0); C4_UNUSED(dim); return val(elm); }
inline T c$$ operator() (I elm, mpos dim) const { C4_XASSERT(dim.x == 0); C4_UNUSED(dim); return val(elm); }
};
struct vector : public _var<T, I>
{
enum : int { N = D };
basic_var<1, T, I> val;
using storage = basic_var<1,T,I>;
using mpos = typename storage::mpos;
inline T $$ operator() (I elm, I dim) { return val(elm * D + dim); }
inline T c$$ operator() (I elm, I dim) const { return val(elm * D + dim); }
inline T c$$ operator() (I elm, mpos dim) { return val(elm * D + dim); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm * D + dim); }
};
template<class Addr>
struct tensor : public _var<T, I>
{
enum : int { N = D*D };
basic_var<1, T, I> val;
using storage = basic_var<1, T, I>;
using mpos = typename storage::mpos;
using addr = Addr;
inline T $$ operator() (I elm, I dim1, I dim2) { return val(elm * N + addr::mpos2lin(dim1, dim2)); }
inline T c$$ operator() (I elm, I dim1, I dim2) const { return val(elm * N + addr::mpos2lin(dim1, dim2)); }
inline T $$ operator() (I elm, mpos dim) { return val(elm * N + addr::mpos2lin(dim)); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm * N + addr::mpos2lin(dim)); }
};
template<class Addr>
struct symtensor : public _var<T, I>
{
enum : int { N = D*(D+1)/2 };
basic_var<1, T, I> val;
using storage = basic_var<1, T, I>;
using mpos = typename storage::mpos;
using addr = Addr;
inline T $$ operator() (I elm, I dim1, I dim2) { return val(elm * N + addr::mpos2lin_sym(dim1, dim2)); }
inline T c$$ operator() (I elm, I dim1, I dim2) const { return val(elm * N + addr::mpos2lin_sym(dim1, dim2)); }
inline T $$ operator() (I elm, mpos dim) { return val(elm * N + addr::mpos2lin_sym(dim)); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm * N + addr::mpos2lin_sym(dim)); }
};
using tensor_rm = tensor<row_major<I,D>>;
using tensor_cm = tensor<col_major<I,D>>;
using symtensor_rm = symtensor<row_major<I,D>>;
using symtensor_cm = symtensor<col_major<I,D>>;
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<int D, typename T=double, typename I=size_t>
struct soa
{
static constexpr const I num_dims = D;
using value_type = T;
using index_type = I;
using mpos = vec<D,I>;
struct scalar : public _var<T, I>
{
enum : int { N = 1 };
basic_var<N, T, I> val;
inline T $$ operator() (I elm) { return val(elm); }
inline T c$$ operator() (I elm) const { return val(elm); }
inline T $$ operator() (I elm, I dim) { return val(elm, dim); }
inline T c$$ operator() (I elm, I dim) const { return val(elm, dim); }
inline T $$ operator() (I elm, mpos dim) { return val(elm, dim); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm, dim); }
};
struct vector : public _var<T, I>
{
enum : int { N = D };
basic_var<N, T, I> val;
using storage = basic_var<D,T,I>;
inline T $$ operator() (I elm, I dim) { return val(elm, dim); }
inline T c$$ operator() (I elm, I dim) const { return val(elm, dim); }
inline T c$$ operator() (I elm, mpos dim) { return val(elm, dim); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm, dim); }
};
template<class Addr>
struct tensor : public _var<T, I>
{
enum : int { N = D*D };
basic_var<N, T, I> val;
using storage = basic_var<N, T, I>;
using mpos = typename storage::mpos;
using addr = Addr;
inline T $$ operator() (I elm, I dim1, I dim2) { return val(elm, addr::mpos2lin(dim1, dim2)); }
inline T c$$ operator() (I elm, I dim1, I dim2) const { return val(elm, addr::mpos2lin(dim1, dim2)); }
inline T $$ operator() (I elm, mpos dim) { return val(elm, addr::mpos2lin(dim)); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm, addr::mpos2lin(dim)); }
};
template<class Addr>
struct symtensor : public _var<T, I>
{
enum : int { N = D*(D+1)/2 };
basic_var<N, T, I> val;
using storage = basic_var<N, T, I>;
using mpos = typename storage::mpos;
using addr = Addr;
inline T $$ operator() (I elm, I dim1, I dim2) { return val(elm, addr::mpos2lin_sym(dim1, dim2)); }
inline T c$$ operator() (I elm, I dim1, I dim2) const { return val(elm, addr::mpos2lin_sym(dim1, dim2)); }
inline T $$ operator() (I elm, mpos dim) { return val(elm, addr::mpos2lin_sym(dim)); }
inline T c$$ operator() (I elm, mpos dim) const { return val(elm, addr::mpos2lin_sym(dim)); }
};
using tensor_rm = tensor<row_major<I,D>>;
using tensor_cm = tensor<col_major<I,D>>;
using symtensor_rm = symtensor<row_major<I,D>>;
using symtensor_cm = symtensor<col_major<I,D>>;
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<typename I>
struct adjlist
{
memblock<I, I> m_pos;
memblock<I, I> m_adj;
adjlist() : m_pos(), m_adj() {}
adjlist(I num_elms, I num_adj_elms) : adjlist() { resize(num_elms, num_adj_elms); }
I num_elms() const { I sz = m_pos.size(); return sz > 0 ? sz-1 : sz; }
void resize(I num_elms, I num_adj_elms)
{
m_pos.resize(num_elms + 1);
m_adj.resize(num_adj_elms);
}
struct adj_iter
{
I c$ b;
I c$ e;
adj_iter(I c$ b_, I c$ e_) : b(b_), e(e_) {}
I const& begin() { return *b; }
I const& end() { return *e; }
};
adj_iter adj(I elm) const
{
C4_XASSERT(elm > 0 && elm < num_elms());
return adj_iter(&m_adj[m_pos[elm]], &m_adj[m_pos[elm+1]]);
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace grid {
template<class I>
struct face_cell
{
I left, right;
};
template<class Storage>
struct cartesian
{
C4_STORAGE_TYPES();
using face_type = face_cell<I>;
memblock<face_type, I> m_boundaries;
vector m_vert_coords;
};
template<class Storage>
struct unstructured
{
C4_STORAGE_TYPES();
using face_type = I;
I m_ncells;
I m_nfaces;
I m_nverts;
adjlist<I> m_cell_faces;
adjlist<I> m_vert_cells;
adjlist<I> m_cell_verts;
memblock<face_cell<I>, I> m_face_cells;
memblock<face_type, I> m_boundaries;
vector m_vert_coords;
vector m_cell_center;
scalar m_cell_vol;
vector m_face_center;
vector m_face_nrml;
};
} // namespace grid
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace bnd {
typedef enum
{
DIRICHLET,
NEUMANN
} MathBoundaryType_e;
template<class T, class I>
struct BoundaryValues
{
T m_single_val;
memblock<T, I> m_val_per_face;
};
template<class T, class I>
struct Dirichlet : public BoundaryValues<T,I>
{
};
template<class T, class I>
struct Neumann : public BoundaryValues<T,I>
{
};
template<class T, class I>
struct MathBoundary
{
MathBoundaryType_e m_math_type;
union {
Dirichlet<T,I> m_dirichlet;
Neumann<T,I> m_neumann;
};
};
typedef enum BoundaryType_e
{
WALL,
INFLOW,
OUTFLOW,
INTERIOR,
AMR,
CUSTOM
} BoundaryType_e;
template<class DependentVars>
struct Boundary
{
using T = typename DependentVars::T;
using I = typename DependentVars::I;
using value_type = typename DependentVars::T;
using index_type = typename DependentVars::I;
BoundaryType_e m_type;
MathBoundary<T, I> m_velocity;
MathBoundary<T, I> m_pressure;
};
} // namespace bnd
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template
<
template<class> class DependentVars,
template<class> class Grid,
class Storage
>
struct problem : public DependentVars<Storage>
{
C4_STORAGE_TYPES();
using vars_type = DependentVars<Storage>;
using grid_type = Grid<Storage>;
using bnd_type = bnd::Boundary<DependentVars<Storage>>;
Grid<Storage> m_grid;
memblock<bnd_type, I> m_boundaries;
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace dvars {
template<class Storage>
struct incompressible
{
C4_STORAGE_TYPES();
vector m_velocity;
scalar m_pressure;
T m_mu;
};
template<class Storage>
struct compressible
{
C4_STORAGE_TYPES();
scalar m_density;
vector m_velocity;
scalar m_pressure;
scalar m_temperature;
scalar m_energy;
T m_mu;
};
} // namespace dvars
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** @namespace amr adaptive mesh refinement */
namespace amr {
template<class ProblemImpl>
struct amr_problem_node
{
ProblemImpl *m_parent;
std::vector<ProblemImpl> m_children;
amr_problem_node(ProblemImpl *parent_=nullptr) : m_parent(parent_), m_children() {}
};
template<class ProblemImpl>
struct amr_problem
{
amr_problem_node<ProblemImpl> m_root;
};
} // namespace amr
} // namespace cfd
} // namespace c4
#include "c4/unrestrict.hpp"
#ifdef __clang__
# pragma clang diagnostic pop
#elif defined(__GNUC__)
#endif
#endif // _C4_CFD_HPP_
<file_sep>/src/c4/cfd/cfd.cpp
#include "c4/cfd/cfd.hpp"
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
project(c4cfd)
include(./cmake/c4Project.cmake)
c4_declare_project(c4cfd)
set(C4CFD_SRC_DIR ${CMAKE_CURRENT_LIST_DIR}/src)
set(C4CFD_EXT_DIR ${CMAKE_CURRENT_LIST_DIR}/ext)
c4_require_subproject(c4core REMOTE
GIT_REPOSITORY https://github.com/biojppm/c4core.git)
c4_require_subproject(ryml REMOTE
GIT_REPOSITORY https://github.com/biojppm/rapidyaml.git)
c4_add_library(c4cfd
SOURCE_ROOT ${C4CFD_SRC_DIR}
SOURCES
c4/cfd/cfd.hpp
c4/cfd/cfd.cpp
LIBS c4core
INC_DIRS
$<BUILD_INTERFACE:${C4CFD_SRC_DIR}> $<INSTALL_INTERFACE:include>
)
c4_install_target(c4cfd)
c4_install_exports()
c4_add_dev_targets()
<file_sep>/test/basic.cpp
#include <gtest/gtest.h>
#include "c4/cfd/cfd.hpp"
template<int N, class T, class I> using soa = c4::cfd::soa<N, T, I>;
template<int N, class T, class I> using aos = c4::cfd::aos<N, T, I>;
template<class S> using inc = c4::cfd::dvars::incompressible<S>;
template<class S> using compr = c4::cfd::dvars::compressible<S>;
template<class S> using cart = c4::cfd::grid::cartesian<S>;
template<class S> using unst = c4::cfd::grid::unstructured<S>;
template
<
int N,
template<class> class DVars,
template<class> class Grid,
template<int,class,class> class Storage,
class T=double,
class I=int32_t
>
void test_instantiation()
{
c4::cfd::problem<DVars, Grid, Storage<N,T,I>> prob;
}
TEST(cart_inc, soa1d)
{
test_instantiation<1, inc, cart, soa>();
}
TEST(cart_inc, soa2d)
{
test_instantiation<2, inc, cart, soa>();
}
TEST(cart_inc, soa3d)
{
test_instantiation<3, inc, cart, soa>();
}
TEST(cart_inc, aos1d)
{
test_instantiation<1, inc, cart, aos>();
}
TEST(cart_inc, aos2d)
{
test_instantiation<2, inc, cart, aos>();
}
TEST(cart_inc, aos3d)
{
test_instantiation<3, inc, cart, aos>();
}
TEST(cart_compr, soa1d)
{
test_instantiation<1, compr, cart, soa>();
}
TEST(cart_compr, soa2d)
{
test_instantiation<2, compr, cart, soa>();
}
TEST(cart_compr, soa3d)
{
test_instantiation<3, compr, cart, soa>();
}
TEST(cart_compr, aos1d)
{
test_instantiation<1, compr, cart, aos>();
}
TEST(cart_compr, aos2d)
{
test_instantiation<2, compr, cart, aos>();
}
TEST(cart_compr, aos3d)
{
test_instantiation<3, compr, cart, aos>();
}
TEST(unst_inc, soa1d)
{
test_instantiation<1, inc, unst, soa>();
}
TEST(unst_inc, soa2d)
{
test_instantiation<2, inc, unst, soa>();
}
TEST(unst_inc, soa3d)
{
test_instantiation<3, inc, unst, soa>();
}
TEST(unst_inc, aos1d)
{
test_instantiation<1, inc, unst, aos>();
}
TEST(unst_inc, aos2d)
{
test_instantiation<2, inc, unst, aos>();
}
TEST(unst_inc, aos3d)
{
test_instantiation<3, inc, unst, aos>();
}
TEST(unst_compr, soa1d)
{
test_instantiation<1, compr, unst, soa>();
}
TEST(unst_compr, soa2d)
{
test_instantiation<2, compr, unst, soa>();
}
TEST(unst_compr, soa3d)
{
test_instantiation<3, compr, unst, soa>();
}
TEST(unst_compr, aos1d)
{
test_instantiation<1, compr, unst, aos>();
}
TEST(unst_compr, aos2d)
{
test_instantiation<2, compr, unst, aos>();
}
TEST(unst_compr, aos3d)
{
test_instantiation<3, compr, unst, aos>();
}
<file_sep>/test/CMakeLists.txt
c4_setup_testing()
function(c4cfd_add_test name)
c4_add_executable(c4cfd-test-${name}
SOURCES ${ARGN} main.cpp
LIBS c4cfd gtest
FOLDER test)
c4_add_test(c4cfd-test-${name})
endfunction(c4cfd_add_test)
c4cfd_add_test(basic basic.cpp)
|
8687748daf8a85796e376a942eb1dd5d4ffed445
|
[
"CMake",
"C++"
] | 5
|
C++
|
biojppm/c4cfd
|
a41320707493f5544dfe089c36438413823254f8
|
a1bc702c4dcd5fd5d89d9fc4c3f7d72717b5e623
|
refs/heads/master
|
<file_sep>//
// ShowMoreViewCell.swift
// Yelp
//
// Created by <NAME> on 9/7/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
@objc protocol ShowMoreViewCellDelegate {
optional func showMoreViewCell(showMoreViewCell: ShowMoreViewCell, clicked value: Bool)
}
class ShowMoreViewCell: UITableViewCell {
var delegate: ShowMoreViewCellDelegate?
@IBOutlet weak var showMoreButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func showMoreButtonClicked(sender: AnyObject) {
delegate?.showMoreViewCell?(self, clicked: true)
}
}
<file_sep>//
// Preferences.swift
// Yelp
//
// Created by <NAME> on 9/7/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
struct Preferences {
var sortName: String?
var categories: [String]?
var radius: String?
var deals: Bool?
let stringToRadiusMap = [
"2 blocks": 100,
"6 blocks": 800,
"1 mile": 1600,
"5 miles": 8000
]
let radiusValues = [
"Best Match",
"2 blocks",
"6 blocks",
"1 mile",
"5 miles"
]
let stringToSortByMap = [
"Best Match" : YelpSortMode.BestMatched,
"Shortest Distance" : YelpSortMode.Distance,
"Highest Rating" : YelpSortMode.HighestRated,
]
let sortByValues = [
"Best Match",
"Shortest Distance",
"Highest Rating"
]
func stringToRadius() -> Int? {
if let val = radius {
return stringToRadiusMap[val] ?? nil
} else {
return nil
}
}
func stringToSortByValue() -> YelpSortMode? {
if let name = sortName {
return stringToSortByMap[name] ?? nil
} else {
return nil
}
}
}
|
7f7cfd9c789cdcd330f13c44dcb04348c2b0ae31
|
[
"Swift"
] | 2
|
Swift
|
wilkesybear/ios_yelp
|
aca2926aeb3d80da86a83b3a90c9f8ffb65402c8
|
018a04cb8f99dcac88af41cd264b0abd7f29dc62
|
refs/heads/main
|
<repo_name>MarcGravel/VuePlaylist<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
emptyPlayMsg: "Click song list to add tracks.",
emptySongMsg: "Click playlist tracks to return them here.",
songList: [
{
title: "Burning Babylon",
artist: "<NAME>",
id: 1
},
{
title: "Last Jungle",
artist: "Sub Focus",
id: 2
},
{
title: "Higher",
artist: "Kanine",
id: 3
},
{
title: "Touch",
artist: "Hybrid Minds",
id: 4
},
{
title: "The View",
artist: "LSB",
id: 5
},
{
title: "On My Mind",
artist: "Macca",
id: 6
},
{
title: "Afterthought",
artist: "Ivy Lab",
id: 7
},
{
title: "Dreaming",
artist: "S.P.Y",
id: 8
},
{
title: "So Many Times",
artist: "Brookes Brothers",
id: 9
},
{
title: "Waveforms",
artist: "Logistics",
id: 10
},
],
playList: []
},
mutations: {
//Takes in passed event and data from songlist.vue
sendToPlay(state, clickedID) {
//loops through the state. songlist array to match id with passed data
for (let i=0; i < state.songList.length; i++) {
if (state.songList[i].id == clickedID) {
//pushes data to playList Array
state.playList.push(state.songList[i]);
}
}
//This filters the clicked song out from the songList
state.songList = state.songList.filter(
sl => {
return sl.id !== clickedID;
})
},
//Takes in passed event and data from playlist.vue
//all code below is just a reverse of the sendToPlay mutation above
sendToSongList(state, clickedPlayID) {
for (let i=0; i < state.playList.length; i++) {
if (state.playList[i].id == clickedPlayID) {
state.songList.push(state.playList[i])
}
}
state.playList = state.playList.filter(
pl => {
return pl.id !== clickedPlayID;
}
)
}
},
actions: {
},
getters: {
//functions to return message if list is empty
playListEmptyMessage(state) {
if (state.playList.length == 0) {
return state.emptyPlayMsg;
}
},
songListEmptyMessage(state) {
if (state.songList.length == 0) {
return state.emptySongMsg;
}
}
}
})
|
60a3eb3edae84b8911e8258dc1f260a4f5b812ad
|
[
"JavaScript"
] | 1
|
JavaScript
|
MarcGravel/VuePlaylist
|
9a2cc4617902cbc7e251976624e4092d397779e0
|
b1336d637fb988813b237787e6d591b8b3f3a35b
|
refs/heads/master
|
<file_sep>package com.example.android_v403_crud;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.example.android_v403_crud.common.MySQLiteOpenHelper;
/**
* Update Activity
*/
public class UpdateActiviy extends Activity implements OnClickListener{
private SQLiteDatabase mydb;
private Cursor cursor;
private SimpleCursorAdapter myadapter;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
//SQLite DB Setting
MySQLiteOpenHelper hlpr = new MySQLiteOpenHelper(getApplicationContext());
mydb = hlpr.getWritableDatabase();
/** ListView DB Data **/
cursor = mydb.query(
"mytable",
new String[] {"_id", "data"}, null, null, null, null, "_id DESC");
String[] from = new String[] {"_id", "data"};
int[] to = new int[] {R.id._id, R.id.data01};
myadapter = new SimpleCursorAdapter(this, R.layout.update_row, cursor, from, to);
//ListView Setting
listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(myadapter);
/** Button01 [update] **/
View btn01 = findViewById(R.id.button1);
btn01.setOnClickListener(this);
}
@Override
public void onPause(){
super.onPause();
cursor.close();
mydb.close();
}
public void onClick(View v){
/* button01 update */
if(v.getId() == R.id.button1){
/** ListViewの子ViewであるEditTextの値を取得する**/
//ListView(親クラス)を取得
ListView listView = (ListView)findViewById(R.id.listview);
for( int i = 0; i< listView.getChildCount();i++) {
Log.v("update", "child1=" + listView.getChildAt(i).getClass());
RelativeLayout layout = (RelativeLayout)listView.getChildAt(i);
String id = null;
String data01 = null;
//EditText(子クラス)を取得する
for( int j = 0; j< layout.getChildCount();j++) {
Log.v("update", "child2=" + layout.getChildAt(j).getClass());
/** 注意:EditTextはTextViewの小クラスのため、判定順番が重要**/
//DATA01 ※EditTextの場合
if( layout.getChildAt(j) instanceof EditText ){
EditText editText = (EditText)layout.getChildAt(j);
data01 = editText.getText().toString();
Log.v("update", "data01=" + data01);
//ID ※TextViewの場合
}else if( layout.getChildAt(j) instanceof TextView ){
TextView textView = (TextView)layout.getChildAt(j);
id = textView.getText().toString();
Log.v("update", "id=" + id);
}
}
//ID、DATA01をUPDATE
ContentValues values = new ContentValues();
values.put("data", data01);
mydb.update("mytable", values, "_id="+id, null);
Log.v("update","id="+id+", data=" + data01);
}
//Back Activity
finish();
}
}
}<file_sep>package com.example.android_v403_crud.common;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* SQLiteOpenHelper Class
*
*/
public class MySQLiteOpenHelper extends SQLiteOpenHelper{
private static final String DB = "android_v403_crud_sqlite.db";
private static final int DB_VERSION = 1;
private static final String CREATE_TABLE_SQL = "create table mytable ( _id integer primary key autoincrement, data integer not null );";
private static final String DROP_TABLE_SQL = "drop table mytable;";
//Constractor
public MySQLiteOpenHelper(Context c){
super(c, DB, null, DB_VERSION);
}
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_TABLE_SQL);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE_SQL);
onCreate(db);
}
}
<file_sep>Android V4.0.3 CRUD Example
=============
AndroidV4.0.3でSQLiteを用いたデータ保存をサンプルです。
Create/Read/Update/Deleteをアプリから実施します。
<file_sep>package com.example.android_v403_crud;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.example.android_v403_crud.common.MySQLiteOpenHelper;
/**
* Delete Activity
*/
public class DeleteActivity extends Activity{
//
private SQLiteDatabase mydb;
private Cursor cursor;
private SimpleCursorAdapter myadapter;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delete);
//SQLite DB Setting
MySQLiteOpenHelper hlpr = new MySQLiteOpenHelper(getApplicationContext());
mydb = hlpr.getWritableDatabase();
/** ListView DB Data **/
cursor = mydb.query(
"mytable",
new String[] {"_id", "data"}, null, null, null, null, "_id DESC");
String[] from = new String[] {"_id", "data"};
int[] to = new int[] {R.id._id, R.id.data01};
myadapter = new SimpleCursorAdapter(this, R.layout.delete_row, cursor, from, to);
//ListView Setting
listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(myadapter);
}
}<file_sep>package com.example.android_v403_crud;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import com.example.android_v403_crud.common.MySQLiteOpenHelper;
/**
* Main Activity Class
* Android V4.0.3 CRUD Example
* SQLite - Create/Read/Updata/Delete
*/
public class MyActivity extends Activity implements OnClickListener{
private SQLiteDatabase mydb;
private Cursor cursor;
private SimpleCursorAdapter myadapter;
private ListView listView;
/**
* Activity Create
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//SQLite DB Setting
MySQLiteOpenHelper hlpr = new MySQLiteOpenHelper(getApplicationContext());
mydb = hlpr.getWritableDatabase();
/** ListView DB Data **/
cursor = mydb.query(
"mytable",
new String[] {"_id", "data"}, null, null, null, null, "_id DESC");
String[] from = new String[] {"_id", "data"};
int[] to = new int[] {R.id._id, R.id.data01};
myadapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
//ListView Setting
listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(myadapter);
/** Button01 [CREATE] **/
View btn01 = findViewById(R.id.button1);
btn01.setOnClickListener(this);
/** Button02 [READ] **/
View btn02 = findViewById(R.id.button2);
btn02.setOnClickListener(this);
/** Button03 [UPDATE] **/
View btn03 = findViewById(R.id.button3);
btn03.setOnClickListener(this);
/** Button04 [DELETE] **/
View btn04 = findViewById(R.id.button4);
btn04.setOnClickListener(this);
}
@Override
public void onPause(){
super.onPause();
cursor.close();
mydb.close();
}
/**
* Click Event Listener
* @param v : View
*/
public void onClick(View v){
/* Button01 Create */
if(v.getId() == R.id.button1){
//Go to Next Activity
Intent intent = new Intent(MyActivity.this, CreateActivity.class);
startActivity(intent);
/* Button02 Read */
}else if(v.getId() == R.id.button2){
finish();
startActivity(getIntent());
Toast.makeText(this, "Updata List!!",Toast.LENGTH_LONG).show();
/* Button03 Update */
}else if(v.getId() == R.id.button3){
//Go to Next Activity(Update Page)
Intent intent = new Intent(MyActivity.this, UpdateActiviy.class);
startActivity(intent);
/* Button04 Delete */
}else if(v.getId() == R.id.button4){
Intent intent = new Intent(MyActivity.this, DeleteActivity.class);
startActivity(intent);
}
}
}
|
1bcc4dd8b7f399823d189c58cbe00c3e64fe2597
|
[
"Markdown",
"Java"
] | 5
|
Java
|
haradatmn/android-v403-crud
|
8e7c8854e25b42048ac482771bd87653f6c4d71c
|
cce308b3063db5dee5bc102c9b0329c3e1baa10e
|
refs/heads/master
|
<repo_name>Atul-Yadav-mnit/Confusion<file_sep>/src/redux/configureStore.js
import {createStore, combineReducers, applyMiddleware} from'redux'
import {Dishes} from './Dishes'
import {Comments} from './Comments'
import {Leaders} from './Leaders'
import {Promotions} from './Promotions'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import {createForms } from 'react-redux-form'
import { InitialFeedbak } from './InitialFeedback'
export const configureStore = () =>{
const store = createStore(
combineReducers({
dishes : Dishes,
comments : Comments,
leaders : Leaders,
promotions : Promotions,
...createForms({
feedback : InitialFeedbak
})
}), applyMiddleware(thunk, logger)
);
return store;
}
|
72d428846ee924eeb1702be36473b498a3b7facf
|
[
"JavaScript"
] | 1
|
JavaScript
|
Atul-Yadav-mnit/Confusion
|
f4723ae4f78d6d2d5a1015d28a9a397004295200
|
0fc46d46f2a60752fa8768fd6bb6548e7b9da2cf
|
refs/heads/master
|
<file_sep>package alekseisivkov.ru.schedule.Model;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class StudyDay {
public static final int FIRST_WEEK = 2;
public static final int SECOND_WEEK = 3;
private String mName;
private ArrayList<Lesson> mUpperLessons;
private ArrayList<Lesson> mLowerLessons;
// public StudyDay(String name, String[] time, ArrayList<Subject> subjects, String[] room) {
// mName = name;
// mTime = time;
// mSubjects = subjects;
// mRoom = room;
// }
public StudyDay(String name) {
mUpperLessons = new ArrayList<>();
mLowerLessons = new ArrayList<>();
mName = "Вечный понедельник";
}
//TODO: а надо ли статик?..
public static class Lesson {
private String mTime;
private Subject mSubject;
private String mRoom;
private String mDay;
// private int mWeekType;
@Override
public boolean equals(Object o) {
if (getClass() != o.getClass())
return false;
Lesson lesson = (Lesson) o;
return lesson.getTime().equals(mTime) && lesson.getSubject().equals(mSubject) && lesson.getRoom().equals(mRoom);
}
public Lesson(String time, Subject subject, String room, String day) {
mTime = time;
mSubject = subject;
mRoom = room;
mDay = day;
// mWeekType = weekType;
}
public Lesson() {
//пусто
}
public void setTime(String time) {
mTime = time;
}
public void setSubject(Subject subject) {
mSubject = subject;
}
public void setRoom(String room) {
mRoom = room;
}
public void setDay(String day) {
mDay = day;
}
public String getRoom() {
return mRoom;
}
public Subject getSubject() {
return mSubject;
}
public String getTime() {
return mTime;
}
public String getDay() {
return mDay;
}
public Date getDateTime() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return sdf.parse(mTime);
}
}
public void addLesson(String time, Subject subject, String room, int weekType, String day) {
if (weekType == FIRST_WEEK) {
mUpperLessons.add(new Lesson(time, subject, room, day));
} else if (weekType == SECOND_WEEK) {
mLowerLessons.add(new Lesson(time, subject, room, day));
}
// mTime.add(time);
// mSubjects.add(subject);
// mRoom.add(room);
// mWeekType = weekType;
}
public void addLesson(Lesson newLesson, int index, int weekType) {
if (weekType == FIRST_WEEK) {
mUpperLessons.add(index, newLesson);
} else if(weekType == SECOND_WEEK) {
mLowerLessons.add(index, newLesson);
}
}
public void addAllLessons(ArrayList<Lesson> lessons) {
mUpperLessons = lessons;
}
public ArrayList<Lesson> getAllUpperLessons() {
return mUpperLessons;
}
public ArrayList<Lesson> getAllLowerLessons() {
return mLowerLessons;
}
public void removeLowerLesson(Lesson removableLesson) { //TODO:возможно надо переопределить метод equals
mLowerLessons.remove(removableLesson);
}
public void copy() { //функция создания пар нижней недели такой же, как верхей
for (int i = 0; i < mUpperLessons.size(); i++) {
mLowerLessons.add(new Lesson(mUpperLessons.get(i).getTime(),
mUpperLessons.get(i).getSubject(), mUpperLessons.get(i).getRoom(),
mUpperLessons.get(i).getDay()));
}
}
public Lesson getUpperLesson(String time) { //получение пары по времени
for (int i = 0; i < mUpperLessons.size(); i++) {
if (mUpperLessons.get(i).mTime.equals(time)) {
return mUpperLessons.get(i);
}
}
return null;
}
public Lesson getLowerLesson(String time) { //получение пары по времени
for (int i = 0; i < mLowerLessons.size(); i++) {
if (mLowerLessons.get(i).mTime.equals(time)) {
return mLowerLessons.get(i);
}
}
return null;
}
public Lesson getLowerLesson(Lesson lesson) { //получение пары по объекту
for (int i = 0; i < mLowerLessons.size(); i++) {
if (mLowerLessons.get(i).equals(lesson)) {
return mLowerLessons.get(i);
}
}
return null;
}
public Lesson getUpperLesson(Subject subject) { //получение пары по предмету
for (int i = 0; i < mUpperLessons.size(); i++) {
if (mUpperLessons.get(i).mSubject.equals(subject)) {
return mUpperLessons.get(i);
}
}
return null;
}
public Lesson getLowerLesson(Subject subject) { //получение пары по предмету
for (int i = 0; i < mLowerLessons.size(); i++) {
if (mLowerLessons.get(i).mSubject.equals(subject)) {
return mLowerLessons.get(i);
}
}
return null;
}
public Lesson getUpperLesson(int index) { //получение пары по номеру
return mUpperLessons.get(index);
}
public Lesson getLowerLesson(int index) { //получение пары по номеру
return mLowerLessons.get(index);
}
public String getName() {
return mName;
}
// public ArrayList<String> getRoom() {
// return mRoom;
// }
// public ArrayList<String> getTime() {
// return mTime;
// }
// public ArrayList<Subject> getSubjects() {
// return mSubjects;
// }
// public int getWeekType() {
// return mWeekType;
// }
public void setName(String name) {
mName = name;
}
// public void setRoom(ArrayList<String> room) {
// mRoom = room;
// }
// public void setSubjects(ArrayList<Subject> subjects) {
// mSubjects = subjects;
// }
// public void setTime(ArrayList<String> time) {
// mTime = time;
// }
// public void setWeekType(int weekType) {
// mWeekType = weekType;
// }
}
<file_sep>package alekseisivkov.ru.schedule.Model;
public class Subject {
public static final String EMPTY = "Неизвестно";
public static final int PRACTICE = 0;
public static final int LECTURE = 1;
public static final int LAB = 2;
private String mTitle;
private int mType; //тип занятия: лекция, парктика или лаба
private String mTeacher;
private String mAnnotation; //комментарии, пометки
private Subject mFirstBrother, mSecondBrother; //указывают на парные предметы (то же название, но лекция и практика)
public Subject(String name, int type) {
// Log.d("TAG", "name is " + name);
mTitle = name.substring(0, name.length()-1); //обрезаем передаваемое в название значение типа
// Log.d("TAG", "mTitle is " + mTitle);
mType = type;
mTeacher = EMPTY;
mAnnotation = EMPTY;
}
public Subject(String name, String teacher, int type) {
mTitle = name.substring(0, name.length()-1);
mType = type;
mTeacher = teacher;
mAnnotation = EMPTY;
}
@Override
public boolean equals(Object o) {
if (getClass() != o.getClass())
return false;
Subject subject = (Subject) o;
return subject.getTitle().equals(mTitle) && subject.getTeacher().equals(mTeacher);
}
public void addBrother(Subject brother) {
if (mFirstBrother == null) {
mFirstBrother = brother;
} else if (mSecondBrother == null) {
mSecondBrother = brother;
} else {
throw new RuntimeException("Brother's are full, can't add");
}
}
public void setEveryTitle(String name) {
mTitle = name;
if (mFirstBrother != null) {
mFirstBrother.mTitle = name;
}
if (mSecondBrother != null) {
mSecondBrother.mTitle = name;
}
}
public int getType() {
return mType;
}
public String getTitle() {
return mTitle;
}
public String getTeacher() {
return mTeacher;
}
public String getAnnotation() {
return mAnnotation;
}
public void setTitle(String title) {
mTitle = title;
}
public void setTeacher(String teacher) {
mTeacher = teacher;
}
public void setAnnotation(String annotation) {
mAnnotation = annotation;
}
}
|
a5e376b0d885a27a8b0debacc4962251ea1adc86
|
[
"Java"
] | 2
|
Java
|
alekseisivkov/Schedule
|
81a700091f98fbce6fe7db72835d4d96f5dc2610
|
d5b60c78319f0388c8086b9cbb56934b51d80dbf
|
refs/heads/master
|
<repo_name>azelio5/java-courses<file_sep>/Calculate.java
public class Calculate{
public static void main(String[] arg){
System.out.println("Hello");
int first = Integer.valueOf(arg[0]);
int second = Integer.valueOf(arg[1]);
int summ = first + second;
int minus = first - second;
int decart = first * second;
int devision = first / second;
int pow = (int)Math.pow(first, second);
System.out.println(summ);
System.out.println(minus);
System.out.println(decart);
System.out.println(devision);
System.out.println(pow);
}
}
|
a862519a4f5a33b1342b2581b69ff853147d9188
|
[
"Java"
] | 1
|
Java
|
azelio5/java-courses
|
28fbc0126c08d4c05f9c215fcf2dd70b76f6fec7
|
329c6cf70c4f5ff42c1c38fd5fb87b5538392d58
|
refs/heads/master
|
<file_sep>package DrawShapesProgram;
public class ShapeRectangle extends Shape {
double width;
double height;
//Constructor
public ShapeRectangle (
double newWidth,
double newHeight)
{
this.width = newWidth;
this.height = newHeight;
}
}
<file_sep>package DrawShapesProgram;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.WritableImage;
import javax.imageio.ImageIO;
import java.io.File;
public class SavePngStrategy {
public void save(WritableImage givenWim, String filePath) {
System.out.println("Saving Png file...");
File file = new File(filePath);
try {
ImageIO.write(SwingFXUtils.fromFXImage(givenWim, null), "png", file);
System.out.println("Saved .png file: " + filePath);
} catch (Exception e) {
System.out.println("error: " + e);
}
}
}
<file_sep>package DrawShapesProgram;
/* NOT ACCESSED IN PROGRAM. FOR WORK, LATER ON.
A class in order to organize shape update
on new changes
*/
import javafx.collections.ObservableList;
import java.util.List;
public class UpdateShape {
public static int updateTheShapePosY (
ObservableList<ShapeVariation> allShapes,
int givenShapeId,
String givenNewPosY) {
double newPosY;
try {
newPosY = Double.parseDouble(givenNewPosY);
System.out.println("new pos Y: " + givenNewPosY);
ShapeVariation shapeToUpdate = new ShapeVariation();
//find the shape in shape list which has the given id:
int i = -1;
int shapeToUpdate_i = -1;
for(ShapeVariation shape : allShapes) {
i++;
if (shape.shapeId == givenShapeId) {
shapeToUpdate_i = i;
}
}
allShapes.get(i).posY = newPosY;
return (shapeToUpdate_i);
} catch (Exception e) {
System.out.println("wrong value type or other error." +
"No change made to shape value y. " +
e);
return (-1);
}
}
}
<file_sep>package DrawShapesProgram;
//import javafx.scene.shape.Circle;
public class ShapeOval extends Shape {
double width, height ;
//Constructor
public ShapeOval(
double newWidth,
double newHeight)
{
this.width = newWidth;
this.height = newHeight;
}
}
|
6d6a7d9fa859d19f11c11b40f4583841859bffee
|
[
"Java"
] | 4
|
Java
|
Bob-Utveckling/Labb_JavaProgLab3_DrawSimpleShapesProgram_useJavaFX
|
f72a2c2f6c82d19c5966984a80aa6a07851a0a8d
|
ca1db37605d086b0963b05c1eb39cc46e2c27519
|
refs/heads/master
|
<repo_name>Rifaz/WebScript<file_sep>/insert.php
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sahara", $con);
$sql="INSERT INTO Products (ProductName, Description, Price)
VALUES
('$_POST[ProductName]','$_POST[Description]','$_POST[Price]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
|
dd74d01a21c0dd3ad969b3290687a62e1c4da65d
|
[
"PHP"
] | 1
|
PHP
|
Rifaz/WebScript
|
850a63f89e8b93b5d91e2b4876fd1565c474f750
|
7dd8305f58a614b338c182881c23b1e58a68a5c6
|
refs/heads/master
|
<repo_name>luckywolf/misc<file_sep>/thread_safe_queue.cpp
/*
version 1
https://www.zybuluo.com/smilence/note/540
*/
template <typename T>
class BlockingQueue{
private:
queue<T> _queue;
mutex _mutex;
condition_variable _not_empty, _not_full;
int _capacity;
public:
BoundedBuffer(int capacity) : _capacity(capacity), queue() {}
void push( const T& item){
unique_lock<mutex> locker(_mutex);
_not_full.wait(locker, [this](){return _queue.size() != _capacity; });
_queue.push(item);
_not_empty.notify_one();
locker.unlock();
}
T pop(){
unique_lock<mutex> locker(_mutex);
_not_empty.wait(locker, [this](){ return !_queue.empty() ;} ); //lambda function, capture by value
T item = _queue.front();
_queue.pop();
_not_full.notify_one();
locker.unlock();
return item;
}
};
/*
version 2
http://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/
*/
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template <typename T>
class Queue
{
public:
T pop()
{
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty())
{
cond_.wait(mlock);
}
auto item = queue_.front();
queue_.pop();
return item;
}
void pop(T& item)
{
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty())
{
cond_.wait(mlock);
}
item = queue_.front();
queue_.pop();
}
void push(const T& item)
{
std::unique_lock<std::mutex> mlock(mutex_);
queue_.push(item);
mlock.unlock();
cond_.notify_one();
}
void push(T&& item)
{
std::unique_lock<std::mutex> mlock(mutex_);
queue_.push(std::move(item));
mlock.unlock();
cond_.notify_one();
}
private:
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable cond_;
};<file_sep>/find_the_second_largest_number_in_an_array.cpp
/*
http://cs-technotes.blogspot.com/2010/11/find-second-largest-number-in-array.html?view=sidebar
write a function to return the second largest number in an array
Method 1: brute force
round 1: put the largest number to the tail x[n-1]
round 2: find the max from x[0..n-2]
time complexity: 2n -3
Code:
*/
int secondLargest(int* arr)
{
if(!arr)
return -1;
int* head = arr;
int len=0;
while((head+1) != NULL)
{
if(*head >*(head+1))
{
int t=*head;
*head = *(head+1);
*(head+1) = t;
}
head++;
len++;
}
int secMax = *arr;
for(int i=1;i<len-1;i++)
{
if(*(arr+i)>secMax)
secMax = *(arr+i);
}
return secMax;
}
/*
Method 2: tournament
the second largest number must be compared to the largest number.
find the largest one from the losers of the largest number
Code:
*/<file_sep>/iterator_list.cpp
template<typename T>
class Node{ //used by List
private:
Node(T data, Node<T>* next):_data(data), _next(next){}
T _data;
Node<T>* _next;
friend class List<T>; //only friend can call private
friend class ListIterator<T>;
};
template<typename T>
class List{
public:
List(Node<T>* head = NULL, Node<T>* tail = NULL);
List(const List<T>& orig);
List<T>& operator=(const List<T>& orig);
void push_front();
void push_end();
void pop_front();
void pop_end();
//the following are used for iterator:
typedef ListIterator<T> iterator;
iterator begin(){return iterator(_head); }
iterator end(){return iterator(); }
private:
Node<T> *_head, *_tail;
};
template<typename T>
class ListIterator{
public:
ListIterator(Node<T>* cur = NULL): _cur(cur){}
ListIterator(const ListIterator<T>& orig){_cur = orig._cur;}
ListIterator& operator=(const ListIterator<T>& orig){
_cur = orig_cur;
return *this;}
bool operator==(const ListIterator<T>& orig){return _cur == orig._cur;}
ListIterator<T>& operator++(){
_cur = _cur->_next;
return *this; }
ListIterator<T> operator++(int i){
ListIterator a(*this);
_cur = _cur->_next;
return a; }
const T operator*() const {
return _cur->_data;
}
private:
Node<T>* _cur;
};
<file_sep>/heap.cpp
#include <vector>
using namespace std;
template <typename T>
class heap {
public:
void insert(T t);
T getMin();
};
/* version 1 */
class intHeap : public heap<int> {
public:
intHeap(int m): _maxSize(m), _size(0), _vec(m) {}
void insert(int val) {
assert(_size < _maxSize);
int i, p;
_vec[_size++] = val;
for (int i = _size-1; i > 0 && _vec[p = (i-1)/2] > _vec[i]; i = p) {
swap(p, i);
}
}
int getMin() {
assert(_size > 0);
int i, c;
int res = _vec[0];
_vec[0] = _vec[--_size];
for (int i = 0; (c = 2*i+1) < _size; i = c) {
if (c+1 < _size && _vec[c+1] < _vec[c]) {
++c;
}
if (_vec[i] <= _vec[c]) {
break;
}
swap(c, i);
}
return res;
}
private:
int _maxSize, _size;
vector<int> _vec;
swap(int i, int j) {
int temp = _vec[i];
_vec[i] = _vec[j];
_vec[j] = temp;
}
};
/* version 2 */
class intHeap : public heap<int> {
public:
intHeap(int m): _maxSize(m), _size(0), _vec() {}
void insert(int val) {
assert(_vec.size() < _maxSize);
int i, p;
_vec.push_back(val);
for (int i = _vec.size()-1; i > 0 && _vec[p = (i-1)/2] > _vec[i]; i = p) {
swap(p, i);
}
}
int getMin() {
assert(_vec.size() > 0);
int i, c;
int res = _vec[0];
_vec[0] = _vec.back();
vec.pop_back();
for (int i = 0; (c = 2*i+1) < _vec.size(); i = c) {
if (c+1 < _vec.size() && _vec[c+1] < _vec[c]) {
++c;
}
if (_vec[i] <= _vec[c]) {
break;
}
swap(c, i);
}
return res;
}
private:
int _maxSize;
vector<int> _vec;
swap(int i, int j) {
int temp = _vec[i];
_vec[i] = _vec[j];
_vec[j] = temp;
}
};<file_sep>/print_Flat_to_Tree.cpp
/*
http://leetcode.com/2010/09/saving-binary-search-tree-to-file.html
http://leetcode.com/2010/09/serializationdeserialization-of-binary.html
*/
#include <iostream>
#include <fstream>
using namespace std;
struct TreeNode {
int val;
TreeNode * parent;
TreeNode(int x, TreeNode) : val(x){}
};
void readFile(unordered_map<int, TreeNode *> &lookup, ifstream &fin)
{
pair<int, int> token;
readNextLine(token, fin);
int empVal = token->first;
int mgrVal = token->second;
TreeNode *empTreeNode, *mgrTreeNode;
if (lookup.find(mgrVal) != lookup.end()) {
mgrTreeNode = lookup[mgrVal];
} else {
mgrTreeNode = new TreeNode(mgrVal);
lookup[mgrVal] = mgrTreeNode;
}
if (lookup.find(empVal) != lookup.end()) {
empTreeNode = lookup[empVal];
} else {
empTreeNode = new TreeNode(empVal);
lookup[empVal] = empTreeNode;
}
empTreeNode->parent = mgrTreeNode;
mgrTreeNode->children.push_back(empTreeNode);
}
void findRoot(unordered_map<int, TreeNode *> &lookup, vector<TreeNode *> &rootVec) {
for (unordered_map<int, TreeNode *>::iterator it = lookup.begin(); it != lookup.end(); ++it) {
if (it->second->parent == NULL) {
rootVec->push_back(it->second);
}
}
void printTreeRe(TreeNode* root, level) {
string padding(level, '\t');
if (root) {
cout << padding << root->val << endl;
}
for (int i = 0; i < root->children.size(); i++) {
printTreeRe(root->children[i], level + 1);
}
}
<file_sep>/binaryTreeToArray.cpp
/* convert the linked list representation of a binary tree to
the array representation
*/
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 100;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int x = -1): val(x), left(NULL), right(NULL) {}
};
TreeNode *p, node[maxn];
int cnt;
void init(){
p = NULL;
memset(node, '\0', sizeof(node));
cnt = 0;
}
void create_minimal_tree(TreeNode* &head, int a[], int start, int end){
if(start <= end){
int mid = (start + end) >> 1;
node[cnt].val = a[mid];
head = &node[cnt++];
create_minimal_tree(head->left, a, start, mid-1);
create_minimal_tree(head->right, a, mid+1, end);
}
}
void convertDFSRe(vector<int> &res, TreeNode* root, int index) {
if (root) {
res[index] = root->val;
if (root->left) {
convertDFSRe(res, root->left, 2 * index + 1);
}
if (root->right) {
convertDFSRe(res, root->right, 2 * index + 2);
}
}
}
vector<int> convert(TreeNode* root, int height){
vector<int> res(1 << height);
// if starting with index 1
// leftChildIndex = 2 * parentIndex, rightChildIndex = 2 * parentIndex + 1
// parentIndex = childIndex / 2;
// if starting with index 0
// leftChildIndex = 2 * parentIndex + 1, rightChildIndex = 2 * parentIndex + 2
// parentIndex = (childIndex - 1) / 2;
convertDFSRe(res, root, 0);
return res;
}
// using array instead of vector
void convertDFSRe_2(int *res2, TreeNode* root, int index) {
if (root) {
res2[index] = root->val;
if (root->left) {
convertDFSRe_2(res2, root->left, 2 * index + 1);
}
if (root->right) {
convertDFSRe_2(res2, root->right, 2 * index + 2);
}
}
}
int *convert_2(TreeNode* root, int height){
int *res2 = new int[1 << height];
// memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
// memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements
memset(res2, 0, (1 << height) * sizeof(res2)); // important
convertDFSRe_2(res2, root, 0);
return res2;
}
int main(){
int a[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
};
init();
TreeNode *head = NULL;
create_minimal_tree(head, a, 0, 9);
int height = 4;
vector<int> res = convert(head, height);
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << " ";
}
cout << endl;
int *res2 = convert_2(head, height);
for (int i = 0; i < (1 << height); ++i) {
cout << res2[i] << " ";
}
cout << endl;
return 0;
}
<file_sep>/thread_safe_circular_queue.cpp
/*
http://cs-technotes.blogspot.com/2010/11/thread-safe-circular-queue.html?view=sidebar
Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(),
enqueue() and dequeue() the queue. Make it thread safe.
*/
#include<pthread.h>
#define DEFAULT_SIZE 100
class circularQueue{
private:
int *m_queue;
int p_head;
int p_tail;
int m_cap;
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
public:
circularQueue(int size)
{
/*in case invalid input*/
if(size<0)
size = DEFAULT_SIZE ;
m_queue = new int[size];
p_head = 0;
p_tail = -1;
m_cap = 0;
pthread_mutex_init(&mp,NULL);
}
bool enqueue(int x)
{
bool res= false;
p_thread_mutex_lock(&mp);
/*queue is full*/
if(m_cap == size)
{
res = false;
}
else
{
m_queue[(++p_tail)%size)] = x;
++m_cap;
res = true;
}
p_thread_mutex_unlock(&mp);
return res;
}
int dequeue()
{
int res=0;
pthread_mutex_lock(&mp);
/*empty queue*/
if(m_cap == 0)
{
throw("empty queue!");
pthread_mutex_unlock(&mp);
}
else{
res = m_queue[p_head];
p_head = (p_head+1)%size;
}
pthread_mutex_unlock(&mp);
return res;
}
~virtual circularQueue()
{
delete[] m_queue;
m_queue = NULL;
pthread_mutex_destroy(&mp);
}
}
<file_sep>/lowest_common_ancestor_of_two_nodes_in_a_binary_tree.cpp
/*
http://cs-technotes.blogspot.com/2010/12/lowest-common-ancestor-of-two-nodes-in_09.html?view=sidebar
find the lowest common ancestor of two nodes in a binary tree
In binary search tree, all values in the left subtree is samller than the node, and all values in the right subtree
is larger than the node, so we can find the lowest common ancestor in binary search tree by comparing the values.
The first node which has value between (a,b] is their lowest common ancestor.
However, in binary tree,there is no such characteristic. We need to search all paths from root to these two nodes. There are two
situation:
1) node a is in the left subtree of current node, and node b is in the right subtree of current node, obviously current node will
the be lowest common ancestor
2) node a and node b are in the same side. If they are both in the left subtree, we could search the lowest common ancestor from
the left node of current node; if they are both in the right subtree, we could search the lowest common ancestor from the right
node of current node.
*/
//find the lowest common ancestor of a and b in a binary tree
BTNode* lowestCommonAncestorinBT(BTNode* root, int a, int b )
{
if(root == NULL) {
return NULL;
}
if(root->val == a || root->val == b) {
return root;
} else{
BTNode* left = lowestCommonAncestorinBT(root->left, a, b);
BTNode* right = lowestCommonAncestorinBT(root->right, a, b);
if(left && right) { //one node is in the left and the other is in the right
return root;
} else { //both in left or both in right
return left ? left : right; //if both in the left,return left
}
}
}
<file_sep>/dijkstra_shorted_path.cpp
/*
http://www.geeksforgeeks.org/greedy-algorithms-set-6-dijkstras-shortest-path-algorithm/
Greedy Algorithms | Set 7 (Dijkstra¡¯s shortest path algorithm)
Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph.
Dijkstra¡¯s algorithm is very similar to Prim¡¯s algorithm for minimum spanning tree. Like Prim¡¯s MST, we generate
a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in
shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the
algorithm, we find a vertex which is in the other set (set of not yet included) and has minimum distance from source.
Below are the detailed steps used in Dijkstra¡¯s algorithm to find the shortest path from a single source vertex
to all other vertices in the given graph.
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree,
i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn¡¯t include all vertices
¡.a) Pick a vertex u which is not there in sptSetand has minimum distance value.
¡.b) Include u to sptSet.
¡.c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all
adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge
u-v, is less than the distance value of v, then update the distance value of v.
Let us understand with the following example:
The set sptSetis initially empty and distances assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF}
where INF indicates infinite. Now pick the vertex with minimum distance value. The vertex 0 is picked, include
it in sptSet. So sptSet becomes {0}. After including 0 to sptSet, update distance values of its adjacent vertices.
Adjacent vertices of 0 are 1 and 7. The distance values of 1 and 7 are updated as 4 and 8. Following subgraph
shows vertices and their distance values, only the vertices with finite distance values are shown. The vertices
included in SPT are shown in green color.
Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). The vertex 1 is
picked and added to sptSet. So sptSet now becomes {0, 1}. Update the distance values of adjacent vertices of 1.
The distance value of vertex 2 becomes 12.
Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). Vertex 7 is picked.
So sptSet now becomes {0, 1, 7}. Update the distance values of adjacent vertices of 7. The distance value of
vertex 6 and 8 becomes finite (15 and 9 respectively).
Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). Vertex 6 is picked.
So sptSet now becomes {0, 1, 7, 6}. Update the distance values of adjacent vertices of 6. The distance value of
vertex 5 and 8 are updated.
We repeat the above steps until sptSet doesn¡¯t include all vertices of given graph. Finally, we get the following
Shortest Path Tree (SPT).
How to implement the above algorithm?
We use a boolean array sptSet[] to represent the set of vertices included in SPT. If a value sptSet[v] is true,
then vertex v is included in SPT, otherwise not. Array dist[] is used to store shortest distance values of all vertices.
*/
// A C / C++ program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
// Funtion that implements Dijkstra's single source shortest path algorithm
// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V-1; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < V; v++)
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolution(dist, V);
}
// driver program to test above function
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
dijkstra(graph, 0);
return 0;
}
/*
Output:
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Notes:
1) The code calculates shortest distance, but doesn¡¯t calculate the path information. We can create a parent array, update the parent array when distance is updated (like prim¡¯s implementation) and use it show the shortest path from source to different vertices.
2) The code is for undirected graph, same dijekstra function can be used for directed graphs also.
3) The code finds shortest distances from source to all vertices. If we are interested only in shortest distance from source to a single target, we can break the for loop when the picked minimum distance vertex is equal to target (Step 3.a of algorithm).
4) Time Complexity of the implementation is O(V^2). If the input graph is represented using adjacency list, it can be reduced to O(E log V) with the help of binary heap. We will soon be discussing O(E Log V) algorithm as a separate post.
5) Dijkstra¡¯s algorithm doesn¡¯t work for graphs with negative weight edges. For graphs with negative weight edges, Bellman¨CFord algorithm can be used, we will soon be discussing it as a separate post.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
*/
<file_sep>/closure_sample.js
/* wrong */
for(var i = 1; i < 10; i++) {
setTimeout(function() { alert(i) }, 100);
}
/* correct */
for(var i = 1; i < 10; i++) {
(function(index) {
setTimeout(function() {
alert(index); }, 100);})(i);
}<file_sep>/read_any_use_read_4k.cpp
class GenericReader {
Reader4k _reader4k;
int _buf_ptr;
char* _internal_buf;
public:
int Read(int n, char* buf) {
int count = 0;
int remain = n;
int buf_ptr = 0;
while (remain > 0) {
if (buf_ptr_ == -1) {
int bytes_read = _reader4k.Read(_internal_buf);
if (bytes_read == 0) { // we have exhausted the buffer
break;
}
_buf_ptr = 0;
if (bytes_read > remain) {
memcpy(buf + buf_ptr, _internal_buf, remain);
count += remain;
_buf_ptr += remain;
return count;
} else {
remain -= bytes_read;
count += bytes_read;
_buf_ptr = -1;
memcpy(buf + buf_ptr, _internal_buf, bytes_read);
buf_ptr += bytes_read;
}
} else { // we still have stuff in _internal_buf, read those first
if (4096 - _buf_ptr > remain) {
memcpy(buf + buf_ptr, _internal_buf + _buf_ptr, remain);
_buf_ptr += remain;
count += remain;
return count;
} else {
remain -= (4096 - _buf_ptr);
count += (4096 - _buf_ptr);
memcpy(but + buf_ptr, _internal_buf + _buf_ptr, 4096 - _buf_ptr);
buf_ptr += (4096 - _buf_ptr);
_buf_ptr = -1;
}
}
}
return count;
}
};
<file_sep>/furniture.cpp
/* bridge pattern */
#include <string>
#include <iostream>
using namespace std;
class testFixture;
class material;
class furniture {
public:
furniture (material* mat): m(mat) {}
virtual void tostring() = 0;
void setMaterial(material* m) {
this->m = m;
}
material* getMaterial() {
return m;
}
void testFurniture() {
m->testMaterial();
}
private:
material* m;
};
class material {
public:
virtual string what() = 0;
void setMaterialName(string s) {
materialName = s;
}
void setTestFixture(testFixture* t) {
this->fixture = t;
}
testFixture* getTestFixture() {
return fixture;
}
void testMaterial() {
fixture->test();
}
private:
string materialName;
testFixture *fixture;
};
class testFixture {
public:
virtual void test() = 0;
};
class chokingTestFixture: testFixture {
virtual void test() {
// test choking
}
}
class fireTestFixture: testFixture {
virtual void test() {
// test fire
}
}
class steel: public material {
public:
steel(){
setMaterialName("steel");
setTestFixture(new fireTestFixture());
}
virtual string what(){
return "steel";
}
};
class wood: public material {
public:
wood(){
setMaterialName("wood");
setTestFixture(new chokingTestFixture());
}
virtual string what() {
return "wood";
}
};
class chair: public furniture {
public:
chair(material* mat): furniture(mat) {}
void tostring() {
cout << "this is chair and I am made of: " << getMaterial()->what() << endl;
}
};
class desk: public furniture {
public:
desk(material* mat): furniture(mat) {}
void tostring() {
cout << "this is desk and I am made of: " << getMaterial()->what() << endl;
}
};
int main() {
furniture* f = new desk(new steel());
f->tostring();
return 0;
}
<file_sep>/binary_tree_serialization.cpp
/*
http://leetcode.com/2010/09/saving-binary-search-tree-to-file.html
http://leetcode.com/2010/09/serializationdeserialization-of-binary.html
*/
#include <iostream>
#include <fstream>
using namespace std;
struct TreeNode {
string val;
TreeNode *left;
TreeNode *right;
TreeNode(string x) : val(x), left(NULL), right(NULL) {}
};
// void serialize(ofstream& outfile, TreeNode* current)
// {
// if(current == NULL)
// {
// outfile << '#';
// return;
// }
// outfile << current->val;
// serialize(outfile, current->left);
// serialize(outfile, current->right);
// }
// void deserialize(ifstream& infile, TreeNode*& current)
// {
// char ch;
// infile >> ch;
// if(ch == '#')
// return;
// current = new TreeNode(int(ch));
// deserialize(infile, current->left);
// deserialize(infile, current->right);
// }
void serialize(vector<string> &strs, TreeNode* root) {
if (root == NULL) {
str.push_back("#");
return;
}
strs.push_back(root->val);
serialize(strs, root->left);
serialize(strs, root->right);
}
TreeNode *deserialize(vector<string> &strs, int index) {
// the last token should be "#", so we don't need to check index < strs.size()
string token = strs[index++];
if( token == "#") {
return NULL;
}
TreeNode *res = new TreeNode(token);
res->left = deserialize(strs, index);
res->right = deserialize(strs, index);
return res;
}
<file_sep>/bitmap.cpp
int mem[maxn];
const int size = 8 * sizeof(int);
void set(int x) {
mem[x / size] |= (1 << (x % size))
}
int get(int x) {
return mem[x / size] & (1 << (x % size));
}
<file_sep>/longest_increasing_sequence_of_an_array.cpp
/*
http://cs-technotes.blogspot.com/2010/12/longest-increasing-sequence-of-array.html?view=sidebar
Given an integer array, return the longest increasing sequence, for instance: for the array {1,3,2,4,3,5,4,6},
the longest increasing sequence is {1,3,4,5,6}
Algorithm: it's a dynamic programming problem, slightly different to longest common sequence.
scan the array, for each integer a_i, compare it with all previous integers [a_0...a_i-1], if it's larger than a_j,
then the length of the sequence that ends with a_j can increase one by adding a_i to that sequence.
Therefore, we need one array(s in below code) to record the current max length of sequences which ends with a_i,
and we also need one array(path in below code) to record the previous integer's position so that we can print the
longest increasing sequence.
Code:
*/
void printpath(int *arr, int *path, int end)
{
if(end> -1){
printpath(arr,path,path[end]);
printf("%d ",arr[end]);
}
}
void longestincreasingsequence(int *arr, int n)
{
int *s = new int[n]; //current max number of ints
int *path = new int[n]; //previous number
memset(path,0,n);
int global_max = 1; //at least one number
int end_pos = 0;
s[0]= 1;
path[0]= -1;
for(int i=1;i<n;i++){
int local_prev = -1;
s[i] = 1;
for(int j=0;j<i;j++){
if(arr[j]<arr[i] && s[i]<(s[j]+1)){
s[i]= s[j]+1;
local_prev = j;
}
}
path[i] = local_prev;
if(global_max < s[i]){
global_max = s[i];
end_pos = i;
}
}
printf(" size of longest seq : %d \n",global_max);
printpath(arr,path,end_pos);
printf("\n");
delete(path);
delete(s);
}
/*
Question:
for above algorithm, the return sequence is {1,3,4,5,6}, however, {1,2,3,4,6} is also a candidate, as well as {1,2,4,5,6}. Why it can't find these two sequences?
I think this algorithm sort of like greedy algorithm. It can find one optimal solution, not enumerate every optimal solution. Need to prove it.
*/
<file_sep>/bst_2nd_max.cpp
/*
Find the second max in BST.
http://stackoverflow.com/questions/11425352/second-max-in-bst
*/
struct TreeNode{
int val;
TreeNode *left, *right, *parent;
TreeNode(int x = -1): val(x), left(NULL), right(NULL), parent(NULL) {}
};
TreeNode *findRightmostNode(TreeNode *&root) {
TreeNode *res = root;
while (res->right != NULL) {
res = res->right;
}
return res;
}
/*
Recursively, and use parent pointer
*/
TreeNode *findSecondMaxInBST(TreeNode *root) {
if (root->right != NULL) {
// The check above establishes that the rightmost node has a parent
return findRightmostNode(root->right)->parent;
else if (root->left != NULL) {
// Root is the rightmost node; find the largest node among the remaining ones
return findRightmostNode(root->left)
} else {
// The tree has only a root and no other nodes
return NULL
}
}
/*
Iteratively, without parent pointer
*/
TreeNode *findSecondMaxInBST_2(TreeNode *root) {
TreeNode *res = NULL;
TreeNode *par = NULL;
TreeNode *cur = root;
while (cur->right != NULL) {
par = cur;
cur = cur->right;
}
if (cur->left != NULL) {
cur = cur->left;
while (cur->right != NULL) {
cur = cur->right;
}
secondMax = cur;
} else if (par != NULL) {
secondMax = par; // BST has at least two nodes
}
return secondMax;
}
<file_sep>/dining_philosophers.cpp
/*
http://code.msdn.microsoft.com/windowsdesktop/Dining-Philosophers-in-C-11-f6bb06a8
*/
class Chopstick
{
public:
Chopstick(){};
mutex m;
};
auto eat = [](Chopstick* leftChopstick, Chopstick* rightChopstick, int philosopherNumber)
{
if (leftChopstick == rightChopstick)
throw exception("Left and right chopsticks should not be the same!");
lock(leftChopstick->m, rightChopstick->m); // ensures there are no deadlocks
lock_guard<mutex> a(leftChopstick->m, adopt_lock);
lock_guard<mutex> b(rightChopstick->m, adopt_lock);
string pe = "Philosopher " + to_string(philosopherNumber) + " eats.\n";
cout << pe;
//std::chrono::milliseconds timeout(500);
//std::this_thread::sleep_for(timeout);
};
static const int numPhilosophers = 5;
// 5 utencils on the left and right of each philosopher. Use them to acquire locks.
vector< unique_ptr<Chopstick> > chopsticks(numPhilosophers);
for (int i = 0; i < numPhilosophers; ++i)
{
auto c1 = unique_ptr<Chopstick>(new Chopstick());
chopsticks[i] = move(c1);
}
// This is where we create philosophers, each of 5 tasks represents one philosopher.
vector<thread> tasks(numPhilosophers);
tasks[0] = thread(eat,
chopsticks[0].get(), // left chopstick: #1
chopsticks[numPhilosophers - 1].get(), // right chopstick: #5
0 + 1, // philosopher number
1,
numPhilosophers
);
for (int i = 1; i < numPhilosophers; ++i)
{
tasks[i] = (thread(eat,
chopsticks[i - 1].get(), // left chopstick
chopsticks[i].get(), // right chopstick
i + 1, // philosopher number
i,
i + 1
)
);
}
// May eat!
for_each(tasks.begin(), tasks.end(), mem_fn(&thread::join));
/*
Philosopher 1 picked 1 chopstick.
Philosopher 3 picked 2 chopstick.
Philosopher 1 picked 5 chopstick.
Philosopher 3 picked 3 chopstick.
Philosopher 1 eats.
Philosopher 3 eats.
Philosopher 5 picked 4 chopstick.
Philosopher 2 picked 1 chopstick.
Philosopher 2 picked 2 chopstick.
Philosopher 5 picked 5 chopstick.
Philosopher 2 eats.
Philosopher 5 eats.
Philosopher 4 picked 3 chopstick.
Philosopher 4 picked 4 chopstick.
Philosopher 4 eats.
*/
<file_sep>/iterator_binary_tree.cpp
using namespace std;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
template <typname T>
class Iterator {
public:
virtual ~Iterator() {}
virtual void Reset() = 0;
virtual bool hasNext() = 0;
virtual T next() = 0;
};
enum traversalMethod {INORDER, PREORDER, POSTORDER};
class BinaryTreeIterator : public Iterator<TreeNode *> {
public:
BinaryTreeIterator(TreeNode *root, traversalMethod method = INORDER) {
_root = root;
_method = method;
initialzation(_root);
}
void Reset() {
_stk.clear();
initialization(_root);
}
bool hasNext() {
return !_stk.empty();
}
TreeNode *next() {
if (!hasNext()) {
return NULL;
}
TreeNode *res = _stk.top();
_stk.pop();
switch(_method) {
case PREORDER:
if (res->right) {
_stk.push(res->right);
}
if (res->left) {
_stk.push(res->left);
}
break;
case POSTORDER:
if (!_stk.empty()) {
TreeNode *peek = _stk.top();
if (res != peek->right) {
initialization(peek->right);
}
}
break;
default: // INORDER
initialization(res->right);
break;
}
return res;
}
private:
stack<TreeNode *> _stk;
TreeNode *_root;
traversalMethod _method;
void initialization(TreeNode *cur) {
swicth(_method) {
case PREORDER:
if (cur != NULL) {
_stk.push(cur);
}
break;
case POSTORDER:
while (cur != NULL) {
_stk.push(cur);
if (cur->left) {
cur = cur->left;
} else {
cur = cur->right;
}
}
break;
default: // INORDER
while (cur != NULL) {
_stk.push(cur);
cur = cur->left;
}
break;
}
}
}
};
<file_sep>/elevator.cpp
/*
1 Elevator Object, 应该包含physical components: Door, Indicator Lights,
Control Panel. 一些性质(Non physical properties): Speed, Num of floors,
capacity, max weight. 所能从事的操作methods: moveto, stop, ringbell。然后电
梯应该能够handle user request, 所以还应有一个requestQueue, 电梯应该根据自己
的state 和 requestQueue做出moveto, stop的决定,所以有一component:
requestHandler(Strategy pattern),可以set不同的requestHanlder.
2 Door, properties: State, method: open, close, getState.
3 Indicator light(指示所到楼层),properties: state; method: on, off,
getState
4 Control Panel, 包含physical component: Floor Buttons, Other buttons(也可直
接把Buttons 当作 elevator的components,还没考虑哪一个方法好)
5 Button, properties: floorNum, Parent Elevator, methods: OnPress(Observer
Pattern).
6 ElevatorRequestHandler: handleRequest(Elevator ele, requestList rlist), 可
以define 一个interface, 然后又各种不同实现
7 Request: 可以define 一个abstract class, 然后有子类movingRequest,
helpRequest doorRequest etc.
*/
class Door {
public:
void open();
void close();
int getState() {
return state;
}
private:
int state; // Door is open or closed.
};
class Button {
public:
void push(); // Send a request to go to a certain floor.
void clear();
int getIndicate() {
return indicate;
}
int getState() {
return state;
}
private:
int indicate; // What does this Button indicate?
int state;
};
class Alarm {
public:
void beep();
void stopBeep();
int getState() {
return state;
}
private:
int state; // Current state of alarm, beeping or not
};
class Light {
public:
void turnOn();
void turnOff();
int getState() {
return state;
}
private:
int state; // Current state of light, on or off
};
class Elevator {
public:
void moveTo(int dest);
int setState(int st);
int getState();
int getDest();
int setIndex();
int getIndex();
int setCurFloor();
int getCurFloor();
int checkOverLoad();
void updateLoad(double load);
private:
int state;
int index;
int destination;
int curFloor;
// int *requests;
Button *buttons;
Alarm al;
Light Lt;
double maxLoad;
double currentLoad;
};
/*
我感觉Elevator类还是应该记录所有它应该停靠的楼层,比如用stop_floors表示,而
不只是一个destination。这个可以用bitmap或者数组来实现。电梯里的人可以按下多
个楼层。另外bank收到楼梯间的request的时候,决定哪个电梯来响应这个服务,并把
该楼层加入到相应服务的电梯的stop_floors里。在某一层停过后就从中删除。
*/
class Manager {
pubic:
distributeRequest(); // Give the request to an elevator.
run();
shutDownElav();
turnOnEval();
powerOff();
powerOn();
private:
Elevator *evals;
int *requests;
int state;
};<file_sep>/trie.cpp
/*
http://www.geeksforgeeks.org/trie-insert-and-search/
Trie | (Insert and Search)
Trie is an efficient information retrieval data structure. Using trie, search complexities can be brought to optimal limit
(key length). If we store keys in binary search tree, a well balanced BST will need time proportional to M * log N, where
M is maximum string length and N is number of keys in tree. Using trie, we can search the key in O(M) time. However the
penalty is on trie storage requirements.
Every node of trie consists of multiple branches. Each branch represents a possible character of keys. We need to mark
the last node of every key as leaf node. A trie node field value will be used to distinguish the node as leaf node
(there are other uses of the value field). A simple structure to represent nodes of English alphabet can be as following,
// struct trie_node
// {
// int value; // Used to mark leaf nodes
// trie_node_t *children[ALPHABET_SIZE];
// };
Inserting a key into trie is simple approach. Every character of input key is inserted as an individual trie node.
Note that the children is an array of pointers to next level trie nodes. The key character acts as an index into the
array children. If the input key is new or an extension of existing key, we need to construct non-existing nodes of
the key, and mark leaf node. If the input key is prefix of existing key in trie, we simply mark the last node of key
as leaf. The key length determines trie depth.
Searching for a key is similar to insert operation, however we only compare the characters and move down. The search
can terminate due to end of string or lack of key in trie. In the former case, if the value field of last node is
non-zero then the key exists in trie. In the second case, the search terminates without examining all the characters
of key, since the key is not present in trie.
The following picture explains construction of trie using keys given in the example below,
root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
In the picture, every character is of type trie_node_t. For example, the root is of type trie_node_t, and it¡¯s children
a, b and t are filled, all other nodes of root will be NULL. Similarly, ¡°a¡± at the next level is having only one
child (¡°n¡±), all other children are NULL. The leaf nodes are in blue.
Insert and search costs O(key_length), however the memory requirements of trie isO(ALPHABET_SIZE * key_length * N)
where N is number of keys in trie. There are efficient representation of trie nodes (e.g. compressed trie, ternary
search tree, etc.) to minimize memory requirements of trie.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
// trie node
struct trie_node {
int value;
trie_node_t *children[ALPHABET_SIZE];
trie_node(): value(0) {
children = new trie_node*[ALPHABET_SIZE]();
}
};
// trie ADT
struct trie {
trie_node *root;
int count;
};
// Returns new trie node (initialized to NULLs)
// trie_node *getNode()
// {
// trie_node *pNode = NULL;
// pNode = new trie_node;
// return pNode;
// }
// Initializes trie (root is dummy node)
void initialize(trie_t *pTrie) {
pTrie->root = new trie_node();
pTrie->count = 0;
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(trie *pTrie, char key[]) {
int index;
trie_node *pCrawl;
pTrie->count++;
pCrawl = pTrie->root;
for(int level = 0; level < strlen(key); level++) {
index = CHAR_TO_INDEX(key[level]);
if( !pCrawl->children[index] ) {
pCrawl->children[index] = new trie_node();
}
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->value = pTrie->count;
}
// Returns non zero, if key presents in trie
int search(trie *pTrie, char key[]) {
int index;
trie_node *pCrawl;
pCrawl = pTrie->root;
for (int level = 0; level < strlen(key); level++) {
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index]) {
return 0;
}
pCrawl = pCrawl->children[index];
}
return (0 != pCrawl && pCrawl->value);
}
// Driver
int main() {
// Input keys (use only 'a' through 'z' and lower case)
char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"};
trie trie;
char output[][32] = {"Not present in trie", "Present in trie"};
initialize(&trie);
// Construct trie
for(int i = 0; i < ARRAY_SIZE(keys); i++) {
insert(&trie, keys[i]);
}
// Search for different keys
printf("%s --- %s\n", "the", output[search(&trie, "the")] );
printf("%s --- %s\n", "these", output[search(&trie, "these")] );
printf("%s --- %s\n", "their", output[search(&trie, "their")] );
printf("%s --- %s\n", "thaw", output[search(&trie, "thaw")] );
return 0;
}
<file_sep>/largest_palindrome_two_3digt_number.cpp
/*
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
*/
/* c++ version */
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
int div = 100000;
if (x < 100000) {
div = 10000;
}
while (x >= 10) {
if (x / div != x % 10) {
return false;
}
x %= div;
x /= 10;
div /= 100;
}
return true;
}
int largestPalindrome() {
int max = 0;
for (int i = 999; i > 99; --i) {
if (i * 999 < max) {
break;
}
for (int j = 999; j > 99; --j) {
int temp = i * j;
if (isPalindrome(temp)) {
if (temp > max) {
max = temp;
}
break;
}
}
}
return max;
}
int main() {
cout << largestPalindrome() << endl;
}
/* python version */
#!/usr/local/bin/python2.7
def largestPalindrome():
max = 0
for x in xrange(999, 99, -1):
if x * 999 < max:
break;
for y in xrange(999, 99, -1):
temp = x * y;
if str(temp) == str(temp)[::-1]:
if temp > max:
max = temp;
break;
return max;
print "result is " , largestPalindrome()
<file_sep>/reverse_linked_list.cpp
/*
Reversing linked list iteratively and recursively
http://leetcode.com/2010/04/reversing-linked-list-iteratively-and.html
*/
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL) {}
};
/* Iteratively */
void reverseLL(ListNode *&head) {
if (!head) {
return;
}
ListNode *pre = NULL;
ListNode *cur = head;
while(cur) {
ListNode *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head = pre;
}
/* Recursively */
void reverseLL(ListNode *&head) {
if (!head) {
return;
}
ListNode *rest = head->next;
if (!rest) {
return;
}
reverseLL(rest);
head->next->next = head;
head->next = NULL;
head = rest;
}<file_sep>/sqrt_float.cpp
/*
Question: Write a function to implement float sqrt(float value).
Solution 1: Use the binary search
When the number is greater than 1, its square root is between 1 and itself.
If the number is less than 1, its square root is between itself and 1.
We first initialize the upper and lower bounds of the square root and use the
middle point as the test. If the square of the middle point is larger than the
given number, we reset the upper bound to the middle point. Otherwise, we reset
the lower bound to be the middle point. We repeat this until the error is
less than a threshold.
*/
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <iostream>
#define EPSILON 1e-3
float sqrt1(float value){
if(value < 0){
std::cout << "Error in the input value" << std::endl;
return -1;
}
float a = 1;
float b = value;
if(value < 1){
a = value;
b = 1;
}
float mid = (a + b) / 2;
float err = mid * mid - value;
while(fabs(err) > EPSILON){
if(err > 0){
b = mid;
}else{
a = mid;
}
mid = (a + b) / 2;
err = mid * mid - value;
}
return mid;
}
/*
Solution 2: Use Newton method
Suppose the given number is a, we want to solve the equation x^2-a=0.
We can first guess a random number as the initial solution. We denote the first guess as x0. x1 is computed as x1=x0-f(x0)/f'(x0), which is equal to x1=x0/2+a/2x0. We do this until we find the root of the equation.
*/
float sqrt2(float value){
if(value < 0){
std::cout << "Error in the input value" << std::endl;
return -1;
}
if(value == 0){
return 0;
}
float x = (float)(rand() + 1) / ((float)RAND_MAX + 1) * std::max(1.0f, value); // x0 is in the range of (0, max(1, value)].
while(fabs(x * x - value) > EPSILON){
x = x / 2 + value / (2 * x);
}
return x;
}<file_sep>/factor_of_n.cpp
/*
Given a method that takes in a positive non-zero number N,
return from that method the total number of factors of N.
4 = 1, 2, 4
27 = 1, 3, 9
36 = 1, 2, 3, 4, 6, 9, 12, 18, 36
*/
vector<int> fatctor(int n) {
assert(n >= 1);
vector<int> res;
for (int i = 1; i <= sqrt(n); ++i) {
if (n % i == 0) {
res.push_back(i);
if (i != sqrt(n)) {
res.push_back(n / i);
}
}
}
return res;
}
|
7d50014460a13299c5f81259d1d9b8af13e127e9
|
[
"JavaScript",
"C++"
] | 24
|
C++
|
luckywolf/misc
|
aeb3f97559d17c35d591f811ca3ed4c17be58c0a
|
6350e1b4ba5ba2906b451d1ff0fe869fed102164
|
refs/heads/master
|
<file_sep>package a.benri.notifications
import android.annotation.SuppressLint
import android.app.Notification
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessage"
override fun onNewToken(token: String?) {
Log.d(TAG, "$token")
}
//Se recoge el mensaje
@SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "Hola: ${remoteMessage.from}")
val mNotificationID = 101
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(mNotificationID, notificationIntent(remoteMessage))
}
//Se crea la notificacion
private fun defaultNotification(remoteMessage: RemoteMessage) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, NotificationUtils.CHANNEL_ID)
}
else {
Notification.Builder(this)
}.apply {
setContentTitle(remoteMessage.notification?.title)
setContentText(remoteMessage.notification?.body)
setSmallIcon(android.R.drawable.ic_dialog_info)
}
//Se crea el Intent que muestra la notificación
private fun notificationIntent(remoteMessage: RemoteMessage) = PendingIntent.getActivity(this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT).run {
defaultNotification(remoteMessage).setContentIntent(this).build()
}
}<file_sep>package a.benri.notifications
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.widget.Button
class MainActivity : AppCompatActivity() {
//Notificaciones en local
var CHANNEL_ID: String = "channel id"
var notificationId: Int = 10
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Util para API >= 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationUtils(this)
}
createNotificationChannel()
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
with(NotificationManagerCompat.from(this)) {
// el id es único para cada notificación
notify(notificationId, mBuilder.build())
}
}
}
var mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_template_icon_bg)
.setContentTitle("My notification")
.setContentText("Here we have our new Notification ;)")
.setStyle(
NotificationCompat.BigTextStyle()
.bigText("Here we have our new Notification ;)")
)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Registro del channel
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
}
|
397fba2cb1f1991c2bd9ecc659ad2723964065d3
|
[
"Kotlin"
] | 2
|
Kotlin
|
Stelio3/NotificationFirebase
|
6fefac02b6d1737873038cc6e74741807d9110d8
|
4dea79ebd44f2a686c9d717546fc52b73731f86f
|
refs/heads/master
|
<repo_name>alicanyesiloglu/Sinif_icinde_geriye_deger_dondurmeyen_metot_4_islem<file_sep>/d 52 sınıf icinde geriye deger donduren metotlar/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace d_52_sınıf_icinde_geriye_deger_donduren_metotlar
{
class Program
{
static void Main(string[] args)
{
islemler isl = new islemler();
int s1, s2;
{
// toplama
Console.Write("sayi 1:");
s1 = Convert.ToInt16(Console.ReadLine());
Console.Write("sayi 2:");
s2 = Convert.ToInt16(Console.ReadLine());
isl.topla(s1, s2);
// fark
Console.Write("sayi 1:");
s1 = Convert.ToInt16(Console.ReadLine());
Console.Write("sayi 2");
s2 = Convert.ToInt16(Console.ReadLine());
isl.cikarma(s1, s2);
//carpma
Console.Write("Sayi 1:");
s1 = Convert.ToInt16(Console.ReadLine());
Console.Write("sayi 2:");
s2 = Convert.ToInt32(Console.ReadLine());
isl.carpma(s1, s2);
//Bolme
Console.Write("Sayi 1:");
s1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Sayi 2:");
s2 = Convert.ToInt32(Console.ReadLine());
isl.bolme(s1, s2);
}
}
}
}
<file_sep>/d 52 sınıf icinde geriye deger donduren metotlar/islemler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace d_52_sınıf_icinde_geriye_deger_donduren_metotlar
{
class islemler
{
public int topla(int s1,int s2)
{
int s3 = s1 + s2;
Console.WriteLine("Toplamı" + s3);
return s3;
}
public int cikarma(int s1,int s2)
{
int s3 = s1 - s2;
Console.WriteLine("Cikarma" + s3);
return s3;
}
public int carpma(int s1,int s2)
{
int s3 = s1 * s2;
Console.WriteLine("Carpma" + s3);
return s3;
}
public int bolme (int s1,int s2)
{
int s3 = s1 / s2;
Console.WriteLine("Bolme" + s3);
return s3;
}
}
}
|
bba1268a92060ffab93ea50a338bab1c1d4beaf0
|
[
"C#"
] | 2
|
C#
|
alicanyesiloglu/Sinif_icinde_geriye_deger_dondurmeyen_metot_4_islem
|
7ca37f7bd9fd9a425232fd654d585c373c7f488d
|
30375284c53058e4398e1592b17e00405b66490a
|
refs/heads/master
|
<repo_name>davidjdclarke/scripts<file_sep>/matplotlib/main.py
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
PERIOD = 10
if __name__ == "__main__":
file = './demo4.csv'
df = pd.read_csv(file)
keys = df.keys()
l = len(df[keys[0]])
t = np.linspace(0, 10, num=l)
if file == './demo1.csv' or file == './demo2.csv':
for i in range(l):
df['qd1'][i] = df['qd1'][0]
df['qd2'][i] = df['qd2'][0]
df['qd3'][i] = df['qd3'][0]
df['qd1'][0] = df['q1'][0]
df['qd2'][0] = df['q2'][0]
df['qd3'][0] = df['q3'][0]
fig, axs = plt.subplots(3)
axs[0].plot(t, df['q1'], label='q1')
axs[0].plot(t, df['qd1'], label='q1_d')
axs[0].set_title("q1 vs q1_d")
axs[0].legend()
axs[1].plot(t, df['q2'], label='q1')
axs[1].plot(t, df['qd2'], label='q2_d')
axs[1].set_title("q2 vs q2_d")
axs[1].legend()
axs[2].plot(t, df['q3'], label='q1')
axs[2].plot(t, df['qd3'], label='q3_d')
axs[2].set_title("q3 vs q3_d")
axs[2].legend()
if file == './demo1.csv':
fig.suptitle("Demo 1")
elif file == './demo2.csv':
fig.suptitle("Demo 2")
elif file == './demo3.csv':
fig.suptitle("Demo 3")
elif file == './demo4.csv':
fig.suptitle("Demo 4")
plt.show()
<file_sep>/requrest/server.py
import requests
r = requests.get('https://xkcd.com/1906/')
sleep(2)<file_sep>/histogram.py
from matplotlib import pyplot as plt
import numpy as np
def lut(offset, mean, e):
max_val = 256
hist = np.zeros((256), dtype=np.uint8)
for i in range(max_val):
if offset >= 0:
num = max_val - 1 - 2*offset
den = 1 + ((mean / (i+1)) ** (10 * e))
hist[i] = (num / den) + 2*offset
else:
num = max_val - 1 + 2*offset
den = 1 + ((mean / (i+1)) ** (10 * e))
hist[i] = (num / den)
return hist
# params
h1 = lut(0, 128, 1)
h2 = lut(25, 128, 1)
h3 = lut(50, 128, 1)
h4 = lut(75, 128, 1)
h5 = lut(100, 128, 1)
plt.plot(h1, label='h1')
plt.plot(h2, label='h2')
plt.plot(h3, label='h3')
plt.plot(h4, label='h4')
plt.plot(h5, label='h5')
print('h1 (mean):' + str(np.mean(h1)))
print('h2 (mean):' + str(np.mean(h2)))
print('h3 (mean):' + str(np.mean(h3)))
print('h4 (mean):' + str(np.mean(h4)))
print('h5 (mean):' + str(np.mean(h5)))
plt.grid()
plt.legend()
plt.show()
<file_sep>/davidclarke.py
import numpy as np
def score_probability(statement):
"""
This function returns true or false depending on what percentage of the elements in the input
array match the key words dictated by the local variable "key_words".
If more than 70% of elements in statements match the key words, functions returns True, else
the function return False.
Input(s):
statement --> list[string]
Output(s):
Boolean
"""
# Set key Words
key_words = ['age', 'year', 'born', 'date of birth']
# Zero word counts
words_total = 0
occurences = 0
# You could also just set words_total as:
# words_total = len(statement)
# Iterate over elements in statement
for word in statement:
words_total += 1 # incerement total words
if word in key_words: # check if word in key_words
occurences += 1 # if so, increment occurences
return (occurences / words_total) > 0.7 # return true if 70% of all words are key_words
def is_ordered1(numbers):
"""
Returns True, if and only if the elements of the input array numbers are ordered from smallest to largest:
Input(s):
numbers --> list[int]
Output(s):
boolean
"""
# Each index larger than or equal to the one before
return True == all([numbers[i] <= numbers[i+1] for i in range(len(numbers)-1)])
def is_ordered2(numbers):
"""
Returns True, if and only if the elements of the input array numbers are ordered from smallest to largest:
Input(s):
numbers --> list[int]
Output(s):
boolean
"""
# Use Recursion
if len(numbers) > 2:
return numbers[0] <= numbers[1] and is_ordered2(numbers[1:])
else:
return numbers[0] <= numbers[1]
def is_ordered3(numbers):
"""
Returns True, if and only if the elements of the input array numbers are ordered from smallest to largest:
Input(s):
numbers --> list[int]
Output(s):
boolean
"""
# Use Numpy
return np.all(np.diff(numbers) >= 0)
def main():
print(is_ordered3([1, 1, 1, 1]))
print(is_ordered3([1, 2, 3]))
print(is_ordered3([7, -4, 8, 12]))
if __name__ == "__main__":
main()<file_sep>/signal_noise_generator/noise_methods.py
import numpy as np
import matplotlib.pyplot as plt
# Part One:
t = np.linspace(1, 100, 1000)
x_volts = 10*np.sin(t/(2*np.pi))
plt.subplot(3,1,1)
plt.plot(t, x_volts)
plt.title('Signal')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
x_watts = x_volts ** 2
plt.subplot(3,1,2)
plt.plot(t, x_watts)
plt.title('Signal Power')
plt.ylabel('Power (W)')
plt.xlabel('Time (s)')
plt.show()
x_db = 10 * np.log10(x_watts)
plt.subplot(3,1,3)
plt.plot(t, x_db)
plt.title('Signal Power in dB')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
# Part Two: Adding noise using target SNR
# Set a target SNR
target_snr_db = 20
# Calculate signal power and convert to dB
sig_avg_watts = np.mean(x_watts)
sig_avg_db = 10 * np.log10(sig_avg_watts)
# Calculate noise according to [2] then convert to watts
noise_avg_db = sig_avg_db - target_snr_db
noise_avg_watts = 10 ** (noise_avg_db / 10)
# Generate an sample of white noise
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts), len(x_watts))
# Noise up the original signal
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise (dB)')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
# Part Three: Adding noise using a target noise power
# Set a target channel noise power to something very noisy
target_noise_db = 10
# Convert to linear Watt units
target_noise_watts = 10 ** (target_noise_db / 10)
# Generate noise samples
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(target_noise_watts), len(x_watts))
# Noise up the original signal (again) and plot
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()<file_sep>/README.md
These are an assortment of helper functions, starter templates and just plain fun stuff.
<file_sep>/signal_noise_generator/generator.py
import numpy as np
from matplotlib import pyplot as plt
import random
class Device:
def __init__(self, T):
measurements = {'speed': [],
'F_B_shock': [],
'GAcc': [],
'leanAngle': [],
'GPS:': [],
'temperature': [],
'light': []}
period = T
active = False
def genParameters(num):
freq_range = [.01, 100]
amp_range = [0, 10]
def deviceRead(measurements, sample_rate):
for key in measurements.keys():
time = np.linspace(1, 60, sample_rate)
freq = random.uniform(0.01, 10)
amp =random.uniform(0, 10)
measurements[key] = genSignal(freq, amp, time)
def getSpeed(num_dir=1):
return 0
def addLinearNoise(signal):
signal += generateNoise(signal, 0)
return signal
def genSignal(freq, amps, time):
new_signal = []
composite_signals = []
for i in range(len(freq)):
composite_signals.append(amps[i] * np.sin(freq[i]*time/np.pi))
for i in range(len(time)):
new_signal.append(0)
for j in range(len(composite_signals)):
new_signal[i] += composite_signals[j][i]
return new_signal
def getWatts(signal):
return [signal[i] ** 2 for i in range(len(sig))]
def generateNoise(signal, mean_noise):
sig_watts = getWatts(signal)
sig_avg_watts = np.mean(sig_watts)
noise = np.random.normal(mean_noise, np.sqrt(sig_avg_watts), len(sig_watts))
return noise
def get_rand_parameters():
params = {'amp': [], 'freq': []}
num = random.randint(0, 10)
for key in params.keys():
for i in range(num):
params[key].append(random.randint(0, 100))
params['amp'] = [params['amp'][i] / 10 for i in range(num)]
params['freq'] = [params['freq'][i] / 100 for i in range(num)]
return params
def main()
# Recorded values
measurements = {'speed': [],
'F_B_shock': [],
'GAcc': [],
'leanAngle': [],
'GPS:': [],
'temperature': [],
'light': []}
time = np.linspace(1, 100, 1000)
params = get_rand_parameters()
sig = genSignal(params['freq'], params['amp'], time)
sig = addLinearNoise(sig)
plt.plot(time, sig)
plt.title('Signal')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
if __name__ == "__main__":
signal = np.
<file_sep>/signal_noise_generator/thread.py
# Part One
import time
import threading
import concurrent.futures
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
print('Done Sleeping...')
threads = []
for _ in range(10):
t = threading.Thread(target=do_something, args=[1.5])
t.start()
threads.append(t)
for thread in threads:
thread.join()
finish = time.perf_counter()
print('Finished in ' + str(finish-start) + ' seconds(s)')<file_sep>/covid19/map.py
import geopandas
import pandas as pd
import pandas_bokeh
import matplotlib.pyplot as plt
pandas_bokeh.output_notebook()
canada = geopandas.read_file("./gfsa000b11a_e.shp")
ontario = canada[canada['PRUID'] == '35']
# Sample data to plot
df=pd.DataFrame({'PCODE': ['P0V','P0L','P0T','P0Y', 'P0G', 'P2N'], 'A':[6,3,5,2,2,4] })
# Join ontario dataset with sample data
new_df=ontario.join(df.set_index('PCODE'), on='CFSAUID')
new_df.plot_bokeh(simplify_shapes=20000,
category="A",
colormap="Spectral",
hovertool_columns=["CFSAUID","A"])<file_sep>/json_test/json_import.py
import json
with open('test.json') as f:
d = json.load(f)
#f = open('test.json',)
#d = json.load(f)
print(d)
<file_sep>/python_socket/http_server.py
import requests
def get():
r = requests.get('http://127.0.0.1:8000/')
# print(r.text)
def post():
pload = {'username': 'davidjc', 'password': '<PASSWORD>'}
r = requests.post('http://127.0.0.1:8000/', data=pload)
print(r)
if __name__ == "__main__":
get()
post()
<file_sep>/covid19/covid19.py
import pandas as pd
from matplotlib import pyplot as plt
def get_all_cases(data):
data_keys = []
for i in range(len(data)):
if data[i] not in data_keys:
data_keys.append(data[i])
return data_keys
def percentage(death_numbers, prints=True):
percent = (death_numbers['deaths'] / death_numbers['cases']) * 100
if prints:
print('Age Range: ' + str(age))
print('Death Percentage: ' + str(percent) + '%')
return percent
def numbers_by_range(age_range=0, print_statement=False):
num_deaths = 0
num_survivals = 0
total = 0
if age_range == 0:
age_range = ['40s']
for i in range(len(df["Age_Group"])):
if df["Outcome1"][i] == 'Resolved' and df['Age_Group'][i] in age_range:
num_survivals += 1
total += 1
elif df["Outcome1"][i] == 'Fatal' and df['Age_Group'][i] in age_range:
num_deaths += 1
total += 1
if print_statement:
print("Age Range: " + str(age_range))
print('Total Cases: ' + str(total))
print('Survived: ' + str(num_survivals))
print('Deaths: ' + str(num_deaths))
return {'deaths': num_deaths, 'cases': total, 'survivals': num_survivals, 'age_range': age_range}
def temp(df):
dates = get_all_cases(df['Accurate_Episode_Date'])
num_entries = len(dates)
num_cases = len(df['Accurate_Episode_Date'])
data = {'active_cases': [0]*num_entries, 'deaths': [], 'recoveries': [], 'total_deaths': [],
'total_recoveries': [], 'total_cases': [], 'date': dates}
active_id = []
index = 0
num_entries = len(df['Accurate_Episode_Date'])
for i in range(len(data['date'])):
if i > 0:
data['active_cases'][i] = data['active_cases'][i-1]
for j in range(num_cases):
if df['Accurate_Episode_Date'][j] == data['date'][i]:
data['active_cases'][i] += 1
index += 1
print(index)
for case_id in active_id:
if df['Test_Reported_Date'][case_id] == data['date'][i]:
pass
# data['active_cases'][i] -= 1
return data
if __name__ == "__main__":
df = pd.read_csv('conposcovidloc.csv')
age_ranges = ['<20', '20s', '30s', '40s', '50s', '60s', '70s', '80s', '90s']
data = {}
'''for age in age_ranges:
data[age] = numbers_by_range([age])
percentage(data[age])
data['total'] = numbers_by_range(age_ranges)'''
'''info = df['Case_AcquisitionInfo']
x = get_all_cases(info)'''
x = temp(df)
|
5fd76ed8167e4259524e2fddfaca3945de0a2e90
|
[
"Markdown",
"Python"
] | 12
|
Python
|
davidjdclarke/scripts
|
acea0b687b2b096e5781ed3fda7d5462d0381082
|
87f71efadbfc873066541a23bc29f8d4044607aa
|
refs/heads/master
|
<repo_name>ReeganArockiasmy/Github-Preview-in-Local<file_sep>/run-github-page.sh
#!/bin/bash
#
# Usage:
# filename="Readme.md" ip="x.x.x.x" port="8000" run-github-page.sh
#
FILENAME=${filename:-"README.md"}
IP=${ip:-"localhost"}
PORT=${port:-"8000"}
URL="http://$IP:$PORT/readme.html"
QUERY="?filename=${FILENAME}"
chromium $URL$QUERY
<file_sep>/README.md
# Github-Preview-in-Local
Single file
Locally hosted (intranet) URL
No browser extension required
No locally hosted server-side processing (for example, no PHP)
Lightweight (for example, no jQuery)
High fidelity: use GitHub to render the Markdown, and same CSS
Ref :- http://stackoverflow.com/questions/9331281/how-can-i-test-what-my-readme-md-file-will-look-like-before-commiting-to-github#answer-34013414
|
f37a414ca386be0adbe0ca632ae24d3b6efe4e4e
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
ReeganArockiasmy/Github-Preview-in-Local
|
cbd67ecbe17aa8b71f764933ccac386af9b910c9
|
508fc6ec3087457062803e6d1cb3a883e36c6576
|
refs/heads/master
|
<file_sep>#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
cd ${BASEDIR}/../
PROTO_DEST=./examples/proto
OUTPUT_DEST=./examples/src/proto
BUILD_DEST=./examples/build/proto
mkdir -p ${OUTPUT_DEST}
# JavaScript code generating
node ./bin/protoc-gen-grpc.js \
--js_out=import_style=commonjs,binary:${OUTPUT_DEST} \
--grpc_out=grpc_js:${OUTPUT_DEST} \
--proto_path ${PROTO_DEST} \
${PROTO_DEST}/*.proto
node ./bin/protoc-gen-grpc-ts.js \
--ts_out=grpc_js:${OUTPUT_DEST} \
--proto_path ${PROTO_DEST} \
${PROTO_DEST}/*.proto
# TypeScript compiling
mkdir -p ${BUILD_DEST}
cp -r ${OUTPUT_DEST}/* ${BUILD_DEST}
tsc<file_sep>#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
cd ${BASEDIR}/../
PROTO_DEST =./proto
OUTPUT_DEST =./src/proto
BUILD_DEST =./build/proto
mkdir -p ${PROTO_DEST}
# JavaScript code generating
protoc-gen-grpc \
--js_out=import_style=commonjs,binary:${OUTPUT_DEST} \
--grpc_out=grpc_js:${OUTPUT_DEST} \
--proto_path ${PROTO_DEST} \
${PROTO_DEST}/*.proto
protoc-gen-grpc-ts \
--ts_out=grpc_js:${OUTPUT_DEST} \
--proto_path ${PROTO_DEST} \
${PROTO_DEST}/*.proto
# TypeScript compiling
mkdir -p ${BUILD_DEST}
cp -r ${OUTPUT_DEST}/* ${BUILD_DEST}
tsc
|
5c69643ebdadbeab55f954536e990c88af0a7da1
|
[
"Shell"
] | 2
|
Shell
|
nigele-stripe/protoc-gen-grpc-ts
|
d72448bb241167d33ec7491e477c8f940f41f106
|
2a56de49d432d4413341a97318e6056bceec3fc5
|
refs/heads/master
|
<repo_name>Akemi-Homura/APUE_Learn<file_sep>/Chapter10/L-10-14/README.md
# a
为进程打印信号屏蔽字
<file_sep>/Chapter10/L-10-8/a.c
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
# include <signal.h>
# include <setjmp.h>
# include <sys/types.h>
static jmp_buf env_alrm;
static void
sig_alrm(int signo){
longjmp(env_alrm, 1);
}
unsigned int
sleep2(unsigned int seconds){
if (signal(SIGALRM, sig_alrm) == SIG_ERR){
return seconds;
}
if (setjmp(env_alrm) == 0) {
alarm(seconds); /* start the timer */
pause(); /* next caught signal wakes us up */
}
return alarm(0);
}
<file_sep>/Chapter8/L-8-8/README.md
# a
fork一个子进程,既不等待子进程终止,也不让子进程处于僵死状态直到父进程终止,实现这一要求的方法是调用fork两次,直接结束第一个fork的子进程,用第二个子进程执行业务代码,这样第二个子进程会被托管给init,由init来等待第二个子进程
<file_sep>/Chapter10/L-10-19/README.md
# a
signal_intr函数,阻止被中断的系统调用重启动
<file_sep>/Chapter8/L-8-31/README.md
# a
计时并执行所有命令行参数
<file_sep>/Chapter8/L-8-20/README.md
# a
执行一个解释器文件的程序
<file_sep>/Chapter10/L-10-31/README.md
# a
如何处理SIGTSTP
<file_sep>/Chapter15/L-15-17/README.md
# a
协同进程实例,从标准输入读取两个数,计算它们的和,然后将和写至其标准输出
<file_sep>/Chapter3/L-3-2/README.md
# a
创建一个具有空洞的文件
<file_sep>/Chapter15/L-15-17/Makefile
CXX = gcc
CXXFLAGS = -g3 -Wall
target = main add2
all: $(target)
main: main.c
$(CXX) $^ $(CXXFLAGS) -o $@
add2: add2.c
$(CXX) $^ $(CXXFLAGS) -o $@
clean:
rm -rf *.dSYM $(target)
<file_sep>/Chapter10/L-10-22/signal_util.c
# include "signal_util.h"
/*
* Reliable version of singal(), using POSIX sigaction().
*/
Sigfunc*
signal(int signo, Sigfunc *func){
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if (signo == SIGALRM){
#ifdef SA_INTERRUPT
act.sa_flags |= SA_INTERRUPT;
#endif
} else {
act.sa_flags |= SA_RESTART;
}
if (sigaction(signo, &act, &oact) < 0){
return SIG_ERR;
}
return oact.sa_handler;
}
void
pr_mask(const char *str){
sigset_t sigset;
int errno_save;
errno_save = errno;
if (sigprocmask(0, NULL, &sigset) < 0){
perror("sigpromask error");
exit(1);
} else {
printf("%s", str);
if (sigismember(&sigset, SIGINT))
printf(" SIGINT");
if (sigismember(&sigset, SIGQUIT))
printf(" SIGQUIT");
if (sigismember(&sigset, SIGUSR1))
printf(" SIGUSR1");
if (sigismember(&sigset, SIGALRM))
printf(" SIGALRM");
/* remaining signals can go here */
printf("\n");
}
errno = errno_save;
}
<file_sep>/Chapter4/L-4-22/README.md
# a
遍历目录,统计文件类型
<file_sep>/Chapter8/L-8-1/README.md
# a
演示了fork函数
<file_sep>/Chapter8/L-8-12/a.c
# include <stdio.h>
# include <unistd.h>
# include <sys/wait.h>
# include <stdlib.h>
static void charatatime(char *);
int
main(void){
pid_t pid;
if ((pid = fork()) < 0){
perror("fork errror");
exit(1);
} else if (pid == 0){
charatatime("output from child\n");
} else {
charatatime("output form parent\n");
}
exit(0);
}
static void
charatatime(char *str){
char *ptr;
int c;
setbuf(stdout, NULL); /* set unbuffered */
for (ptr = str; ( c = *ptr++) != 0;){
putc(c, stdout);
}
}
<file_sep>/Chapter9/L-9-12/README.md
# a
创建一个孤儿进程组
<file_sep>/Chapter4/L-4-21/README.md
# a
使用带O_TRUNC选项的open函数将文件截断,再使用futimens重置访问时间与修改时间
<file_sep>/Chapter10/L-10-6/README.md
# a
不能正常工作的SIGCLD处理程序
<file_sep>/Chapter7/L-7-4/README.md
# a
将所有命令行参数显示到标准输出
<file_sep>/Chapter3/L-3-1/README.md
# test
测试标准输入能否设置偏移量
测试表明不能给标准输入设置偏移量
<file_sep>/Chapter4/L-4-24/README.md
# a
测试getcwd函数
<file_sep>/Chapter3/L-3-5/README.md
# L-3-5
使用read和write复制一个文件
<file_sep>/Chapter10/L-10-10/README.md
# a
待时间限制调用read
read是自动重启动的,不会被信号中断
<file_sep>/Chapter10/L-10-22/signal_util.h
#ifndef SIGNAL_UTIL_H
#define SIGNAL_UTIL_H
# include <signal.h>
# include <stdio.h>
# include <stdlib.h>
# include <errno.h>
# include <unistd.h>
# include <sys/types.h>
/*
* Reliable version of singal(), using POSIX sigaction().
*/
typedef void Sigfunc(int);
Sigfunc*
signal(int signo, Sigfunc *func);
void
pr_mask(const char*);
#endif
<file_sep>/Chapter5/L-5-4/a.c
# include <stdio.h>
# include <stdlib.h>
int main(){
int c;
while ((c = getc(stdin)) != EOF){
if (putc(c, stdout) == EOF){
perror("output error");
}
}
if (ferror(stdin)){
perror("input error");
}
return 0;
}
<file_sep>/Chapter7/L-7-13/README.md
# a
说明在调用longjmp后,自动变量,全局变量,寄存器变量,静态变量和易失变量的不同情况。
<file_sep>/Chapter10/L-10-7/README.md
# a
sleep 简化而不完整的实现
<file_sep>/Chapter10/L-10-18/a.c
# include <signal.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/types.h>
/*
* Reliable version of singal(), using POSIX sigaction().
*/
typedef void Sigfunc(int);
Sigfunc*
signal(int signo, Sigfunc *func){
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if (signo == SIGALRM){
#ifdef SA_INTERRUPT
act.sa_flags |= SA_INTERRUPT;
#endif
} else {
act.sa_flags |= SA_RESTART;
}
if (sigaction(signo, &act, &oact) < 0){
return SIG_ERR;
}
return oact.sa_handler;
}
<file_sep>/Chapter3/L-3-11/README.md
# L-3-11
打印指定的文件描述符的文件标志说明
<file_sep>/Chapter10/L-10-18/README.md
# a
用sigaction实现的signal函数
<file_sep>/Chapter4/L-4-3/a.cc
# include <unistd.h>
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
int main(int argc, char** argv){
struct stat buf;
char *ptr;
for(int i=1;i<argc; i++){
printf("%s: ",argv[i]);
if (lstat(argv[i], &buf) < 0){
perror("lstat error");
continue;
}
if (S_ISREG(buf.st_mode)){
ptr = strdup("regular");
}else if(S_ISDIR(buf.st_mode)){
ptr = strdup("directory");
}else if(S_ISCHR(buf.st_mode)){
ptr = strdup("character special");
}else if(S_ISBLK(buf.st_mode)){
ptr = strdup("block special");
}else if(S_ISFIFO(buf.st_mode)){
ptr = strdup("fifo");
}else if(S_ISLNK(buf.st_mode)){
ptr = strdup("symbolic link");
}else if(S_ISSOCK(buf.st_mode)){
ptr = strdup("socket");
}
printf("%s\n",ptr);
}
return 0;
}
<file_sep>/Chapter8/L-8-23/README.md
# a
调用system函数
<file_sep>/Chapter15/L-15-14/README.md
# a
将标准输入复制到标准输出,在复制时将大写字母变换成小写字母
<file_sep>/Chapter4/L-4-9/README.md
# a
测试umask函数
<file_sep>/countfile.sh
#!/bin/bash
nreg=0
ndir=0
function listfiles(){
for file in `ls $1`
do
if [ -d $1/$file ]
then
let ndir=ndir+1
listfiles $1/$file
else
let nreg=nreg+1
fi
done
}
dir='.'
if [ $# -gt 0 ]
then
if [ -d $1 ]
then
dir=$1
else
echo $1 not a directory
fi
fi
listfiles $dir
let ntot=nreg+ndir
echo "ntot: $ntot"
echo "nreg: $nreg"
echo "ndir: $ndir"
<file_sep>/Chapter10/L-10-9/README.md
# a
在一个捕捉其他信号的程序中调用sleep2
<file_sep>/Chapter7/L-7-9/README.md
# a
命令行处理程序的典型骨架部分
<file_sep>/Chapter5/L-5-12/README.md
# a
tmpnam和tmpfile函数实例
<file_sep>/Chapter5/L-5-13/README.md
# a
mkstemp函数的应用
<file_sep>/Chapter10/L-10-10/a.c
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/types.h>
# include <signal.h>
# define MAXLINE 100
static void sig_alrm(int);
int
main(void){
int n;
char line[MAXLINE];
if (signal(SIGALRM, sig_alrm) == SIG_ERR){
perror("signal(SIGALRM) error");
exit(1);
}
alarm(10);
if ((n = read(STDIN_FILENO, line, MAXLINE)) < 0){
perror("read error");
exit(1);
}
alarm(0);
write(STDOUT_FILENO, line, n);
exit(0);
}
static void
sig_alrm(int signo){
/* nothing to do, just return to interrupt the read */
}
<file_sep>/Chapter10/L-10-5/README.md
# a
在信号处理程序中调用不可再入函数
<file_sep>/Chapter4/L-4-8/a.c
# include <fcntl.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
int main(int argc, char** argv){
if (argc != 2){
fprintf(stderr,"usage: a.out <pathname>");
}
if (access(argv[1], R_OK) < 0){
fprintf(stderr,"access error for %s\n",argv[1]);
}else{
printf("read access OK\n");
}
if(open(argv[1], O_RDONLY) < 0){
fprintf(stderr,"open error for %s",argv[1]);
perror("");
}else{
printf("open for reading OK\n");
}
return 0;
}
<file_sep>/Chapter10/L-10-11/README.md
# a
使用longjmp,带时间限制的read
<file_sep>/Chapter8/L-8-3/README.md
# a
L-8-1的修改版,使用vfork代替了fork,删除了对于标准输出的write调用和父进程的sleep
#### 运行测试
发现父进程的的数据被修改了,因为子进程在父进程的地址空间中运行
调用的是_exit而不是exit,因为_exit不执行标准I/O缓冲区的冲洗操作。如果调用exit则该程序的输出是不确定的。
<file_sep>/Chapter5/L-5-15/README.md
# a
观察内存流的写入操作
<file_sep>/Chapter5/L-5-5/README.md
# a
将标准输入复制到标准输出,使用fgetc和fputc
<file_sep>/Chapter5/L-5-11/README.md
# a
对各个标准I/O流打印缓冲状态信息
<file_sep>/Chapter15/L-15-11/README.md
# a
用popen向分页程序传送文件
<file_sep>/Chapter7/L-7-16/README.md
# a
打印由系统支持的所有资源当前的软限制和硬限制
<file_sep>/Chapter4/L-4-3/Makefile
CXX = g++
CXXFLAGS = -g3 -Wall -std=c++11
sources = a.cc
target = a.out
$(target): $(sources)
$(CXX) $^ $(CXXFLAGS) -o $@
clean:
rm -rf $(target) *.dSYM
<file_sep>/README.md
# APUE_Learn
文件名按书中图片编号命名
complete first learning on Chapter3-10(except Chapter6) on 2018.10.09
<file_sep>/Chapter10/L-10-14/a.c
# include <stdio.h>
# include <stdlib.h>
# include <signal.h>
# include <unistd.h>
# include <errno.h>
void
pr_mask(const char *str){
sigset_t sigset;
int errno_save;
errno_save = errno;
if (sigpromask(0, NULL, &sigset) < 0){
perror("sigpromask error");
exit(1);
} else {
printf("%s", str);
if (sigismember(&sigset, SIGINT))
printf(" SIGINT");
if (sigismember(&sigset, SIGQUIT))
printf(" SIGQUIT");
if (sigismember(&sigset, SIGUSR1))
printf(" SIGUSR1");
if (sigismember(&sigset, SIGALRM))
printf(" SIGALRM");
/* remaining signals can go here */
printf("\n");
}
errno = errno_save;
}
<file_sep>/Chapter10/L-10-11/a.c
# include <stdio.h>
# include <signal.h>
# include <unistd.h>
# include <setjmp.h>
# include <stdlib.h>
# define MAXLINE 100
static void sig_alrm(int);
static jmp_buf env_alrm;
int
main(void){
int n;
char line[MAXLINE];
if (signal(SIGALRM, sig_alrm) == SIG_ERR){
perror("signal(SIGALRM) error");
exit(1);
}
if (setjmp(env_alrm) != 0){
fprintf(stderr, "read timeout");
exit(1);
}
alarm(10);
if ((n = read(STDIN_FILENO, line, MAXLINE)) < 0){
perror("read error");
exit(1);
}
alarm(0);
write(STDOUT_FILENO, line, n);
exit(0);
}
static void
sig_alrm(int signo){
longjmp(env_alrm, 1);
}
<file_sep>/Chapter10/L-10-26/README.md
# a
用system调用edit编辑器
<file_sep>/Chapter15/L-15-17/add2.c
# include <stdio.h>
# include <unistd.h>
# include <string.h>
# include <stdlib.h>
# define MAXLINE 100
# define RELEASE 1
# define DEBUG 0
# define RUNTYPE DEBUG
int
main(void){
int int1, int2;
char line[MAXLINE];
if (setvbuf(stdin, NULL, _IOLBF, 0) != 0){
perror("setvbuf errro");
exit(1);
}
if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) {
perror("setvbuf error");
exit(1);
}
while (fgets(line, MAXLINE, stdin) != NULL) {
if (sscanf(line, "%d%d", &int1, &int2) == 2){
if (printf("%d\n", int1 + int2 ) == EOF){
perror("printf error");
exit(1);
}
} else if (printf("invalid args\n") == EOF){
perror("printf error");
exit(1);
}
}
exit(0);
}
<file_sep>/Chapter4/L-4-12/README.md
# a
测试chmod函数
<file_sep>/Chapter9/L-9-12/Makefile
CXX = clang
CXXFLAGS = -g3 -Wall
sources = a.c
target = a.out
$(target): $(sources)
$(CXX) $^ $(CXXFLAGS) -o $@
clean:
rm -rf *.dSYM $(target)
<file_sep>/Chapter5/L-5-5/a.c
# include <stdio.h>
# include <stdlib.h>
# define MAXLINE 100
int main(){
char buf[MAXLINE];
while (fgets(buf, MAXLINE, stdin) != NULL){
if (fputs(buf, stdout) == EOF){
perror("output error");
}
}
if (ferror(stdin)){
perror("input error");
}
return 0;
}
<file_sep>/Chapter10/L-10-15/README.md
# a
信号设置和sigprocmask实例
信号没有被排队
<file_sep>/Chapter3/L-3-2/a.c
# include <fcntl.h>
# include <sys/types.h>
# include <stdlib.h>
# include <stdio.h>
# include <unistd.h>
# include <sys/stat.h>
/*
* read and write permission for user.
* read permission for group members
* read permission for others
*/
# define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
# define oops(m) {perror(m); exit(1);}
int main(){
int fd;
const char buf1[] = "abcdefghij";
const char buf2[] = "ABCDEFGHIJ";
if ((fd = creat("file.hole", FILE_MODE)) < 0 ){
oops("creat error");
}
if (write(fd, buf1, 10) != 10){
oops("buf1 write error");
}
/* offset now 10 */
if (lseek(fd, 16384, SEEK_SET) == -1){
oops("lseek error");
}
/* offset now 16384 */
if (write(fd, buf2, 10) != 10){
oops("buf2 write error");
}
/* offset now 16394 */
return 0;
}
<file_sep>/Chapter8/L-8-5/README.md
# a
打印exit状态的说明
<file_sep>/Chapter8/L-8-24/README.md
# 8-24
在一个设置用户ID程序中调用system
tsys: 设置用户ID程序
printuids: 被调用的程序,打印uid和euid
<file_sep>/Chapter8/L-8-16/README.md
# a
演示exec函数的使用
<file_sep>/Chapter4/L-4-8/README.md
# a
测试access函数的使用方法
#### test command
```shell
su # be root
chown root a.out # change uid
chmod u+s # 打开设置用户ID
exit # be normal user
./a.out /etc/shadow # can open and read
<file_sep>/Chapter7/L-7-2/README.md
# a
说明如何使用atexit函数
<file_sep>/Chapter8/L-8-16/Makefile
CXX = gcc
CXXFLAGS = -g3 -Wall
target = a.out echoall
all: $(target)
a.out: a.c
$(CXX) $^ $(CXXFLAGS) -o $@
echoall: echoall.c
$(CXX) $^ $(CXXFLAGS) -o $@
mv echoall ${HOME}/bin
clean:
rm -rf *.dSYM $(target)
<file_sep>/Chapter4/L-4-3/README.md
# a
取命令行参数,针对每一个命令行参数打印其文件类型
<file_sep>/Chapter15/L-15-6/README.md
# a
将文件复制到分页程序
<file_sep>/Chapter7/L-7-4/a.c
# include <stdio.h>
# include <stdlib.h>
int main(int argc, char** argv){
int i;
for (i=0; i < argc ; i++){
printf("argv[%d]: %s\n",i,argv[i]);
}
exit(0);
}
<file_sep>/Chapter10/L-10-22/README.md
# a
保护临界区不被信号中断
<file_sep>/Chapter10/L-10-2/README.md
# a
捕捉SIGUSR1和SIGUSR2的简单程序
<file_sep>/Chapter10/L-10-8/README.md
# a
sleep的另一个不完善实现
<file_sep>/Chapter5/L-5-4/README.md
# a
使用getc和putc将标准输入复制到标准输出
<file_sep>/Chapter4/L-4-25/README.md
# a
为每个命令行参数打印设备号,若此参数引用的是字符特殊文件或块特殊文件,则还打印该特殊文件的st_rdev值
#### test
```shell
./a.out /home/quals /dev/tty[01]
mount
ls -l /dev/tty[01] /dev/sda[34]
```
<file_sep>/Chapter4/L-4-24/a.c
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
int main(){
char ptr[256];
size_t size = 256;
if (chdir("/usr/src/") < 0){
perror("chdir failed");
exit(1);
}
if (getcwd(ptr, size) == NULL){
perror("getcwd failed");
exit(1);
}
printf("cwd = %s\n", ptr);
return 0;
}
<file_sep>/Chapter3/L-3-12/README.md
# a.c
修改文件描述符的文件状态标志
<file_sep>/Chapter10/L-10-23/README.md
# a
用sigsuspend等待一个全局变量被设置
<file_sep>/Chapter10/L-10-20/README.md
# a
信号屏蔽,sigsetjmp和siglongjmp实例
<file_sep>/Chapter3/L-3-11/a.c
# include <fcntl.h>
# include <unistd.h>
# include <stdio.h>
# include <stdlib.h>
# define oops(m) { perror(m); exit(1); }
int main(int argc, char** argv){
int val;
if (argc != 2){
fprintf(stderr,"usage: a.out <descriptor#>");
exit(1);
}
if (( val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0 ){
fprintf(stderr,"fcntl error for fd %d", atoi(argv[1]));
}
/* mask O_ACCMODE first */
switch (val & O_ACCMODE){
case O_RDONLY:
printf("read only");
break;
case O_WRONLY:
printf("write only");
break;
case O_RDWR:
printf("read write");
break;
default:
perror("unkown access mode");
}
/* didn't mask O_ACCMODE */
if (val & O_APPEND){
printf(", append");
}
if( val & O_NONBLOCK){
printf(", nonblocking");
}
if (val & O_SYNC){
printf(", synchronous writes");
}
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC) && (O_FSYNC != O_SYNC)
if (val & O_FSYNC){
printf(", synchronous writes");
}
#endif
putchar('\n');
return 0;
}
<file_sep>/Chapter8/L-8-30/README.md
# a
更改nice值的效果
#### test
```shell
./a.out
./a.out 20
```
nice值相等时,父子进程占用的cpu周期基本相同,优先级不同时,父子进程占用的cpu周期有很大差异。
<file_sep>/Chapter8/L-8-24/Makefile
CXX = gcc
CXXFLAGS = -g3 -Wall
target = tsys printutils
all: $(target)
tsys: tsys.c
$(CXX) $^ $(CXXFLAGS) -o $@
printutils: printutils.c
$(CXX) $^ $(CXXFLAGS) -o $@
clean:
rm -rf *.dSYM $(target)
<file_sep>/Chapter4/L-4-16/README.md
# a
测试link和unlink函数
#### 测试步骤
```shell
dd if=/dev/zero of=tempfile bs=1024 count=1024000 # 生成测试文件 1GB
df /home # 检查可用磁盘空间
./a.out & # 后台运行
ls -l tempfile # 观察文件是否仍然存在
df /home # 检查可用磁盘空间
df /home # 程序结束后再次检查磁盘空间
```
#### 结论
执行unlink后文件就已经不存在,磁盘空间未释放,程序结束后磁盘空间才被释放
<file_sep>/cleanall.sh
#!/bin/bash
mkname="Makefile"
function listfiles(){
for file in `ls $1`
do
if [ -d $1/$file ]
then
listfiles $1/$file
else
if [ $file = $mkname ]
then
make -C $1 clean
break
fi
fi
done
}
dir='.'
if [ $# -gt 0 ]
then
if [ -d $1 ]
then
dir=$1
else
echo $1 not a directory
fi
fi
listfiles $dir
<file_sep>/Chapter4/L-4-23/a.c
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
int main(){
if (chdir("/tmp") < 0){
perror("chdir failed");
exit(1);
}
printf("chdir to /tmp succeeded\n");
return 0;
}
<file_sep>/Chapter3/L-3-12/a.c
# include <stdio.h>
# include <fcntl.h>
# include <stdlib.h>
void set_fl(int fd, int flags){
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0){
perror("fcntl F_GETFL error");
exit(1);
}
val |= flags;
if (fcntl(fd, F_SETFL, val) < 0){
perror("fcntl F_SETFL error");
}
}
<file_sep>/Chapter8/L-8-12/README.md
# a
程序输出两个字符串:一个由子进程输出,另一个由父进程输出。因为输出依赖于内核使这两个进程运行的顺序及每个进程运行的时间长度,所以该程序包含了一个竞争条件
<file_sep>/Chapter4/L-4-23/README.md
# a
测试chdir函数
<file_sep>/Chapter15/L-15-5/README.md
# a
经由管道从父进程向子进程传递数据
|
52872ddd42fdeef2936163924c670cd4f1ab0eab
|
[
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 87
|
Markdown
|
Akemi-Homura/APUE_Learn
|
733f2bcc3b06cee9a25df40271ced8ba97379d77
|
c586deb8d6ac68c599db03997efe3016a709d09f
|
refs/heads/master
|
<file_sep>function main( con ){
}
|
ddcea6d9ab0d03a51ba5a12cde8d1de06496ff3a
|
[
"JavaScript"
] | 1
|
JavaScript
|
SatisKia/test
|
4429a1ae2e3a4ec134c0f2c3afe170a8a63b5cab
|
583b74c4ffbe25d242c3a41619decfb26d7e5769
|
refs/heads/main
|
<file_sep>import { OmdbClass } from './omdb-class';
describe('OmdbClass', () => {
it('should create an instance', () => {
expect(new OmdbClass()).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { OmdbapiService } from "./service/omdbapi.service";
import { MovieDetail } from "./class/omdb-class";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'javascript-test';
search:string;
lst_movies;
constructor(public _omdbService:OmdbapiService){
this.search='';
this.lst_movies=new MovieDetail;
}
ngOnInit(){
// this.getService();
}
openUrl(imdb_id:string){
var url='https://www.imdb.com/title/'+imdb_id;
window.open(url);
}
getService(){
this._omdbService.getMoviesList(this.search).subscribe(data=>{
debugger;
this.lst_movies=data;
this.lst_movies.Search=this.lst_movies.Search.slice(0,3);
});
}
}
|
40c5c758e380b78d79cbef5d039e4265b23efbe3
|
[
"TypeScript"
] | 2
|
TypeScript
|
tayyabxatti/movies-database
|
d30e4110050f0c016aaefb78d32a2dab1af5698d
|
27b6a2266c04b5996f3e3dde12351cb0b866b467
|
refs/heads/master
|
<repo_name>asbjornh/kompis<file_sep>/CHANGELOG.md
# 0.5.0
- Adds `always`
- Adds `isOneOf`
- Adds docs
- Fixes `toFixed` returning `0` for `0`. `toFixed` now always returns a string
# 0.4.0
- Reimplements in typescript (non-breaking) to enhance developer experience in typescript capable editors.
# 0.3.3
- Adds `not`
# 0.3.2
- Adds `repository` in `package.json`
# 0.3.1
- Adds `mapIf`
# 0.3.0
- Adds `label` to `trace`
- Fixes `get` with default value returning `undefined`
# 0.2.0
- `get` now uses string paths instead of arrays (like `lodash/get`)
- Renames `isAtKey` to `isAtPath`
<file_sep>/README.md
# kompis
A collection of plain and higher order functions for doing composition stuff in javascript.
[Documentation](/docs)
## Usage
```
npm install kompis
```
All exports are named. Example:
```js
import { Pipe, map, add } from "kompis";
Pipe(map(add(10)));
// You can also do:
import * as K from "kompis";
K.Pipe(K.map(K.add(10)));
```
## ES6
ES6 source can be imported from `kompis/es6` (it's about a third of the size of the regular ES5 version).
## About
The functions can be divided in two groups: core functions and utils. The utils are properly documented below. The core functions are all pretty small so their implementations are included (without further documentation) [at the bottom](#core) of this readme.
## Argument order
Higher order functions that accept more than one thing accept the data to operate on last (opposite of native js counerparts). This makes partial application more practical.
```js
// Vanilla javascript (data first)
"A".padStart(3, "_"); // "__A"
[1, 2, 3].map(n => n + 1); // [2, 3, 4]
// 'padStart' and 'map' from this package (data last)
padStart(3, "_")("A"); // "__A"
map(add(1))([1, 2, 3]); // [2, 3, 4]
```
Note: this also applies to math functions like `subtract` and `divide`:
```js
// Vanilla javascript
2 / 4; // 0.5
// 'divide' from this package
const divideByTwo = divide(2);
divideByTwo(4); // 2
divide(2)(4); // also 2
```
<file_sep>/source/index.ts
import { get, match, not, otherwise, Pipe, trace } from "./utils";
export { get, match, not, otherwise, Pipe, trace };
// Misc
/** Returns a [constant function](https://en.wikipedia.org/wiki/Constant_function) of `x` */
export const always = x => () => x;
/** Compares to `null` and `undefined` */
export const exists = x => x !== undefined && x !== null;
/** [Identity function](https://en.wikipedia.org/wiki/Identity_function) */
export const id = x => x;
/** Returns `x` if it exists. Otherwise returns `fallback` */
export const or = fallback => x => (exists(x) ? x : fallback);
/** Always returns `false` */
export const no = () => false;
/** [No operation](https://en.wikipedia.org/wiki/NOP_(code)). Always returns `undefined` */
export const noop = () => {};
/** Always returns `true` */
export const yes = () => true;
/** Runs the `ifFunc` or the `elseFunc` based on the result of `predicate(v)` */
export const mapIf = (predicate, ifFunc = id, elseFunc = id) => v =>
predicate(v) ? ifFunc(v) : elseFunc(v);
// Predicates
/** Is `a` greater than `b`? */
export const gt = b => a => a > b;
/** Is `a` greater than or equal to `b`? */
export const gte = b => a => a >= b;
/** Is `a` less than `b`? */
export const lt = b => a => a < b;
/** Is `a` less than or equal to `b`? */
export const lte = b => a => a <= b;
/** Is `a` equal to `b`? */
export const is = a => b => a === b;
export const isNumber = n => typeof n === "number";
export const isString = n => typeof n === "string";
export const isEven = n => isNumber(n) && n % 2 === 0;
export const isOdd = n => isNumber(n) && n % 2 !== 0;
export const isOneOf = (...values) => v => values.includes(v);
export const isAtPath = (path, predicate) => v => predicate(get(path)(v));
export const isAtIndex = (index, predicate) => isAtPath(`[${index}]`, predicate);
/** Checks whether the `v` fulfils all the `predicates` */
export const isAll = (...predicates) => v =>
predicates.reduce((a, pred) => a && pred(v), predicates.length ? true : false);
/** Checks whether the `v` fulfils some of the `predicates` */
export const isSome = (...predicates) => v =>
predicates.reduce((a, pred) => a || pred(v), false);
// safeString
const sS = str => (exists(str) && typeof str === "string" ? str : "");
// String
export const charCodeAt = index => str => sS(str).charCodeAt(index);
export const endsWith = term => str => sS(str).endsWith(term);
export const fromCharCode = num => String.fromCharCode(num);
export const padEnd = (length, char) => str => sS(str).padEnd(length, char);
export const padStart = (length, char) => str => sS(str).padStart(length, char);
export const repeat = length => str => sS(str).repeat(length);
export const replace = (regexp, newStr) => str => sS(str).replace(regexp, newStr);
export const split = sep => str => sS(str).split(sep);
export const startsWith = term => str => sS(str).startsWith(term);
export const substring = (start, end) => str => sS(str).substring(start, end);
export const toLowerCase = str => sS(str).toLowerCase();
export const toUpperCase = str => sS(str).toUpperCase();
export const trim = str => sS(str).trim();
/** SafeArray */
const sA = arr => (Array.isArray(arr) ? arr : []);
const ensureArray = a => (Array.isArray(a) ? a : exists(a) ? [a] : []);
// Array
/** Creates an array. Kind of similar to list comprehension in python
```js
array(5); // [0, 1, 2, 3, 4, 5]
array(5, add(1), isEven); // [0, 3, 5]
```
*/
export const array = (range = 0, mapper = id, filter = v => true): any[] =>
new Array(range).fill(0).reduce((a, _, i) => a.concat(filter(i) ? mapper(i) : []), []);
/** Concatenates `b` into `a`. Does not concat `undefined` or `null`
```js
concat(2)([1]); // [1, 2]
```
*/
export const concat = b => a => ensureArray(a).concat(ensureArray(b));
/** Concatenates `a` into `b`. Does not concat `undefined` or `null`
```js
concat([1])(2); // [1, 2]
```
*/
export const concatRight = a => b => ensureArray(a).concat(ensureArray(b)); // Doesn't concat undefined/null
export const every = func => arr => sA(arr).every(func);
export const filter = func => arr => sA(arr).filter(func);
export const find = func => arr => sA(arr).find(func);
export const findIndex = func => arr => sA(arr).findIndex(func);
export const forEach = (...funcs) => arr => sA(arr).forEach(Pipe(...funcs));
export const includes = thing => arr => sA(arr).includes(thing);
export const indexOf = term => arr => sA(arr).indexOf(term);
export const join = (sep: string) => arr => sA(arr).join(sep);
export const length = arr => sA(arr).length;
export const map = (...funcs) => arr => sA(arr).map(Pipe(...funcs));
export const reverse = arr => sA(arr).reverse();
export const slice = (begin, end) => arr => sA(arr).slice(begin, end);
export const some = func => arr => sA(arr).some(func);
export const sort = func => arr => sA(arr).sort(func);
/** Sort objects or arrays by key or index (or both)
```js
sortBy("a[0]")([{ a: [3] }, { a: [2] }, { a: [1] }]);
// [{ a: [1] }, { a: [2] }, { a: [3] }]
```
*/
export const sortBy = (path = "") =>
sort((a, b) => {
const A = get(path)(a);
const B = get(path)(b);
return lt(B)(A) ? -1 : gt(B)(A) ? 1 : 0;
});
/** See `reduce` for documentation */
export const plainReduce = (func, initial) => arr =>
sA(arr).reduce((a, c) => func(c)(a), initial);
/** See `reduce` for documentation */
export const mapFilterReduce = (reducer, initial, map, filter = v => true) => arr =>
sA(arr).reduce((a, c) => (filter(c) ? reducer(map(c))(a) : a), initial);
/**
Note that `reducer` needs to be a higher order unary function (returning another unary function) and that the order of the current and accumulator are reversed. This makes it possible to use other functions from this package as the `reducer`.
```js
reduce(curr => accum => accum + curr, 0)([1, 2, 3]); // 6
reduce(add, 0)([1, 2, 3]); // 6
reduce(concat, [])([[1, 2], [3, 4]]); // [1, 2, 3, 4]
```
`map` and `filter` can be used to do many operations that otherwise would require iterating over a list many times, like `[].filter(fn).map(fn).reduce(fn)` which can be orders of magnitude slower. Filtering happens before mapping.
```js
const numbers = [1, 2, 3, 4];
// 4 iterations
reduce(add, 0, pow(2), isEven)(numbers); // 20
// 4 + 2 + 2 iterations
Pipe(filter(isEven), map(pow(2)), reduce(add))(numbers); // 20
```
*/
export const reduce = (reducer, initial, map, filter) =>
map ? mapFilterReduce(reducer, initial, map, filter) : plainReduce(reducer, initial);
// Number
/** Unary version of parseInt (can safely be used in `map` etc) */
export const int = n => parseInt(n);
/** Unary version of parseFloat (can safely be used in `map` etc) */
export const float = n => parseFloat(n);
export const toFixed = (digits: number) => (num: number) =>
isNumber(num) ? num.toFixed(digits) : "";
// Math
export const add = b => a => a + b;
export const divide = b => a => a / b;
export const multiply = b => a => a * b;
export const subtract = b => a => a - b;
export const max = arr => Math.max(...arr);
export const min = arr => Math.min(...arr);
export const clamp = (min, max) => n => Math.min(max, Math.max(min, n));
export const pow = exp => base => Math.pow(base, exp);
export const rangeMap = (inMin, inMax, outMin, outMax) => n =>
((n - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
// Object
export const assign = b => a => Object.assign({}, a, b);
/** Checks whether `obj` has a value at the given `path`. Not to be confused with `object.hasOwnProperty` */
export const has = (path = "") => obj => exists(get(path)(obj));
type Entry = [string?, any?];
export const objectFromEntry = ([k, v]: Entry = []) => (k ? { [k]: v } : {});
export const mapEntry = (mapKey, mapValue) => ([k, v]: Entry = []) => [
mapKey(k),
mapValue(v)
];
export const mapObject = (map, filter) => (obj = {}) =>
reduce(assign, {}, Pipe(map, objectFromEntry), filter)(Object.entries(obj));
<file_sep>/test/match.test.js
import test from "ava";
import { isEven, isOdd, isString, otherwise, match } from "../source/index";
test("Happy path", t => {
const matcher = match(
[isEven, () => true],
[isOdd, () => false],
[isString, () => null]
);
t.is(true, matcher(2));
t.is(false, matcher(1));
t.is(null, matcher("a"));
t.is(undefined, matcher(null));
});
test("With fallback", t => {
const matcher = match(
[isEven, () => true],
[isOdd, () => false],
[otherwise, () => "No match"]
);
t.is(true, matcher(2));
t.is(false, matcher(1));
t.is("No match", matcher("a"));
t.is("No match", matcher(null));
});
test("Throws on non-function", t => {
const error1 = t.throws(() => {
match([isEven, null])(1);
});
const error2 = t.throws(() => {
match([true, n => n])(1);
});
const error3 = t.throws(() => {
match([])(1);
});
const error4 = t.throws(() => {
match()(1);
});
t.is("Non-function passed to 'match[0]'", error1.message);
t.is("Non-function passed to 'match[0]'", error2.message);
t.is("Non-function passed to 'match[0]'", error3.message);
t.is("No patterns passed to 'match'", error4.message);
});
<file_sep>/test/number.test.js
import test from "ava";
import { int, float, toFixed } from "../source/index";
const macro = (t, expected, input) => {
t.is(expected, input);
};
test("int", macro, 1, int("1"));
test("float", macro, 1.5, float("1.5"));
test("toFixed", macro, "1.50", toFixed(2)(1.500001));
test("toFixed: empty", macro, "", toFixed(2)());
test("toFixed: zero", macro, "0.00", toFixed(2)(0));
<file_sep>/test/math.test.js
import test from "ava";
import {
add,
divide,
multiply,
subtract,
max,
min,
clamp,
pow,
rangeMap
} from "../source/index";
const macro = (t, expected, input) => {
t.is(expected, input);
};
test("add", macro, 2, add(1)(1));
test("divide", macro, 5, divide(2)(10));
test("multiply", macro, 10, multiply(2)(5));
test("subtract", macro, 2, subtract(4)(6));
test("max", macro, 2, max([1, 2, 0]));
test("min", macro, 0, min([1, 2, 0]));
test("clamp upper", macro, 2, clamp(0, 2)(4));
test("clamp lower", macro, 0, clamp(0, 2)(-4));
test("pow", macro, 100, pow(2)(10));
test("rangeMap", macro, 15, rangeMap(0, 1, 10, 20)(0.5));
<file_sep>/test/pipe.test.js
import test from "ava";
import { charCodeAt, join, map, Pipe, subtract } from "../source/index";
test("Pipe", t => {
const myMap = Pipe(charCodeAt(0), subtract(65));
const myPipe = Pipe(map(myMap), join(""));
const result = myPipe(["A", "B", "C", "D"]);
t.is("0123", result);
});
<file_sep>/test/array.test.js
import test from "ava";
// NOTE: Used for more readable tests
import { add, is, isEven, multiply, pow } from "../source/index";
import {
array,
concat,
concatRight,
every,
filter,
find,
findIndex,
forEach,
includes,
indexOf,
join,
length,
map,
reduce,
reverse,
slice,
some,
sort,
sortBy
} from "../source/index";
const macro = (t, expected, input) => {
t.deepEqual(expected, input);
};
test("array", macro, [0, 4, 16], array(5, pow(2), isEven));
test("concat", macro, [1, 2], concat(2)([1]));
test("concat: empty", macro, [], concat()());
test("concatRight", macro, [1, 2], concatRight([1])(2));
test("concatRight: empty", macro, [], concatRight()());
test("every: true", macro, true, every(isEven)([2, 4, 6]));
test("every: false", macro, false, every(isEven)([2, 4, 5]));
test("every: empty", macro, true, every(() => {})()); // array.every always returns true for empty arrays
test("filter", macro, [0, 2, 4], filter(isEven)([0, 1, 2, 3, 4, 5]));
test("filter: empty", macro, [], filter(isEven)());
test("find", macro, 2, find(is(2))([0, 1, 2]));
test("find: empty", macro, undefined, find(is(2))());
test("findIndex", macro, 1, findIndex(is(1))([0, 1, 2]));
test("findIndex: empty", macro, -1, findIndex(is(1))());
test("includes: true", macro, true, includes(2)([0, 1, 2]));
test("includes: false", macro, false, includes(3)([0, 1, 2]));
test("includes: empty", macro, false, includes(3)());
test("indexOf", macro, 1, indexOf(1)([0, 1, 2]));
test("indexOf: empty", macro, -1, indexOf(1)());
test("join", macro, "012", join("")([0, 1, 2]));
test("join: empty", macro, "", join("")());
test("length", macro, 3, length([0, 1, 2]));
test("length: empty", macro, 0, length());
test("map", macro, [0, 2, 4], map(multiply(2))([0, 1, 2]));
test("map: empty", macro, [], map(multiply(2))());
test("reduce", macro, 3, reduce(c => a => a + c, 0)([0, 1, 2]));
test("reduce: empty", macro, 0, reduce(c => a => a + c, 0)());
test("reduce: map + filter", macro, 4, reduce(add, 0, multiply(2), isEven)([1, 2, 3]));
test("reverse", macro, [3, 2, 1], reverse([1, 2, 3]));
test("reverse: empty", macro, [], reverse());
test("slice", macro, [1, 2], slice(1, 3)([0, 1, 2]));
test("slice: empty", macro, [], slice(1, 3)());
test("some: true", macro, true, some(is(2))([0, 1, 2]));
test("some: false", macro, false, some(is(3))([0, 1, 2]));
test("some: empty", macro, false, some(is(3))()); // array.some always returns false for empty arrays
test("sort", macro, [0, 1, 2], sort()([2, 0, 1]));
test("sort: empty", macro, [], sort()());
test(
"sortBy",
macro,
[{ a: { b: 0 } }, { a: { b: 1 } }, { a: { b: 2 } }],
sortBy("a.b")([{ a: { b: 2 } }, { a: { b: 0 } }, { a: { b: 1 } }])
);
test(
"sortBy: index keys",
macro,
[["a", 0], ["a", 1], ["a", 2]],
sortBy("[1]")([["a", 2], ["a", 0], ["a", 1]])
);
test("sortBy: empty", macro, [], sortBy("a")());
test("sortBy: non-object elements", macro, [2, 1], sortBy("a")([2, 1]));
test("forEach", t => {
let sum = 0;
forEach(() => {
sum++;
})([0, 0, 0]);
t.is(3, sum);
});
test("forEach: empty", macro, undefined, forEach(() => {})());
<file_sep>/test/predicates.test.js
import test from "ava";
import {
gt,
gte,
is,
isAll,
isAtIndex,
isAtPath,
isEven,
isNumber,
isOdd,
isOneOf,
isSome,
isString,
lt,
lte
} from "../source/index";
test("gt", t => {
t.is(true, gt(2)(3));
t.is(false, gt(2)(2));
t.is(false, gt(2)(1));
});
test("gte", t => {
t.is(true, gte(2)(3));
t.is(true, gte(2)(2));
t.is(false, gte(2)(1));
});
test("is", t => {
t.is(true, is(2)(2));
t.is(true, is("a")("a"));
t.is(true, is(false)(false));
t.is(true, is(null)(null));
t.is(false, is(2)(1));
t.is(false, is(2)("2"));
t.is(false, is({ a: 1 })({ a: 1 }));
});
test("isEven", t => {
t.is(true, isEven(2));
t.is(false, isEven(3));
t.is(false, isEven("2"));
});
test("isOdd", t => {
t.is(true, isOdd(3));
t.is(false, isOdd(2));
t.is(false, isOdd("3"));
});
test("isOneOf", t => {
t.is(true, isOneOf("a", 1, true)("a"));
t.is(true, isOneOf("a", 1, true)(1));
t.is(true, isOneOf("a", 1, true)(true));
t.is(false, isOneOf("a", 1, true)("c"));
t.is(false, isOneOf("a", 1, true)());
});
test("lt", t => {
t.is(false, lt(2)(3));
t.is(false, lt(2)(2));
t.is(true, lt(2)(1));
});
test("lte", t => {
t.is(false, lte(2)(3));
t.is(true, lte(2)(2));
t.is(true, lte(2)(1));
});
test("isNumber", t => {
t.is(true, isNumber(1));
t.is(true, isNumber(1.5));
t.is(false, isNumber("1"));
t.is(false, isNumber());
});
test("isAtIndex", t => {
const arr = [1, 1, 4];
t.is(true, isAtIndex(2, isEven)(arr));
t.is(false, isAtIndex(0, isEven)(arr));
t.is(false, isAtIndex(10, isEven)(arr));
});
test("isAtPath", t => {
const obj = { a: 2, b: 3, c: { d: 4 } };
t.is(true, isAtPath("a", isEven)(obj));
t.is(true, isAtPath("c.d", is(4))(obj));
t.is(false, isAtPath("b", isEven)(obj));
t.is(false, isAtPath("x", isEven)(obj));
});
test("isAll", t => {
t.is(true, isAll(isNumber, isEven)(2));
t.is(false, isAll(isNumber, isOdd)(2));
t.is(false, isAll(isNumber, isOdd)("1"));
t.is(false, isAll()());
});
test("isSome", t => {
t.is(true, isSome(isString, isEven)(2));
t.is(true, isSome(isString, isEven)("1"));
t.is(false, isSome(isString, isEven)(1));
t.is(false, isSome()());
});
test("isString", t => {
t.is(true, isString("a"));
t.is(true, isString(""));
t.is(false, isString(1));
});
<file_sep>/test/not.test.js
import test from "ava";
import { isEven, isString, not } from "../source/index";
test("Unary", t => {
t.is(false, isEven(1));
t.is(true, not(isEven)(1));
t.is(true, not(isString)(1));
});
test("Variadic", t => {
const isEqual = (a, b) => a === b;
const isDifferent = not(isEqual);
t.is(true, isDifferent("a", "b"));
t.is(false, isDifferent("a", "a"));
});
<file_sep>/test/object.test.js
import test from "ava";
import { assign, has, mapEntry, mapObject, objectFromEntry } from "../source/index";
test("assign", t => {
const a = { a: 1, b: 2 };
const b = { b: "b" };
t.deepEqual({ a: 1, b: "b" }, assign(b)(a));
t.deepEqual({ a: 1, b: 2 }, assign(a)(b));
// Should not mutate:
t.not(a, assign(b)(a));
});
test("has", t => {
const a = { a: { b: 0, c: false } };
t.is(true, has("a")(a));
t.is(true, has("a.b")(a));
t.is(true, has("a.c")(a));
t.is(false, has("a.x")(a));
t.is(false, has()());
});
test("mapEntry", t => {
const entry = ["a", 2];
t.deepEqual(["a_a", 3], mapEntry(k => `${k}_${k}`, v => v + 1)(entry));
t.deepEqual([undefined, undefined], mapEntry(n => n, n => n)());
});
test("mapObject", t => {
const a = { a: 1, b: "a" };
const map = mapEntry(k => `${k}_${k}`, v => v + 1);
t.deepEqual({ a_a: 2 }, mapObject(map, ([_, v]) => typeof v === "number")(a));
t.deepEqual({}, mapObject(n => n)());
});
test("objectFromEntry", t => {
t.deepEqual({ a: 1 }, objectFromEntry(["a", 1]));
t.deepEqual({}, objectFromEntry());
});
<file_sep>/docs/README.md
# Kompis API
<details>
<summary>Table of contents</summary>
<ul>
<li><a href="#Pipe">Pipe</a></li>
<li><a href="#not">not</a></li>
<li><a href="#get">get</a></li>
<li><a href="#trace">trace</a></li>
<li><a href="#match">match</a></li>
<li><a href="#otherwise">otherwise</a></li>
<li><a href="#always">always</a></li>
<li><a href="#exists">exists</a></li>
<li><a href="#id">id</a></li>
<li><a href="#or">or</a></li>
<li><a href="#no">no</a></li>
<li><a href="#noop">noop</a></li>
<li><a href="#yes">yes</a></li>
<li><a href="#mapIf">mapIf</a></li>
<li><a href="#gt">gt</a></li>
<li><a href="#gte">gte</a></li>
<li><a href="#lt">lt</a></li>
<li><a href="#lte">lte</a></li>
<li><a href="#is">is</a></li>
<li><a href="#isNumber">isNumber</a></li>
<li><a href="#isString">isString</a></li>
<li><a href="#isEven">isEven</a></li>
<li><a href="#isOdd">isOdd</a></li>
<li><a href="#isOneOf">isOneOf</a></li>
<li><a href="#isAtPath">isAtPath</a></li>
<li><a href="#isAtIndex">isAtIndex</a></li>
<li><a href="#isAll">isAll</a></li>
<li><a href="#isSome">isSome</a></li>
<li><a href="#charCodeAt">charCodeAt</a></li>
<li><a href="#endsWith">endsWith</a></li>
<li><a href="#fromCharCode">fromCharCode</a></li>
<li><a href="#padEnd">padEnd</a></li>
<li><a href="#padStart">padStart</a></li>
<li><a href="#repeat">repeat</a></li>
<li><a href="#replace">replace</a></li>
<li><a href="#split">split</a></li>
<li><a href="#startsWith">startsWith</a></li>
<li><a href="#substring">substring</a></li>
<li><a href="#toLowerCase">toLowerCase</a></li>
<li><a href="#toUpperCase">toUpperCase</a></li>
<li><a href="#trim">trim</a></li>
<li><a href="#array">array</a></li>
<li><a href="#concat">concat</a></li>
<li><a href="#concatRight">concatRight</a></li>
<li><a href="#every">every</a></li>
<li><a href="#filter">filter</a></li>
<li><a href="#find">find</a></li>
<li><a href="#findIndex">findIndex</a></li>
<li><a href="#forEach">forEach</a></li>
<li><a href="#includes">includes</a></li>
<li><a href="#indexOf">indexOf</a></li>
<li><a href="#join">join</a></li>
<li><a href="#length">length</a></li>
<li><a href="#map">map</a></li>
<li><a href="#reverse">reverse</a></li>
<li><a href="#slice">slice</a></li>
<li><a href="#some">some</a></li>
<li><a href="#sort">sort</a></li>
<li><a href="#sortBy">sortBy</a></li>
<li><a href="#plainReduce">plainReduce</a></li>
<li><a href="#mapFilterReduce">mapFilterReduce</a></li>
<li><a href="#reduce">reduce</a></li>
<li><a href="#int">int</a></li>
<li><a href="#float">float</a></li>
<li><a href="#toFixed">toFixed</a></li>
<li><a href="#add">add</a></li>
<li><a href="#divide">divide</a></li>
<li><a href="#multiply">multiply</a></li>
<li><a href="#subtract">subtract</a></li>
<li><a href="#max">max</a></li>
<li><a href="#min">min</a></li>
<li><a href="#clamp">clamp</a></li>
<li><a href="#pow">pow</a></li>
<li><a href="#rangeMap">rangeMap</a></li>
<li><a href="#assign">assign</a></li>
<li><a href="#has">has</a></li>
<li><a href="#objectFromEntry">objectFromEntry</a></li>
<li><a href="#mapEntry">mapEntry</a></li>
<li><a href="#mapObject">mapObject</a></li>
</ul>
</details>
## <div id="Pipe"></div> Pipe
```ts
Pipe: (...funcs: any[]) => (value: any) => any
```
Creates a pipeline. `funcs` are composed left to right
```js
const addTwoAndDouble = Pipe(add(2), multiply(2));
addTwoAndDouble(1); // 6
[1, 2].map(addTwoAndDouble); // [6, 8]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const Pipe = (...funcs) => value => funcs.reduce((a, func) => func(a), value)
```
<p>
</details>
## <div id="not"></div> not
```ts
not: (predicate: any) => (...args: any[]) => boolean
```
Negates the result of a `predicate`
```js
const isNotString = not(isString);
isString("hello"); // true
isNotString("hello"); // false
```
<details>
<summary>Implementation</summary>
<p>
```ts
const not = predicate => (...args) => !predicate(...args)
```
<p>
</details>
## <div id="get"></div> get
```ts
get: (path: string, defaultValue?: any) => (obj: any) => any
```
Safely access properties of objects and arrays (like `lodash.get` ).
```js
const person = { name: { last: "a" } };
get("name.last")(person); // "a"
get("name.first", "b")(person); // "b"
get("[1]")([1, 2]); // 2
```
<details>
<summary>Implementation</summary>
<p>
```ts
const get = (path: string, defaultValue?) => obj => {
const sep = assertString(path).startsWith("[") || path === "" ? "" : ".";
try {
const result = eval(`obj${sep}${path}`);
return result === undefined ? defaultValue : result;
} catch {
return defaultValue;
}
}
```
<p>
</details>
## <div id="trace"></div> trace
```ts
trace: (label?: string) => (v: any) => any
```
Logs `v` to the console and returns `v` .
```js
Pipe(
add(2),
trace("after add:"), // logs "after add: 3" to the console
multiply(2),
trace("after multiply:") // Logs "after multilpy: 6" to the console
)(1);
```
<details>
<summary>Implementation</summary>
<p>
```ts
const trace = (label = "") => v => {
console.log(label, v);
return v;
}
```
<p>
</details>
## <div id="match"></div> match
```ts
match: (...patterns: [(v: any) => boolean, (v: any) => any][]) => (x: any) => any
```
Takes any number of pairs of `[predicate, mapper]` . When a match is found for `x` , returns the result of the associated mapper applied to `x` . `otherwise` can be used as a fallback pattern (must be the last pattern).
```js
const matcher = match(
[isEven, x => `${x} is even!`],
[isOdd, x => `${x} is odd!`],
[otherwise, x => `${x} is not a number :/`]
);
matcher(1); // "1 is odd!"
matcher(2); // "2 is even!"
matcher("a"); // "a is not a number :/"
```
If you use `match` recursively you'll get a maximum call stack exceeded error. To avoid this, execute `match` with a value explicitly if you need recursion:
```js
// This will always create a maximum call stack exceeded error
const badMatch = match([somePredicate, badMatch], [otherwise, n => n]);
// This won't
const goodMatch = value => match([somePredicate, goodMatch], [otherwise, n => n])(value);
```
<details>
<summary>Implementation</summary>
<p>
```ts
const match = (...patterns: [(v: any) => boolean, (v: any) => any][]) => x => {
if (patterns.length === 0) throw new TypeError("No patterns passed to 'match'");
patterns.forEach(([p, m], index) => {
assertType("function", matchError(index))(p);
assertType("function", matchError(index))(m);
});
const result = patterns.find(([predicate]) => predicate(x));
return result ? (([_, map]) => map(x))(result) : undefined;
}
```
<p>
</details>
## <div id="otherwise"></div> otherwise
```ts
otherwise: () => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const otherwise = () => true
```
<p>
</details>
## <div id="always"></div> always
```ts
always: (x: any) => () => any
```
Returns a [constant function](https://en.wikipedia.org/wiki/Constant_function) of `x`
<details>
<summary>Implementation</summary>
<p>
```ts
const always = x => () => x
```
<p>
</details>
## <div id="exists"></div> exists
```ts
exists: (x: any) => boolean
```
Compares to `null` and `undefined`
<details>
<summary>Implementation</summary>
<p>
```ts
const exists = x => x !== undefined && x !== null
```
<p>
</details>
## <div id="id"></div> id
```ts
id: (x: any) => any
```
[Identity function](https://en.wikipedia.org/wiki/Identity_function)
<details>
<summary>Implementation</summary>
<p>
```ts
const id = x => x
```
<p>
</details>
## <div id="or"></div> or
```ts
or: (fallback: any) => (x: any) => any
```
Returns `x` if it exists. Otherwise returns `fallback`
<details>
<summary>Implementation</summary>
<p>
```ts
const or = fallback => x => (exists(x) ? x : fallback)
```
<p>
</details>
## <div id="no"></div> no
```ts
no: () => boolean
```
Always returns `false`
<details>
<summary>Implementation</summary>
<p>
```ts
const no = () => false
```
<p>
</details>
## <div id="noop"></div> noop
```ts
noop: () => void
```
[No operation](https://en.wikipedia.org/wiki/NOP_(code)). Always returns `undefined`
<details>
<summary>Implementation</summary>
<p>
```ts
const noop = () => {}
```
<p>
</details>
## <div id="yes"></div> yes
```ts
yes: () => boolean
```
Always returns `true`
<details>
<summary>Implementation</summary>
<p>
```ts
const yes = () => true
```
<p>
</details>
## <div id="mapIf"></div> mapIf
```ts
mapIf: (predicate: any, ifFunc?: (x: any) => any, elseFunc?: (x: any) => any) => (v: any) => any
```
Runs the `ifFunc` or the `elseFunc` based on the result of `predicate(v)`
<details>
<summary>Implementation</summary>
<p>
```ts
const mapIf = (predicate, ifFunc = id, elseFunc = id) => v =>
predicate(v) ? ifFunc(v) : elseFunc(v)
```
<p>
</details>
## <div id="gt"></div> gt
```ts
gt: (b: any) => (a: any) => boolean
```
Is `a` greater than `b` ?
<details>
<summary>Implementation</summary>
<p>
```ts
const gt = b => a => a > b
```
<p>
</details>
## <div id="gte"></div> gte
```ts
gte: (b: any) => (a: any) => boolean
```
Is `a` greater than or equal to `b` ?
<details>
<summary>Implementation</summary>
<p>
```ts
const gte = b => a => a >= b
```
<p>
</details>
## <div id="lt"></div> lt
```ts
lt: (b: any) => (a: any) => boolean
```
Is `a` less than `b` ?
<details>
<summary>Implementation</summary>
<p>
```ts
const lt = b => a => a < b
```
<p>
</details>
## <div id="lte"></div> lte
```ts
lte: (b: any) => (a: any) => boolean
```
Is `a` less than or equal to `b` ?
<details>
<summary>Implementation</summary>
<p>
```ts
const lte = b => a => a <= b
```
<p>
</details>
## <div id="is"></div> is
```ts
is: (a: any) => (b: any) => boolean
```
Is `a` equal to `b` ?
<details>
<summary>Implementation</summary>
<p>
```ts
const is = a => b => a === b
```
<p>
</details>
## <div id="isNumber"></div> isNumber
```ts
isNumber: (n: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isNumber = n => typeof n === "number"
```
<p>
</details>
## <div id="isString"></div> isString
```ts
isString: (n: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isString = n => typeof n === "string"
```
<p>
</details>
## <div id="isEven"></div> isEven
```ts
isEven: (n: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isEven = n => isNumber(n) && n % 2 === 0
```
<p>
</details>
## <div id="isOdd"></div> isOdd
```ts
isOdd: (n: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isOdd = n => isNumber(n) && n % 2 !== 0
```
<p>
</details>
## <div id="isOneOf"></div> isOneOf
```ts
isOneOf: (...values: any[]) => (v: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isOneOf = (...values) => v => values.includes(v)
```
<p>
</details>
## <div id="isAtPath"></div> isAtPath
```ts
isAtPath: (path: any, predicate: any) => (v: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isAtPath = (path, predicate) => v => predicate(get(path)(v))
```
<p>
</details>
## <div id="isAtIndex"></div> isAtIndex
```ts
isAtIndex: (index: any, predicate: any) => (v: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const isAtIndex = (index, predicate) => isAtPath(`[${index}]`, predicate)
```
<p>
</details>
## <div id="isAll"></div> isAll
```ts
isAll: (...predicates: any[]) => (v: any) => any
```
Checks whether the `v` fulfils all the `predicates`
<details>
<summary>Implementation</summary>
<p>
```ts
const isAll = (...predicates) => v =>
predicates.reduce((a, pred) => a && pred(v), predicates.length ? true : false)
```
<p>
</details>
## <div id="isSome"></div> isSome
```ts
isSome: (...predicates: any[]) => (v: any) => any
```
Checks whether the `v` fulfils some of the `predicates`
<details>
<summary>Implementation</summary>
<p>
```ts
const isSome = (...predicates) => v =>
predicates.reduce((a, pred) => a || pred(v), false)
```
<p>
</details>
## <div id="charCodeAt"></div> charCodeAt
```ts
charCodeAt: (index: any) => (str: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const charCodeAt = index => str => sS(str).charCodeAt(index)
```
<p>
</details>
## <div id="endsWith"></div> endsWith
```ts
endsWith: (term: any) => (str: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const endsWith = term => str => sS(str).endsWith(term)
```
<p>
</details>
## <div id="fromCharCode"></div> fromCharCode
```ts
fromCharCode: (num: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const fromCharCode = num => String.fromCharCode(num)
```
<p>
</details>
## <div id="padEnd"></div> padEnd
```ts
padEnd: (length: any, char: any) => (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const padEnd = (length, char) => str => sS(str).padEnd(length, char)
```
<p>
</details>
## <div id="padStart"></div> padStart
```ts
padStart: (length: any, char: any) => (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const padStart = (length, char) => str => sS(str).padStart(length, char)
```
<p>
</details>
## <div id="repeat"></div> repeat
```ts
repeat: (length: any) => (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const repeat = length => str => sS(str).repeat(length)
```
<p>
</details>
## <div id="replace"></div> replace
```ts
replace: (regexp: any, newStr: any) => (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const replace = (regexp, newStr) => str => sS(str).replace(regexp, newStr)
```
<p>
</details>
## <div id="split"></div> split
```ts
split: (sep: any) => (str: any) => string[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const split = sep => str => sS(str).split(sep)
```
<p>
</details>
## <div id="startsWith"></div> startsWith
```ts
startsWith: (term: any) => (str: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const startsWith = term => str => sS(str).startsWith(term)
```
<p>
</details>
## <div id="substring"></div> substring
```ts
substring: (start: any, end: any) => (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const substring = (start, end) => str => sS(str).substring(start, end)
```
<p>
</details>
## <div id="toLowerCase"></div> toLowerCase
```ts
toLowerCase: (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const toLowerCase = str => sS(str).toLowerCase()
```
<p>
</details>
## <div id="toUpperCase"></div> toUpperCase
```ts
toUpperCase: (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const toUpperCase = str => sS(str).toUpperCase()
```
<p>
</details>
## <div id="trim"></div> trim
```ts
trim: (str: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const trim = str => sS(str).trim()
```
<p>
</details>
## <div id="array"></div> array
```ts
array: (range?: number, mapper?: (x: any) => any, filter?: (v: any) => boolean) => any[]
```
Creates an array. Kind of similar to list comprehension in python
```js
array(5); // [0, 1, 2, 3, 4, 5]
array(5, add(1), isEven); // [0, 3, 5]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const array = (range = 0, mapper = id, filter = v => true): any[] =>
new Array(range).fill(0).reduce((a, _, i) => a.concat(filter(i) ? mapper(i) : []), [])
```
<p>
</details>
## <div id="concat"></div> concat
```ts
concat: (b: any) => (a: any) => any[]
```
Concatenates `b` into `a` . Does not concat `undefined` or `null`
```js
concat(2)([1]); // [1, 2]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const concat = b => a => ensureArray(a).concat(ensureArray(b))
```
<p>
</details>
## <div id="concatRight"></div> concatRight
```ts
concatRight: (a: any) => (b: any) => any[]
```
Concatenates `a` into `b` . Does not concat `undefined` or `null`
```js
concat([1])(2); // [1, 2]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const concatRight = a => b => ensureArray(a).concat(ensureArray(b))
```
<p>
</details>
## <div id="every"></div> every
```ts
every: (func: any) => (arr: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const every = func => arr => sA(arr).every(func)
```
<p>
</details>
## <div id="filter"></div> filter
```ts
filter: (func: any) => (arr: any) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const filter = func => arr => sA(arr).filter(func)
```
<p>
</details>
## <div id="find"></div> find
```ts
find: (func: any) => (arr: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const find = func => arr => sA(arr).find(func)
```
<p>
</details>
## <div id="findIndex"></div> findIndex
```ts
findIndex: (func: any) => (arr: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const findIndex = func => arr => sA(arr).findIndex(func)
```
<p>
</details>
## <div id="forEach"></div> forEach
```ts
forEach: (...funcs: any[]) => (arr: any) => void
```
<details>
<summary>Implementation</summary>
<p>
```ts
const forEach = (...funcs) => arr => sA(arr).forEach(Pipe(...funcs))
```
<p>
</details>
## <div id="includes"></div> includes
```ts
includes: (thing: any) => (arr: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const includes = thing => arr => sA(arr).includes(thing)
```
<p>
</details>
## <div id="indexOf"></div> indexOf
```ts
indexOf: (term: any) => (arr: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const indexOf = term => arr => sA(arr).indexOf(term)
```
<p>
</details>
## <div id="join"></div> join
```ts
join: (sep: string) => (arr: any) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const join = (sep: string) => arr => sA(arr).join(sep)
```
<p>
</details>
## <div id="length"></div> length
```ts
length: (arr: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const length = arr => sA(arr).length
```
<p>
</details>
## <div id="map"></div> map
```ts
map: (...funcs: any[]) => (arr: any) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const map = (...funcs) => arr => sA(arr).map(Pipe(...funcs))
```
<p>
</details>
## <div id="reverse"></div> reverse
```ts
reverse: (arr: any) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const reverse = arr => sA(arr).reverse()
```
<p>
</details>
## <div id="slice"></div> slice
```ts
slice: (begin: any, end: any) => (arr: any) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const slice = (begin, end) => arr => sA(arr).slice(begin, end)
```
<p>
</details>
## <div id="some"></div> some
```ts
some: (func: any) => (arr: any) => boolean
```
<details>
<summary>Implementation</summary>
<p>
```ts
const some = func => arr => sA(arr).some(func)
```
<p>
</details>
## <div id="sort"></div> sort
```ts
sort: (func: any) => (arr: any) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const sort = func => arr => sA(arr).sort(func)
```
<p>
</details>
## <div id="sortBy"></div> sortBy
```ts
sortBy: (path?: string) => (arr: any) => any[]
```
Sort objects or arrays by key or index (or both)
```js
sortBy("a[0]")([{ a: [3] }, { a: [2] }, { a: [1] }]);
// [{ a: [1] }, { a: [2] }, { a: [3] }]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const sortBy = (path = "") =>
sort((a, b) => {
const A = get(path)(a);
const B = get(path)(b);
return lt(B)(A) ? -1 : gt(B)(A) ? 1 : 0;
})
```
<p>
</details>
## <div id="plainReduce"></div> plainReduce
```ts
plainReduce: (func: any, initial: any) => (arr: any) => any
```
See `reduce` for documentation
<details>
<summary>Implementation</summary>
<p>
```ts
const plainReduce = (func, initial) => arr =>
sA(arr).reduce((a, c) => func(c)(a), initial)
```
<p>
</details>
## <div id="mapFilterReduce"></div> mapFilterReduce
```ts
mapFilterReduce: (reducer: any, initial: any, map: any, filter?: (v: any) => boolean) => (arr: any) => any
```
See `reduce` for documentation
<details>
<summary>Implementation</summary>
<p>
```ts
const mapFilterReduce = (reducer, initial, map, filter = v => true) => arr =>
sA(arr).reduce((a, c) => (filter(c) ? reducer(map(c))(a) : a), initial)
```
<p>
</details>
## <div id="reduce"></div> reduce
```ts
reduce: (reducer: any, initial: any, map: any, filter: any) => (arr: any) => any
```
Note that `reducer` needs to be a higher order unary function (returning another unary function) and that the order of the current and accumulator are reversed. This makes it possible to use other functions from this package as the `reducer` .
```js
reduce(curr => accum => accum + curr, 0)([1, 2, 3]); // 6
reduce(add, 0)([1, 2, 3]); // 6
reduce(concat, [])([[1, 2], [3, 4]]); // [1, 2, 3, 4]
```
`map` and `filter` can be used to do many operations that otherwise would require iterating over a list many times, like `[].filter(fn).map(fn).reduce(fn)` which can be orders of magnitude slower. Filtering happens before mapping.
```js
const numbers = [1, 2, 3, 4];
// 4 iterations
reduce(add, 0, pow(2), isEven)(numbers); // 20
// 4 + 2 + 2 iterations
Pipe(filter(isEven), map(pow(2)), reduce(add))(numbers); // 20
```
<details>
<summary>Implementation</summary>
<p>
```ts
const reduce = (reducer, initial, map, filter) =>
map ? mapFilterReduce(reducer, initial, map, filter) : plainReduce(reducer, initial)
```
<p>
</details>
## <div id="int"></div> int
```ts
int: (n: any) => number
```
Unary version of parseInt (can safely be used in `map` etc)
<details>
<summary>Implementation</summary>
<p>
```ts
const int = n => parseInt(n)
```
<p>
</details>
## <div id="float"></div> float
```ts
float: (n: any) => number
```
Unary version of parseFloat (can safely be used in `map` etc)
<details>
<summary>Implementation</summary>
<p>
```ts
const float = n => parseFloat(n)
```
<p>
</details>
## <div id="toFixed"></div> toFixed
```ts
toFixed: (digits: number) => (num: number) => string
```
<details>
<summary>Implementation</summary>
<p>
```ts
const toFixed = (digits: number) => (num: number) =>
isNumber(num) ? num.toFixed(digits) : ""
```
<p>
</details>
## <div id="add"></div> add
```ts
add: (b: any) => (a: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const add = b => a => a + b
```
<p>
</details>
## <div id="divide"></div> divide
```ts
divide: (b: any) => (a: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const divide = b => a => a / b
```
<p>
</details>
## <div id="multiply"></div> multiply
```ts
multiply: (b: any) => (a: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const multiply = b => a => a * b
```
<p>
</details>
## <div id="subtract"></div> subtract
```ts
subtract: (b: any) => (a: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const subtract = b => a => a - b
```
<p>
</details>
## <div id="max"></div> max
```ts
max: (arr: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const max = arr => Math.max(...arr)
```
<p>
</details>
## <div id="min"></div> min
```ts
min: (arr: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const min = arr => Math.min(...arr)
```
<p>
</details>
## <div id="clamp"></div> clamp
```ts
clamp: (min: any, max: any) => (n: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const clamp = (min, max) => n => Math.min(max, Math.max(min, n))
```
<p>
</details>
## <div id="pow"></div> pow
```ts
pow: (exp: any) => (base: any) => number
```
<details>
<summary>Implementation</summary>
<p>
```ts
const pow = exp => base => Math.pow(base, exp)
```
<p>
</details>
## <div id="rangeMap"></div> rangeMap
```ts
rangeMap: (inMin: any, inMax: any, outMin: any, outMax: any) => (n: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const rangeMap = (inMin, inMax, outMin, outMax) => n =>
((n - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin
```
<p>
</details>
## <div id="assign"></div> assign
```ts
assign: (b: any) => (a: any) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const assign = b => a => Object.assign({}, a, b)
```
<p>
</details>
## <div id="has"></div> has
```ts
has: (path?: string) => (obj: any) => boolean
```
Checks whether `obj` has a value at the given `path` . Not to be confused with `object.hasOwnProperty`
<details>
<summary>Implementation</summary>
<p>
```ts
const has = (path = "") => obj => exists(get(path)(obj))
```
<p>
</details>
## <div id="objectFromEntry"></div> objectFromEntry
```ts
objectFromEntry: ([k, v]?: [(string | undefined)?, any?]) => { [x: string]: any; }
```
<details>
<summary>Implementation</summary>
<p>
```ts
const objectFromEntry = ([k, v]: Entry = []) => (k ? { [k]: v } : {})
```
<p>
</details>
## <div id="mapEntry"></div> mapEntry
```ts
mapEntry: (mapKey: any, mapValue: any) => ([k, v]?: [(string | undefined)?, any?]) => any[]
```
<details>
<summary>Implementation</summary>
<p>
```ts
const mapEntry = (mapKey, mapValue) => ([k, v]: Entry = []) => [
mapKey(k),
mapValue(v)
]
```
<p>
</details>
## <div id="mapObject"></div> mapObject
```ts
mapObject: (map: any, filter: any) => (obj?: {}) => any
```
<details>
<summary>Implementation</summary>
<p>
```ts
const mapObject = (map, filter) => (obj = {}) =>
reduce(assign, {}, Pipe(map, objectFromEntry), filter)(Object.entries(obj))
```
<p>
</details>
<file_sep>/source/utils.ts
/** Creates a pipeline. `funcs` are composed left to right
```js
const addTwoAndDouble = Pipe(add(2), multiply(2));
addTwoAndDouble(1); // 6
[1, 2].map(addTwoAndDouble); // [6, 8]
```
*/
export const Pipe = (...funcs) => value => funcs.reduce((a, func) => func(a), value);
/** Negates the result of a `predicate`
```js
const isNotString = not(isString);
isString("hello"); // true
isNotString("hello"); // false
```
*/
export const not = predicate => (...args) => !predicate(...args);
const throwError = error => {
throw error;
};
const assertType = (type, label) => value =>
typeof value !== type ? throwError(new TypeError(label)) : value;
const assertString = assertType("string", "path must be a string");
/** Safely access properties of objects and arrays (like `lodash.get`).
```js
const person = { name: { last: "a" } };
get("name.last")(person); // "a"
get("name.first", "b")(person); // "b"
get("[1]")([1, 2]); // 2
```
*/
export const get = (path: string, defaultValue?) => obj => {
const sep = assertString(path).startsWith("[") || path === "" ? "" : ".";
try {
const result = eval(`obj${sep}${path}`);
return result === undefined ? defaultValue : result;
} catch {
return defaultValue;
}
};
/** Logs `v` to the console and returns `v`.
```js
Pipe(
add(2),
trace("after add:"), // logs "after add: 3" to the console
multiply(2),
trace("after multiply:") // Logs "after multilpy: 6" to the console
)(1);
```
*/
// eslint-disable-next-line no-console
export const trace = (label = "") => v => {
console.log(label, v);
return v;
};
const matchError = index => `Non-function passed to 'match[${index}]'`;
/** Takes any number of pairs of `[predicate, mapper]`. When a match is found for `x`, returns the result of the associated mapper applied to `x`. `otherwise` can be used as a fallback pattern (must be the last pattern).
```js
const matcher = match(
[isEven, x => `${x} is even!`],
[isOdd, x => `${x} is odd!`],
[otherwise, x => `${x} is not a number :/`]
);
matcher(1); // "1 is odd!"
matcher(2); // "2 is even!"
matcher("a"); // "a is not a number :/"
```
If you use `match` recursively you'll get a maximum call stack exceeded error. To avoid this, execute `match` with a value explicitly if you need recursion:
```js
// This will always create a maximum call stack exceeded error
const badMatch = match([somePredicate, badMatch], [otherwise, n => n]);
// This won't
const goodMatch = value => match([somePredicate, goodMatch], [otherwise, n => n])(value);
```
*/
export const match = (...patterns: [(v: any) => boolean, (v: any) => any][]) => x => {
if (patterns.length === 0) throw new TypeError("No patterns passed to 'match'");
patterns.forEach(([p, m], index) => {
assertType("function", matchError(index))(p);
assertType("function", matchError(index))(m);
});
const result = patterns.find(([predicate]) => predicate(x));
return result ? (([_, map]) => map(x))(result) : undefined;
};
// To be used in combination with 'match'
export const otherwise = () => true;
<file_sep>/test/string.test.js
import test from "ava";
import {
charCodeAt,
endsWith,
fromCharCode,
padEnd,
padStart,
repeat,
replace,
split,
startsWith,
substring,
toLowerCase,
toUpperCase,
trim
} from "../source/index";
const macro = (t, expected, input) => {
t.deepEqual(expected, input);
};
test("charCodeAt", macro, 65, charCodeAt(0)("ABC"));
test("charCodeAt: empty", macro, NaN, charCodeAt(0)());
test("endsWith: true", macro, true, endsWith("C")("ABC"));
test("endsWith: false", macro, false, endsWith("A")("ABC"));
test("endsWith: empty", macro, false, endsWith("A")());
// Should ignore extra arguments:
test("fromCharCode", macro, "A", fromCharCode(65, false, false));
test("padEnd", macro, "A__", padEnd(3, "_")("A"));
test("padEnd: empty", macro, "___", padEnd(3, "_")());
test("padStart", macro, "__A", padStart(3, "_")("A"));
test("padStart: empty", macro, "___", padStart(3, "_")());
test("repeat", macro, "AAA", repeat(3)("A"));
test("repeat: empty", macro, "", repeat(3)());
test("replace", macro, "ABC", replace("x", "B")("AxC"));
test("replace: empty", macro, "", replace("x", "B")());
test("split", macro, ["A", "B", "C"], split("")("ABC"));
test("split: empty", macro, [], split("")());
test("startsWith: true", macro, true, startsWith("A")("ABC"));
test("startsWith: false", macro, false, startsWith("C")("ABC"));
test("startsWith: empty", macro, false, startsWith("C")());
test("substring", macro, "B", substring(1, 2)("ABC"));
test("substring: empty", macro, "", substring(1, 2)());
test("toLowerCase", macro, "abc", toLowerCase("ABC"));
test("toLowerCase: empty", macro, "", toLowerCase());
test("toUpperCase", macro, "ABC", toUpperCase("abc"));
test("toUpperCase: empty", macro, "", toUpperCase());
test("trim", macro, "ABC", trim(" ABC "));
test("trim: empty", macro, "", trim());
|
43dbb775c794c71792865c1b7435e58b2dd282e7
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 14
|
Markdown
|
asbjornh/kompis
|
9c827eb678871d386a4bb21f895890390fff39c2
|
94b4e12c35fa917e7f7ede456f14201bd6c0af00
|
refs/heads/main
|
<file_sep>package com.example.mvvm_room_rxjava.db.dao
import androidx.room.*
import com.example.mvvm_room_rxjava.db.entities.HomeItem
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
@Dao
interface HomeItemDao {
@Query("SELECT * FROM db_item")
fun getAll(): Flowable<List<HomeItem>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(homeItems: List<HomeItem>): Completable
@Query("SELECT COUNT(*) FROM db_item")
fun getDbSize(): Single<Int>
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateDb(homeItems: List<HomeItem>)
}<file_sep>package com.example.mvvm_room_rxjava.ui.viewmodels
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mvvm_room_rxjava.db.entities.HomeItem
import com.example.mvvm_room_rxjava.repository.ItemRepository
class HomeListViewModel(application: Application) : AndroidViewModel(application) {
private lateinit var mHomeItems: MutableLiveData<List<HomeItem>>
private var mItemRepository = ItemRepository
private val TAG = "HomeListViewModel"
init {
run {
if (this::mHomeItems.isInitialized) {
Log.d(TAG, "HomeListViewModel init: mHomeItems is already initialize")
return@run
}
Log.d(TAG, "HomeListViewModel init: initialize repository 1 time")
// Init Database
mItemRepository.initDb(application)
// Get data from database
mHomeItems = mItemRepository.getDataFromDb() as MutableLiveData<List<HomeItem>>
}
}
override fun onCleared() {
super.onCleared()
mItemRepository.cleanCompositeDisposable()
}
fun makeInternetRequest(): LiveData<List<HomeItem>> {
mHomeItems = mItemRepository.getDataFromInternet() as MutableLiveData<List<HomeItem>>
return mHomeItems
}
fun getDbSize(): LiveData<Int> {
return mItemRepository.getDbSize()
}
fun insertItemToDb(testItems: List<HomeItem>) {
mItemRepository.insertToDb(testItems)
}
fun getDataFromViewModel(): LiveData<List<HomeItem>> {
return mHomeItems
}
}<file_sep>package com.example.mvvm_room_rxjava.repository
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mvvm_room_rxjava.db.database.HomeItemDatabase
import com.example.mvvm_room_rxjava.db.entities.HomeItem
import com.example.mvvm_room_rxjava.retrofit.MyRetrofitBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
object ItemRepository {
private val TAG = "ItemRepository"
private lateinit var mHomeItemDatabase: HomeItemDatabase
private var compositeDisposable = CompositeDisposable()
fun initDb(context: Context) {
mHomeItemDatabase = HomeItemDatabase.getDatabase(context)
}
fun cleanCompositeDisposable() {
compositeDisposable.clear()
}
fun getDataFromDb(): LiveData<List<HomeItem>> {
val liveDataTestItem = MutableLiveData<List<HomeItem>>()
compositeDisposable.add(
mHomeItemDatabase.homeItemDao().getAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Log.d(TAG, "call getDataFromDb() finish ok")
liveDataTestItem.value = it
}, {
Log.e(TAG, "call getDataFromDb() finish Throwable: ${it.localizedMessage}")
})
)
return liveDataTestItem
}
fun getDbSize(): LiveData<Int> {
val dbSize = MutableLiveData<Int>()
compositeDisposable.add(
mHomeItemDatabase.homeItemDao().getDbSize()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
dbSize.value = it
}, {
Log.e(TAG, "call getDbSize() finish Throwable: ${it.localizedMessage}")
})
)
return dbSize
}
fun insertToDb(testItems: List<HomeItem>) {
compositeDisposable.add(
mHomeItemDatabase.homeItemDao().insertAll(testItems)
.subscribeOn(Schedulers.io())
.subscribe({
Log.d(TAG, "call insertToDb() finish ok")
}, {
Log.e(TAG, "call insertToDb() finish Throwable: ${it.localizedMessage}")
})
)
}
fun getDataFromInternet(): LiveData<List<HomeItem>> {
val liveDataTestItem = MutableLiveData<List<HomeItem>>()
compositeDisposable.add(
MyRetrofitBuilder.buildService().getData()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
Log.d(TAG, "call getDataFromInternet() finish ok")
val testItems = ArrayList<HomeItem>()
if (it.hits != null) {
it.hits.forEach { hitsItem ->
val testItem = HomeItem(id = hitsItem?.id!!, hitsItem.largeImageURL)
testItems.add(testItem)
}
}
liveDataTestItem.value = testItems
}, {
Log.e(
TAG,
"call getDataFromInternet() finish Throwable: ${it.localizedMessage}"
)
})
)
return liveDataTestItem
}
}<file_sep>package com.example.mvvm_room_rxjava.ui.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mvvm_room_rxjava.R
import com.example.mvvm_room_rxjava.db.entities.HomeItem
class HomeRecyclerAdapter(
private val items: List<HomeItem>,
private val listener: OnImageListener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_activity_list, parent, false)
return HomeViewHolder(view, listener)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is HomeViewHolder -> {
holder.bind(homeItem = items[position])
}
}
}
override fun getItemCount(): Int {
return items.size
}
class HomeViewHolder constructor(
itemView: View,
private val listener: OnImageListener
) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val image = itemView.findViewById<ImageView>(R.id.item_list_image)
fun bind(homeItem: HomeItem) {
itemView.setOnClickListener(this)
val requestOption = RequestOptions
.placeholderOf(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.override(1000, 1000)
Glide.with(itemView)
.applyDefaultRequestOptions(requestOption)
.load(homeItem.largeImageURL)
.into(image)
}
override fun onClick(v: View?) {
listener.onClickRecycler(absoluteAdapterPosition)
}
}
interface OnImageListener {
fun onClickRecycler(position: Int)
}
}<file_sep>package com.example.mvvm_room_rxjava.ui.fragments
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.mvvm_room_rxjava.R
import com.example.mvvm_room_rxjava.db.entities.HomeItem
import com.example.mvvm_room_rxjava.ui.activities.ImageActivity
import com.example.mvvm_room_rxjava.ui.adapters.HomeRecyclerAdapter
import com.example.mvvm_room_rxjava.ui.viewmodels.HomeListViewModel
import com.example.mvvm_room_rxjava.utils.isNetworkAvailable
import com.example.mvvm_room_rxjava.utils.showMessage
class HomeListFragment :
Fragment(R.layout.fragment_home_list),
HomeRecyclerAdapter.OnImageListener {
private val TAG = "HomeListFragment"
private var mHomeItems = ArrayList<HomeItem>()
private lateinit var mHomeAdapter: HomeRecyclerAdapter
private lateinit var mRecyclerView: RecyclerView
private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
private lateinit var mViewModel: HomeListViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mRecyclerView = view.findViewById(R.id.homeListRecycler)
mSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout)
}
private fun initRecyclerView() {
mRecyclerView.apply {
layoutManager = LinearLayoutManager(requireContext())
mHomeAdapter = HomeRecyclerAdapter(mHomeItems, this@HomeListFragment)
adapter = mHomeAdapter
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mViewModel = ViewModelProvider(requireActivity()).get(HomeListViewModel::class.java)
mViewModel.getDataFromViewModel().observe(requireActivity(), Observer { dataViewModel ->
// If database value is null make internet request
if (dataViewModel.isEmpty()) {
updateFromInternet()
} else {
changeValuesInAdapter(dataViewModel)
}
})
mViewModel.getDbSize().observe(requireActivity(), Observer {
Log.d(TAG, "call onActivityCreated: ViewModel get DB size: $it")
})
initOnClickListener()
initRecyclerView()
}
private fun changeValuesInAdapter(data: List<HomeItem>) {
mHomeItems.clear()
mHomeItems.addAll(data)
mHomeAdapter.notifyDataSetChanged()
}
private fun initOnClickListener() {
mSwipeRefreshLayout.setOnRefreshListener {
updateFromInternet()
}
}
private fun updateFromInternet() {
if (isNetworkAvailable(requireContext())) {
isRefreshing(true)
mViewModel.makeInternetRequest()
.observe(requireActivity(), Observer { dataFromInternet ->
showMessage(requireContext(), getString(R.string.update_data_from_internet))
// Get value from internet and update adapter
changeValuesInAdapter(dataFromInternet)
// Save new data to db
mViewModel.insertItemToDb(dataFromInternet)
isRefreshing(false)
})
} else {
showMessage(requireContext(), getString(R.string.please_check_internet_connection))
isRefreshing(false)
}
}
// Open image in new Activity
override fun onClickRecycler(position: Int) {
val imageUrl = mHomeItems[position].largeImageURL
val intent = Intent(requireContext(), ImageActivity::class.java)
intent.putExtra(getString(R.string.image_url), imageUrl)
startActivity(intent)
}
private fun isRefreshing(boolean: Boolean) {
mSwipeRefreshLayout.isRefreshing = boolean
}
}<file_sep>package com.example.mvvm_room_rxjava.retrofit
import com.example.mvvm_room_rxjava.retrofit.models.Response
import io.reactivex.Single
import retrofit2.http.GET
interface ApiService {
@GET("api/?key=<KEY>&image_type=photo")
fun getData(): Single<Response>
}<file_sep>package com.example.mvvm_room_rxjava.db.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity (tableName = "db_item")
data class HomeItem(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
@ColumnInfo(name = "largeImageURL")
val largeImageURL: String? = null
)
<file_sep>package com.example.mvvm_room_rxjava.ui.activities
import androidx.appcompat.app.AppCompatActivity
import com.example.mvvm_room_rxjava.R
class HomeListActivity : AppCompatActivity(R.layout.activity_home_list)<file_sep>package com.example.mvvm_room_rxjava.retrofit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
object MyRetrofitBuilder {
private var httpLoggingInterceptor = HttpLoggingInterceptor()
init {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
}
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl("https://pixabay.com/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
.create(ApiService::class.java)
fun buildService(): ApiService {
// Initialize Retrofit
return retrofit
}
}<file_sep>package com.example.mvvm_room_rxjava.ui.activities
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mvvm_room_rxjava.R
class ImageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image)
val constraintLayout = findViewById<ConstraintLayout>(R.id.constraint_image_fragment)
val imageView = findViewById<ImageView>(R.id.image_view)
if (intent.hasExtra(getString(R.string.image_url))) {
val imageUrl = intent.getStringExtra(getString(R.string.image_url))
val requestOption = RequestOptions()
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
Glide.with(constraintLayout)
.applyDefaultRequestOptions(requestOption)
.load(imageUrl)
.into(imageView)
}
}
}<file_sep>package com.example.mvvm_room_rxjava.retrofit.models
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
data class Response(
@field:SerializedName("hits")
val hits: List<HitsItem?>? = null,
@field:SerializedName("total")
val total: Int? = null,
@field: SerializedName("totalHits")
val totalHits: Int? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.createTypedArrayList(HitsItem.CREATOR),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(total)
parcel.writeValue(totalHits)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Response> {
override fun createFromParcel(parcel: Parcel): Response {
return Response(parcel)
}
override fun newArray(size: Int): Array<Response?> {
return arrayOfNulls(size)
}
}
}
data class HitsItem(
@field:SerializedName("webformatHeight")
val webformatHeight: Int? = null,
@field:SerializedName("imageWidth")
val imageWidth: Int? = null,
@field:SerializedName("favorites")
val favorites: Int? = null,
@field:SerializedName("previewHeight")
val previewHeight: Int? = null,
@field:SerializedName("webformatURL")
val webformatURL: String? = null,
@field:SerializedName("userImageURL")
val userImageURL: String? = null,
@field:SerializedName("previewURL")
val previewURL: String? = null,
@field:SerializedName("comments")
val comments: Int? = null,
@field:SerializedName("type")
val type: String? = null,
@field:SerializedName("imageHeight")
val imageHeight: Int? = null,
@field:SerializedName("tags")
val tags: String? = null,
@field:SerializedName("previewWidth")
val previewWidth: Int? = null,
@field:SerializedName("downloads")
val downloads: Int? = null,
@field:SerializedName("user_id")
val userId: Int? = null,
@field:SerializedName("largeImageURL")
val largeImageURL: String? = null,
@field:SerializedName("pageURL")
val pageURL: String? = null,
@field:SerializedName("id")
val id: Int? = null,
@field:SerializedName("imageSize")
val imageSize: Int? = null,
@field:SerializedName("webformatWidth")
val webformatWidth: Int? = null,
@field:SerializedName("user")
val user: String? = null,
@field:SerializedName("views")
val views: Int? = null,
@field:SerializedName("likes")
val likes: Int? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString(),
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(webformatHeight)
parcel.writeValue(imageWidth)
parcel.writeValue(favorites)
parcel.writeValue(previewHeight)
parcel.writeString(webformatURL)
parcel.writeString(userImageURL)
parcel.writeString(previewURL)
parcel.writeValue(comments)
parcel.writeString(type)
parcel.writeValue(imageHeight)
parcel.writeString(tags)
parcel.writeValue(previewWidth)
parcel.writeValue(downloads)
parcel.writeValue(userId)
parcel.writeString(largeImageURL)
parcel.writeString(pageURL)
parcel.writeValue(id)
parcel.writeValue(imageSize)
parcel.writeValue(webformatWidth)
parcel.writeString(user)
parcel.writeValue(views)
parcel.writeValue(likes)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<HitsItem> {
override fun createFromParcel(parcel: Parcel): HitsItem {
return HitsItem(parcel)
}
override fun newArray(size: Int): Array<HitsItem?> {
return arrayOfNulls(size)
}
}
}
|
b0feec6b86faef78e7369b493779e0dc65caddb0
|
[
"Kotlin"
] | 11
|
Kotlin
|
serhiibondarenko16/mvvm_room_rxjava
|
8579700520a32b6f8bdff43bb4042e92db2b965f
|
fde28bd307a248a292095558a54408b5f0675388
|
refs/heads/master
|
<file_sep>//
// main.c
// StructDemo
//
// Created by liujunyi on 16/3/5.
// Copyright © 2016年 LJY. All rights reserved.
//
#include <stdio.h>
#include <string.h>
struct component {
char name[50];
char number[10];
int score;
};
struct component Person[] = {
{"传奇码农海事姐姐", "11099", 97},
{"大表妹", "11100", 95},
{"吃土少年郑晓悦", "11101", 94},
{"工会书记童比大雄", "11102", 91},
{"撸狗码农小母", "11103", 93},
{"宁神", "11104", 94}
};
void getPersonWithMaxScore();
void printInfo();
int main(int argc, const char * argv[]) {
// insert code here...
getPersonWithMaxScore();
printf("==========我叫分界线==========\n");
printInfo();
return 0;
}
void getPersonWithMaxScore() {
int n = ((int)(sizeof(Person)))/((int)(sizeof(Person[0])));
int max = 0;
char nameString[100] = "";
for (int i = 0; i < n; i ++) {
if (max < Person[i].score) {
max = Person[i].score;
strcpy(nameString, Person[i].name);
}
}
printf("成绩最高的人为:%s, 成绩为:%d\n", nameString, max);
}
void printInfo() {
int n = ((int)(sizeof(Person)))/((int)(sizeof(Person[0])));
printf("全体人员信息如下:\n");
for (int i = 0; i < n; i ++) {
printf("姓名:%s, 编号:%s, 成绩:%d\n", Person[i].name, Person[i].number, Person[i].score);
}
}
<file_sep>//
// main.c
// GetResult
//
// Created by liujunyi on 16/3/5.
// Copyright © 2016年 LJY. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("请输入一个正整数:");
__block int number;
scanf("%d", &number);
void (^calculationBlock)(int) = ^(int number){
int sum = 0;
for (int i = 1; i <= number; i ++) {
if ((i & 1) != 0) {
sum += i*i;
} else {
sum -= i*i;
}
}
printf("结果为:%d\n", sum);
return;
};
calculationBlock(number);
return 0;
}
|
f5a115dbc7a448cf20e58e77f5bf84fe9cb44e73
|
[
"C"
] | 2
|
C
|
liujunyi271828/SomeCDemo
|
f2701f75e1e019e9b54cda37b8215bff91a2b1ba
|
1722e8faf18969d940544a7b536dbd4839f84a32
|
refs/heads/master
|
<file_sep>This is a web app running on Node web server using MongoDB that have endpoints to handle a basic school information system. This app:
- Creates Students’ resource
- Reads Students’ resource
- Updates and deletes students.
# Student-Resource-App
<file_sep>var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
expressSanitizer = require("express-sanitizer"),
mongoose = require("mongoose"),
methodOverride = require("method-override");
//APP CONFIG
var url = process.env.DATABASEURL || "mongodb://localhost/student_app";
mongoose.connect(url);
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressSanitizer());
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(methodOverride("_method"));
//MONGOOSE/MODEL CONFIG
var studentSchema = new mongoose.Schema({
name: String,
age: Number,
passport: String,
sex: String,
created: {type: Date, default: Date.now}
});
var Student = mongoose.model("Blog", studentSchema);
// Student.create({
// name: "Jerry",
// age: 24,
// sex: "Male",
// passport: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSEhIWFRUVFRcVFRUVFRUVFRUVFRUWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODUtNygtLisBCgoKDg0OGhAQGi0lHx0tLS0tLS0vLS0tLS0tLS0rLS0tLS0tLS0tLS0tLS0tLS0rLS0tLS0tLS0tLS0tLS0tLf/AABEIAMUBAAMBIgACEQEDEQH/xAAcAAABBAMBAAAAAAAAAAAAAAAEAwUGBwABAgj/xABGEAABAwIEAwcCAgYHBQkAAAABAAIDBBEFEiExBkFRBxMiYXGBkaGxMsEUQlJyktEVIzNiguHxJEOToqMIFiU0Y2SywvD/xAAaAQADAQEBAQAAAAAAAAAAAAABAgMABAUG/8QALBEAAgIBAwMDAwMFAAAAAAAAAAECEQMSITE<KEY>"
// });
//RESTFUL ROUTES
app.get("/", function(req, res) {
res.redirect("/students");
});
//INDEX ROUTE
app.get("/students", function(req, res){
Student.find({}, function(err, students){
if(err){
console.log("ERROR!");
} else {
res.render("index", {students: students});
}
});
});
//NEW ROUTE
app.get("/students/new", function(req, res) {
res.render("new");
});
//CREATE ROUTE
app.post("/students", function(req, res){
//create new student
req.body.student.name = req.sanitize(req.body.student.name);
Student.create(req.body.student, function(err, newStudent){
if(err){
res.render("new");
} else {
//then redirect to the index
res.redirect("/students");
}
});
});
//SHOW ROUTE
app.get("/students/:id", function(req, res) {
Student.findById(req.params.id, function(err, foundStudent){
if(err){
res.redirect("/students");
} else {
res.render("show", {student: foundStudent});
}
});
});
//EDIT ROUTE
app.get("/students/:id/edit", function(req, res) {
Student.findById(req.params.id, function(err, foundStudent){
if(err){
res.redirect("/students");
} else {
res.render("edit", {student: foundStudent});
}
});
});
//UPDATE ROUTE
app.put("/students/:id", function(req, res){
req.body.student.name = req.sanitize(req.body.student.name);
Student.findByIdAndUpdate(req.params.id, req.body.student, function(err, updatedStudent){
if(err){
res.redirect("/students")
} else {
res.redirect("/students/" + req.params.id);
}
});
});
//DELETE ROUTE
app.delete("/students/:id", function(req, res){
Student.findByIdAndRemove(req.params.id, function(err){
//destroy student resource
if(err){
res.redirect("/students");
} else {
res.redirect("/students");
}
});
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("StudentsApp Server has started!");
});
|
cc636f74563af149e78b4fcb0a6c6de19a2d6f9a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
jherey/Student-Resource-App
|
f275322bf444d7b43d2797e5729a98e9c3af20af
|
6fe3e576de5e84f9f0cab926d73bd93dae162b7d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.